Compare commits

..

213 Commits

Author SHA1 Message Date
Maurice dbf011f026 fix(ci): use the bound database for map defaults and retry preloads
Write both defaults in one guarded statement so a SQLite source imported by the Postgres suite needs no Postgres lock. Release a failed speculative chunk promise so opening the map can retry it.
2026-11-30 16:45:35 +01:00
Maurice 54c54d5e65 fix(ci): repair map fixtures and keep renderer dependencies layered
Use the engine write lock for map defaults and clean the metadata-free test snapshot with Kysely. Model the Leaflet bridge option, keep the renderer failure state below the settings store, and make the tile tests independent of the transpiler quote style.
2026-11-30 16:34:55 +01:00
Maurice 5c133bbf40 feat(maps): start new installations with MapLibre Liberty 2026-11-30 16:24:50 +01:00
Maurice f814b0000d feat(maps): keep GL maps responsive through style and GPU changes 2026-11-30 16:24:49 +01:00
Maurice 69eacd5316 feat(settings): pick your own map template or the theme style for MapLibre
The MapLibre style picker offers two more entries after the OpenFreeMap
styles: OpenFreeMap that follows the light or dark theme (trek:ofm-auto),
and the user's own map template (trek:template), which brings the template
field under the picker, and the CARTO key for a CARTO template. Where the
trip map will draw the template with the classic 2D map (Amap, a host the
CSP does not name) the form says so and the preview shows that map. The
preview draws exactly what the trip map will.

Every place the forms load or save a MapLibre style keeps a keyword now,
where it used to turn it into Liberty on the first unchanged save: the
user form on desktop and phone (load, save, the phone's mirrored field,
a provider switch there and back) and the admin defaults (provider switch,
preset pick, typed style). The rules live in mapSettingsModel, so both
shells render from one decision:

- the template keyword with an empty template saves Liberty;
- switching from Leaflet with a template and an empty MapLibre slot
  preselects the template, shown and not saved until Save;
- Leaflet never writes a keyword into the Mapbox slot, and Mapbox shows its
  default for one.

New strings in all locales.
2026-11-30 16:22:53 +01:00
Maurice d39d544297 fix(offline): raster tiles a GL map fetches get a service worker cache of their own
Leaflet loads a tile as an image without CORS and the prefetch fetches it
no-cors, so map-tiles holds opaque answers. A GL map reads tiles with a
CORS fetch and cannot use one: once Leaflet had drawn an OpenTopoMap tile,
the GL tour layer failed on the same URL, and a MapLibre template would
fail the same way on every prefetched tile.

A CORS request for a raster preset's tile now goes to map-tiles-gl, which
keeps only readable answers, ahead of the Leaflet rules; images and the
no-cors prefetch stay in map-tiles. The matcher is written into the
service worker by its source text, so its host list is inline, and a test
holds it to the hosts the CSP lets a GL map fetch. OpenHikingMap and
CyclOSM stay out, their usage policies allow no offline copy.

The prefetch takes exactly one way per user: a template MapLibre draws on
such a host is fetched with CORS into map-tiles-gl, at the density the map
asks for, everything else as before. Clearing offline maps drops both
caches, and the iOS trim keeps both within its budget.
2026-11-30 16:22:52 +01:00
Maurice 32879dd528 feat(maps): MapLibre draws the user's map template on trek:template
A MapLibre user could only draw OpenFreeMap styles; a raster template was
Leaflet's alone. With maplibre_style set to trek:template, MapLibre now
draws the template the trip map already resolves for Leaflet (CARTO key,
keyless fallback and dark default included), so both renderers show the
same map. No stored row holds the keyword, so every existing user sees
exactly the map they saw before, and Mapbox is untouched.

- glBasemap turns the basemap spec into a raster style document (256px
  tiles as Leaflet requests them, the provider's deepest zoom, the credit,
  OpenFreeMap glyphs for the map's own labels) and resolves trek:ofm-auto
  to Liberty or OpenFreeMap Dark with the colour scheme.
- glCanFetch decides whether a GL map may fetch a basemap here: https on a
  host the CSP names, the shipped ones or MAP_EXTRA_CONNECT_HOSTS from the
  app config. GCJ-02 tiles (Amap) and other hosts are drawn by Leaflet for
  that render, the setting untouched.
- rasterHealth watches the first tiles of a template map: a CSP refusal or
  twelve failures without a success move every map drawing that template
  to Leaflet for the session, with a pill that says so.
- useEffectiveMapEngine decides this on the engine that actually draws and
  runs the offline checks after it; a stored raster template keeps drawing
  offline where Leaflet would keep the same tiles.
- The journey map uses the same hook: the same template, the same fallback
  and now the offline basemap with its pill as the trip map has it.
- A MapLibre raster style stops at zoom 19 like Leaflet; the Mapbox options
  stay as they were.

The offline pill moves to BasemapPill for both maps. Dropping the unused
imports there lowers the eslint baseline.
2026-11-30 16:22:52 +01:00
Maurice dc008ad7a5 feat(shared): keywords for MapLibre's template and theme styles
The maplibre_style slot gains two values that name no style document:
trek:template, which has MapLibre draw the user's map template the way
Leaflet does, and trek:ofm-auto, OpenFreeMap Liberty in the light theme
and OpenFreeMap Dark in the dark one. No stored row holds either, so no
saved setting changes its meaning, and a client that predates them reads
them as a foreign style and draws the default.

mapConnectHostAllows reads a host-source entry the way the browser reads
the policy (a wildcard never covers its apex, no port means the default
one), so the client can ask whether a GL map may fetch a tile before it
tries.
2026-11-30 16:22:52 +01:00
Maurice 06cd140bd3 chore(maps): keep the new map types local and lower the knip baseline
BasemapSpec and EffectiveMapEngine are only named inside their own
modules so far, so they stay unexported until a caller needs the name.
The basemap spec reads the Tours raster zoom limits from mapDefaults, so
one export there is no longer unused; the knip baseline follows.
2026-11-30 16:22:52 +01:00
Maurice 33f6540ec3 feat(settings): keep the account's settings for a start without a connection
/api/settings is never cached, so an app started offline ran on
DEFAULT_SETTINGS until the server answered: Leaflet instead of the map
the user chose, and the default units. The answer the server gave last
time now stands in until the next one arrives.

- Dexie v18 adds accountSettings, one row in the signed-in user's own
  database, so another account on the device never reads it and logout
  deletes it with the database. The anonymous database never holds one.
  A new table only; the upgrade test covers it.
- loadSettings lays the kept answer over the defaults while nothing newer
  arrived and keeps every server answer. A key the server then leaves out
  goes back to its default, so the server stays the source of truth.
- A setting the server accepted is laid over the kept answer, so a change
  made online is what the next offline start shows. A refused save keeps
  nothing.

Keeping is best effort: where IndexedDB is refused the app starts on the
defaults as before.
2026-11-30 16:22:51 +01:00
Maurice 9cbbbdb2e9 refactor(maps): one hook decides which engine draws a map
MapViewAuto chose the renderer and the offline fallback inline, so the
journey map, which needs the same choice, could only copy it.
useEffectiveMapEngine now holds it: the user's provider where it can run
(Mapbox needs a token, both GL engines WebGL2), Leaflet where it cannot,
and offline the stored basemap with its pill, checked on the engine that
actually draws. It returns what to draw and never writes a setting.

The logic is the one MapViewAuto ran, moved and not changed, and the hook
is tested on the same cases as the trip map's offline suite. The header
comment no longer claims the Atlas uses Leaflet.
2026-11-30 16:22:51 +01:00
Maurice 6dafbc6d05 refactor(maps): build every GL map from one set of options
The trip map, the journey map and the settings preview each assembled
their own constructor options and their own 3D setup on load, and the
copies had drifted: the preview laid terrain under every style outside
the Standard family, while the trip map only under the satellite and
outdoor styles, so the preview showed a map the trip never drew.

glMapOptions builds the options for all three and applyGl3d sets up
terrain, buildings and the flattened Standard DEM. For Mapbox the options
are exactly the ones each map built before, key for key and in the same
order, which a test pins; the preview now follows the trip map's terrain
rule. The next steps tune MapLibre in this one place.

MapViewGL.tsx shrinks, and its size baseline follows.
2026-11-30 16:22:51 +01:00
Maurice 0a72ed5e76 feat(maps): describe the basemap once for every renderer
The Leaflet map read the resolved template and sniffed it again for the
datum and the credit, and a GL raster source would need the same template
with its placeholders decided. resolveBasemapSpec wraps resolveBasemap and
adds what a renderer needs: the template Leaflet takes as before, the tile
URLs a GL source takes ({s} as Leaflet's a/b/c shards, {r} as @2x on any
screen denser than one, {-y} as a TMS scheme), the tile size, the
provider's deepest zoom, the credit, the datum and the host.

The Leaflet map draws from the spec now, with the same template, credit
and datum as before, so nothing on screen changes. The tests cover every
template a user can have saved today.
2026-11-30 16:22:51 +01:00
Maurice d8a93af2f5 feat(maps): one shared list of the shipped tile hosts for the CSP and the client
A GL map fetches its style and its tiles, so it can only draw from a host
the server's connect-src names. The raster presets and OpenFreeMap were
written out in the middleware while the client kept its own idea of them,
and nothing held the two together.

The hosts, their reasons and the default OpenFreeMap style now live in
shared/src/maps/map-defaults.ts. The middleware builds those sources from
the list, and the client takes the default style from it, so the renderer
choice the next steps add reads the same hosts the policy allows.

The policy an install sends stays byte for byte the same: a test pins the
whole connect-src in its order.
2026-11-30 16:22:50 +01:00
Maurice b27b3f6563 docs(maps): classify MAP_EXTRA_CONNECT_HOSTS and separate its wiki section
The app-config README lists every variable as boot-stable or runtime-toggled;
the new one was missing. The CSP takes it when the app is built, so it is
boot-stable. The wiki section also lacked the rule that separates it from
Storage & Paths like every other section.
2026-11-30 16:22:50 +01:00
Maurice fdfc034a68 fix(settings): a managed install keeps a map provider somebody chose
With the operator's Mapbox token a managed install replaced every empty or
Leaflet provider with Mapbox, including a Leaflet the user picked and a
Leaflet default the admin set. A plain "only when empty" would switch
everyone whose Leaflet row only exists because the settings form writes
every field (#1634), so the choice is recorded instead, by the server alone:

- map_provider_chosen on the user's settings, set when a write changes the
  provider the user is shown (so saving the form unchanged is no choice,
  and leaving the Mapbox a managed install shows is one). A client patch
  naming the key is dropped on both routes, false included, so no client
  can set or clear it.
- map_provider_default_chosen in app_settings, set when the admin saves a
  map_provider default and removed when it is reset.

Mapbox now replaces an empty provider, or a Leaflet without the mark of
where it came from. No stored row is rewritten: rows without a mark read
exactly as before. The client Settings type gains the read-only field.
2026-11-30 16:22:50 +01:00
Maurice 51dc0e6a82 feat(maps): MAP_EXTRA_CONNECT_HOSTS adds the operator's map hosts to the CSP
A GL map fetches its tiles and its style, so a template on a host of the
operator's own (a self-hosted tile server) was refused by connect-src while
Leaflet drew it as images. The new variable lists such hosts; each entry
becomes an https source in connect-src and the same list reaches the client
as map_extra_connect_hosts in the app config, so the renderer choice and the
policy can never disagree.

The variable is owned by readEnv() like the rest of the maps namespace and
read once when the middleware is applied. The boot refuses an entry outside
the shared grammar; a path that skips the boot check drops it, so a bad
value never widens the policy. Unset, the CSP and the app config are as
before apart from an empty list.

Documented in .env.example, docker-compose.yml, the Helm values and
ConfigMap and the wiki. Making room for the app config field shrinks
auth.service.ts by one line, and its size baseline follows.
2026-11-30 16:22:50 +01:00
Maurice 6c68f6ebec feat(shared): host grammar for the operator's own map hosts
MAP_EXTRA_CONNECT_HOSTS lets an operator name tile and style hosts beyond
the ones TREK ships. The server adds them to the CSP connect-src and the
client will only ask a GL renderer to draw what that list names, so both
sides read entries through one grammar: a lower-case host name with at
least two labels, an optional port and an optional leading wildcard over
two or more labels. No scheme, path or user, so an entry can never widen
the policy past a single host family.

The parser returns the accepted hosts and the refused entries, for the
boot check, and the app config field gets a Zod contract.
2026-11-30 16:22:50 +01:00
Maurice dbf808362d ci(sonar): analyse the server tests in the server's own TypeScript program
The scan ran out of memory since the places work: the analyser keeps every
file it parsed until the end, finds only files named tsconfig.json, and
server/tsconfig.json leaves out tests/, so the server tests landed in a
catch-all program that parsed server/src and shared/src a second time,
about 9,400 files and some 2 GB. Naming the tsconfigs, with the server's
tsconfig.tests.json in place of tsconfig.json, keeps them in the program
that already parsed those files. No file leaves the analysis.
2026-11-30 14:04:47 +01:00
Maurice dc645b1205 fix(places): All saved acts on every copy of the place a row stands for
All saved shows a place kept in several lists once, but deleting that row
removed only the copy shown, so the next copy took its place, and the
status filter and counts read only that copy. The filters now look at
every copy before the places are shown once, the counts count a place
under each status its copies hold, and deleting or setting the status of
the row reaches every copy.
2026-11-30 13:28:01 +01:00
Maurice 73e3ac2606 fix(places): the closed-day tests parse, and the inspector keeps its size
A test title held an unescaped apostrophe, so the file did not parse. The
inspector maps a provider's week through one helper again, which keeps it
at its size baseline, and the counts type of the rail stays inside its file.
2026-11-30 13:28:00 +01:00
Maurice f15b9e73a0 fix(dashboard): the more-countries chip on the passport card is solid
The +N chip after the visited countries' flags sat on the last flag with a
see-through white, so that flag showed through it. It is now the same tone,
solid.
2026-11-30 13:21:03 +01:00
Maurice 7f2c6638a8 fix(places): a closed day from OSM reads closed, not off
OSM tags a closed day as off ("Mo off"), which the tag parser hands on
as "Monday: off", and the place view showed that word as the day's hours
and as today's line. A day the provider wrote as off or closed now reads
in the reader's own word for closed, in the place view and in the details
column of the place dialog.
2026-11-30 13:18:00 +01:00
Maurice 07d54d6f6e fix(maps): a place's marker photo is its community picture where it has one
An OSM or index place with a reviewed TREK Community picture showed it in
its gallery but only a category pin in the lists and on the map: the
marker photo asked Google and Wikimedia, never the community's pictures.
It now asks them first, the order the gallery shows them in, and only
while the TREK Places API is on.
2026-11-30 13:14:23 +01:00
Maurice 51c45d0573 feat(places): the picker shows how many places All places holds from the start
The count beside All places in the place dialog's picker appeared only
once All places was chosen and read. It is now read with the picker,
with one entry, the way the rail reads it.
2026-11-30 13:10:34 +01:00
Maurice 91bf941e4c fix(places): the picker's All lists and All places count places alike
All lists in the place dialog's picker now shows a place kept in several
lists once, as All saved does, and All places keeps the places of the
trip being planned, so it always holds at least what All lists holds and
its count matches the rail.
2026-11-30 13:09:02 +01:00
Maurice 2204e851fa feat(places): All saved shows each place once, All places shows its count
A place saved into several lists from the same trip place showed once per
list in All saved and counted that often, while All places groups the
copies as one place. All saved now shows such a place once, the first
copy read standing for it, and the rail counts All saved and All places
the way All places groups them, on the desktop and the phone.
2026-11-30 13:09:01 +01:00
Maurice b36b83a32e test(places): the saved place forms send no tags or notes
The desktop dialog and the phone sheet tests still expected label_ids and
notes in the edit form's patch, which the form no longer sends: the tags
card and the notes tab write those.
2026-11-30 13:09:01 +01:00
Maurice 101c4b5d7a feat(places): All places in the saved-place picker of the place dialog
The picker beside the add place form only offered the places of the
lists. Its list filter now also offers All places: the places of the
other trips beside the lists', each place once, read when chosen, with
the same search, status filter and distance order. The trip being
planned stays out, it has those places already. A pick fills the form
with the place's name, address, position and category.
2026-11-30 13:01:20 +01:00
Maurice e90380e2b4 fix(places): votes copied with a place keep when they were last changed
Saving a trip place into a list and copying a saved place into a trip
carried the votes with no change time, so each copy read as cast now and
could outrank a newer vote on another copy of the same place, moving the
entry's own vote, average, filter and sort. Both copies now carry the
source vote's time, as the vote carry-over already does.
2026-11-30 12:55:07 +01:00
Maurice 09ae971cc8 fix(places): an edit left open does not follow onto the next place
In All places the edit state outlived the place it was opened on, so on
the phone a draft started on one place and left open was saved onto the
next place the sheet showed. The form now closes when another place
opens.
2026-11-30 12:55:06 +01:00
Maurice 1435076cec fix(places): a saved place's edit form no longer undoes its tags and notes
The tags card and the notes tab write a list copy's labels and notes
directly, but the edit form still sent the label_ids and notes it was
seeded with when the place opened, so saving a name change laid the old
tags and note back over them. The form now sends only the fields it shows.
2026-11-30 12:55:06 +01:00
Maurice 501e4449ef refactor(places): one label for a rating badge
The list rows and the map pins wrote the average with their own copy of
the whole star or one decimal rule; both now read ratingBadge.
2026-11-30 12:34:50 +01:00
Maurice 7008427022 refactor(places): drop the unused note chooser from the origin notes
The composer opens the first writable trip or list and its chips switch it,
so the old "+ Note" toggle and its chooser state are read by no view.
2026-11-30 12:34:47 +01:00
Maurice 1997a49e3d chore(places): export only what other files use
The media targets, the rating label, the rating score constants, the rating
match and the copy editor types are read inside their own files only, which
lint:knip holds.
2026-11-30 00:33:35 +00:00
Maurice 8057688da3 fix(places): say why registering the join listeners writes nothing itself
onModuleInit only hands the list and trip joins their listener; each join
then carries the joiner's votes in a transaction of its own, which
lint:tx reads from the @txIndependent note.
2026-11-30 00:24:37 +00:00
Maurice 29ae0de1ef fix(places): the third CI run, no awaits in loops and an edit target that may be none
The rating order test pages through its cursor with a recursion and checks
the refused floors at once instead of awaiting in a loop, and the edit hook
types its first editable copy as possibly none, which the strict check reads
from a conditional rather than a narrowed assignment.
2026-11-30 00:16:23 +00:00
Maurice 1c9ac0b159 fix(places): the second CI run, split the library reads and test the rating order
The reads of what an entry of All places keeps beside its facts (tags,
notes, votes, planned days, bookings, list roles) move from
PlacesLibraryRepository into PlacesLibraryDetailsRepository, so neither
file passes the size limit. New end to end tests cover the rating filter,
the tab counts under it, the rating order and its cursor, and
list_all_places with both. The test types follow the vote shapes, the edit
target says it may be null, the bookings pair names the booking card that
now holds the booking model, and the size baselines drop to the measured
lengths.
2026-11-30 00:06:47 +00:00
Maurice 7104fa6dd4 fix(places): the first CI run on the place view and the copies in step
Imports the picture icon the media sections draw for "use as the place
picture", narrows the types the type check refused, moves the dropdown
open state and the media lightbox into one module each for both views,
replaces an await in a loop, and lowers the ratchet baselines to the counts
the run measured. The tests follow the place view: the vote route of a trip
place lives with the votes now, the history holds an entry per copy that
followed an edit, the rate_library_place tool has its broadcast case, and
the row tags of a list are dots behind the name.
2026-11-29 23:53:36 +00:00
Maurice 71392ec9c1 docs(mcp): copies in step, the rating filter and the voters of an entry
The place and saved place update tools say that the general facts follow
onto the other copies, list_all_places names min_rating, the rating sort
and the voters, and the tool count is current.
2026-11-29 23:36:43 +00:00
Maurice d6708f6ff2 feat(i18n): translate the new Places strings and drop the unused ones
The media, notes and tag strings of the place view and the rating sort in
every language; the strings nothing reads any more leave every locale.
2026-11-29 23:36:43 +00:00
Maurice 20e3d2d9ae test(places): cover the place view, the rating row and the rating filter
Tests for the vote by entry key in the api and the repository, the rating
row and its voters, the rating filter and sort on both views, the edit form
without a choice of copy, and the place view's sections, aligned with the
renamed tag strings.
2026-11-29 23:36:43 +00:00
Maurice d758f4c592 feat(places): one place view for All places and the lists
The desktop dialog and the phone sheet of a place show its overview, notes,
tours and bookings, photos and files and its history in tabs, with the tags
of each list and trip, a markdown notes editor, uploads and the place
picture. The rating bar of All places is the rating row the lists show,
with its voters, and votes once for every copy. All places filters by a
lowest rating and sorts by it, and the edit form changes the first copy the
reader may edit, which the server carries to the others.
2026-11-29 23:36:43 +00:00
Maurice 783c98f41e feat(places): one vote per person across copies, copies stay in step
A vote belongs to its person: cast or taken back on one copy of a place, it
lands on every copy of that place in the lists and trips the person may vote
on, in one transaction. A pass on the first start carries the existing votes
over, and whoever joins a list or a trip brings their latest vote onto its
copies of the places they voted on elsewhere, as inserts that never
overwrite.

An edit of the general facts of a place (name, description, address,
position, category, picture, website, phone) on a trip place or a saved
place is made on every other copy of it the editor may edit, with a history
entry per copy and an announcement per trip and list. Notes, tags, status
and votes stay with each copy, and a copy the editor may not edit is
skipped. REST and MCP take the same path; a token reaches only the kinds of
copies it holds write scope for.

The entry rating names its voters, the library list filters by a lowest
average vote and sorts by rating, and the tab counts honour the filter.
2026-11-29 23:36:43 +00:00
Maurice c24c724861 feat(places): contracts for the one vote per person and the rating filter
The entry rating of All places names its voters (user_id, username,
avatar_url, rating), the people the average counts. The library query takes
min_rating (1 to 5) and the sort rating, the vote by entry key has its
request and response schemas, and the personal place tags give way to the
tags of the lists and trips a place is in.
2026-11-29 23:36:42 +00:00
Maurice 2653f0cb07 docs(mcp): list the place history, activity and tag tools 2026-11-29 21:16:51 +01:00
Maurice c944ef6de5 test(places): cover the place sheet sections, tags, trip lists and the visited filter 2026-11-29 21:16:51 +01:00
Maurice d008331e5f feat(places): notes, visits, tours, history, tags and location in the place sheet, saved lists on the trip map
Both the desktop sheet and the phone sheet of All places show the place's
location as a badge, its notes per list, its visits from trips (hidden without
any), linked tours and bookings, its change history and the reader's own tags
with a tag filter. A trip map can show the places of linked lists and add one
to the trip. All places reloads after a list is added or removed.
2026-11-29 21:16:51 +01:00
Maurice 9abd16b907 feat(i18n): the new Places strings in every language 2026-11-29 21:16:51 +01:00
Maurice 382ba79584 feat(places): visits read from trips, change history, linked tours and bookings, personal tags
A visit is a place planned on a day of one of the reader's trips; nothing is kept
or confirmed by hand. A place keeps a log of changes to its details, links the
tours and bookings it is about, and carries tags private to the reader, which a
copy into a trip takes along only when picked. Contracts, routes, MCP tools and
migrations for both engines.
2026-11-29 21:16:50 +01:00
Maurice ab7468f028 fix(ci): the file error helper no longer shadows the modal's own errorText
The new switch over the file errors took the name of the component's local errorText, so the local constant was read before its declaration (TS2448, the import tests and an unused-var warning). It is fileErrorText now.
2026-11-29 18:39:54 +01:00
Maurice b1c7bd0a33 fix(ci): the file import's words resolve through t, the unused key count drops
The KML skip reasons and the file errors were looked up from plain maps, which lint:i18n-keys cannot follow, so the new map keys counted as unused. Both are switches over t() now; the older file error keys are reached as well, so collection.ts holds 29 unused keys instead of 35.
2026-11-29 18:29:37 +01:00
Maurice 2b0ef098fd fix(ci): one save-to-list mapping for both All places views
lint:dup found the trip place to save dialog mapping copied in the desktop and phone views of All places; it is now saveDraftOf in libraryPairs, with a test.
2026-11-29 18:16:27 +01:00
Maurice 587f5f6bb6 fix(ci): drop the stale theme exception and format the filter bar
AddPlaceToCollectionModal no longer holds its theme-lint-disable line, so its entry in theme-disable-baseline.json goes; LibraryFilterBar is formatted after its import moved to the component status model.
2026-11-29 18:06:28 +01:00
Maurice 026d593c8d fix(ci): layering and theme counts after the places changes
- LibraryFilterBar reads the list statuses from the component-level
  collectionStatus model instead of reaching into pages/.
- The phone filter kit moved out of MCollections with its raw text sizes; it
  now uses the type tiers (control, caption), so the user's text size applies.
- The cover of a place of All places on the phone keeps its scrim, close button
  and name colours in a small stylesheet, as the desktop sheet does.
- theme-baseline: ratingBadge back to the two corner-badge literals it holds,
  MapView, MapViewGL and MCollections lowered to what they hold now.
2026-11-29 16:48:45 +01:00
Maurice f99c7f5421 fix(ci): the second round of gates after the places changes
- index.css stays at its size: the map canvas colour moves to its own
  stylesheet.
- The rating badge on map markers takes its amber and white from a class in
  ratingBadge.css instead of inline literals; the theme entry drops with it.
- Strict mode: the identity a link joins is resolved without a widened union,
  the description of an entry's origins is string or undefined, and the map
  search rows are typed.
- knip: PLACE_NAME_ATTR is module private, the linked-by enum names the values
  the service writes, and the unlink contract is its own described schema
  rather than a second name for the use schema.
- The duplicates hook test reads toasts through a module mock instead of the
  window hook; react-hooks/refs is lowered to the count the run measured.
- Tests follow the rename to Places and the list icon on an edit.
2026-11-29 16:38:53 +01:00
Maurice bacc6a29a7 feat(places): review possible duplicates, and repair the client gates
All places offers the pairs that look like one place: both sides side by side
with what differs marked, "keep this one" to group them as one place of the
user's own (undo right after), and "not the same place" to set a pair aside for
good. Desktop dialog and phone sheet share usePlaceDuplicates; every locale has
the new strings.

What the last dev run flagged on the client:
- Tailwind's Prettier plugin had trimmed the leading space of conditional class
  names (col-filter-btn, col-lrow sel, col-split map-full, col-detail docked),
  so the filter row and the open row lost their styling; those classes are now
  joined so the formatter cannot glue them.
- The dock position lives in one helper for the lists and All places, which
  moves the measured-position markers there instead of adding new ones.
- usePlacesLibrary is split into filters, pages, detail and cover hooks that
  derive their loading state instead of setting it inside effects; the big
  sheets and views are cut into parts under the complexity limit, dynamic icons
  go through createElement, originName moves out of a component file.
- formatRange is guarded like in the packing export, the cover lookup skips
  places without a position.
- Tests follow the rename to Places, the category icon, the default list icon
  and the new trip collections store; react-hooks/refs is lowered to the count
  the run measured.
- The rating on a place is a round badge again, in the list and on the map.
2026-11-29 16:28:22 +01:00
Maurice 62232ec87e fix(places): undo, unlink and dismissals that hold after a key or access change
Review findings on the place identities and trip list links:

- The assistant offers PlacesLibraryMcp, PlaceIdentitiesMcp and
  TripCollectionsMcp with the collections group (done with the CI fix).
- Undoing a merge restores the entries as they were: the merge logs, in its
  moved_link_ids JSON, each link it moved and each link it made with the use
  that link names, and whether the merged side became an own place only for
  the merge. The undo deletes what the merge made and moves the rest back,
  and only touches a link still in the leading place naming the same use, so
  a link id SQLite hands out again never moves someone else's link. The
  sweep counts a merge as spent by the same rule. Same unreleased migration,
  no schema change.
- A use can be taken out of an own place by the user's own link row also
  once its trip or list is out of reach; the answer then holds no entry, and
  the place left can be merged again.
- A dismissed duplicate is kept by one use of each side (an own place by its
  first link) and matched by the uses each entry holds, so it stays out when
  an entry becomes an own place or a merge is undone.
- link() checks the named uses with one targeted read instead of reading
  every use of the user, and the library reads its rows in blocks of 500 ids.
- Saved place reorders and the trip tags of a copy run one statement after
  the other again; a copy takes the first spelling of a tag name, as before.
- Unlinking a list from a trip takes place_edit alone, so a link to a list
  the writer cannot open can be taken off; a member leaving or taken off the
  trip takes the links whose list nobody left on it can open.
- The linked lists and their map places sort by lower(name), then by id, the
  same on both engines.
- list_all_places names the own:<id> keys and identity_id (MCP and wiki); the
  undo, unlink and trip unlink descriptions say what they do now; README
  counts 451 tools.
2026-11-29 16:27:12 +01:00
Maurice 7a06db393f fix(ci): repair server and shared gates after the place identities change
Push run 46275645144 on dev (f69a4c1a2) was red in these jobs:

- Server types: UserPlacesRepository.create, UserPlaceMergesRepository.create
  and UserPlaceLinksRepository.insert shadowed MikroORM's EntityRepository
  methods with other signatures (TS2416), which also broke defineEntity on the
  three entities (TS2769). They are createOwn, record and insertUses now.
- Server lint: collections.service.ts had grown to 1411 lines against 1410.
  The trip tag lookup of a copy moved into collections.helpers.ts
  (tripTagIdsOf, tagKeyOf); the size baseline is lowered to the 1398 it holds.
- ASTCAP-001/002/005b: the trip chat core had taken in PlacesLibraryMcp,
  PlaceIdentitiesMcp and TripCollectionsMcp, so core and the tours group
  offered 132 tools against 128. They load with the collections group now.
- PLIB-001, PLIB-MCP-001 and the places library e2e: the two entries named
  Museum tie on the name and go by their anchor, which the expected order
  hard coded the other way. The fixture orders every tie by its anchors.
- ENT-003 and CLASSFIELD-002: the five new entities and their 18 NOT NULL
  columns without a default are counted.
- Shared tests: collections.ratingBadge was missing in 26 locales; each has
  its translation now.
2026-11-29 16:14:42 +01:00
Maurice f69a4c1a24 feat(places): own place identities, duplicate merging and lists linked to a trip
- A user can group the uses of one place (trip places and saved places) into a
  place identity of their own (user_places, user_place_links). It is personal:
  it groups their "All places" and is never written into a shared trip or list
  row. An identity without a use they can still reach is not shown, and one
  left without links is pruned on their next write and nightly.
- Possible duplicates are suggested server side (same provider id, or the same
  name at the same spot), each pair with what differs and whether the user may
  merge it. A merge joins two identities in one transaction and can be undone;
  a dismissed pair does not come back. No trip or list row is deleted or changed.
- A trip can link lists (trip_collection_links, needs place_edit and access to
  the list). A member sees a linked list only with their own access to it; the
  map layer lists its places and whether each is already in the trip.
  tripCollections:changed tells the members to read their view again.
- REST, MCP tools and client data layer for all of it; migrations on both
  engines, additive only.
- CI: the stage 1 to 2 places-library helper types, and the await-in-loop and
  non-null counts it had raised.
2026-11-29 15:57:05 +01:00
Maurice 01d327b502 feat(places): Places replaces Collections, with All places, place sheets and a calmer list
- Collections is Places now: /places opens "All places", every place of the
  trips and lists with where it comes from, the same filter row (where from,
  status, category, order), map bar (search, lock, list toggle) and place sheet
  as a list; /places/saved and /places/:id are the lists, and the old
  /collections links still land there. On the phone the same, with its own
  sheet. A place sheet shows each trip (planned day or trip dates, stay,
  booking, notes) and each list (status, labels, rating, notes) as one row
  that opens it.
- The rail: a calm "New list" with its plus tile, All places and All saved as
  views, a "My lists" heading, every name on one edge. Lists can carry one of
  24 symbols, shown in their colour in the rail and the editor.
- A saved place's row keeps to two lines: its category as an icon before the
  name, its average vote as a star on the picture. Map pins wear the same star.
- The place forms put the category in front of the name as a tile that opens
  the category list, instead of a row of chips.
- All saved gets a subtitle; the import dialog opens centred.
- Fixes: a pasted coordinate pair splits from either field of the place form;
  "more" in All places frees itself when a filter changes mid-load; place
  names on the trip map and the rating badge follow the reading direction.
2026-11-29 15:49:35 +01:00
Maurice 0ecca2b46c feat(places): read every place of the trips and lists in one view
A read-only overview of every place a user can reach: the saved places of
their lists and the places of their trips, viewer trips included, with tours,
tracks and the stops of a drive left out. A saved place and a trip place are
one entry only when the saved place came from that trip place, the trip is
still open to the user, and both agree (a provider id, or the same name at the
same spot); anything else stays apart. Every entry names where it comes from
and whether it may be changed there.

- GET /api/addons/collections/library/places: paged by cursor, search,
  category, kind, list, trip and status filters, counts per kind.
- GET /api/addons/collections/library/places/{trip|list}/🆔 one entry with
  what each origin keeps on its own (notes after the existing rights, labels,
  ratings, a trip's planned days, whether a stay or booking uses it).
- MCP tools list_all_places and get_library_place.

Nothing is written and nothing migrates; the rights are the existing list and
trip checks, read on every call.
2026-11-29 14:57:10 +01:00
Maurice 82165855c7 feat(collections): own order, KML/KMZ import, copy options, position search, place names on the trip map
- A list keeps its own order: drag a place by its grip (desktop and phone) or
  move it with the arrow keys. Reordering is off while a search or filter hides
  places and the list says why. New PUT /collections/:id/places/reorder and the
  MCP tool reorder_collection_places; new places go to the end. Client and
  server now order ties the same way (sort_order, oldest first, id).
- Copying saved places into a trip no longer takes their notes and tags along
  unasked. The picker offers both; a tag taken along becomes a trip tag (a trip
  tag of the same name is reused), never someone's personal tag.
- The source trip and place a saved place names are only kept when the user can
  open that trip and the place belongs to it.
- A KML or KMZ map can be read into a list: the dialog lists every placemark to
  keep or leave out and says which entries were skipped and why
  (POST /collections/map/read writes nothing; the import does).
- A saved place without coordinates says so and can be looked up on the map
  from its edit form, on the phone too, where a missing position could not be
  added at all. A typed address without a pick says it will not be on the map.
- The trip map can show the place names beside the pins (desktop and phone,
  both renderers). Names that would cover another pin or a control give way,
  the selected place and the planned stops first.
2026-11-29 14:57:00 +01:00
Maurice 177a0febe2 test(db): the Postgres engine migrates in a context of its own
SonarCloud counted the two new lines in PostgresEngine.schemaBootstrap as uncovered: the Postgres lane runs them but does not feed the coverage it reads. PGENGINE-BOOT-001/002 run the bootstrap against a stand-in ORM whose first statement records the request context it runs in, on its own and inside a caller's request.
2026-11-29 13:02:32 +01:00
Maurice 80853fcf03 fix(ci): the Postgres engine forks its context without reaching into nest
Server lint: src/db may not import src/nest, so the Postgres engine opens the request context with RequestContext.create itself, as demo-reset and the backup restore already do. Server types: the base EntityManager has no execute(); RESTORE-002 reads through the connection.
2026-11-29 12:31:02 +01:00
Maurice 67049c1065 fix(backup): a restore that migrates no longer breaks the request it runs in
Restoring a backup whose database was behind the running version migrated it inside the admin's HTTP request. A MikroORM migration's getEntityManager() pins the migration's transaction on the EntityManager of the context it runs in, which was the request's. Once the migrations committed, every later read on that request failed with "Transaction is already committed": the storage registry reload kept the pre-restore config (uploads, including the archive's own, went to the old backend), and the restore's audit row was lost.

Both engines now run their migrations in a request context of their own (runSchemaBootstrap on SQLite, bootstrapPostgresSchema on Postgres), so the transaction stays on a throwaway EntityManager, at boot and on restore alike. RESTORE-002 restores a file six migrations behind head inside a request and reads on through that request's EntityManager.

Closes #3264
2026-11-29 12:00:08 +01:00
Maurice f89ebf6882 feat(atlas): unvisited regions of a visited country almost clear when zoomed in
Zoomed in, a country with visited regions kept about a fifth of its colour under its other regions. It now keeps about a twentieth, as in the regions view, so only the regions really visited carry the country's colour.
2026-11-29 11:54:41 +01:00
Maurice 14443a17be feat(atlas): a regions view, and visited regions that stand out
A traveller who visited only Alberta saw all of Canada colored on the zoomed-out globe. A new layer switch, Regions instead of countries, keeps the coarse regions of every country with a visited region on screen at every zoom: the engine loads and holds them (setPinnedRegions), the renderer draws them at full strength with faint inner borders, and the country itself only tints faintly beneath them once they are drawn. The switch is remembered per device, on the desktop layers dialog and the phone sheet, in all 28 languages.

Also without the switch, a country with visited regions now steps far back once its regions fade in (to about a fifth instead of two thirds), so the regions really visited stand out from the rest of the country.
2026-11-29 11:53:46 +01:00
Maurice 00675c59b0 fix(ci): decouple realtime presence and test Atlas fill indices
Bind the realtime activity port to the existing SessionsService at app startup to remove the domain import cycle. Check the Atlas mesh through its triangle indices because degenerate rings can leave vertices that never contribute to the fill.
2026-11-29 11:06:16 +01:00
Maurice 96976d3ece test(atlas): settle the first CI round of the new Atlas tests
Client types: Array.at is past the lib target, typed mocks where a spy is called. Client lint: mock components named so hooks may run in them, state reported from effects instead of written into props, promises voided or awaited. Client tests: class order as passed, month names checked in Japanese whatever the ICU build, mesh vertex counts asserted by shape, the buffer growth case built from many small squares instead of one strip that took 15 s, the shooting star tests driving the sky's own schedule, and reduced motion mocked once so it no longer silences later tests. Server: the hidden-setting cases as it.each (no-await-in-loop), and the presence branches the realtime 100% threshold asks for.
2026-11-29 10:42:20 +01:00
Maurice ab0e6fda8b fix(atlas): give back every GPU object when the globe goes
dispose() freed the world and region layers only; the ocean, arcs, outline, pick texture and framebuffer, status textures, shared buffers and programs stayed on the context, which React keeps alive across a remount, so each visit to the Atlas left them behind.
2026-11-29 10:42:19 +01:00
Maurice 9018ee8980 test(atlas): cover the new Atlas from engine to hub views
SonarCloud measured 16.9% coverage on this PR's new code. Tests now cover the WebGL globe engine (boot, caching, input, camera, regions, prefetch) and renderer (against a fake WebGL2 context that reads the real shaders), the paint, labels, sky and pins, the central useAtlasGlobe hook and the hub hooks, the snapshot, account queue and Atlas repos, every desktop and phone hub view, the server's people, flights and mesh routes, the shared badge rules, and the new view transition, warm bags and kept planner maps.
2026-11-29 10:21:28 +01:00
Maurice 10ad92574d fix(ci): presence through the sessions domain, warm bags taken once, a slimmer planner page
Server lint: the realtime gateway injected the user_sessions repository, a table the sessions domain owns; it now asks SessionsService. The presence tests reuse the handshake's gateway instead of building one more by hand (test-new-service ratchet).

Client tests: the packing bags kept per trip leaked from one test (and one list) into the next; bags read ahead are now taken once as the list's first state, and only while bag tracking is on. The planner hook hands the page planMapKept, tourMapKept and the tour stage's class, so page tests that mock the hook keep working and TripPlannerPage is back at its size baseline (1127); the B4A wiring test reads the new condition.

Client lint: max-depth in src is down to 19, the baseline follows; the new websocket tests call onopen with ?. instead of a non-null assertion.
2026-11-29 10:13:53 +01:00
Maurice 5401728c41 feat(admin): online means a tab in front, and keeps last activity current
Online in the user list meant any open socket, so a tab left in the background showed as online for days while its last activity stood still. The client now sends a presence frame on connect and on every visibility change; only sockets whose tab is visible count as online (one that never sent the frame still counts, so older clients are unchanged). While a tab is in front, the gateway writes its session's last_seen_at at most every five minutes, on the frame and on the heartbeat, so last activity follows the online state.
2026-11-29 10:04:15 +01:00
Maurice 467287f138 perf(planner): tabs that open ready instead of building in front of the user
Two seconds after a trip opens, the code of every tab panel loads in the background, and the packing list's bags with it, which are kept per trip so Lists opens with its bag sidebar in place. The plan and tour planner maps stay mounted (hidden) once opened, so switching between them no longer starts a map again and flickers. Not on a narrow screen, where the plan tab portals its own controls over the page.
2026-11-29 10:04:15 +01:00
Maurice 64697fdb7f perf(vacay): read the calendar in parallel and keep it on screen
loadAll ran eight requests one after another, and the holidays fetched each calendar and year in turn, behind a full spinner on every visit. Plan and year settings now load together, then the years, then everything for the year at once; the holiday calendars are asked in parallel and laid out in the calendars' order. The spinner shows only for the first load; coming back keeps the calendar and refreshes it.
2026-11-29 10:04:14 +01:00
Maurice 7e3ce20e6b feat(client): calm page changes on the desktop and sections loaded ahead
The desktop now runs the View Transition the phone already had: one short cross-fade under a navbar that stands still. The route fallback holds the previous page until the new one is ready (at most 350 ms), so the full-screen spinner no longer flashes. Once signed in, the main sections' code loads in the background, so the first switch to one does not wait for it. The shared transition helpers move to utils/viewTransition.ts. The navbar tabs lose their title tooltips; their aria-label stays.
2026-11-29 10:04:14 +01:00
Maurice f8a7d674f9 perf(atlas): keep the globe's geometry for the next visit
Every visit read the manifest and the world file again and triangulated the countries in the worker, which showed the loading notice for about a second. The manifest and the built world meshes are now kept for the tab's lifetime, keyed by the content-hashed file name, so coming back puts the globe up at once. A page load starts empty, so a deploy's new geometry is read as before.
2026-11-29 10:04:13 +01:00
Maurice c3935ff027 fix(packing): a wider item window so the visibility choice fits
At 320 px the three options of "Visible to" ran past the window's edge and "Selected" was cut off. The window is 380 px wide now, still capped to the screen.
2026-11-29 09:41:30 +01:00
Maurice ce2b521ae7 feat(atlas): a neutral night sky and steadier globe details
- The globe, sky, glass and medals use black and neutral greys instead of
  blue tones; the atmosphere glow is a quarter of its former strength.
- No shooting stars on load: the visited set is compared only once the
  Atlas has loaded. Now and then a shooting star crosses on its own.
- The stars stand still while the Earth turns, and three constellations
  (Big Dipper, Orion, Cassiopeia) are drawn from their stars' real places,
  sized and tinted by brightness.
- Wishlist stripes are slices through the globe, so they stay on the land
  as it turns.
- Country names keep their own element while shown and hold their place
  against a near equal neighbour, so they no longer jump or flicker.
- The flat map fades into the sky towards its cut edges at the poles, and
  the view's latitude is held where those edges stay off screen.
2026-11-29 09:36:14 +01:00
Maurice 7eb2c9334b chore(knip): drop the hazard popup's unlisted entry
hazardPopup.ts typed against geojson without listing it; with
@types/geojson now a client dev dependency it is listed, so the baseline
entry goes.
2026-11-29 02:29:40 +01:00
Maurice cac5b5c501 fix(atlas): clear the knip findings of the globe Atlas
- The globe's geometry code types against geojson and
  topojson-specification; both are listed as client dev dependencies now
  (already installed through @types/topojson-client).
- Constants, helpers and types used only inside their own module lose
  their export.
- The GeoJSON types only the classic Atlas map read are removed; the knip
  baseline follows the lower counts in types.ts and offlineDb.ts.
2026-11-29 01:59:04 +01:00
Maurice a3db6e93bf fix(atlas): drop the keys the classic map left unused, tag the people reads
- lint:i18n-keys: common.reset, dawarich.bucket.visitedFrom and the two
  mobileAtlas keys were only read by the classic map and its popups; they
  go from every locale, and the atlas entry follows its lower count.
- lint:tx: AtlasPeopleService.profile also carries @txIndependent, so the
  method itself is no longer reported for its cache refresh reads.
2026-11-29 01:26:58 +01:00
Maurice e6ba039abc fix(atlas): share the wish form and tour figures, mark the people reads
- lint:dup: the add-a-wish form state and the tour figures of the hub were
  written twice, once per view; they live in useWishAddForm and
  tourHubFigures now, and both views read them.
- lint:tx: AtlasPeopleService.profile only writes through the region cache
  refreshes of the Atlas reads it calls, each complete on its own, so it is
  marked @txStandalone.
2026-11-29 00:53:28 +01:00
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
1646 changed files with 101576 additions and 17604 deletions
+15 -1
View File
@@ -28,8 +28,10 @@ updates:
groups: groups:
# Packages that release in lockstep move together, so a PR never pins # Packages that release in lockstep move together, so a PR never pins
# half of them on one version and half on the next. # 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: mikro-orm:
patterns: ['@mikro-orm/*'] patterns: ['@mikro-orm/*', better-sqlite3, kysely]
update-types: [minor, patch] update-types: [minor, patch]
nestjs: nestjs:
patterns: ['@nestjs/*'] patterns: ['@nestjs/*']
@@ -54,6 +56,18 @@ updates:
# by hand once mapbox-gl checks the built-ins first again. # by hand once mapbox-gl checks the built-ins first again.
- dependency-name: mapbox-gl - dependency-name: mapbox-gl
versions: ['>=3.33.0'] 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. # plugin-sdk is standalone with a lockfile of its own and ships to npm.
- package-ecosystem: npm - package-ecosystem: npm
+55 -1
View File
@@ -105,9 +105,63 @@ jobs:
track: ${{ inputs.track || 'internal' }} track: ${{ inputs.track || 'internal' }}
status: draft 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 - name: Remove the upload key
if: always() if: always()
run: rm -f "$RUNNER_TEMP/upload.jks" run: rm -f "$RUNNER_TEMP/upload.jks" "$RUNNER_TEMP/play-apk.json"
ios: ios:
if: github.repository == 'liketrek/TREK' 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 tests i/10 one slice of the server suite, with coverage
# Server coverage merges the slices, checks the per-domain # Server coverage merges the slices, checks the per-domain
# thresholds, uploads lcov # 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 # per supported major, in three slices: the probe
# (the repository SQL against Postgres, first slice # (the repository SQL against Postgres, first slice
# only), then a slice of the lane (every suite that # 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 # Client e2e i/2 one slice of the browser flows in Chromium and
# WebKit, in the Playwright container # WebKit, in the Playwright container
# Docker and Helm builds the image and boots it until ready, on # 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 # Helm chart and checks the compose files
# Sonar SonarCloud analysis, not required # Sonar SonarCloud analysis, not required
# ci-ok the one required check (below) # ci-ok the one required check (below)
@@ -600,7 +600,7 @@ jobs:
uses: actions/upload-artifact@v6 uses: actions/upload-artifact@v6
with: with:
name: server-blob-${{ matrix.shard }} name: server-blob-${{ matrix.shard }}
path: server/.vitest-reports/ path: server/.vitest/blob/
include-hidden-files: true include-hidden-files: true
if-no-files-found: error if-no-files-found: error
retention-days: 1 retention-days: 1
@@ -621,7 +621,7 @@ jobs:
uses: actions/download-artifact@v7 uses: actions/download-artifact@v7
with: with:
pattern: server-blob-* pattern: server-blob-*
path: server/.vitest-reports/ path: server/.vitest/blob/
merge-multiple: true merge-multiple: true
- name: Merge the slices and check the thresholds - name: Merge the slices and check the thresholds
@@ -639,7 +639,7 @@ jobs:
retention-days: 1 retention-days: 1
# TREK on Postgres, once per supported major: the oldest (14) and the newest # 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. # database of its own, the lane on databases it creates and drops.
# #
# The probe (server/scripts/pg-probe.ts): against an empty Postgres it # The probe (server/scripts/pg-probe.ts): against an empty Postgres it
@@ -696,7 +696,7 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
postgres: [14, 18] postgres: [14, 19]
shard: [1, 2, 3] shard: [1, 2, 3]
services: services:
postgres: postgres:
@@ -757,14 +757,14 @@ jobs:
if-no-files-found: ignore if-no-files-found: ignore
retention-days: 14 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. # 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: | run: |
set -euo pipefail set -euo pipefail
sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh -y >/dev/null 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 sudo apt-get install -y --no-install-recommends postgresql-client-19 >/dev/null
/usr/lib/postgresql/18/bin/pg_restore --version /usr/lib/postgresql/19/bin/pg_restore --version
- name: Run the Postgres lane - name: Run the Postgres lane
if: ${{ !cancelled() }} if: ${{ !cancelled() }}
@@ -1028,7 +1028,7 @@ jobs:
uses: actions/upload-artifact@v6 uses: actions/upload-artifact@v6
with: with:
name: client-blob-${{ matrix.shard }} name: client-blob-${{ matrix.shard }}
path: client/.vitest-reports/ path: client/.vitest/blob/
include-hidden-files: true include-hidden-files: true
if-no-files-found: error if-no-files-found: error
retention-days: 1 retention-days: 1
@@ -1049,7 +1049,7 @@ jobs:
uses: actions/download-artifact@v7 uses: actions/download-artifact@v7
with: with:
pattern: client-blob-* pattern: client-blob-*
path: client/.vitest-reports/ path: client/.vitest/blob/
merge-multiple: true merge-multiple: true
- name: Merge the slices and check the thresholds - name: Merge the slices and check the thresholds
@@ -1224,6 +1224,14 @@ jobs:
--set service.port=8080 \ --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"}}' \ --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" > "$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 - name: Check the manifests against the Kubernetes schemas
# The pinned Gateway API schema adds HTTPRoute validation without skipping unknown resources. # The pinned Gateway API schema adds HTTPRoute validation without skipping unknown resources.
@@ -1339,7 +1347,7 @@ jobs:
set -euo pipefail set -euo pipefail
docker network create trek-ci-pg docker network create trek-ci-pg
docker run -d --name trek-ci-db --network 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 for _ in $(seq 1 30); do
docker exec trek-ci-db pg_isready -U postgres -d trek >/dev/null 2>&1 && break docker exec trek-ci-db pg_isready -U postgres -d trek >/dev/null 2>&1 && break
sleep 2 sleep 2
@@ -1460,7 +1468,7 @@ jobs:
path: plugin-sdk/coverage/ path: plugin-sdk/coverage/
- name: Scan - name: Scan
uses: SonarSource/sonarqube-scan-action@59202af334b4ba7b5db01b701b8e79f8b3bef0f4 # v8.5.0 uses: SonarSource/sonarqube-scan-action@70bad232163b09d998ea0707ee80c0ec80798c16 # v8.5.1
env: env:
# SonarQube Cloud is the scan action's default host, so no # SonarQube Cloud is the scan action's default host, so no
# SONAR_HOST_URL — the token is a sonarcloud.io token for the # SONAR_HOST_URL — the token is a sonarcloud.io token for the
+5 -1
View File
@@ -55,7 +55,8 @@ coverage
coverage-*/ coverage-*/
*.lcov *.lcov
.nyc_output .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 .vitest-reports
# Cache # Cache
@@ -73,3 +74,6 @@ minio-licence.key
.run .run
.full-review .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 ## 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. - **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. - **What the folded jobs hold.** `Shared tests` is the plugin SDK's typecheck and coverage, run before the root install so the SDK resolves only its own dependencies, then i18n parity and shared's coverage. `Client types` is the typecheck and the strict ratchet; `Client checks` the source ratchets, then the production build with `check:gl-split`. `Docker and Helm` builds and boots the image when the image area changed and checks the chart and compose files when the deploy area changed. Inside a folded job each group of steps runs after a failure in another, so one red check shows every gate that failed; the step names say which.
+21 -12
View File
@@ -41,9 +41,10 @@ COPY server/package.json ./server/
RUN npm ci --workspace=server --ignore-scripts RUN npm ci --workspace=server --ignore-scripts
COPY --from=shared-builder /app/shared/dist ./shared/dist COPY --from=shared-builder /app/shared/dist ./shared/dist
COPY server/ ./server/ COPY server/ ./server/
# tsc needs more than the 2 GB heap Node picks on a host with about 12 GB of RAM; # The globe Atlas geometry is built from the committed boundary files (no network,
# on a bigger build machine the default is larger, so only small hosts failed. # deterministic) here rather than committed; it lands in server/assets with the rest.
RUN NODE_OPTIONS=--max-old-space-size=4096 npm run build --workspace=server RUN node server/scripts/build-atlas-mesh.mjs
RUN npm run build --workspace=server
# ── Stage 4: production runtime ────────────────────────────────────────────── # ── Stage 4: production runtime ──────────────────────────────────────────────
FROM node:24-trixie-slim 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 # 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). # (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 # postgresql-client-19 brings pg_dump, pg_restore and psql to
# /usr/lib/postgresql/18/bin, which back up and restore an install on Postgres # /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 # (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 # 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 # repository (PGDG): its `main` component carries every major the project
# other, and the repository's signing key (fingerprint B97B 0AFC AA1A 47F0 44F2 # supports, and the package name pins the one installed. The per-major
# 44A0 7FCC 7D46 ACCC 4CF8) is kept beside the entrypoint instead of fetched at # components can trail a new release, so the image does not rely on them. The
# build time. Raise both together when TREK supports a newer major. # 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 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 && \ > /etc/apt/sources.list.d/pgdg.list && \
apt-get update && \ apt-get update && \
apt-get upgrade -y --no-install-recommends && \ apt-get upgrade -y --no-install-recommends && \
apt-get install -y --no-install-recommends tzdata dumb-init wget ca-certificates \ 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 && \ 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; } && \ { 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 && \ rm -rf /var/lib/apt/lists/* /usr/local/lib/node_modules/npm /usr/local/bin/npm /usr/local/bin/npx && \
+2 -2
View File
@@ -156,7 +156,7 @@ Most of what follows is an addon an admin switches on or off. Lists, Costs, Docu
- **Your own model**: an API key for Anthropic, OpenAI, Gemini or OpenRouter, a ChatGPT plan, or any OpenAI-compatible endpoint, set for the instance or per user - **Your own model**: an API key for Anthropic, OpenAI, Gemini or OpenRouter, a ChatGPT plan, or any OpenAI-compatible endpoint, set for the instance or per user
- **You stay in charge**: reads run at once, every change waits as a card to apply or discard and can be undone for 15 minutes. Nothing leaves before you agree to the provider, and a file's text only with your consent - **You stay in charge**: reads run at once, every change waits as a card to apply or discard and can be undone for 15 minutes. Nothing leaves before you agree to the provider, and a file's text only with your consent
- **Attachments**: drop a booking confirmation, a GPX file or a photo into the chat, and the assistant offers what to do with it - **Attachments**: drop a booking confirmation, a GPX file or a photo into the chat, and the assistant offers what to do with it
- **MCP server** (off by default): OAuth 2.1 with mandatory PKCE and dynamic client registration, 410 tools, 30 resources and 4 prompts, 35 scopes in 17 groups ticked on the consent screen, and every call in the audit log - **MCP server** (off by default): OAuth 2.1 with mandatory PKCE and dynamic client registration, 453 tools, 30 resources and 4 prompts, 35 scopes in 17 groups ticked on the consent screen, and every call in the audit log
- **Addon-aware**: twelve addon gates decide which tools a session sees, and flipping one re-registers live sessions - **Addon-aware**: twelve addon gates decide which tools a session sees, and flipping one re-registers live sessions
</td> </td>
@@ -288,7 +288,7 @@ docker compose up -d
See [Install with Docker Compose](https://github.com/liketrek/TREK/wiki/Install-Docker-Compose) See [Install with Docker Compose](https://github.com/liketrek/TREK/wiki/Install-Docker-Compose)
for the full walkthrough. 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 [`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 [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. how to move an existing SQLite install to Postgres with the command TREK ships for it.
+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. - 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`. - `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 `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 apiVersion: v2
name: trek name: trek
version: 5.2.1 version: 5.2.2
description: Minimal Helm chart for TREK app description: Minimal Helm chart for TREK app
appVersion: "5.2.1" home: https://github.com/liketrek/TREK
sources:
- https://github.com/liketrek/TREK
appVersion: "5.2.2"
+3
View File
@@ -136,6 +136,9 @@ data:
{{- if .Values.env.AMAP_API_BASE }} {{- if .Values.env.AMAP_API_BASE }}
AMAP_API_BASE: {{ .Values.env.AMAP_API_BASE | quote }} AMAP_API_BASE: {{ .Values.env.AMAP_API_BASE | quote }}
{{- end }} {{- end }}
{{- if .Values.env.MAP_EXTRA_CONNECT_HOSTS }}
MAP_EXTRA_CONNECT_HOSTS: {{ .Values.env.MAP_EXTRA_CONNECT_HOSTS | quote }}
{{- end }}
{{- if .Values.env.VAPID_PUBLIC_KEY }} {{- if .Values.env.VAPID_PUBLIC_KEY }}
VAPID_PUBLIC_KEY: {{ .Values.env.VAPID_PUBLIC_KEY | quote }} VAPID_PUBLIC_KEY: {{ .Values.env.VAPID_PUBLIC_KEY | quote }}
{{- end }} {{- end }}
+8
View File
@@ -0,0 +1,8 @@
{{- range .Values.extraObjects }}
---
{{- if kindIs "string" . }}
{{ tpl . $ }}
{{- else }}
{{ tpl (toYaml .) $ }}
{{- end }}
{{- end }}
+29 -1
View File
@@ -170,6 +170,11 @@ env:
# Send the Amap (高德地图) calls through an egress proxy, a cache or a gateway that speaks the same API instead of # Send the Amap (高德地图) calls through an egress proxy, a cache or a gateway that speaks the same API instead of
# restapi.amap.com directly. The key itself is a credential and goes under secretEnv.AMAP_API_KEY, or into # restapi.amap.com directly. The key itself is a credential and goes under secretEnv.AMAP_API_KEY, or into
# Admin > Settings > API Keys. Defaults to https://restapi.amap.com. # Admin > Settings > API Keys. Defaults to https://restapi.amap.com.
# MAP_EXTRA_CONNECT_HOSTS: ""
# Hosts of your own map tiles or vector styles that the GL maps may load, comma-separated, e.g.
# "tiles.example.com,*.maps.example.org:8443": a host name, optionally with a port or as a wildcard over
# its subdomains; https is implied. They are added to the Content-Security-Policy and told to the app.
# An entry that is not a plain host name aborts startup.
# VAPID_PUBLIC_KEY: "" # VAPID_PUBLIC_KEY: ""
# Web Push key pair, public half (base64url, 65 bytes). Leave both halves empty and TREK generates a pair on # Web Push key pair, public half (base64url, 65 bytes). Leave both halves empty and TREK generates a pair on
# first start and keeps it in the database, so it travels with backups. To use your own pair, set this and # first start and keeps it in the database, so it travels with backups. To use your own pair, set this and
@@ -190,7 +195,7 @@ env:
# starting it on SQLite. The role in the URL owns TREK's database and must not be a superuser # 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 # (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 # 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" # url: "postgres://trek:<password>@postgres.example.internal:5432/trek?sslmode=require"
database: database:
url: "" url: ""
@@ -338,6 +343,29 @@ extraVolumes: []
# readOnly: true # readOnly: true
extraVolumeMounts: [] 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: resources:
requests: requests:
cpu: 100m cpu: 100m
+1 -1
View File
@@ -68,7 +68,7 @@ The offline core is flagship work surrounded by a periphery that ignores it. New
## Big-picture pieces ## Big-picture pieces
- **Maps** (`src/components/Map/`): two interchangeable renderers — Leaflet and Mapbox/MapLibre GL — chosen at runtime by `MapViewAuto.tsx`. Keep both in sync when changing map features, and keep `mapbox-gl` and `maplibre-gl` in separate chunks (`check:gl-split`). The raster prefetcher fetches tiles `no-cors` so custom tile providers without CORS headers keep working; the vector prefetcher deliberately uses `cors` because it has to read the responses — don't "align" one with the other. - **Maps** (`src/components/Map/`): two interchangeable renderers — Leaflet and Mapbox/MapLibre GL — chosen at runtime by `MapViewAuto.tsx`. Keep both in sync when changing map features, and keep `mapbox-gl` and `maplibre-gl` in separate chunks (`check:gl-split`). The raster prefetcher fetches tiles `no-cors` so custom tile providers without CORS headers keep working, except a template MapLibre draws (`trek:template`), whose tiles a GL map reads with CORS and the service worker keeps apart in `map-tiles-gl` (`src/sync/glTileCache.ts`); the vector prefetcher deliberately uses `cors` because it has to read the responses — don't "align" one with the other.
- **i18n** (`src/i18n/TranslationContext.tsx`): `en` is bundled; every other locale is a dynamic `import('@trek/shared/i18n/<locale>')` so Vite emits one chunk per locale. Strings live in `shared/`, never here. `t()` returns an unknown key unchanged, so `lint:i18n-keys` (`scripts/i18n-keys.mjs`) resolves every literal key in `t()`, `tHtml()`, `tr()`, `<TransHtml html>`, `translateApiError` and `*Key` props against `shared/src/i18n/en`; a template whose interpolations only choose between string literals is expanded and each branch checked as a key; any other template key is read with each interpolation as one key segment and passes by itself only when it reaches between 1 and `MAX_IMPLICIT_MATCHES` (30) en keys; a wider one, or one with no fixed dotted prefix, needs a `DYNAMIC_ALLOWED` entry keyed by file and template that says what bounds the value, and an entry the check no longer needs fails. Pass counts as numbers, and let a plural group pick the wording instead of switching keys on the count. - **i18n** (`src/i18n/TranslationContext.tsx`): `en` is bundled; every other locale is a dynamic `import('@trek/shared/i18n/<locale>')` so Vite emits one chunk per locale. Strings live in `shared/`, never here. `t()` returns an unknown key unchanged, so `lint:i18n-keys` (`scripts/i18n-keys.mjs`) resolves every literal key in `t()`, `tHtml()`, `tr()`, `<TransHtml html>`, `translateApiError` and `*Key` props against `shared/src/i18n/en`; a template whose interpolations only choose between string literals is expanded and each branch checked as a key; any other template key is read with each interpolation as one key segment and passes by itself only when it reaches between 1 and `MAX_IMPLICIT_MATCHES` (30) en keys; a wider one, or one with no fixed dotted prefix, needs a `DYNAMIC_ALLOWED` entry keyed by file and template that says what bounds the value, and an entry the check no longer needs fails. Pass counts as numbers, and let a plural group pick the wording instead of switching keys on the count.
- **Mobile shell** (`src/mobile/`): below the phone breakpoint (`useIsPhone`) `App.tsx` wraps routes in `MobileShell` and the `M*` screens under `mobile/screens/` take over. A UI change to a domain with an `M*` twin usually needs both, and the logic change goes into the shared hook (see "Desktop and phone views" below). - **Mobile shell** (`src/mobile/`): below the phone breakpoint (`useIsPhone`) `App.tsx` wraps routes in `MobileShell` and the `M*` screens under `mobile/screens/` take over. A UI change to a domain with an `M*` twin usually needs both, and the logic change goes into the shared hook (see "Desktop and phone views" below).
- **Plugins UI** (`src/components/Plugins/`): third-party surfaces render only inside the sandboxed `PluginFrame` iframe (postMessage bridge, live theme-token sync). Host-rendered contribution points (widgets, schedule rows, map layers, planner columns/actions) render server-normalized primitives only — plugin markup never runs inline. Authoring is covered by the `trek-plugin-dev` skill. - **Plugins UI** (`src/components/Plugins/`): third-party surfaces render only inside the sandboxed `PluginFrame` iframe (postMessage bridge, live theme-token sync). Host-rendered contribution points (widgets, schedule rows, map layers, planner columns/actions) render server-normalized primitives only — plugin markup never runs inline. Authoring is covered by the `trek-plugin-dev` skill.
@@ -1,6 +1,9 @@
package com.liketrek.trek; package com.liketrek.trek;
import android.content.Intent; 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.graphics.drawable.GradientDrawable;
import android.os.Bundle; import android.os.Bundle;
import android.util.TypedValue; import android.util.TypedValue;
@@ -11,11 +14,13 @@ import android.view.Menu;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.webkit.CookieManager; import android.webkit.CookieManager;
import android.webkit.WebView;
import android.widget.Button; import android.widget.Button;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
import com.getcapacitor.BridgeActivity; import com.getcapacitor.BridgeActivity;
import com.getcapacitor.WebViewListener;
import com.liketrek.trek.screen.TrekKeyCommands; import com.liketrek.trek.screen.TrekKeyCommands;
import com.liketrek.trek.tiles.TrekTileStore; import com.liketrek.trek.tiles.TrekTileStore;
import com.liketrek.trek.widget.TrekWidgetUpdater; 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. */ /** The share sheet (share/ShareActivity.kt) left an item for the import. */
public static final String ACTION_SHARE_HANDOFF = "com.liketrek.trek.SHARE_HANDOFF"; 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 @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
registerPlugin(TrekShellPlugin.class); 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 // 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. // scroller natively. It scales the whole view, top bar and bottom dock included.
bridge.getWebView().setOverScrollMode(View.OVER_SCROLL_NEVER); 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. // Set before any WebView callback can run: they are posted to this thread.
if (onServer) { if (onServer) {
bridge.setWebViewClient( bridge.setWebViewClient(
+10 -6
View File
@@ -2,7 +2,8 @@ import { expect, test, type Locator } from '@playwright/test';
// #2981: labels, category and status took the whole row, so a place with two or // #2981: labels, category and status took the whole row, so a place with two or
// three long labels showed one letter of its name or none, and the status pill // three long labels showed one letter of its name or none, and the status pill
// ran out of the card. Measured in a real browser because the layout is the bug. // ran out of the card. The labels are tags now, shown as dots behind the name.
// Measured in a real browser because the layout is the bug.
const PLACES = [ const PLACES = [
{ name: 'Oceanario de Lisboa', labels: ['Core shortlist', 'Heritage specialist', 'Pair with another stop'] }, { name: 'Oceanario de Lisboa', labels: ['Core shortlist', 'Heritage specialist', 'Pair with another stop'] },
{ name: 'Cove of Ursa', labels: ['Heritage specialist', 'Pair with another stop'] }, { name: 'Cove of Ursa', labels: ['Heritage specialist', 'Pair with another stop'] },
@@ -83,11 +84,14 @@ for (const viewport of [
// The whole name fits: it is not cut to an ellipsis. // The whole name fits: it is not cut to an ellipsis.
expect(await name.evaluate((el) => el.scrollWidth <= el.clientWidth + 1)).toBe(true); expect(await name.evaluate((el) => el.scrollWidth <= el.clientWidth + 1)).toBe(true);
await expectInside(row); await expectInside(row);
// Every label is either on the row or counted by its "+N" chip. // The labels are the place's tags: dots behind the name, every name in their label.
const shown = await row.locator('.col-lrow-label:not(.is-over)').count(); const dots = row.locator('.li .t [role="img"]:not(.col-lrow-caticon)');
// Read without waiting: a row whose labels all fit has no "+N". if (place.labels.length === 0) {
const [more] = await row.locator('.col-lrow-more').allTextContents(); await expect(dots).toHaveCount(0);
expect(shown + (more ? Number(more.replace('+', '')) : 0)).toBe(place.labels.length); } else {
const named = ((await dots.getAttribute('aria-label')) ?? '').split(', ');
expect([...named].sort()).toEqual([...place.labels].sort());
}
} }
// The map's label strip stays inside the map: whole, or folded into its button. // The map's label strip stays inside the map: whole, or folded into its button.
const topbar = page.locator('.col-map-topbar'); const topbar = page.locator('.col-map-topbar');
+3 -3
View File
@@ -31,7 +31,7 @@ test('#1432 iPad: the places list scrolls under a swipe', async ({ page }) => {
await page.getByText(title).first().click() await page.getByText(title).first().click()
await expect(page).toHaveURL(/\/trips\/\d+/) await expect(page).toHaveURL(/\/trips\/\d+/)
await expect(page.locator('.leaflet-container')).toBeVisible({ timeout: 20_000 }) await expect(page.locator('.leaflet-container, .maplibregl-canvas, .mapboxgl-canvas').first()).toBeVisible({ timeout: 20_000 })
const tripId = page.url().match(/\/trips\/(\d+)/)![1] const tripId = page.url().match(/\/trips\/(\d+)/)![1]
@@ -43,7 +43,7 @@ test('#1432 iPad: the places list scrolls under a swipe', async ({ page }) => {
expect(res.ok(), `seed place ${i}`).toBeTruthy() expect(res.ok(), `seed place ${i}`).toBeTruthy()
} }
await page.reload() await page.reload()
await expect(page.locator('.leaflet-container')).toBeVisible({ timeout: 20_000 }) await expect(page.locator('.leaflet-container, .maplibregl-canvas, .mapboxgl-canvas').first()).toBeVisible({ timeout: 20_000 })
// An iPad is inside the 768-1023px band, where only one side panel is open at a // An iPad is inside the 768-1023px band, where only one side panel is open at a
// time so the map keeps a usable width (#2247). The places list is one tap away. // time so the map keeps a usable width (#2247). The places list is one tap away.
@@ -88,7 +88,7 @@ test('#1432 iPad: the places list scrolls under a swipe', async ({ page }) => {
// 3. The iPad must still get the desktop shell — isMobile stayed width-based. One // 3. The iPad must still get the desktop shell — isMobile stayed width-based. One
// panel at a time (#2247), so opening Places closed the day plan and left its // panel at a time (#2247), so opening Places closed the day plan and left its
// tab as the way back. // tab as the way back.
await expect(page.locator('.leaflet-container')).toBeVisible() await expect(page.locator('.leaflet-container, .maplibregl-canvas, .mapboxgl-canvas').first()).toBeVisible()
// The top tab bar has a button named Plan as well; the way back is the panel's // The top tab bar has a button named Plan as well; the way back is the panel's
// own tab, which is accented while its panel is closed. // own tab, which is accented while its panel is closed.
await expect(page.locator('button[aria-label="Plan"].bg-accent')).toBeVisible() await expect(page.locator('button[aria-label="Plan"].bg-accent')).toBeVisible()
+2 -2
View File
@@ -22,7 +22,7 @@ test('desktop: reorder arrows are hidden-and-inert until the row is hovered', as
await page.getByText(title).first().click() await page.getByText(title).first().click()
await expect(page).toHaveURL(/\/trips\/\d+/) await expect(page).toHaveURL(/\/trips\/\d+/)
await expect(page.locator('.leaflet-container')).toBeVisible({ timeout: 20_000 }) await expect(page.locator('.leaflet-container, .maplibregl-canvas, .mapboxgl-canvas').first()).toBeVisible({ timeout: 20_000 })
// Two places on day 1, so the day plan renders rows carrying reorder arrows. // Two places on day 1, so the day plan renders rows carrying reorder arrows.
const tripId = page.url().match(/\/trips\/(\d+)/)![1] const tripId = page.url().match(/\/trips\/(\d+)/)![1]
@@ -38,7 +38,7 @@ test('desktop: reorder arrows are hidden-and-inert until the row is hovered', as
}) })
} }
await page.reload() await page.reload()
await expect(page.locator('.leaflet-container')).toBeVisible({ timeout: 20_000 }) await expect(page.locator('.leaflet-container, .maplibregl-canvas, .mapboxgl-canvas').first()).toBeVisible({ timeout: 20_000 })
const row = page.locator('.dp-row').filter({ hasText: 'Alpha' }).first() const row = page.locator('.dp-row').filter({ hasText: 'Alpha' }).first()
await expect(row).toBeVisible({ timeout: 20_000 }) await expect(row).toBeVisible({ timeout: 20_000 })
+3 -1
View File
@@ -58,7 +58,9 @@ test('desktop: a stay booked in another session shows in the day plan without a
const hotel = `Mercure Hotel ${Date.now()}`; const hotel = `Mercure Hotel ${Date.now()}`;
const { tripId, dayIds } = await seedTrip(page.request, `Stay live ${Date.now()}`); const { tripId, dayIds } = await seedTrip(page.request, `Stay live ${Date.now()}`);
await openPlanner(page, tripId); await openPlanner(page, tripId);
await expect(page.locator('.leaflet-container')).toBeVisible({ timeout: 20_000 }); await expect(page.locator('.leaflet-container, .maplibregl-canvas, .mapboxgl-canvas').first()).toBeVisible({
timeout: 20_000,
});
await bookElsewhere(browser, tripId, dayIds, hotel); await bookElsewhere(browser, tripId, dayIds, hotel);
+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
@@ -24,6 +24,6 @@ test('open a trip and land in the planner with a map', async ({ page }) => {
await page.getByText(title).first().click() await page.getByText(title).first().click()
await expect(page).toHaveURL(/\/trips\/\d+/) await expect(page).toHaveURL(/\/trips\/\d+/)
// The planner shows a Leaflet map once mounted (past the splash screen). // The planner shows its configured map once mounted.
await expect(page.locator('.leaflet-container')).toBeVisible({ timeout: 20_000 }) await expect(page.locator('.leaflet-container, .maplibregl-canvas, .mapboxgl-canvas').first()).toBeVisible({ timeout: 20_000 })
}) })
+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 // 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. // the map must not collapse to zero height now that the shell has none.
await page.goto('/atlas') 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 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) window.scrollBy(0, 400)
return { return {
top: document.scrollingElement!.scrollTop, 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 { StatusBar, Style } from '@capacitor/status-bar';
import { PASSWORD_MIN_LENGTH, passwordProblem, passwordRuleStates } from '../../shared/src/auth/password-policy'; 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 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 { AUTH_GATE_NAMES, canSignInInApp, type AuthGate } from '../src/native/authGate';
import { opensSoon, refundedBeforeOpening } from '../src/native/cloudOrders'; import { opensSoon, refundedBeforeOpening } from '../src/native/cloudOrders';
import { fakeIapClient, getIapClient, productIdFor, type Purchase } from '../src/native/iap'; 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> { async function paintStatusBar(): Promise<void> {
try { 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(); if (wideLayout.matches) await StatusBar.hide();
else await StatusBar.show(); else await StatusBar.show();
} catch { } catch {
+26 -5
View File
@@ -204,11 +204,32 @@
--sea: #cfe3ef; --sea: #cfe3ef;
--text-face: 'Plus Jakarta Sans', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif; --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; --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. */ /* The insets of the device, from the web view or from the native side. On
--safe-top: max(env(safe-area-inset-top, 0px), var(--trek-native-safe-top, 0px)); * Android a web view can report env() as 0 while the page reaches under the
--safe-bottom: max(env(safe-area-inset-bottom, 0px), var(--trek-native-safe-bottom, 0px)); * status and navigation bars; Capacitor's SystemBars writes the real insets
--safe-start: max(env(safe-area-inset-left, 0px), var(--trek-native-safe-left, 0px)); * to --safe-area-inset-* instead (0 where it lays the web view out between
--safe-end: max(env(safe-area-inset-right, 0px), var(--trek-native-safe-right, 0px)); * 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; color-scheme: light;
-webkit-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;
} }
+20 -14
View File
@@ -1,6 +1,6 @@
{ {
"name": "@trek/client", "name": "@trek/client",
"version": "5.2.1", "version": "5.2.2",
"engines": { "engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0" "node": "^22.22.2 || ^24.15.0 || >=26.0.0"
}, },
@@ -53,7 +53,7 @@
"format:check": "prettier --check \"src/**/*.tsx\" \"src/**/*.css\"" "format:check": "prettier --check \"src/**/*.tsx\" \"src/**/*.css\""
}, },
"dependencies": { "dependencies": {
"@assistant-ui/react": "0.15.37", "@assistant-ui/react": "0.15.38",
"@capacitor/action-sheet": "^8.1.1", "@capacitor/action-sheet": "^8.1.1",
"@capacitor/android": "^8.6.2", "@capacitor/android": "^8.6.2",
"@capacitor/app": "^8.1.1", "@capacitor/app": "^8.1.1",
@@ -102,12 +102,13 @@
"@fontsource/shrikhand": "^5.3.0", "@fontsource/shrikhand": "^5.3.0",
"@fontsource/yellowtail": "^5.3.0", "@fontsource/yellowtail": "^5.3.0",
"@maplibre/maplibre-gl-leaflet": "0.1.4", "@maplibre/maplibre-gl-leaflet": "0.1.4",
"@noble/hashes": "^1.8.0", "@noble/hashes": "^2.4.0",
"@simplewebauthn/browser": "^14.0.0", "@simplewebauthn/browser": "^14.0.0",
"@trek/shared": "*", "@trek/shared": "*",
"axios": "^1.21.0", "axios": "^1.21.0",
"dexie": "^4.4.7", "dexie": "^4.4.7",
"drag-drop-touch": "^1.3.1", "drag-drop-touch": "^1.3.1",
"earcut": "^3.0.2",
"heic-to": "^1.6.7", "heic-to": "^1.6.7",
"iso-3166-2": "^1.0.0", "iso-3166-2": "^1.0.0",
"leaflet": "^1.9.4", "leaflet": "^1.9.4",
@@ -118,7 +119,7 @@
"plyr": "^3.8.5", "plyr": "^3.8.5",
"react": "^19.3.1", "react": "^19.3.1",
"react-dom": "^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": "^5.0.0",
"react-leaflet-cluster": "^4.1.3", "react-leaflet-cluster": "^4.1.3",
"react-markdown": "^10.1.0", "react-markdown": "^10.1.0",
@@ -126,6 +127,7 @@
"rehype-sanitize": "^6.0.0", "rehype-sanitize": "^6.0.0",
"remark-breaks": "^4.0.0", "remark-breaks": "^4.0.0",
"remark-gfm": "^4.0.1", "remark-gfm": "^4.0.1",
"topojson-client": "^3.1.0",
"tz-lookup": "^6.1.25", "tz-lookup": "^6.1.25",
"zod": "^4.6.7", "zod": "^4.6.7",
"zustand": "^5.0.15" "zustand": "^5.0.15"
@@ -136,16 +138,20 @@
"@jscpd/core": "^4.2.5", "@jscpd/core": "^4.2.5",
"@jscpd/tokenizer": "^4.2.6", "@jscpd/tokenizer": "^4.2.6",
"@playwright/test": "^1.65.1", "@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/react": "^16.3.3",
"@testing-library/user-event": "^14.6.13", "@testing-library/user-event": "^14.6.13",
"@trivago/prettier-plugin-sort-imports": "^6.0.2", "@trivago/prettier-plugin-sort-imports": "^6.0.3",
"@types/leaflet": "^1.9.22", "@types/geojson": "^7946.0.16",
"@types/node": "^25.9.8", "@types/leaflet": "^1.9.23",
"@types/react": "^19.3.0", "@types/node": "^26.6.11",
"@types/react": "^19.3.2",
"@types/react-dom": "^19.3.0", "@types/react-dom": "^19.3.0",
"@types/topojson-client": "^3.1.5",
"@types/topojson-specification": "^1.0.5",
"@vitejs/plugin-react": "^6.2.1", "@vitejs/plugin-react": "^6.2.1",
"@vitest/coverage-v8": "^4.1.12", "@vitest/coverage-v8": "^5.1.2",
"autoprefixer": "^10.7.0", "autoprefixer": "^10.7.0",
"eslint": "^10.11.0", "eslint": "^10.11.0",
"eslint-config-flat-gitignore": "^2.4.0", "eslint-config-flat-gitignore": "^2.4.0",
@@ -154,18 +160,18 @@
"eslint-plugin-react-refresh": "^0.5.8", "eslint-plugin-react-refresh": "^0.5.8",
"fake-indexeddb": "^6.2.7", "fake-indexeddb": "^6.2.7",
"jsdom": "^29.1.1", "jsdom": "^29.1.1",
"msw": "^2.15.0", "msw": "^3.0.8",
"postcss": "^8.5.33", "postcss": "^8.5.33",
"prettier": "^3.10.1", "prettier": "^3.10.1",
"prettier-plugin-organize-imports": "^4.3.0", "prettier-plugin-organize-imports": "^4.3.0",
"prettier-plugin-tailwindcss": "^0.8.1", "prettier-plugin-tailwindcss": "^0.8.1",
"rollup-plugin-visualizer": "^7.1.2", "rollup-plugin-visualizer": "^7.3.0",
"sharp": "^0.35.5", "sharp": "^0.35.5",
"tailwindcss": "^3.4.19", "tailwindcss": "^3.4.19",
"typescript": "^6.0.3", "typescript": "^6.0.3",
"typescript-eslint": "^8.73.0", "typescript-eslint": "^8.74.0",
"vite": "8.3.8", "vite": "8.3.8",
"vite-plugin-pwa": "^2.0.0", "vite-plugin-pwa": "^2.0.0",
"vitest": "^4.1.12" "vitest": "^5.1.2"
} }
} }
+10
View File
@@ -12,6 +12,16 @@
(function () { (function () {
try { try {
var raw = localStorage.getItem('trek_appearance'); 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; if (!raw) return;
var s = JSON.parse(raw); var s = JSON.parse(raw);
if (!s || s.v !== 1) return; if (!s || s.v !== 1) return;
+24 -25
View File
@@ -1,28 +1,28 @@
{ {
"src": { "src": {
"@typescript-eslint/no-non-null-assertion": 354, "@typescript-eslint/no-non-null-assertion": 345,
"@typescript-eslint/no-misused-promises": 820, "@typescript-eslint/no-misused-promises": 810,
"no-console": 88, "no-console": 85,
"complexity": 216, "complexity": 214,
"@typescript-eslint/no-explicit-any": 138, "@typescript-eslint/no-explicit-any": 114,
"trek/no-swallowed-catch": 126, "trek/no-swallowed-catch": 124,
"max-params": 31, "max-params": 31,
"trek/store-without-selector": 66, "trek/store-without-selector": 65,
"react-hooks/refs": 534, "react-hooks/refs": 385,
"react-hooks/set-state-in-effect": 189, "react-hooks/set-state-in-effect": 188,
"@typescript-eslint/no-floating-promises": 162, "@typescript-eslint/no-floating-promises": 162,
"react-hooks/exhaustive-deps": 113, "react-hooks/exhaustive-deps": 112,
"@typescript-eslint/no-unused-vars": 117, "@typescript-eslint/no-unused-vars": 95,
"react-hooks/immutability": 28, "react-hooks/immutability": 26,
"max-lines-per-function": 127, "max-lines-per-function": 126,
"react-hooks/static-components": 50, "react-hooks/static-components": 38,
"react-hooks/preserve-manual-memoization": 12, "react-hooks/preserve-manual-memoization": 12,
"no-useless-assignment": 7, "no-useless-assignment": 7,
"no-empty": 19, "no-empty": 18,
"trek/no-window-globals": 41, "trek/no-window-globals": 41,
"react-refresh/only-export-components": 44, "react-refresh/only-export-components": 44,
"unused-disable-directive": 5, "unused-disable-directive": 5,
"max-depth": 21, "max-depth": 19,
"react-hooks/void-use-memo": 1, "react-hooks/void-use-memo": 1,
"@typescript-eslint/no-unused-expressions": 2, "@typescript-eslint/no-unused-expressions": 2,
"react-hooks/purity": 1, "react-hooks/purity": 1,
@@ -30,22 +30,21 @@
"no-useless-escape": 1 "no-useless-escape": 1
}, },
"suppressed": { "suppressed": {
"@typescript-eslint/no-explicit-any": 38, "@typescript-eslint/no-explicit-any": 37,
"react-hooks/exhaustive-deps": 44 "react-hooks/exhaustive-deps": 44
}, },
"tests": { "tests": {
"@typescript-eslint/no-explicit-any": 489, "@typescript-eslint/no-explicit-any": 484,
"@typescript-eslint/no-non-null-assertion": 1872, "@typescript-eslint/no-non-null-assertion": 1849,
"@typescript-eslint/no-misused-promises": 22, "@typescript-eslint/no-misused-promises": 22,
"@typescript-eslint/no-unused-vars": 51, "@typescript-eslint/no-unused-vars": 48,
"@typescript-eslint/no-floating-promises": 33, "@typescript-eslint/no-floating-promises": 33,
"trek/no-window-globals": 325, "trek/no-window-globals": 321,
"trek/no-swallowed-catch": 14, "trek/no-swallowed-catch": 6,
"react-hooks/globals": 5, "react-hooks/globals": 4,
"react-hooks/refs": 22, "react-hooks/refs": 16,
"@typescript-eslint/no-this-alias": 1, "@typescript-eslint/no-this-alias": 1,
"trek/store-without-selector": 3, "trek/store-without-selector": 3,
"@typescript-eslint/no-unsafe-function-type": 2,
"no-console": 2, "no-console": 2,
"react-refresh/only-export-components": 1 "react-refresh/only-export-components": 1
} }
+113 -14
View File
@@ -135,24 +135,24 @@
{ {
"feature": "Atlas country/region action sheet", "feature": "Atlas country/region action sheet",
"hooks": ["src/pages/atlas/useAtlasCountryActions.ts"], "hooks": ["src/pages/atlas/useAtlasCountryActions.ts"],
"desktop": ["src/pages/AtlasPage.tsx"], "desktop": ["src/pages/atlas/AtlasCountryActionDialog.tsx"],
"mobile": ["src/mobile/screens/atlas/MAtlasCountryPopup.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", "feature": "Atlas page: atlasModel",
"hooks": ["src/pages/atlas/atlasModel.ts"], "hooks": ["src/pages/atlas/atlasModel.ts"],
"desktop": [ "desktop": [
"src/components/Atlas/AtlasCountryPlaces.tsx", "src/components/Atlas/AtlasCountryPlaces.tsx",
"src/components/shared/CountryFlag.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"] "mobile": ["src/mobile/screens/atlas/MAtlasGlobe.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"]
}, },
{ {
"feature": "Audit log", "feature": "Audit log",
@@ -208,7 +208,7 @@
"desktop": [ "desktop": [
"src/components/Planner/DayDetailPanel.tsx", "src/components/Planner/DayDetailPanel.tsx",
"src/components/Planner/DayPlanSidebar.tsx", "src/components/Planner/DayPlanSidebar.tsx",
"src/components/Planner/PlaceInspector.tsx", "src/components/Planner/PlaceLinkedBookingCard.tsx",
"src/components/Planner/ReservationModal.tsx", "src/components/Planner/ReservationModal.tsx",
"src/components/Planner/ReservationsPanel.tsx", "src/components/Planner/ReservationsPanel.tsx",
"src/components/Planner/TransportModal.tsx", "src/components/Planner/TransportModal.tsx",
@@ -287,10 +287,94 @@
}, },
{ {
"feature": "Collection place detail", "feature": "Collection place detail",
"hooks": ["src/components/Collections/useCollectionPlaceForm.ts"], "hooks": [
"src/components/Collections/useCollectionPlaceForm.ts",
"src/components/Collections/useLibraryPlace.ts",
"src/components/Collections/usePlaceSheet.ts",
"src/components/Collections/usePlaceTags.ts",
"src/components/Collections/libraryPairs.ts"
],
"desktop": ["src/components/Collections/CollectionPlaceDetail.tsx"], "desktop": ["src/components/Collections/CollectionPlaceDetail.tsx"],
"mobile": ["src/mobile/screens/collections/MCollPlaceSheet.tsx"] "mobile": ["src/mobile/screens/collections/MCollPlaceSheet.tsx"]
}, },
{
"feature": "Collection place order",
"hooks": ["src/components/Collections/usePlaceReorder.ts"],
"desktop": ["src/components/Collections/CollectionList.tsx"],
"mobile": ["src/mobile/screens/collections/MCollections.tsx"]
},
{
"feature": "Collection place position search",
"hooks": ["src/components/shared/useLocationSearch.ts"],
"desktop": ["src/components/Collections/CollectionLocationSearch.tsx"],
"mobile": ["src/mobile/screens/collections/MCollLocationSearch.tsx"]
},
{
"feature": "Places: a place of all places",
"hooks": [
"src/components/Collections/libraryPairs.ts",
"src/components/Collections/usePlaceSheet.ts",
"src/components/Collections/usePlaceTags.ts",
"src/components/Collections/usePlaceEdit.ts",
"src/components/Collections/usePlaceRating.ts"
],
"desktop": ["src/components/Collections/LibraryPlaceDetail.tsx"],
"mobile": ["src/mobile/screens/collections/MLibraryPlaceSheet.tsx"]
},
{
"feature": "Places: where a place is kept",
"hooks": ["src/components/Collections/libraryDates.ts"],
"desktop": ["src/components/Collections/PlaceOrigins.tsx"],
"mobile": ["src/mobile/screens/collections/MPlaceOrigins.tsx"]
},
{
"feature": "Places: the tabs of a place",
"hooks": ["src/components/Collections/usePlaceSheet.ts"],
"desktop": ["src/components/Collections/PlaceSheetTabs.tsx"],
"mobile": ["src/mobile/screens/collections/MPlaceSheetTabs.tsx"]
},
{
"feature": "Places: tours and bookings of a place",
"hooks": ["src/components/Collections/usePlaceActivities.ts", "src/components/Collections/placeExtrasText.ts"],
"desktop": ["src/components/Collections/PlaceActivitiesSection.tsx"],
"mobile": ["src/mobile/screens/collections/MPlaceActivitiesSection.tsx"]
},
{
"feature": "Places: changes of a place",
"hooks": ["src/components/Collections/usePlaceHistory.ts", "src/components/Collections/placeExtrasText.ts"],
"desktop": ["src/components/Collections/PlaceHistorySection.tsx"],
"mobile": ["src/mobile/screens/collections/MPlaceHistorySection.tsx"]
},
{
"feature": "Places: notes of a place",
"hooks": ["src/components/Collections/useOriginNotes.ts"],
"desktop": ["src/components/Collections/OriginNotesSection.tsx"],
"mobile": ["src/mobile/screens/collections/MOriginNotesSection.tsx"]
},
{
"feature": "Places: pictures and files of a place",
"hooks": ["src/components/Collections/usePlaceMedia.ts", "src/components/Collections/mediaAdd.tsx"],
"desktop": ["src/components/Collections/PlaceMediaSection.tsx"],
"mobile": ["src/mobile/screens/collections/MPlaceMediaSection.tsx"]
},
{
"feature": "Places: visits of a place",
"hooks": ["src/components/Collections/usePlaceVisits.ts"],
"desktop": ["src/components/Collections/VisitsSection.tsx", "src/components/Collections/TripPlaceVisits.tsx"],
"mobile": ["src/mobile/screens/collections/MVisitsSection.tsx"]
},
{
"feature": "Places: possible duplicates",
"hooks": ["src/components/Collections/DuplicatePairCard.tsx"],
"desktop": ["src/components/Collections/DuplicatesDialog.tsx"],
"mobile": ["src/mobile/screens/collections/MDuplicatesSheet.tsx"]
},
{
"feature": "Places: all places",
"hooks": ["src/components/Collections/usePlacesLibrary.ts", "src/components/Collections/usePlaceDuplicates.ts"],
"desktop": ["src/components/Collections/PlacesLibraryView.tsx"],
"mobile": ["src/mobile/screens/collections/MPlacesLibrary.tsx"]
},
{ {
"feature": "Collection sharing", "feature": "Collection sharing",
"hooks": ["src/components/Collections/useCollectionSharing.ts"], "hooks": ["src/components/Collections/useCollectionSharing.ts"],
@@ -1120,6 +1204,11 @@
} }
], ],
"mobileOnly": { "mobileOnly": {
"src/mobile/screens/collections/MPlaceCard.tsx": "The frame of a group in the phone's place view; the desktop twin is PlaceCard, plain markup with no logic to share.",
"src/mobile/screens/collections/MPlaceEditForm.tsx": "Markup over the usePlaceEdit state MLibraryPlaceSheet passes in; the hook is in the \"a place of all places\" pair.",
"src/mobile/screens/collections/MPlaceSheetShell.tsx": "The phone's frame of the one place view (cover, body, bottom row); the desktop frame is DialogShell.",
"src/mobile/screens/collections/MPlaceTagsCard.tsx": "Markup over the usePlaceTags state the place sheets pass in; the hook is in their pairs.",
"src/mobile/screens/collections/MCollFilterKit.tsx": "Markup only: the filter chips, dropdown rows and empty note the phone's lists and all-places screens share; the desktop draws its own filter row (FilterDropdown).",
"src/mobile/screens/trip/sheets/MReviewNotice.tsx": "The transport sheet's row asking for a look at an imported booking; the desktop dialog folds the same \"looks right\" action into its review pill (ReviewPill in bookingParts.tsx), so there is no separate twin.", "src/mobile/screens/trip/sheets/MReviewNotice.tsx": "The transport sheet's row asking for a look at an imported booking; the desktop dialog folds the same \"looks right\" action into its review pill (ReviewPill in bookingParts.tsx), so there is no separate twin.",
"src/mobile/screens/mail/MMailInboxHost.tsx": "Mounts the phone shell's one inbox sheet and reads the person's import settings; the desktop mounts its dialog from the Navbar, so there is no twin.", "src/mobile/screens/mail/MMailInboxHost.tsx": "Mounts the phone shell's one inbox sheet and reads the person's import settings; the desktop mounts its dialog from the Navbar, so there is no twin.",
"src/mobile/screens/admin/MAdminOidcCard.tsx": "Markup only; the OIDC card of MAdminSettingsSection, with the form state from useAdmin and the save from its useAdminSettingsActions handed in through props.", "src/mobile/screens/admin/MAdminOidcCard.tsx": "Markup only; the OIDC card of MAdminSettingsSection, with the form state from useAdmin and the save from its useAdminSettingsActions handed in through props.",
@@ -1127,8 +1216,8 @@
"src/mobile/screens/admin/MAdminUi.tsx": "Phone only admin UI primitives (button, card, field, input, secret input, sheet frame).", "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/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/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/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 AtlasStats that MAtlas passes in.", "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/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/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.", "src/mobile/screens/collections/MCollLabelsSheet.tsx": "Phone label sheet; create, update, delete and assign come through props from useCollections.",
@@ -1207,6 +1296,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/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/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/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."
} }
} }
-23
View File
@@ -139,7 +139,6 @@
"src/components/Admin/useSchoolHolidayCatalog.ts", "src/components/Admin/useSchoolHolidayCatalog.ts",
"src/components/Atlas/AtlasCountryPlaces.test.tsx", "src/components/Atlas/AtlasCountryPlaces.test.tsx",
"src/components/Atlas/AtlasCountryPlaces.tsx", "src/components/Atlas/AtlasCountryPlaces.tsx",
"src/components/Atlas/useGlassGlare.ts",
"src/components/BackgroundTasks/BackgroundTasksWidget.extra.test.tsx", "src/components/BackgroundTasks/BackgroundTasksWidget.extra.test.tsx",
"src/components/BackgroundTasks/BackgroundTasksWidget.test.tsx", "src/components/BackgroundTasks/BackgroundTasksWidget.test.tsx",
"src/components/BackgroundTasks/BackgroundTasksWidget.tsx", "src/components/BackgroundTasks/BackgroundTasksWidget.tsx",
@@ -234,7 +233,6 @@
"src/components/Collections/CollectionPicker.test.tsx", "src/components/Collections/CollectionPicker.test.tsx",
"src/components/Collections/CollectionPicker.tsx", "src/components/Collections/CollectionPicker.tsx",
"src/components/Collections/CollectionPlaceDetail.test.tsx", "src/components/Collections/CollectionPlaceDetail.test.tsx",
"src/components/Collections/CollectionPlaceDetail.tsx",
"src/components/Collections/CopyToTripModal.test.tsx", "src/components/Collections/CopyToTripModal.test.tsx",
"src/components/Collections/CopyToTripModal.tsx", "src/components/Collections/CopyToTripModal.tsx",
"src/components/Collections/ImportCollectionModal.test.tsx", "src/components/Collections/ImportCollectionModal.test.tsx",
@@ -266,10 +264,6 @@
"src/components/Dashboard/CollectionsWidget.tsx", "src/components/Dashboard/CollectionsWidget.tsx",
"src/components/Dawarich/DawarichAcceptDialog.test.tsx", "src/components/Dawarich/DawarichAcceptDialog.test.tsx",
"src/components/Dawarich/DawarichAcceptDialog.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.test.tsx",
"src/components/Dawarich/DawarichBadge.tsx", "src/components/Dawarich/DawarichBadge.tsx",
"src/components/Dawarich/DawarichSuggestionsPanel.test.tsx", "src/components/Dawarich/DawarichSuggestionsPanel.test.tsx",
@@ -1146,7 +1140,6 @@
"src/constants/tripTabs.ts", "src/constants/tripTabs.ts",
"src/db/cacheAssignment.ts", "src/db/cacheAssignment.ts",
"src/db/offlineDb.test.ts", "src/db/offlineDb.test.ts",
"src/db/offlineDb.ts",
"src/help/contexts/admin.ts", "src/help/contexts/admin.ts",
"src/help/contexts/atlas.ts", "src/help/contexts/atlas.ts",
"src/help/contexts/collections.ts", "src/help/contexts/collections.ts",
@@ -1284,12 +1277,9 @@
"src/mobile/screens/admin/MAdminUsersSection.tsx", "src/mobile/screens/admin/MAdminUsersSection.tsx",
"src/mobile/screens/admin/MApiProviderBlocks.tsx", "src/mobile/screens/admin/MApiProviderBlocks.tsx",
"src/mobile/screens/atlas/MAtlas.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.test.tsx",
"src/mobile/screens/atlas/MAtlasCountryPopup.tsx", "src/mobile/screens/atlas/MAtlasCountryPopup.tsx",
"src/mobile/screens/atlas/MAtlasSearch.tsx",
"src/mobile/screens/atlas/MAtlasStatsCard.tsx", "src/mobile/screens/atlas/MAtlasStatsCard.tsx",
"src/mobile/screens/atlas/atlasController.ts",
"src/mobile/screens/collections/MCollAddSheet.tsx", "src/mobile/screens/collections/MCollAddSheet.tsx",
"src/mobile/screens/collections/MCollCategoryPicker.tsx", "src/mobile/screens/collections/MCollCategoryPicker.tsx",
"src/mobile/screens/collections/MCollEditSheet.tsx", "src/mobile/screens/collections/MCollEditSheet.tsx",
@@ -1297,7 +1287,6 @@
"src/mobile/screens/collections/MCollLinksEditor.tsx", "src/mobile/screens/collections/MCollLinksEditor.tsx",
"src/mobile/screens/collections/MCollListPickerSheet.tsx", "src/mobile/screens/collections/MCollListPickerSheet.tsx",
"src/mobile/screens/collections/MCollPlaceRow.tsx", "src/mobile/screens/collections/MCollPlaceRow.tsx",
"src/mobile/screens/collections/MCollPlaceSheet.tsx",
"src/mobile/screens/collections/MCollShareSheet.tsx", "src/mobile/screens/collections/MCollShareSheet.tsx",
"src/mobile/screens/collections/MCollSheetKit.tsx", "src/mobile/screens/collections/MCollSheetKit.tsx",
"src/mobile/screens/collections/MCollTripPickerSheet.tsx", "src/mobile/screens/collections/MCollTripPickerSheet.tsx",
@@ -1440,9 +1429,7 @@
"src/mobile/useIsPhone.ts", "src/mobile/useIsPhone.ts",
"src/pages/AdminPage.test.tsx", "src/pages/AdminPage.test.tsx",
"src/pages/AdminPage.tsx", "src/pages/AdminPage.tsx",
"src/pages/AtlasPage.test.tsx",
"src/pages/AtlasPage.tsx", "src/pages/AtlasPage.tsx",
"src/pages/AtlasPage.wiring.test.tsx",
"src/pages/CollectionsPage.test.tsx", "src/pages/CollectionsPage.test.tsx",
"src/pages/CollectionsPage.tsx", "src/pages/CollectionsPage.tsx",
"src/pages/CollectionsPage.wiring.test.tsx", "src/pages/CollectionsPage.wiring.test.tsx",
@@ -1497,7 +1484,6 @@
"src/pages/admin/AdminSettingsTab.test.tsx", "src/pages/admin/AdminSettingsTab.test.tsx",
"src/pages/admin/AdminSettingsTab.tsx", "src/pages/admin/AdminSettingsTab.tsx",
"src/pages/admin/AdminStatCard.tsx", "src/pages/admin/AdminStatCard.tsx",
"src/pages/admin/AdminUpdateBanner.test.tsx",
"src/pages/admin/AdminUpdateBanner.tsx", "src/pages/admin/AdminUpdateBanner.tsx",
"src/pages/admin/AdminUserModals.test.tsx", "src/pages/admin/AdminUserModals.test.tsx",
"src/pages/admin/AdminUserModals.tsx", "src/pages/admin/AdminUserModals.tsx",
@@ -1509,13 +1495,8 @@
"src/pages/admin/adminModel.ts", "src/pages/admin/adminModel.ts",
"src/pages/admin/useAdmin.ts", "src/pages/admin/useAdmin.ts",
"src/pages/admin/useNotificationDefaults.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.test.ts",
"src/pages/atlas/atlasModel.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.test.ts",
"src/pages/collections/collectionsModel.ts", "src/pages/collections/collectionsModel.ts",
"src/pages/collections/useCollections.test.tsx", "src/pages/collections/useCollections.test.tsx",
@@ -1888,10 +1869,7 @@
"tests/unit/mobile/admin/MAdminSheets.test.tsx", "tests/unit/mobile/admin/MAdminSheets.test.tsx",
"tests/unit/mobile/admin/MAdminStoragePanel.test.tsx", "tests/unit/mobile/admin/MAdminStoragePanel.test.tsx",
"tests/unit/mobile/admin/MAdminUsersSection.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/MAtlasCountryPopup.test.tsx",
"tests/unit/mobile/atlas/MAtlasSearch.test.tsx",
"tests/unit/mobile/atlas/MAtlasStatsCard.test.tsx", "tests/unit/mobile/atlas/MAtlasStatsCard.test.tsx",
"tests/unit/mobile/collections/MCollAddSheet.test.tsx", "tests/unit/mobile/collections/MCollAddSheet.test.tsx",
"tests/unit/mobile/collections/MCollCategoryPicker.test.tsx", "tests/unit/mobile/collections/MCollCategoryPicker.test.tsx",
@@ -2121,7 +2099,6 @@
"tests/unit/sync/tripSyncManager.test.ts", "tests/unit/sync/tripSyncManager.test.ts",
"tests/unit/tripStore.test.ts", "tests/unit/tripStore.test.ts",
"tests/unit/utils/cleanAmount.test.ts", "tests/unit/utils/cleanAmount.test.ts",
"tests/unit/utils/fileDownload.test.ts",
"tests/unit/utils/formatters.test.ts", "tests/unit/utils/formatters.test.ts",
"tests/unit/utils/placeFiles.test.ts", "tests/unit/utils/placeFiles.test.ts",
"tests/unit/utils/shellGuard.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 * Where else a translation key can be named: the server sends keys for the
* client to translate (system notices, notification channels), the plugin * client to translate (system notices, notification channels), the plugin
* SDK names the ones plugin surfaces use, and the shared book engine names * SDK names the ones plugin surfaces use, the shared book engine names
* its layout templates. Read only to find which en keys are reached. * its layout templates and the Atlas badge rules their titles. Read only to find which en keys are reached.
*/ */
export const REFERENCE_ROOTS = [ export const REFERENCE_ROOTS = [
// The address screen the native apps ship (vite.native.config.js): its own // 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, '..', '..', 'server', 'src'),
join(HERE, '..', '..', 'plugin-sdk', 'src'), join(HERE, '..', '..', 'plugin-sdk', 'src'),
join(HERE, '..', '..', 'shared', 'src', 'book'), 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. */ /** How many en keys a template may reach and still pass without an entry below. */
+2 -2
View File
@@ -1,11 +1,11 @@
{ {
"admin.ts": 112, "admin.ts": 112,
"atlas.ts": 9, "atlas.ts": 7,
"backup.ts": 10, "backup.ts": 10,
"budget.ts": 35, "budget.ts": 35,
"categories.ts": 1, "categories.ts": 1,
"collab.ts": 9, "collab.ts": 9,
"collection.ts": 35, "collection.ts": 29,
"common.ts": 7, "common.ts": 7,
"dashboard.ts": 64, "dashboard.ts": 64,
"dawarich.ts": 15, "dawarich.ts": 15,
-1
View File
@@ -13,7 +13,6 @@
"src/components/Collections/ListEditorModal.tsx": 1, "src/components/Collections/ListEditorModal.tsx": 1,
"src/components/Collections/MSaveToCollectionSheet.tsx": 3, "src/components/Collections/MSaveToCollectionSheet.tsx": 3,
"src/components/Dawarich/DawarichAcceptDialog.tsx": 3, "src/components/Dawarich/DawarichAcceptDialog.tsx": 3,
"src/components/Dawarich/DawarichAtlasDialog.tsx": 3,
"src/components/Dawarich/DawarichSuggestionsPanel.tsx": 1, "src/components/Dawarich/DawarichSuggestionsPanel.tsx": 1,
"src/components/Journey/ContributorInviteDialog.tsx": 1, "src/components/Journey/ContributorInviteDialog.tsx": 1,
"src/components/Journey/JourneyDetailPageAddTripDialog.tsx": 1, "src/components/Journey/JourneyDetailPageAddTripDialog.tsx": 1,
-3
View File
@@ -42,7 +42,6 @@
"src/components/Collections/useSaveTripPlacesToList.ts", "src/components/Collections/useSaveTripPlacesToList.ts",
"src/components/Collections/useTripCopyPicker.ts", "src/components/Collections/useTripCopyPicker.ts",
"src/components/Dashboard/useCollectionLists.ts", "src/components/Dashboard/useCollectionLists.ts",
"src/components/Dawarich/DawarichAtlasDialog.tsx",
"src/components/Files/FileManagerAuthedImg.tsx", "src/components/Files/FileManagerAuthedImg.tsx",
"src/components/Files/FileManagerImageLightbox.tsx", "src/components/Files/FileManagerImageLightbox.tsx",
"src/components/Files/docsync/useConflicts.ts", "src/components/Files/docsync/useConflicts.ts",
@@ -130,8 +129,6 @@
"src/pages/OAuthAuthorizePage.tsx", "src/pages/OAuthAuthorizePage.tsx",
"src/pages/admin/useAdmin.ts", "src/pages/admin/useAdmin.ts",
"src/pages/admin/useNotificationDefaults.ts", "src/pages/admin/useNotificationDefaults.ts",
"src/pages/atlas/useAtlas.ts",
"src/pages/atlas/useAtlasCountryActions.ts",
"src/pages/collections/useCollections.ts", "src/pages/collections/useCollections.ts",
"src/pages/dashboard/useDashboard.ts", "src/pages/dashboard/useDashboard.ts",
"src/pages/dashboard/useTripSearch.ts", "src/pages/dashboard/useTripSearch.ts",
+2 -5
View File
@@ -6,7 +6,6 @@
"components/Collab/CollabChatEmojiPicker.tsx": 3, "components/Collab/CollabChatEmojiPicker.tsx": 3,
"components/Collab/CollabChatReactionBadge.tsx": 3, "components/Collab/CollabChatReactionBadge.tsx": 3,
"components/Collab/CollabChatReactionMenu.tsx": 1, "components/Collab/CollabChatReactionMenu.tsx": 1,
"components/Collections/CollectionPlaceDetail.tsx": 2,
"components/Files/FileManagerAvatarChip.tsx": 3, "components/Files/FileManagerAvatarChip.tsx": 3,
"components/Journey/JourneyDayJump.tsx": 1, "components/Journey/JourneyDayJump.tsx": 1,
"components/Journey/JourneyDetailPageDatePicker.tsx": 1, "components/Journey/JourneyDetailPageDatePicker.tsx": 1,
@@ -24,8 +23,8 @@
"components/Map/DawarichTrailPill.tsx": 1, "components/Map/DawarichTrailPill.tsx": 1,
"components/Map/LocationButton.tsx": 1, "components/Map/LocationButton.tsx": 1,
"components/Map/MapTogglePill.tsx": 1, "components/Map/MapTogglePill.tsx": 1,
"components/Map/MapView.tsx": 5, "components/Map/MapView.tsx": 4,
"components/Map/MapViewGL.tsx": 7, "components/Map/MapViewGL.tsx": 6,
"components/Map/NightPauseTooltip.tsx": 1, "components/Map/NightPauseTooltip.tsx": 1,
"components/Map/PlaceHoverCard.tsx": 1, "components/Map/PlaceHoverCard.tsx": 1,
"components/Map/PoiCategoryPill.tsx": 1, "components/Map/PoiCategoryPill.tsx": 1,
@@ -82,7 +81,6 @@
"mobile/screens/trip/map/MMapArea.tsx": 3, "mobile/screens/trip/map/MMapArea.tsx": 3,
"mobile/screens/trip/tabs/MFileLightbox.tsx": 2, "mobile/screens/trip/tabs/MFileLightbox.tsx": 2,
"mobile/screens/vacay/MVacayMonth.tsx": 1, "mobile/screens/vacay/MVacayMonth.tsx": 1,
"pages/AtlasPage.tsx": 2,
"pages/JourneyDetailPage.tsx": 1, "pages/JourneyDetailPage.tsx": 1,
"pages/JourneyPublicPage.tsx": 3, "pages/JourneyPublicPage.tsx": 3,
"pages/LoginPage.tsx": 23, "pages/LoginPage.tsx": 23,
@@ -90,7 +88,6 @@
"pages/VacayPage.tsx": 1, "pages/VacayPage.tsx": 1,
"pages/admin/AdminNotificationsTab.tsx": 1, "pages/admin/AdminNotificationsTab.tsx": 1,
"pages/admin/AdminSettingsTab.tsx": 1, "pages/admin/AdminSettingsTab.tsx": 1,
"pages/atlas/AtlasLayerToggle.tsx": 1,
"pages/sharedTrip/SharedMap.tsx": 4, "pages/sharedTrip/SharedMap.tsx": 4,
"styles/collections.css": 1, "styles/collections.css": 1,
"styles/studio.css": 7, "styles/studio.css": 7,
+2 -1
View File
@@ -1,4 +1,5 @@
{ {
"components/AtlasGlobe/atlasGlobe.css": 1,
"components/Collections/CollectionMap.tsx": 1, "components/Collections/CollectionMap.tsx": 1,
"components/Packing/PackingItemDetail.tsx": 1, "components/Packing/PackingItemDetail.tsx": 1,
"components/Studio/LineHandles.tsx": 1, "components/Studio/LineHandles.tsx": 1,
@@ -7,6 +8,6 @@
"mobile/components/trek3d/MascotClip.tsx": 1, "mobile/components/trek3d/MascotClip.tsx": 1,
"mobile/screens/trip/MTripShell.tsx": 1, "mobile/screens/trip/MTripShell.tsx": 1,
"mobile/screens/vacay/MVacay.tsx": 1, "mobile/screens/vacay/MVacay.tsx": 1,
"pages/CollectionsPage.tsx": 1, "pages/atlas/AtlasGlobeView.tsx": 1,
"pages/tripPlanner/PlanMapStage.tsx": 4 "pages/tripPlanner/PlanMapStage.tsx": 4
} }
+7 -8
View File
@@ -5,22 +5,21 @@
"src/components/Admin/AdminPluginsPanel.tsx": 1265, "src/components/Admin/AdminPluginsPanel.tsx": 1265,
"src/components/Budget/CostsPanel.test.tsx": 2725, "src/components/Budget/CostsPanel.test.tsx": 2725,
"src/components/Budget/CostsPanel.tsx": 1607, "src/components/Budget/CostsPanel.tsx": 1607,
"src/components/Map/MapView.tsx": 1200, "src/components/Map/MapView.tsx": 1191,
"src/components/Map/MapViewGL.test.tsx": 2919, "src/components/Map/MapViewGL.test.tsx": 2919,
"src/components/Map/MapViewGL.tsx": 2116, "src/components/Map/MapViewGL.tsx": 2083,
"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.test.tsx": 5349,
"src/components/Planner/DayPlanSidebar.tsx": 2908, "src/components/Planner/DayPlanSidebar.tsx": 2908,
"src/components/Planner/PlaceFormModal.test.tsx": 2836, "src/components/Planner/PlaceFormModal.test.tsx": 2836,
"src/components/Planner/PlaceInspector.tsx": 1128, "src/components/Planner/PlaceInspector.tsx": 1030,
"src/components/Studio/TravelElements.tsx": 1559, "src/components/Studio/TravelElements.tsx": 1559,
"src/components/Studio/countryShapes.ts": 2595, "src/components/Studio/countryShapes.ts": 2595,
"src/index.css": 1636, "src/index.css": 1636,
"src/mobile/screens/admin/MAdminPluginsPanel.tsx": 1503, "src/mobile/screens/admin/MAdminPluginsPanel.tsx": 1503,
"src/pages/JourneyDetailPage.test.tsx": 4028, "src/pages/JourneyDetailPage.test.tsx": 3886,
"src/pages/LoginPage.tsx": 1294, "src/pages/LoginPage.tsx": 1273,
"src/pages/TripPlannerPage.tsx": 1128, "src/pages/TripPlannerPage.tsx": 1127,
"src/pages/atlas/useAtlas.ts": 1207,
"src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx": 3518, "src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx": 3518,
"src/pages/tripPlanner/useTripPlanner.test.tsx": 3267, "src/pages/tripPlanner/useTripPlanner.test.tsx": 3267,
"src/styles/studio.css": 1918 "src/styles/studio.css": 1918
-2
View File
@@ -110,14 +110,12 @@
"src/mobile/screens/trip/sheets/MReservationSheet.tsx": 1, "src/mobile/screens/trip/sheets/MReservationSheet.tsx": 1,
"src/mobile/screens/trip/tabs/transportsModel.ts": 1, "src/mobile/screens/trip/tabs/transportsModel.ts": 1,
"src/mobile/screens/vacay/MVacaySettingsSheet.tsx": 1, "src/mobile/screens/vacay/MVacaySettingsSheet.tsx": 1,
"src/pages/AtlasPage.tsx": 6,
"src/pages/FilesPage.tsx": 1, "src/pages/FilesPage.tsx": 1,
"src/pages/JourneyDetailPage.tsx": 1, "src/pages/JourneyDetailPage.tsx": 1,
"src/pages/LoginPage.tsx": 1, "src/pages/LoginPage.tsx": 1,
"src/pages/VacayPage.tsx": 1, "src/pages/VacayPage.tsx": 1,
"src/pages/admin/useAdmin.ts": 4, "src/pages/admin/useAdmin.ts": 4,
"src/pages/atlas/atlasModel.ts": 2, "src/pages/atlas/atlasModel.ts": 2,
"src/pages/atlas/useAtlas.ts": 9,
"src/pages/collections/collectionsModel.ts": 1, "src/pages/collections/collectionsModel.ts": 1,
"src/pages/journeyDetail/useJourneyDetail.ts": 3, "src/pages/journeyDetail/useJourneyDetail.ts": 3,
"src/pages/sharedTrip/SharedPlanView.tsx": 1, "src/pages/sharedTrip/SharedPlanView.tsx": 1,
+6 -13
View File
@@ -21,7 +21,6 @@
"components/Collections/CollectionHero.tsx": 1, "components/Collections/CollectionHero.tsx": 1,
"components/Collections/MSaveToCollectionSheet.tsx": 12, "components/Collections/MSaveToCollectionSheet.tsx": 12,
"components/Collections/StatusBadge.tsx": 4, "components/Collections/StatusBadge.tsx": 4,
"components/Dawarich/DawarichAtlasDialog.tsx": 3,
"components/Files/FileManagerAvatarChip.tsx": 1, "components/Files/FileManagerAvatarChip.tsx": 1,
"components/Files/FileManagerImageLightbox.tsx": 8, "components/Files/FileManagerImageLightbox.tsx": 8,
"components/Journey/ContributorInviteDialog.tsx": 76, "components/Journey/ContributorInviteDialog.tsx": 76,
@@ -45,7 +44,7 @@
"components/Journey/JourneyMapGL.tsx": 5, "components/Journey/JourneyMapGL.tsx": 5,
"components/Journey/MobileEntryView.tsx": 94, "components/Journey/MobileEntryView.tsx": 94,
"components/Journey/MobileMapTimeline.tsx": 8, "components/Journey/MobileMapTimeline.tsx": 8,
"components/Journey/PhotoLightbox.tsx": 13, "components/Journey/PhotoLightbox.tsx": 11,
"components/Journey/VideoPlayer.tsx": 2, "components/Journey/VideoPlayer.tsx": 2,
"components/Journey/VideoPlayerLazy.tsx": 1, "components/Journey/VideoPlayerLazy.tsx": 1,
"components/Journey/journeyMapPopup.ts": 17, "components/Journey/journeyMapPopup.ts": 17,
@@ -60,8 +59,8 @@
"components/Map/LocationButton.tsx": 1, "components/Map/LocationButton.tsx": 1,
"components/Map/MapPluginMarkers.tsx": 2, "components/Map/MapPluginMarkers.tsx": 2,
"components/Map/MapTogglePill.tsx": 1, "components/Map/MapTogglePill.tsx": 1,
"components/Map/MapView.tsx": 7, "components/Map/MapView.tsx": 5,
"components/Map/MapViewGL.tsx": 10, "components/Map/MapViewGL.tsx": 8,
"components/Map/NightPauseTooltip.tsx": 1, "components/Map/NightPauseTooltip.tsx": 1,
"components/Map/PlaceHoverCard.tsx": 1, "components/Map/PlaceHoverCard.tsx": 1,
"components/Map/ReservationOverlay.tsx": 5, "components/Map/ReservationOverlay.tsx": 5,
@@ -163,11 +162,8 @@
"mobile/screens/admin/MAdminUi.tsx": 7, "mobile/screens/admin/MAdminUi.tsx": 7,
"mobile/screens/admin/MAdminUsersSection.tsx": 13, "mobile/screens/admin/MAdminUsersSection.tsx": 13,
"mobile/screens/admin/MApiProviderBlocks.tsx": 10, "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/MAtlasCountryPopup.tsx": 11,
"mobile/screens/atlas/MAtlasSearch.tsx": 5, "mobile/screens/atlas/MAtlasStatsCard.tsx": 2,
"mobile/screens/atlas/MAtlasStatsCard.tsx": 3,
"mobile/screens/collections/MCollAddSheet.tsx": 6, "mobile/screens/collections/MCollAddSheet.tsx": 6,
"mobile/screens/collections/MCollCategoryPicker.tsx": 2, "mobile/screens/collections/MCollCategoryPicker.tsx": 2,
"mobile/screens/collections/MCollEditSheet.tsx": 2, "mobile/screens/collections/MCollEditSheet.tsx": 2,
@@ -175,11 +171,10 @@
"mobile/screens/collections/MCollLinksEditor.tsx": 2, "mobile/screens/collections/MCollLinksEditor.tsx": 2,
"mobile/screens/collections/MCollListPickerSheet.tsx": 3, "mobile/screens/collections/MCollListPickerSheet.tsx": 3,
"mobile/screens/collections/MCollPlaceRow.tsx": 3, "mobile/screens/collections/MCollPlaceRow.tsx": 3,
"mobile/screens/collections/MCollPlaceSheet.tsx": 11,
"mobile/screens/collections/MCollShareSheet.tsx": 14, "mobile/screens/collections/MCollShareSheet.tsx": 14,
"mobile/screens/collections/MCollSheetKit.tsx": 5, "mobile/screens/collections/MCollSheetKit.tsx": 5,
"mobile/screens/collections/MCollTripPickerSheet.tsx": 4, "mobile/screens/collections/MCollTripPickerSheet.tsx": 4,
"mobile/screens/collections/MCollections.tsx": 13, "mobile/screens/collections/MCollections.tsx": 9,
"mobile/screens/dashboard/MDashWidgets.tsx": 22, "mobile/screens/dashboard/MDashWidgets.tsx": 22,
"mobile/screens/dashboard/MDashboard.tsx": 30, "mobile/screens/dashboard/MDashboard.tsx": 30,
"mobile/screens/dashboard/MNewTripSheet.tsx": 12, "mobile/screens/dashboard/MNewTripSheet.tsx": 12,
@@ -262,7 +257,7 @@
"mobile/screens/trip/tabs/MCollabTab.tsx": 1, "mobile/screens/trip/tabs/MCollabTab.tsx": 1,
"mobile/screens/trip/tabs/MCostsTab.tsx": 70, "mobile/screens/trip/tabs/MCostsTab.tsx": 70,
"mobile/screens/trip/tabs/MDocSyncSheet.tsx": 43, "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/MFileLinkSheet.tsx": 2,
"mobile/screens/trip/tabs/MFileMenuSheet.tsx": 1, "mobile/screens/trip/tabs/MFileMenuSheet.tsx": 1,
"mobile/screens/trip/tabs/MFileTrashSheet.tsx": 4, "mobile/screens/trip/tabs/MFileTrashSheet.tsx": 4,
@@ -282,7 +277,6 @@
"mobile/screens/vacay/MVacaySettingsSheet.tsx": 34, "mobile/screens/vacay/MVacaySettingsSheet.tsx": 34,
"mobile/screens/vacay/MVacayShareSheet.tsx": 10, "mobile/screens/vacay/MVacayShareSheet.tsx": 10,
"mobile/screens/vacay/vacayDayModel.ts": 1, "mobile/screens/vacay/vacayDayModel.ts": 1,
"pages/AtlasPage.tsx": 32,
"pages/DashboardPage.tsx": 1, "pages/DashboardPage.tsx": 1,
"pages/FilesPage.tsx": 11, "pages/FilesPage.tsx": 11,
"pages/ForgotPasswordPage.tsx": 18, "pages/ForgotPasswordPage.tsx": 18,
@@ -297,7 +291,6 @@
"pages/ResetPasswordPage.tsx": 23, "pages/ResetPasswordPage.tsx": 23,
"pages/TripPlannerPage.tsx": 7, "pages/TripPlannerPage.tsx": 7,
"pages/VacayPage.tsx": 13, "pages/VacayPage.tsx": 13,
"pages/atlas/useAtlas.ts": 2,
"pages/collections/useCollections.ts": 1, "pages/collections/useCollections.ts": 1,
"pages/login/MfaCodeStep.tsx": 4, "pages/login/MfaCodeStep.tsx": 4,
"pages/sharedTrip/SharedChrome.tsx": 2, "pages/sharedTrip/SharedChrome.tsx": 2,
+7 -6
View File
@@ -2,16 +2,16 @@
"components/Admin/GitHubPanel.tsx": 3, "components/Admin/GitHubPanel.tsx": 3,
"components/Admin/PluginPoiCategoryList.tsx": 1, "components/Admin/PluginPoiCategoryList.tsx": 1,
"components/Admin/useCategoryAdmin.ts": 1, "components/Admin/useCategoryAdmin.ts": 1,
"components/AtlasGlobe/BadgeMedal.tsx": 2,
"components/AtlasGlobe/badgeTiers.ts": 4,
"components/Budget/CostsPanel.tsx": 1, "components/Budget/CostsPanel.tsx": 1,
"components/Budget/CostsToolbar.tsx": 1, "components/Budget/CostsToolbar.tsx": 1,
"components/Collab/CollabNotesFilePreviewPortal.tsx": 3, "components/Collab/CollabNotesFilePreviewPortal.tsx": 3,
"components/Collections/AddPlaceToCollectionModal.tsx": 1,
"components/Collections/BulkAssignLabelModal.tsx": 1, "components/Collections/BulkAssignLabelModal.tsx": 1,
"components/Collections/CollectionPicker.tsx": 1, "components/Collections/CollectionPicker.tsx": 1,
"components/Collections/ImportCollectionModal.tsx": 1, "components/Collections/ImportCollectionModal.tsx": 1,
"components/Collections/MoveToListModal.tsx": 1, "components/Collections/MoveToListModal.tsx": 1,
"components/Collections/SaveTripPlacesToListModal.tsx": 1, "components/Collections/SaveTripPlacesToListModal.tsx": 1,
"components/Dawarich/DawarichAtlasSidePanel.tsx": 1,
"components/Files/FileManagerImageLightbox.tsx": 1, "components/Files/FileManagerImageLightbox.tsx": 1,
"components/Files/FileManagerRow.tsx": 3, "components/Files/FileManagerRow.tsx": 3,
"components/Files/FileManagerToolbar.tsx": 1, "components/Files/FileManagerToolbar.tsx": 1,
@@ -56,11 +56,9 @@
"components/shared/PasswordChecklist.tsx": 2, "components/shared/PasswordChecklist.tsx": 2,
"mobile/components/MSheet.tsx": 1, "mobile/components/MSheet.tsx": 1,
"mobile/components/MWalletButton.tsx": 1, "mobile/components/MWalletButton.tsx": 1,
"mobile/screens/atlas/MAtlas.tsx": 1,
"mobile/screens/atlas/MAtlasCountryPopup.tsx": 2, "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/MCollEditSheet.tsx": 2,
"mobile/screens/collections/MCollPlaceSheet.tsx": 2,
"mobile/screens/collections/MCollShareSheet.tsx": 1, "mobile/screens/collections/MCollShareSheet.tsx": 1,
"mobile/screens/collections/collectionsMobileModel.ts": 15, "mobile/screens/collections/collectionsMobileModel.ts": 15,
"mobile/screens/dashboard/MDashboard.tsx": 3, "mobile/screens/dashboard/MDashboard.tsx": 3,
@@ -71,8 +69,11 @@
"mobile/screens/trip/roadtrip/MRtKindSheet.tsx": 1, "mobile/screens/trip/roadtrip/MRtKindSheet.tsx": 1,
"mobile/screens/trip/roadtrip/MRtStopSheet.tsx": 1, "mobile/screens/trip/roadtrip/MRtStopSheet.tsx": 1,
"mobile/screens/trip/sheets/MCostSheet.tsx": 1, "mobile/screens/trip/sheets/MCostSheet.tsx": 1,
"pages/AtlasPage.tsx": 1,
"pages/admin/AdminUserModals.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/SharedChrome.tsx": 4,
"pages/sharedTrip/SharedMap.tsx": 2 "pages/sharedTrip/SharedMap.tsx": 2
} }
+41 -5
View File
@@ -1,13 +1,13 @@
import React from 'react'
import { render, screen, waitFor, act } from '@testing-library/react' import { render, screen, waitFor, act } from '@testing-library/react'
import { MemoryRouter, useLocation } from 'react-router' 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 { http, HttpResponse } from 'msw'
import { server } from '../tests/helpers/msw/server' import { server } from '../tests/helpers/msw/server'
import { useAuthStore } from './store/authStore' import { useAuthStore } from './store/authStore'
import { useSettingsStore } from './store/settingsStore' import { useSettingsStore } from './store/settingsStore'
import { resetAllStores } from '../tests/helpers/store' import { resetAllStores } from '../tests/helpers/store'
import { buildUser, buildSettings, buildTrip } from '../tests/helpers/factories' import { buildUser, buildSettings, buildTrip } from '../tests/helpers/factories'
import { locationAt } from '../tests/helpers/location'
import { offlineDb } from './db/offlineDb' import { offlineDb } from './db/offlineDb'
import { SETTINGS_WAIT_MS } from './utils/startDestination' import { SETTINGS_WAIT_MS } from './utils/startDestination'
import App from './App' import App from './App'
@@ -185,9 +185,29 @@ describe('RootRedirect — startup destination', () => {
seedAuth({ isAuthenticated: true, user: buildUser() }) seedAuth({ isAuthenticated: true, user: buildUser() })
useSettingsStore.setState({ isLoaded: false }) useSettingsStore.setState({ isLoaded: false })
stubActiveTrip({ id: 42, title: 'Japan' }) 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('/') renderApp('/')
await waitFor(() => expect(screen.getByText('TripPlanner')).toBeInTheDocument()) 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))
}) })
}) })
@@ -436,6 +456,19 @@ describe('App — on-mount effects', () => {
await waitFor(() => expect(setManaged).toHaveBeenCalledWith(false)) await waitFor(() => expect(setManaged).toHaveBeenCalledWith(false))
}) })
it("FE-COMP-APP-018d: the operator's map hosts reach the store the map engine reads", async () => {
server.use(
http.get('/api/auth/app-config', () => HttpResponse.json({ map_extra_connect_hosts: ['tiles.example.com'] }))
)
useAuthStore.setState({
isLoading: false,
isAuthenticated: false,
loadUser: vi.fn().mockResolvedValue(undefined),
})
renderApp('/')
await waitFor(() => expect(useAuthStore.getState().mapExtraConnectHosts).toEqual(['tiles.example.com']))
})
it('FE-COMP-APP-018c: app-config is asked again after a failed answer, so managed is not lost', async () => { it('FE-COMP-APP-018c: app-config is asked again after a failed answer, so managed is not lost', async () => {
// A page opened while the server restarts got a 502 here and kept every // A page opened while the server restarts got a 502 here and kept every
// default for the session, which brought back the operator's settings. // default for the session, which brought back the operator's settings.
@@ -532,7 +565,7 @@ describe('Version cache-busting', () => {
const reload = vi.fn() const reload = vi.fn()
Object.defineProperty(window, 'location', { Object.defineProperty(window, 'location', {
writable: true, writable: true,
value: { ...window.location, reload }, value: locationAt('/', { reload }),
}) })
server.use( server.use(
@@ -587,7 +620,7 @@ describe('Version cache-busting', () => {
// and try to update. // and try to update.
localStorage.setItem('trek_app_version', '2.9.9') localStorage.setItem('trek_app_version', '2.9.9')
const reload = vi.fn() 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( server.use(
http.get('/api/auth/app-config', () => http.get('/api/auth/app-config', () =>
@@ -609,7 +642,7 @@ describe('Version cache-busting', () => {
// failure neither deletes anything nor reloads into the old worker's shell. // failure neither deletes anything nor reloads into the old worker's shell.
localStorage.setItem('trek_app_version', '2.9.9') localStorage.setItem('trek_app_version', '2.9.9')
const reload = vi.fn() 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 cachesDelete = vi.fn().mockResolvedValue(true)
const unregister = vi.fn().mockResolvedValue(true) const unregister = vi.fn().mockResolvedValue(true)
vi.stubGlobal('caches', { keys: vi.fn().mockResolvedValue(['workbox-precache-v2', 'map-tiles']), delete: cachesDelete }) vi.stubGlobal('caches', { keys: vi.fn().mockResolvedValue(['workbox-precache-v2', 'map-tiles']), delete: cachesDelete })
@@ -685,6 +718,9 @@ describe('RootRedirect — preference not mirrored on this device', () => {
vi.useFakeTimers({ shouldAdvanceTime: true }) vi.useFakeTimers({ shouldAdvanceTime: true })
seedAuth({ isAuthenticated: true, user: buildUser() }) seedAuth({ isAuthenticated: true, user: buildUser() })
useSettingsStore.setState({ isLoaded: false }) 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('/') renderApp('/')
expect(screen.queryByText('Dashboard')).not.toBeInTheDocument() expect(screen.queryByText('Dashboard')).not.toBeInTheDocument()
+68 -22
View File
@@ -1,7 +1,9 @@
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 { Routes, Route, Navigate, useLocation, useNavigationType } from 'react-router'
import LegacyCollectionsRedirect from './components/Collections/LegacyCollectionsRedirect'
import { useAuthStore } from './store/authStore' import { useAuthStore } from './store/authStore'
import { useSettingsStore } from './store/settingsStore' import { useSettingsStore } from './store/settingsStore'
import { preloadTripMapRenderer } from './components/Map/glLazy'
import { applyAppearance } from './theme/applyAppearance' import { applyAppearance } from './theme/applyAppearance'
import { useAddonStore } from './store/addonStore' import { useAddonStore } from './store/addonStore'
import { usePluginStore } from './store/pluginStore' import { usePluginStore } from './store/pluginStore'
@@ -17,6 +19,8 @@ import BackgroundTasksWidget from './components/BackgroundTasks/BackgroundTasksW
import MobileShell from './mobile/MobileShell' import MobileShell from './mobile/MobileShell'
import MRouteFallback from './mobile/components/MRouteFallback' import MRouteFallback from './mobile/components/MRouteFallback'
import ErrorBoundary from './components/shared/ErrorBoundary' import ErrorBoundary from './components/shared/ErrorBoundary'
import AppBootScreen from './components/shared/AppBootScreen'
import { endAppBoot, isAppBoot } from './native/appBoot'
import { lazyWithRetry } from './utils/lazyWithRetry' import { lazyWithRetry } from './utils/lazyWithRetry'
import { reconcileAppVersion } from './utils/versionHandover' import { reconcileAppVersion } from './utils/versionHandover'
import { useServerVersionStore } from './store/serverVersionStore' import { useServerVersionStore } from './store/serverVersionStore'
@@ -95,6 +99,26 @@ const MJourneyDetailScreen = lazyWithRetry(() => import('./mobile/screens/journe
const MCollectionsScreen = lazyWithRetry(() => import('./mobile/screens/collections/MCollections')) const MCollectionsScreen = lazyWithRetry(() => import('./mobile/screens/collections/MCollections'))
const MNotificationsScreen = lazyWithRetry(() => import('./mobile/screens/notifications/MNotifications')) const MNotificationsScreen = lazyWithRetry(() => import('./mobile/screens/notifications/MNotifications'))
// The main sections, loaded ahead once signed in and settled, so the first
// switch to one does not wait for its code. A load that fails here is no
// error: the route loads it again when it is opened.
const DESKTOP_SECTIONS = [
() => import('./pages/DashboardPage'),
() => import('./pages/VacayPage'),
() => import('./pages/AtlasPage'),
() => import('./pages/CollectionsPage'),
() => import('./pages/JourneyPage'),
]
const PHONE_SECTIONS = [
() => import('./mobile/screens/dashboard/MDashboard'),
() => import('./mobile/screens/vacay/MVacay'),
() => import('./mobile/screens/atlas/MAtlas'),
() => import('./mobile/screens/collections/MCollections'),
() => import('./mobile/screens/journey/MJourney'),
]
const SECTIONS_AHEAD_AFTER_MS = 1500
function loadedOnOpenInstead(): void {}
interface ProtectedRouteProps { interface ProtectedRouteProps {
children: ReactNode children: ReactNode
adminRequired?: boolean adminRequired?: boolean
@@ -113,6 +137,7 @@ function ProtectedRoute({ children, adminRequired = false, addonId }: ProtectedR
const isPhone = useIsPhone() const isPhone = useIsPhone()
if (isLoading) { if (isLoading) {
if (isAppBoot()) return <AppBootScreen />
return ( return (
<div className="min-h-screen flex items-center justify-center bg-slate-50"> <div className="min-h-screen flex items-center justify-center bg-slate-50">
<div className="flex flex-col items-center gap-3"> <div className="flex flex-col items-center gap-3">
@@ -286,6 +311,7 @@ function RootRedirect() {
}, [isLoading, isAuthenticated, settingsLoaded, settingsGaveUp, settings, target]) }, [isLoading, isAuthenticated, settingsLoaded, settingsGaveUp, settings, target])
if (isLoading || (isAuthenticated && !target)) { if (isLoading || (isAuthenticated && !target)) {
if (isAppBoot()) return <AppBootScreen />
return ( return (
<div className="min-h-screen flex items-center justify-center bg-slate-50"> <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> <div className="w-10 h-10 border-4 border-slate-200 border-t-slate-900 rounded-full animate-spin"></div>
@@ -306,16 +332,17 @@ function RouteFallback() {
// on a phone the desktop spinner on bg-surface would be a foreign white sheet // on a phone the desktop spinner on bg-surface would be a foreign white sheet
// in front of the mobile screen. // in front of the mobile screen.
const isPhone = useIsPhone() const isPhone = useIsPhone()
if (isAppBoot()) return <AppBootScreen />
if (isPhone) return <MRouteFallback /> if (isPhone) return <MRouteFallback />
return ( return (
<div className="min-h-screen flex items-center justify-center bg-surface"> <div data-route-fallback="" className="min-h-screen flex items-center justify-center bg-surface">
<div className="w-10 h-10 border-4 border-edge border-t-content rounded-full animate-spin"></div> <div className="w-10 h-10 border-4 border-edge border-t-content rounded-full animate-spin"></div>
</div> </div>
) )
} }
export default function App() { 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 { loadSettings } = useSettingsStore()
const { loadAddons } = useAddonStore() const { loadAddons } = useAddonStore()
const { loadPlugins } = usePluginStore() const { loadPlugins } = usePluginStore()
@@ -346,7 +373,7 @@ export default function App() {
}, Math.min(30_000, 1_000 * 2 ** attempt)) }, 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; map_extra_connect_hosts?: string[]; 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) setManaged(!!config?.managed)
setDemoMode(!!config?.demo_mode) setDemoMode(!!config?.demo_mode)
if (config?.dev_mode) setDevMode(true) if (config?.dev_mode) setDevMode(true)
@@ -354,10 +381,12 @@ export default function App() {
if (config?.version) setAppVersion(config.version) if (config?.version) setAppVersion(config.version)
if (config?.has_maps_key !== undefined) setHasMapsKey(config.has_maps_key) if (config?.has_maps_key !== undefined) setHasMapsKey(config.has_maps_key)
if (config?.has_amap_key !== undefined) setHasAmapKey(config.has_amap_key) if (config?.has_amap_key !== undefined) setHasAmapKey(config.has_amap_key)
if (Array.isArray(config?.map_extra_connect_hosts)) useAuthStore.getState().setMapExtraConnectHosts(config.map_extra_connect_hosts)
if (config?.places_provider) setPlacesProvider(config.places_provider) if (config?.places_provider) setPlacesProvider(config.places_provider)
if (config?.timezone) setServerTimezone(config.timezone) if (config?.timezone) setServerTimezone(config.timezone)
if (config?.require_mfa !== undefined) setAppRequireMfa(!!config.require_mfa) if (config?.require_mfa !== undefined) setAppRequireMfa(!!config.require_mfa)
if (config?.trip_reminders_enabled !== undefined) setTripRemindersEnabled(config.trip_reminders_enabled) 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_photos_enabled !== undefined) setPlacesPhotosEnabled(config.places_photos_enabled)
if (config?.places_autocomplete_enabled !== undefined) setPlacesAutocompleteEnabled(config.places_autocomplete_enabled) if (config?.places_autocomplete_enabled !== undefined) setPlacesAutocompleteEnabled(config.places_autocomplete_enabled)
if (config?.places_details_enabled !== undefined) setPlacesDetailsEnabled(config.places_details_enabled) if (config?.places_details_enabled !== undefined) setPlacesDetailsEnabled(config.places_details_enabled)
@@ -378,6 +407,10 @@ export default function App() {
const { settings } = useSettingsStore() const { settings } = useSettingsStore()
useEffect(() => {
if (isAuthenticated) preloadTripMapRenderer(settings.map_provider, settings.mapbox_access_token)
}, [isAuthenticated, settings.map_provider, settings.mapbox_access_token])
useInAppNotificationListener() useInAppNotificationListener()
useRoadtripPreferencesSync() useRoadtripPreferencesSync()
useTripAddonsSync() useTripAddonsSync()
@@ -398,6 +431,12 @@ export default function App() {
const location = useLocation() const location = useLocation()
const isSharedPage = location.pathname.startsWith('/shared/') 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(() => { useEffect(() => {
const run = () => const run = () =>
applyAppearance({ applyAppearance({
@@ -416,9 +455,18 @@ export default function App() {
}, [settings.dark_mode, settings.appearance, isSharedPage]) }, [settings.dark_mode, settings.appearance, isSharedPage])
const isPhone = useIsPhone() const isPhone = useIsPhone()
// On the phone, pages slide like a native navigation stack (mobile/routeTransition.ts). // On the phone, pages slide like a native navigation stack; on the desktop they
// cross-fade under a navbar that stands still (mobile/routeTransition.ts).
const navigationType = useNavigationType() const navigationType = useNavigationType()
const routedLocation = useRouteTransition(location, navigationType, isPhone) const routedLocation = useRouteTransition(location, navigationType, isPhone ? 'phone' : 'desktop')
useEffect(() => {
if (!isAuthenticated) return
const timer = window.setTimeout(() => {
for (const load of isPhone ? PHONE_SECTIONS : DESKTOP_SECTIONS) load().catch(loadedOnOpenInstead)
}, SECTIONS_AHEAD_AFTER_MS)
return () => window.clearTimeout(timer)
}, [isAuthenticated, isPhone])
const keepingTour = useSaveToCollectionStore(s => s.tour !== null) const keepingTour = useSaveToCollectionStore(s => s.tour !== null)
const isAuthPage = location.pathname.startsWith('/login') const isAuthPage = location.pathname.startsWith('/login')
|| location.pathname.startsWith('/register') || location.pathname.startsWith('/register')
@@ -596,22 +644,20 @@ export default function App() {
journey, not navigated away to. */} journey, not navigated away to. */}
<Route path="studio" element={<JourneyStudioPage />} /> <Route path="studio" element={<JourneyStudioPage />} />
</Route> </Route>
<Route {['/places', '/places/saved', '/places/:id'].map(path => (
path="/collections" <Route
element={ key={path}
<ProtectedRoute addonId="collections"> path={path}
<ViewportRoute phone={MCollectionsScreen} desktop={CollectionsPage} /> element={
</ProtectedRoute> <ProtectedRoute addonId="collections">
} <ViewportRoute phone={MCollectionsScreen} desktop={CollectionsPage} />
/> </ProtectedRoute>
<Route }
path="/collections/:id" />
element={ ))}
<ProtectedRoute addonId="collections"> {/* Collections became Places (PLC-07); the old links keep working. */}
<ViewportRoute phone={MCollectionsScreen} desktop={CollectionsPage} /> <Route path="/collections" element={<LegacyCollectionsRedirect />} />
</ProtectedRoute> <Route path="/collections/:id" element={<LegacyCollectionsRedirect />} />
}
/>
<Route <Route
path="/notifications" path="/notifications"
element={ element={
-1
View File
@@ -1,4 +1,3 @@
import React from 'react'
import { render, waitFor, act } from '@testing-library/react' import { render, waitFor, act } from '@testing-library/react'
import { MemoryRouter } from 'react-router' import { MemoryRouter } from 'react-router'
import { describe, it, expect, beforeEach, vi } from 'vitest' import { describe, it, expect, beforeEach, vi } from 'vitest'
+4 -1
View File
@@ -1,4 +1,3 @@
import React from 'react'
import { render, screen } from '@testing-library/react' import { render, screen } from '@testing-library/react'
import { MemoryRouter } from 'react-router' import { MemoryRouter } from 'react-router'
import { describe, it, expect, beforeEach, vi } from 'vitest' import { describe, it, expect, beforeEach, vi } from 'vitest'
@@ -57,6 +56,10 @@ const ROUTES: [string, string, string][] = [
['/atlas', 'm-atlas', 'd-atlas'], ['/atlas', 'm-atlas', 'd-atlas'],
['/journey', 'm-journey', 'd-journey'], ['/journey', 'm-journey', 'd-journey'],
['/journey/1', 'm-journey-detail', 'd-journey-detail'], ['/journey/1', 'm-journey-detail', 'd-journey-detail'],
['/places', 'm-collections', 'd-collections'],
['/places/saved', 'm-collections', 'd-collections'],
['/places/1', 'm-collections', 'd-collections'],
// The old Collections links land in Places (PLC-07).
['/collections', 'm-collections', 'd-collections'], ['/collections', 'm-collections', 'd-collections'],
['/collections/1', 'm-collections', 'd-collections'], ['/collections/1', 'm-collections', 'd-collections'],
['/notifications', 'm-notifications', 'd-notifications'], ['/notifications', 'm-notifications', 'd-notifications'],
+47 -1
View File
@@ -1,4 +1,4 @@
// FE-API-COLLECTIONS-001 to FE-API-COLLECTIONS-035 // FE-API-COLLECTIONS-001 to FE-API-COLLECTIONS-038
// //
// The Collections addon wrapper is thin, but every method encodes a URL, a verb and a // The Collections addon wrapper is thin, but every method encodes a URL, a verb and a
// request-body shape that the server contract depends on. These tests drive each method // request-body shape that the server contract depends on. These tests drive each method
@@ -370,4 +370,50 @@ describe('collectionsApi', () => {
expect(requestBody).toEqual({ gpx: '<gpx/>', file_name: 'tokyo.gpx' }) expect(requestBody).toEqual({ gpx: '<gpx/>', file_name: 'tokyo.gpx' })
expect(res).toEqual({ file, skipped: 0, track_points: 12 }) expect(res).toEqual({ file, skipped: 0, track_points: 12 })
}) })
it('FE-API-COLLECTIONS-036: copyToTrip() passes the notes and tags a copy takes along (D9)', async () => {
server.use(http.post(`${BASE}/copy-to-trip`, record({ copied: 1, skipped: [], created: [] })))
await collectionsApi.copyToTrip({ trip_id: 7, place_ids: [10], include_notes: true, tag_ids: [4] })
expect(requestBody).toEqual({ trip_id: 7, place_ids: [10], include_notes: true, tag_ids: [4] })
})
it('FE-API-COLLECTIONS-037: reorderPlaces() puts the ordered ids of a list (PLC-03)', async () => {
let method = ''
server.use(
http.put(`${BASE}/:id/places/reorder`, async (info) => {
method = info.request.method
return record({ success: true })(info)
}),
)
const res = await collectionsApi.reorderPlaces(1, [11, 10])
expect(method).toBe('PUT')
expect(requestUrl).toContain(`${BASE}/1/places/reorder`)
expect(requestBody).toEqual({ orderedIds: [11, 10] })
expect(res).toEqual({ success: true })
})
it('FE-API-COLLECTIONS-038: readMap() uploads the map file as multipart and returns the list file (PLC-22)', async () => {
const read = {
file: { format: 'trek.collection', version: 1, name: 'Lisbon', places: [{ name: 'Miradouro' }] },
folders: ['Views'],
skipped: [{ name: 'Tram 28', folder: null, reason: 'line' }],
}
let contentType: string | null = null
server.use(
// jsdom cannot read a multipart body back, so the header says what was sent.
http.post(`${BASE}/map/read`, ({ request }) => {
contentType = request.headers.get('content-type')
return HttpResponse.json(read)
}),
)
const res = await collectionsApi.readMap(new File(['<kml/>'], 'lisbon.kml'))
expect(contentType).toMatch(/^multipart\/form-data/)
expect(res).toEqual(read)
})
}) })
+12
View File
@@ -18,6 +18,8 @@ import type {
CollectionGpxReadRequest, CollectionGpxReadRequest,
CollectionGpxReadResult, CollectionGpxReadResult,
CollectionKmlExport, CollectionKmlExport,
CollectionMapReadResult,
CollectionPlacesReorderRequest,
CollectionPlaceUpdateRequest, CollectionPlaceUpdateRequest,
CollectionCopyToTripRequest, CollectionCopyToTripRequest,
CollectionInviteRequest, CollectionInviteRequest,
@@ -76,6 +78,12 @@ export const collectionsApi = {
ax.get(`${base}/${id}/export/gpx`).then((r: AxiosResponse) => r.data), ax.get(`${base}/${id}/export/gpx`).then((r: AxiosResponse) => r.data),
readGpx: (body: CollectionGpxReadRequest): Promise<CollectionGpxReadResult> => readGpx: (body: CollectionGpxReadRequest): Promise<CollectionGpxReadResult> =>
ax.post(`${base}/gpx/read`, body satisfies CollectionGpxReadRequest).then((r: AxiosResponse) => r.data), ax.post(`${base}/gpx/read`, body satisfies CollectionGpxReadRequest).then((r: AxiosResponse) => r.data),
/** A KML or KMZ map (PLC-22) read by the server into a list file; it writes nothing, importFile(Into) does. */
readMap: (file: File): Promise<CollectionMapReadResult> => {
const fd = new FormData()
fd.append('file', file)
return postMultipart(`${base}/map/read`, fd)
},
/** The same list as pins for Google My Maps (#1866). */ /** The same list as pins for Google My Maps (#1866). */
exportKml: (id: number): Promise<CollectionKmlExport> => exportKml: (id: number): Promise<CollectionKmlExport> =>
ax.get(`${base}/${id}/export/kml`).then((r: AxiosResponse) => r.data), ax.get(`${base}/${id}/export/kml`).then((r: AxiosResponse) => r.data),
@@ -94,6 +102,10 @@ export const collectionsApi = {
reorder: (orderedIds: number[]): Promise<unknown> => reorder: (orderedIds: number[]): Promise<unknown> =>
ax.post(`${base}/reorder`, { orderedIds }).then((r: AxiosResponse) => r.data), ax.post(`${base}/reorder`, { orderedIds }).then((r: AxiosResponse) => r.data),
/** A list's places in a new order (PLC-03): every id a place of that list, the ones left out follow. */
reorderPlaces: (id: number, orderedIds: number[]): Promise<{ success: true }> =>
ax.put(`${base}/${id}/places/reorder`, { orderedIds } satisfies CollectionPlacesReorderRequest).then((r: AxiosResponse) => r.data),
savePlace: (body: CollectionSavePlaceRequest): Promise<CollectionSaveResult> => savePlace: (body: CollectionSavePlaceRequest): Promise<CollectionSaveResult> =>
ax.post(`${base}/places`, body satisfies CollectionSavePlaceRequest).then((r: AxiosResponse) => r.data), ax.post(`${base}/places`, body satisfies CollectionSavePlaceRequest).then((r: AxiosResponse) => r.data),
saveFromTrip: (body: CollectionSaveFromTripRequest): Promise<CollectionSaveResult> => saveFromTrip: (body: CollectionSaveFromTripRequest): Promise<CollectionSaveResult> =>
+63
View File
@@ -0,0 +1,63 @@
// FE-API-PLACE-ACTIVITIES-001
//
// PLC-18: each method pins its verb, its path and its body.
import { http, HttpResponse } from 'msw';
import { beforeEach, describe, expect, it } from 'vitest';
import { server } from '../../tests/helpers/msw/server';
import { placeActivitiesApi } from './placeActivities';
const activities = { activities: [], can_link: true };
const candidates = { candidates: [] };
const entry = { activities: [], sources: [] };
let calls: Array<[string, string, unknown]> = [];
beforeEach(() => {
calls = [];
});
function record(data: object) {
return async ({ request }: { request: Request }) => {
const text = request.method === 'POST' ? await request.text() : '';
calls.push([request.method, new URL(request.url).pathname, text ? JSON.parse(text) : null]);
return HttpResponse.json(data);
};
}
describe('placeActivitiesApi', () => {
it('FE-API-PLACE-ACTIVITIES-001: reads, links and unlinks the activities of trip places, saved places and entries', async () => {
server.use(
http.get('/api/trips/4/places/7/activities', record(activities)),
http.get('/api/trips/4/places/7/activities/candidates', record(candidates)),
http.post('/api/trips/4/places/7/activities', record(activities)),
http.delete('/api/trips/4/places/7/activities/reservations/9', record(activities)),
http.delete('/api/trips/4/places/7/activities/tours/11', record(activities)),
http.get('/api/addons/collections/places/8/activities', record(activities)),
http.get('/api/addons/collections/places/8/activities/candidates', record(candidates)),
http.post('/api/addons/collections/places/8/activities', record(activities)),
http.delete('/api/addons/collections/places/8/activities/tours/5', record(activities)),
http.get('/api/addons/collections/library/places/list/8/activities', record(entry))
);
expect(await placeActivitiesApi.tripPlace(4, 7)).toEqual(activities);
expect(await placeActivitiesApi.tripCandidates(4, 7)).toEqual(candidates);
expect(await placeActivitiesApi.linkTrip(4, 7, { reservation_id: 9 })).toEqual(activities);
expect(await placeActivitiesApi.unlinkTripBooking(4, 7, 9)).toEqual(activities);
expect(await placeActivitiesApi.unlinkTripTour(4, 7, 11)).toEqual(activities);
expect(await placeActivitiesApi.savedPlace(8)).toEqual(activities);
expect(await placeActivitiesApi.savedCandidates(8)).toEqual(candidates);
expect(await placeActivitiesApi.linkSaved(8, 5)).toEqual(activities);
expect(await placeActivitiesApi.unlinkSaved(8, 5)).toEqual(activities);
expect(await placeActivitiesApi.libraryEntry('list', 8)).toEqual(entry);
expect(calls).toEqual([
['GET', '/api/trips/4/places/7/activities', null],
['GET', '/api/trips/4/places/7/activities/candidates', null],
['POST', '/api/trips/4/places/7/activities', { reservation_id: 9 }],
['DELETE', '/api/trips/4/places/7/activities/reservations/9', null],
['DELETE', '/api/trips/4/places/7/activities/tours/11', null],
['GET', '/api/addons/collections/places/8/activities', null],
['GET', '/api/addons/collections/places/8/activities/candidates', null],
['POST', '/api/addons/collections/places/8/activities', { collection_tour_id: 5 }],
['DELETE', '/api/addons/collections/places/8/activities/tours/5', null],
['GET', '/api/addons/collections/library/places/list/8/activities', null],
]);
});
});
+41
View File
@@ -0,0 +1,41 @@
import type {
PlaceActivitiesResponse,
PlaceActivityCandidatesResponse,
PlaceLibraryActivitiesResponse,
PlacesLibraryKind,
TripPlaceActivityLinkRequest,
} from '@trek/shared';
import apiClient from './client';
const tripBase = (tripId: number, placeId: number) => `/trips/${tripId}/places/${placeId}/activities`;
const savedBase = (collectionPlaceId: number) => `/addons/collections/places/${collectionPlaceId}/activities`;
/**
* PLC-18: the bookings and tours a place is about. A trip place links bookings
* and tours of its trip, a saved place tours kept in its list; an entry of All
* places reads them over every origin it has. Unlinking takes only the link off.
*/
export const placeActivitiesApi = {
tripPlace: (tripId: number, placeId: number, signal?: AbortSignal): Promise<PlaceActivitiesResponse> =>
apiClient.get(tripBase(tripId, placeId), { signal }).then((r) => r.data),
tripCandidates: (tripId: number, placeId: number, signal?: AbortSignal): Promise<PlaceActivityCandidatesResponse> =>
apiClient.get(`${tripBase(tripId, placeId)}/candidates`, { signal }).then((r) => r.data),
linkTrip: (tripId: number, placeId: number, body: TripPlaceActivityLinkRequest): Promise<PlaceActivitiesResponse> =>
apiClient.post(tripBase(tripId, placeId), body).then((r) => r.data),
unlinkTripBooking: (tripId: number, placeId: number, reservationId: number): Promise<PlaceActivitiesResponse> =>
apiClient.delete(`${tripBase(tripId, placeId)}/reservations/${reservationId}`).then((r) => r.data),
unlinkTripTour: (tripId: number, placeId: number, tourId: number): Promise<PlaceActivitiesResponse> =>
apiClient.delete(`${tripBase(tripId, placeId)}/tours/${tourId}`).then((r) => r.data),
savedPlace: (collectionPlaceId: number, signal?: AbortSignal): Promise<PlaceActivitiesResponse> =>
apiClient.get(savedBase(collectionPlaceId), { signal }).then((r) => r.data),
savedCandidates: (collectionPlaceId: number, signal?: AbortSignal): Promise<PlaceActivityCandidatesResponse> =>
apiClient.get(`${savedBase(collectionPlaceId)}/candidates`, { signal }).then((r) => r.data),
linkSaved: (collectionPlaceId: number, collectionTourId: number): Promise<PlaceActivitiesResponse> =>
apiClient.post(savedBase(collectionPlaceId), { collection_tour_id: collectionTourId }).then((r) => r.data),
unlinkSaved: (collectionPlaceId: number, collectionTourId: number): Promise<PlaceActivitiesResponse> =>
apiClient.delete(`${savedBase(collectionPlaceId)}/tours/${collectionTourId}`).then((r) => r.data),
libraryEntry: (kind: PlacesLibraryKind, id: number, signal?: AbortSignal): Promise<PlaceLibraryActivitiesResponse> =>
apiClient.get(`/addons/collections/library/places/${kind}/${id}/activities`, { signal }).then((r) => r.data),
};
+29
View File
@@ -0,0 +1,29 @@
// FE-API-PLACE-HISTORY-001
//
// PLC-14: the history pins its verb, its path and its query, and hands back
// what the server answered.
import { http, HttpResponse } from 'msw';
import { describe, expect, it } from 'vitest';
import { server } from '../../tests/helpers/msw/server';
import { placeHistoryApi } from './placeHistory';
const BASE = '/api/addons/collections/library/places';
describe('placeHistoryApi', () => {
it('FE-API-PLACE-HISTORY-001: reads the history of the trip place or saved place it names, page by page', async () => {
const calls: Array<{ path: string; query: Record<string, string> }> = [];
const page = { entries: [], next_cursor: null };
const record = ({ request }: { request: Request }) => {
const url = new URL(request.url);
calls.push({ path: url.pathname, query: Object.fromEntries(url.searchParams) });
return HttpResponse.json(page);
};
server.use(http.get(`${BASE}/trip/4/history`, record), http.get(`${BASE}/list/9/history`, record));
expect(await placeHistoryApi.history('trip', 4)).toEqual(page);
expect(await placeHistoryApi.history('list', 9, { cursor: '12', limit: 20 })).toEqual(page);
expect(calls).toEqual([
{ path: `${BASE}/trip/4/history`, query: {} },
{ path: `${BASE}/list/9/history`, query: { cursor: '12', limit: '20' } },
]);
});
});
+15
View File
@@ -0,0 +1,15 @@
import type { PlaceHistoryPageResponse, PlaceHistoryQueryInput, PlacesLibraryKind } from '@trek/shared';
import apiClient from './client';
const base = '/addons/collections/library/places';
/** PLC-14: what changed in the details of an entry of All places, opened from a trip place or a saved place. */
export const placeHistoryApi = {
history: (
kind: PlacesLibraryKind,
id: number,
query: PlaceHistoryQueryInput = {},
signal?: AbortSignal
): Promise<PlaceHistoryPageResponse> =>
apiClient.get(`${base}/${kind}/${id}/history`, { params: query, signal }).then((r) => r.data),
};
+57
View File
@@ -0,0 +1,57 @@
// FE-API-PLACE-IDENTITIES-001 to FE-API-PLACE-IDENTITIES-002
//
// D5/PLC-13: each method pins its verb, its path and its body or query, and
// hands back what the server answered.
import { http, HttpResponse } from 'msw';
import { beforeEach, describe, expect, it } from 'vitest';
import { server } from '../../tests/helpers/msw/server';
import { placeIdentitiesApi } from './placeIdentities';
const BASE = '/api/addons/collections/library';
let calls: Array<[string, string, Record<string, string>, unknown]> = [];
beforeEach(() => {
calls = [];
});
function record(data: object) {
return async ({ request }: { request: Request }) => {
const url = new URL(request.url);
const text = request.method === 'GET' ? '' : await request.text();
calls.push([request.method, url.pathname, Object.fromEntries(url.searchParams), text ? JSON.parse(text) : null]);
return HttpResponse.json(data);
};
}
describe('placeIdentitiesApi', () => {
it('FE-API-PLACE-IDENTITIES-001: links and unlinks uses of an own place', async () => {
const answer = { entry: null };
server.use(http.post(`${BASE}/places/link`, record(answer)), http.post(`${BASE}/places/unlink`, record(answer)));
expect(await placeIdentitiesApi.link({ uses: [{ kind: 'trip', id: 3 }], identity_id: 2 })).toEqual(answer);
expect(await placeIdentitiesApi.unlink({ kind: 'list', id: 4 })).toEqual(answer);
expect(calls).toEqual([
['POST', `${BASE}/places/link`, {}, { uses: [{ kind: 'trip', id: 3 }], identity_id: 2 }],
['POST', `${BASE}/places/unlink`, {}, { kind: 'list', id: 4 }],
]);
});
it('FE-API-PLACE-IDENTITIES-002: reads duplicates, dismisses, merges and undoes', async () => {
server.use(
http.get(`${BASE}/duplicates`, record({ duplicates: [], next_cursor: null })),
http.post(`${BASE}/duplicates/dismiss`, record({ success: true })),
http.post(`${BASE}/merges`, record({ merge_id: 5, entry: null })),
http.post(`${BASE}/merges/5/undo`, record({ success: true }))
);
expect(await placeIdentitiesApi.duplicates({ limit: 10 })).toEqual({ duplicates: [], next_cursor: null });
expect(await placeIdentitiesApi.dismiss('trip:1', 'list:2')).toEqual({ success: true });
expect(await placeIdentitiesApi.merge('trip:1', 'list:2')).toEqual({ merge_id: 5, entry: null });
expect(await placeIdentitiesApi.undoMerge(5)).toEqual({ success: true });
expect(calls).toEqual([
['GET', `${BASE}/duplicates`, { limit: '10' }, null],
['POST', `${BASE}/duplicates/dismiss`, {}, { a: 'trip:1', b: 'list:2' }],
['POST', `${BASE}/merges`, {}, { leading: 'trip:1', other: 'list:2' }],
['POST', `${BASE}/merges/5/undo`, {}, null],
]);
});
});
+31
View File
@@ -0,0 +1,31 @@
import type {
PlacesLibraryDuplicatesQueryInput,
PlacesLibraryDuplicatesResponse,
PlacesLibraryEntryResponse,
PlacesLibraryLinkRequest,
PlacesLibraryMergeResponse,
PlacesLibraryUse,
SuccessResponse,
} from '@trek/shared';
import apiClient from './client';
const base = '/addons/collections/library';
/** D5/PLC-13: the user's own places in "All places", the duplicate suggestions and merges. */
export const placeIdentitiesApi = {
link: (body: PlacesLibraryLinkRequest): Promise<PlacesLibraryEntryResponse> =>
apiClient.post(`${base}/places/link`, body).then((r) => r.data),
unlink: (use: PlacesLibraryUse): Promise<PlacesLibraryEntryResponse> =>
apiClient.post(`${base}/places/unlink`, use).then((r) => r.data),
duplicates: (
query: PlacesLibraryDuplicatesQueryInput = {},
signal?: AbortSignal
): Promise<PlacesLibraryDuplicatesResponse> =>
apiClient.get(`${base}/duplicates`, { params: query, signal }).then((r) => r.data),
dismiss: (a: string, b: string): Promise<SuccessResponse> =>
apiClient.post(`${base}/duplicates/dismiss`, { a, b }).then((r) => r.data),
merge: (leading: string, other: string): Promise<PlacesLibraryMergeResponse> =>
apiClient.post(`${base}/merges`, { leading, other }).then((r) => r.data),
undoMerge: (mergeId: number): Promise<SuccessResponse> =>
apiClient.post(`${base}/merges/${mergeId}/undo`).then((r) => r.data),
};
+48
View File
@@ -0,0 +1,48 @@
// FE-API-PLACE-VISITS-001
//
// D7/PLC-10 to PLC-23: each read pins its verb, its path and its query; there is nothing to write.
import { http, HttpResponse } from 'msw';
import { beforeEach, describe, expect, it } from 'vitest';
import { server } from '../../tests/helpers/msw/server';
import { placeVisitsApi } from './placeVisits';
let calls: Array<[string, string]> = [];
beforeEach(() => {
calls = [];
});
function record(data: object) {
return ({ request }: { request: Request }) => {
const url = new URL(request.url);
calls.push([request.method, `${url.pathname}${url.search}`]);
return HttpResponse.json(data);
};
}
describe('placeVisitsApi', () => {
it('FE-API-PLACE-VISITS-001: reads the visits and the media at the routes the server serves', async () => {
server.use(
http.get('/api/place-visits', record({ visits: [], total: 0 })),
http.get('/api/place-visits/place', record({ visits: [], visit_count: 0, last_visit: null })),
http.get('/api/trips/4/place-visits/mine', record({ place_ids: [], places: [] })),
http.get(
'/api/addons/collections/library/places/trip/3/media',
record({ images: [], journey_photos: [], files: [] })
)
);
expect(await placeVisitsApi.list({ trip_id: 4 })).toEqual({ visits: [], total: 0 });
expect(await placeVisitsApi.forPlace('trip', 3)).toEqual({ visits: [], visit_count: 0, last_visit: null });
expect(await placeVisitsApi.tripVisited(4)).toEqual({ place_ids: [], places: [] });
expect(await placeVisitsApi.media('trip', 3)).toEqual({ images: [], journey_photos: [], files: [] });
expect(Object.keys(placeVisitsApi).sort()).toEqual(['forPlace', 'list', 'media', 'tripVisited']);
expect(calls).toEqual([
['GET', '/api/place-visits?trip_id=4'],
['GET', '/api/place-visits/place?kind=trip&id=3'],
['GET', '/api/trips/4/place-visits/mine'],
['GET', '/api/addons/collections/library/places/trip/3/media'],
]);
});
});
+25
View File
@@ -0,0 +1,25 @@
import type {
PlaceMediaResponse,
PlacesLibraryKind,
PlaceVisitsForPlaceResponse,
PlaceVisitsListQuery,
PlaceVisitsListResponse,
PlaceVisitTripVisitedResponse,
} from '@trek/shared';
import apiClient from './client';
/**
* D7/PLC-10, PLC-19, PLC-20, PLC-23: the visits the server reads from the
* trips (nothing to write: a visit comes from the trip's plan), the trip
* places visited, and the photos and files of an entry of All places.
*/
export const placeVisitsApi = {
list: (query: PlaceVisitsListQuery = {}, signal?: AbortSignal): Promise<PlaceVisitsListResponse> =>
apiClient.get('/place-visits', { params: query, signal }).then((r) => r.data),
forPlace: (kind: PlacesLibraryKind, id: number, signal?: AbortSignal): Promise<PlaceVisitsForPlaceResponse> =>
apiClient.get('/place-visits/place', { params: { kind, id }, signal }).then((r) => r.data),
tripVisited: (tripId: number, signal?: AbortSignal): Promise<PlaceVisitTripVisitedResponse> =>
apiClient.get(`/trips/${tripId}/place-visits/mine`, { signal }).then((r) => r.data),
media: (kind: PlacesLibraryKind, id: number, signal?: AbortSignal): Promise<PlaceMediaResponse> =>
apiClient.get(`/addons/collections/library/places/${kind}/${id}/media`, { signal }).then((r) => r.data),
};
+73
View File
@@ -0,0 +1,73 @@
// FE-API-PLACES-LIBRARY-001 to FE-API-PLACES-LIBRARY-004
//
// PLC-07/PLC-08: each method pins its verb, its path and its query, and hands
// back what the server answered.
import { http, HttpResponse } from 'msw';
import { beforeEach, describe, expect, it } from 'vitest';
import { server } from '../../tests/helpers/msw/server';
import { placesLibraryApi } from './placesLibrary';
const BASE = '/api/addons/collections/library/places';
const page = { entries: [], total: 0, counts: { all: 0, trip: 0, list: 0 }, next_cursor: null };
let calls: Array<{ path: string; query: Record<string, string> }> = [];
beforeEach(() => {
calls = [];
});
function record(data: object) {
return ({ request }: { request: Request }) => {
const url = new URL(request.url);
calls.push({ path: url.pathname, query: Object.fromEntries(url.searchParams) });
return HttpResponse.json(data);
};
}
describe('placesLibraryApi', () => {
it('FE-API-PLACES-LIBRARY-001: lists a page with the filters as query parameters', async () => {
server.use(http.get(BASE, record(page)));
expect(await placesLibraryApi.list()).toEqual(page);
expect(
await placesLibraryApi.list({ q: 'cafe', kind: 'list', collection_id: 3, limit: 20, cursor: 'abc' })
).toEqual(page);
expect(calls).toEqual([
{ path: BASE, query: {} },
{ path: BASE, query: { q: 'cafe', kind: 'list', collection_id: '3', limit: '20', cursor: 'abc' } },
]);
});
it('FE-API-PLACES-LIBRARY-002: opens one entry by the trip place or the saved place it names', async () => {
const answer = { entry: { key: 'trip:4' }, details: [] };
server.use(http.get(`${BASE}/trip/4`, record(answer)), http.get(`${BASE}/list/9`, record(answer)));
expect(await placesLibraryApi.detail('trip', 4)).toEqual(answer);
expect(await placesLibraryApi.detail('list', 9)).toEqual(answer);
expect(calls.map((call) => call.path)).toEqual([`${BASE}/trip/4`, `${BASE}/list/9`]);
});
it('FE-API-PLACES-LIBRARY-003: sends a tag filter as its names joined by commas, a comma in a name escaped', async () => {
server.use(http.get(BASE, record(page)));
await placesLibraryApi.list({ tags: ['Coffee', 'Food, drinks'], q: 'x' });
await placesLibraryApi.list({ tags: 'View' });
await placesLibraryApi.list({ tags: [] });
expect(calls.map((call) => call.query)).toEqual([{ q: 'x', tags: 'Coffee,Food\\, drinks' }, { tags: 'View' }, {}]);
});
it('FE-API-PLACES-LIBRARY-004: votes by the entry key, PUT with the stars and DELETE with the key to take it back', async () => {
const answer = { key: 'trip:4', rating: { average: 3, count: 1, mine: 3, votes: [] } };
const sent: Array<{ method: string; query: Record<string, string>; body: unknown }> = [];
const handle = async ({ request }: { request: Request }) => {
const url = new URL(request.url);
const body = request.method === 'PUT' ? await request.json() : null;
sent.push({ method: request.method, query: Object.fromEntries(url.searchParams), body });
return HttpResponse.json(answer);
};
server.use(http.put(`${BASE}/rating`, handle), http.delete(`${BASE}/rating`, handle));
expect(await placesLibraryApi.rate('trip:4', 3)).toEqual(answer);
expect(await placesLibraryApi.rate('trip:4', null)).toEqual(answer);
expect(sent).toEqual([
{ method: 'PUT', query: {}, body: { key: 'trip:4', rating: 3 } },
{ method: 'DELETE', query: { key: 'trip:4' }, body: null },
]);
});
});
+35
View File
@@ -0,0 +1,35 @@
import {
joinLibraryTagNames,
type PlacesLibraryDetailResponse,
type PlacesLibraryKind,
type PlacesLibraryPageResponse,
type PlacesLibraryQueryInput,
type PlacesLibraryRateResponse,
} from '@trek/shared';
import apiClient from './client';
const base = '/addons/collections/library/places';
/**
* The query as the server reads it: a tag filter (PLC-21) as its names joined by commas, a comma
* inside a name escaped (`joinLibraryTagNames`), not `tags[]=`.
*/
function queryParams(query: PlacesLibraryQueryInput): Record<string, unknown> {
const { tags, ...rest } = query;
if (tags === undefined) return rest;
const joined = Array.isArray(tags) ? joinLibraryTagNames(tags) : tags;
return joined === '' ? rest : { ...rest, tags: joined };
}
/** PLC-07/PLC-08 "All places": one page of entries, and one entry by the trip place or saved place it was opened from. */
export const placesLibraryApi = {
list: (query: PlacesLibraryQueryInput = {}, signal?: AbortSignal): Promise<PlacesLibraryPageResponse> =>
apiClient.get(base, { params: queryParams(query), signal }).then((r) => r.data),
detail: (kind: PlacesLibraryKind, id: number, signal?: AbortSignal): Promise<PlacesLibraryDetailResponse> =>
apiClient.get(`${base}/${kind}/${id}`, { signal }).then((r) => r.data),
/** The reader's vote on an entry, on every copy of it they may vote on; null takes it back. */
rate: (key: string, rating: number | null): Promise<PlacesLibraryRateResponse> =>
rating === null
? apiClient.delete(`${base}/rating`, { params: { key } }).then((r) => r.data)
: apiClient.put(`${base}/rating`, { key, rating }).then((r) => r.data),
};
+43
View File
@@ -0,0 +1,43 @@
// FE-API-TRIP-COLLECTIONS-001
//
// PLC-15/PLC-16: each method pins its verb, its path and its body.
import { http, HttpResponse } from 'msw';
import { beforeEach, describe, expect, it } from 'vitest';
import { server } from '../../tests/helpers/msw/server';
import { tripCollectionsApi } from './tripCollections';
const links = { links: [], can_link: true };
let calls: Array<[string, string, unknown]> = [];
beforeEach(() => {
calls = [];
});
function record(data: object) {
return async ({ request }: { request: Request }) => {
const text = request.method === 'POST' ? await request.text() : '';
calls.push([request.method, new URL(request.url).pathname, text ? JSON.parse(text) : null]);
return HttpResponse.json(data);
};
}
describe('tripCollectionsApi', () => {
it('FE-API-TRIP-COLLECTIONS-001: lists, maps, links and unlinks the lists of a trip', async () => {
server.use(
http.get('/api/trips/4/collections', record(links)),
http.get('/api/trips/4/collections/places', record({ places: [] })),
http.post('/api/trips/4/collections', record(links)),
http.delete('/api/trips/4/collections/9', record(links))
);
expect(await tripCollectionsApi.list(4)).toEqual(links);
expect(await tripCollectionsApi.layer(4)).toEqual({ places: [] });
expect(await tripCollectionsApi.link(4, 9)).toEqual(links);
expect(await tripCollectionsApi.unlink(4, 9)).toEqual(links);
expect(calls).toEqual([
['GET', '/api/trips/4/collections', null],
['GET', '/api/trips/4/collections/places', null],
['POST', '/api/trips/4/collections', { collection_id: 9 }],
['DELETE', '/api/trips/4/collections/9', null],
]);
});
});
+14
View File
@@ -0,0 +1,14 @@
import type { TripCollectionLayerResponse, TripCollectionLinksResponse } from '@trek/shared';
import apiClient from './client';
/** PLC-15/PLC-16: the lists a trip draws on, and their saved places for the trip map. */
export const tripCollectionsApi = {
list: (tripId: number, signal?: AbortSignal): Promise<TripCollectionLinksResponse> =>
apiClient.get(`/trips/${tripId}/collections`, { signal }).then((r) => r.data),
layer: (tripId: number, signal?: AbortSignal): Promise<TripCollectionLayerResponse> =>
apiClient.get(`/trips/${tripId}/collections/places`, { signal }).then((r) => r.data),
link: (tripId: number, collectionId: number): Promise<TripCollectionLinksResponse> =>
apiClient.post(`/trips/${tripId}/collections`, { collection_id: collectionId }).then((r) => r.data),
unlink: (tripId: number, collectionId: number): Promise<TripCollectionLinksResponse> =>
apiClient.delete(`/trips/${tripId}/collections/${collectionId}`).then((r) => r.data),
};
+37 -3
View File
@@ -1,7 +1,7 @@
// vi.unmock must run before the module is imported (tests/setup.ts mocks it globally) // vi.unmock must run before the module is imported (tests/setup.ts mocks it globally)
vi.unmock('./websocket') vi.unmock('./websocket')
// FE-WSCORE-001 to FE-WSCORE-016 // FE-WSCORE-001 to FE-WSCORE-018
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { http, HttpResponse } from 'msw' import { http, HttpResponse } from 'msw'
import { server } from '../../tests/helpers/msw/server' import { server } from '../../tests/helpers/msw/server'
@@ -135,18 +135,52 @@ describe('websocket > reconnect refetch hook', () => {
) )
}) })
it('FE-WSCORE-005: with no joined trips onopen sends nothing and skips the refetch', async () => { it('FE-WSCORE-005: with no joined trips onopen sends only its presence and skips the refetch', async () => {
const refetch = vi.fn((_tripId: string) => {}) const refetch = vi.fn((_tripId: string) => {})
setRefetchCallback(refetch) setRefetchCallback(refetch)
const sock = await openSocket() const sock = await openSocket()
sock.onopen!() sock.onopen!()
expect(sock.send).not.toHaveBeenCalled() expect(sock.send.mock.calls.map(([raw]) => JSON.parse(raw).type)).toEqual(['presence'])
expect(refetch).not.toHaveBeenCalled() expect(refetch).not.toHaveBeenCalled()
}) })
}) })
describe('websocket > presence', () => {
function presences(sock: MockWebSocket): unknown[] {
return sock.send.mock.calls.map(([raw]) => JSON.parse(raw)).filter(m => m.type === 'presence').map(m => m.visible)
}
function setVisibility(state: 'visible' | 'hidden'): void {
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => state })
document.dispatchEvent(new Event('visibilitychange'))
}
afterEach(() => {
delete (document as { visibilityState?: unknown }).visibilityState
})
it('FE-WSCORE-017: tells the server on open and on every change whether the tab is in front', async () => {
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'visible' })
const sock = await openSocket()
sock.onopen?.()
setVisibility('hidden')
setVisibility('visible')
expect(presences(sock)).toEqual([true, false, true])
})
it('FE-WSCORE-018: stops telling it once logged out', async () => {
const sock = await openSocket()
sock.onopen?.()
disconnect()
setVisibility('hidden')
expect(presences(sock)).toHaveLength(1)
})
})
describe('websocket > connection lifecycle', () => { describe('websocket > connection lifecycle', () => {
it('FE-WSCORE-006: connect() is a no-op while a socket is still CONNECTING', async () => { it('FE-WSCORE-006: connect() is a no-op while a socket is still CONNECTING', async () => {
const sock = await openSocket() const sock = await openSocket()
+14
View File
@@ -129,6 +129,7 @@ async function connectInternal(_isReconnect = false): Promise<void> {
socket.onopen = () => { socket.onopen = () => {
reconnectDelay = 1000 reconnectDelay = 1000
sendPresence()
activeBooks.forEach(journeyId => { activeBooks.forEach(journeyId => {
if (socket && socket.readyState === WebSocket.OPEN) { if (socket && socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify({ type: 'book:join', journeyId })) socket.send(JSON.stringify({ type: 'book:join', journeyId }))
@@ -173,6 +174,17 @@ async function connectInternal(_isReconnect = false): Promise<void> {
} }
} }
/**
* Tells the server whether this tab is in front. Online, in the admin's user
* list, means a tab someone is looking at, not one left open in the
* background, and while one is in front the server keeps the account's
* last activity current.
*/
function sendPresence(): void {
if (!socket || socket.readyState !== WebSocket.OPEN || typeof document === 'undefined') return
socket.send(JSON.stringify({ type: 'presence', visible: document.visibilityState === 'visible' }))
}
/** /**
* The network came back or the tab became visible: a socket waiting out its * The network came back or the tab became visible: a socket waiting out its
* backoff (up to 30 s) reconnects now. Does nothing while logged out or while * backoff (up to 30 s) reconnects now. Does nothing while logged out or while
@@ -186,6 +198,7 @@ export function reconnectNow(): void {
export function connect(): void { export function connect(): void {
shouldReconnect = true shouldReconnect = true
if (typeof document !== 'undefined') document.addEventListener('visibilitychange', sendPresence)
reconnectDelay = 1000 reconnectDelay = 1000
if (reconnectTimer) { if (reconnectTimer) {
clearTimeout(reconnectTimer) clearTimeout(reconnectTimer)
@@ -196,6 +209,7 @@ export function connect(): void {
export function disconnect(): void { export function disconnect(): void {
shouldReconnect = false shouldReconnect = false
if (typeof document !== 'undefined') document.removeEventListener('visibilitychange', sendPresence)
generation++ generation++
if (reconnectTimer) { if (reconnectTimer) {
clearTimeout(reconnectTimer) clearTimeout(reconnectTimer)
+6
View File
@@ -50,6 +50,12 @@ export const HANDLED_OUTSIDE_TRIP_STORE = [
// hooks/useTripAddonsSync) puts the trip's list into the store and the device's copy, so the // hooks/useTripAddonsSync) puts the trip's list into the store and the device's copy, so the
// tabs and panels a trip switched off disappear for every member at once. // tabs and panels a trip switched off disappear for every member at once.
'tripAddons:changed', 'tripAddons:changed',
// Linked lists (PLC-15/PLC-16): store/tripCollectionsStore (watchTripCollections) reads the
// trip's linked lists and map layer again; content-free because each member's answer differs.
'tripCollections:changed',
// Place activities (PLC-18): store/placeActivitiesStore (watchPlaceActivities) reads the
// bookings and tours of the held trip place, and the All places entries it is an origin of, again.
'placeActivities:changed',
// components/Roadtrip/useDayBoundaries reloads the shared boundaries. // components/Roadtrip/useDayBoundaries reloads the shared boundaries.
'roadtripBoundary:changed', 'roadtripBoundary:changed',
// In-app notifications: hooks/useInAppNotificationListener, which also keeps // In-app notifications: hooks/useInAppNotificationListener, which also keeps
@@ -0,0 +1,87 @@
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { server } from '../../../tests/helpers/msw/server';
import { render, screen, waitFor } from '../../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { useAddonStore } from '../../store/addonStore';
import { useAuthStore } from '../../store/authStore';
import { useSettingsStore } from '../../store/settingsStore';
import { ToastContainer } from '../shared/Toast';
import AddonManager from './AddonManager';
// FE-ATLAS2-REST-040 to 042: the Atlas ranking row under the Atlas addon on the desktop admin page.
const RANKING = 'Ranking and profiles';
function atlasAddon(enabled: boolean) {
return { id: 'atlas', name: 'Atlas', description: 'World map', icon: 'Globe', type: 'global', enabled };
}
function isOn(toggle: HTMLElement): boolean {
return toggle.getAttribute('aria-pressed') === 'true';
}
beforeAll(() => {
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: vi.fn(() => ({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() })),
});
});
beforeEach(() => {
resetAllStores();
seedStore(useSettingsStore, { settings: { dark_mode: false } });
useAuthStore.setState({ atlasCompareEnabled: true });
vi.spyOn(useAddonStore.getState(), 'loadAddons').mockResolvedValue(undefined);
server.use(
http.get('/api/admin/tours-wanderer', () => HttpResponse.json({ enabled: false })),
http.get('/api/admin/tours-hiking-map', () => HttpResponse.json({ enabled: false })),
http.get('/api/admin/tours-cycle-map', () => HttpResponse.json({ enabled: false })),
http.get('/api/admin/tours-ski-routing', () => HttpResponse.json({ enabled: false }))
);
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('AddonManager: Atlas ranking', () => {
it('FE-ATLAS2-REST-040: an enabled Atlas shows the ranking row, on as the app config says', async () => {
server.use(http.get('/api/admin/addons', () => HttpResponse.json({ addons: [atlasAddon(true)] })));
render(<AddonManager />);
const toggle = await screen.findByRole('button', { name: RANKING });
expect(isOn(toggle)).toBe(true);
expect(screen.getByText(RANKING)).toHaveAttribute('title', expect.stringContaining('Atlas ranking'));
});
it('FE-ATLAS2-REST-041: the row stays away while Atlas itself is off', async () => {
server.use(http.get('/api/admin/addons', () => HttpResponse.json({ addons: [atlasAddon(false)] })));
render(<AddonManager />);
await screen.findByRole('button', { name: 'Atlas' });
expect(screen.queryByRole('button', { name: RANKING })).not.toBeInTheDocument();
});
it('FE-ATLAS2-REST-042: flipping the row saves atlas_compare_enabled and shows it off', async () => {
const user = userEvent.setup();
const bodies: unknown[] = [];
server.use(
http.get('/api/admin/addons', () => HttpResponse.json({ addons: [atlasAddon(true)] })),
http.put('/api/auth/app-settings', async ({ request }) => {
bodies.push(await request.json());
return HttpResponse.json({ success: true });
})
);
render(
<>
<ToastContainer />
<AddonManager />
</>
);
await user.click(await screen.findByRole('button', { name: RANKING }));
await screen.findByText('Addon updated');
expect(bodies).toEqual([{ atlas_compare_enabled: false }]);
await waitFor(() => expect(isOn(screen.getByRole('button', { name: RANKING }))).toBe(false));
expect(useAuthStore.getState().atlasCompareEnabled).toBe(false);
});
});
+14 -1
View File
@@ -1,6 +1,6 @@
import type { ComponentType } from 'react' import type { ComponentType } from 'react'
import { useTranslation } from '../../i18n' 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 EmptyState from '../shared/EmptyState'
import DawarichIcon from '../shared/DawarichIcon' import DawarichIcon from '../shared/DawarichIcon'
import AirTrailIcon from '../shared/AirTrailIcon' import AirTrailIcon from '../shared/AirTrailIcon'
@@ -94,6 +94,8 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
wandererOffered, wandererOffered,
toggleToursWanderer, toggleToursWanderer,
mapSwitches, mapSwitches,
atlasCompare,
toggleAtlasCompare,
} = useAddonManager() } = useAddonManager()
if (loading) { if (loading) {
return ( 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 — * 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. */ * a provider toggled under a disabled Journey would hit the server's 409. */
const shelfFor = (addon: Addon) => { 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) { if (addon.id === 'packing' && addon.enabled && onToggleBagTracking) {
return ( return (
<AddonSubRow <AddonSubRow
@@ -1,7 +1,7 @@
// FE-ADMIN-DUS-001 to FE-ADMIN-DUS-031 // FE-ADMIN-DUS-001 to FE-ADMIN-DUS-031
import { render, screen, waitFor, within, fireEvent } from '../../../tests/helpers/render'; import { render, screen, waitFor, within, fireEvent } from '../../../tests/helpers/render';
import userEvent from '@testing-library/user-event'; 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 { server } from '../../../tests/helpers/msw/server';
import { resetAllStores, seedStore } from '../../../tests/helpers/store'; import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { buildAdmin } from '../../../tests/helpers/factories'; import { buildAdmin } from '../../../tests/helpers/factories';
@@ -341,12 +341,43 @@ describe('DefaultUserSettingsTab', () => {
expect(input).toHaveValue('pk.old'); expect(input).toHaveValue('pk.old');
await user.clear(input); await user.clear(input);
await user.type(input, 'pk.new'); 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' }])); 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 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('')); await waitFor(() => expect(screen.getByPlaceholderText('pk.eyJ…')).toHaveValue(''));
}); });
@@ -449,12 +480,14 @@ describe('DefaultUserSettingsTab', () => {
expect(input).toHaveValue('ck.old'); expect(input).toHaveValue('ck.old');
await user.clear(input); await user.clear(input);
await user.type(input, 'ck.new'); 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' }])); 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 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('')); await waitFor(() => expect(cartoInput()).toHaveValue(''));
}); });
@@ -11,6 +11,39 @@ import DevNotificationsPanel from './DevNotificationsPanel';
const ADMIN_USER = buildUser({ id: 1, username: 'testadmin', role: 'admin' }); 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(() => { beforeEach(() => {
resetAllStores(); resetAllStores();
seedStore(useAuthStore, { user: ADMIN_USER, isAuthenticated: true }); seedStore(useAuthStore, { user: ADMIN_USER, isAuthenticated: true });
@@ -21,9 +54,12 @@ afterEach(() => {
}); });
describe('DevNotificationsPanel', () => { 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 /></>); render(<><ToastContainer /><DevNotificationsPanel /></>);
expect(screen.getByText('DEV ONLY')).toBeInTheDocument(); 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 () => { 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 () => { it('FE-ADMIN-DEVNOTIF-003: trip selector populated from API', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>); await renderSettled();
await screen.findByText('Trip-Scoped Events');
const [tripSelect] = screen.getAllByRole('combobox'); const [tripSelect] = screen.getAllByRole('combobox');
const options = Array.from(tripSelect.querySelectorAll('option')); const options = Array.from(tripSelect.querySelectorAll('option'));
const labels = options.map(o => o.textContent); const labels = options.map(o => o.textContent);
@@ -46,8 +81,7 @@ describe('DevNotificationsPanel', () => {
}); });
it('FE-ADMIN-DEVNOTIF-004: user selector populated from API', async () => { it('FE-ADMIN-DEVNOTIF-004: user selector populated from API', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>); await renderSettled();
await screen.findByText('User-Scoped Events');
const selects = screen.getAllByRole('combobox'); const selects = screen.getAllByRole('combobox');
// Second combobox is the user selector (first is trip selector) // Second combobox is the user selector (first is trip selector)
const userSelect = selects[1]; const userSelect = selects[1];
@@ -66,8 +100,7 @@ describe('DevNotificationsPanel', () => {
}), }),
); );
const user = userEvent.setup(); const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>); await renderSettled();
await screen.findByText('Type Testing');
await user.click(screen.getByText('Simple → Me').closest('button')!); await user.click(screen.getByText('Simple → Me').closest('button')!);
await waitFor(() => expect(capturedBody).toBeDefined()); await waitFor(() => expect(capturedBody).toBeDefined());
expect(capturedBody).toMatchObject({ expect(capturedBody).toMatchObject({
@@ -75,6 +108,8 @@ describe('DevNotificationsPanel', () => {
scope: 'user', scope: 'user',
targetId: ADMIN_USER.id, 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 () => { it('FE-ADMIN-DEVNOTIF-006: success toast shown after fire', async () => {
@@ -84,30 +119,34 @@ describe('DevNotificationsPanel', () => {
), ),
); );
const user = userEvent.setup(); const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>); await renderSettled();
await screen.findByText('Type Testing');
await user.click(screen.getByText('Simple → Me').closest('button')!); await user.click(screen.getByText('Simple → Me').closest('button')!);
expect(await screen.findByText('Sent: simple-me')).toBeInTheDocument(); expect(await screen.findByText('Sent: simple-me')).toBeInTheDocument();
}); });
it('FE-ADMIN-DEVNOTIF-007: all buttons disabled while a send is in-flight', async () => { 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( server.use(
http.post('/api/admin/dev/test-notification', async () => { http.post('/api/admin/dev/test-notification', async () => {
await new Promise(() => {}); // never resolves — simulates in-flight await gate;
return HttpResponse.json({ ok: true }); return HttpResponse.json({ ok: true });
}), }),
); );
const user = userEvent.setup(); const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>); await renderSettled();
await screen.findByText('Type Testing');
// 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 user.click(screen.getByText('Simple → Me').closest('button')!);
await waitFor(() => { await waitFor(() => {
const buttons = screen.getAllByRole('button'); const buttons = screen.getAllByRole('button');
buttons.forEach(btn => expect(btn).toBeDisabled()); 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 () => { 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(); const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>); await renderSettled();
await screen.findByText('Type Testing');
await user.click(screen.getByText('Simple → Me').closest('button')!); await user.click(screen.getByText('Simple → Me').closest('button')!);
expect(await screen.findByText('No channel configured')).toBeInTheDocument(); expect(await screen.findByText('No channel configured')).toBeInTheDocument();
}); });
@@ -130,8 +168,7 @@ describe('DevNotificationsPanel', () => {
), ),
); );
const user = userEvent.setup(); const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>); await renderSettled();
await screen.findByText('Type Testing');
await user.click(screen.getByText('Simple → Me').closest('button')!); await user.click(screen.getByText('Simple → Me').closest('button')!);
expect(await screen.findByText('Failed')).toBeInTheDocument(); expect(await screen.findByText('Failed')).toBeInTheDocument();
}); });
@@ -145,8 +182,7 @@ describe('DevNotificationsPanel', () => {
}), }),
); );
const user = userEvent.setup(); const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>); await renderSettled();
await screen.findByText('Trip-Scoped Events');
const [tripSelect] = screen.getAllByRole('combobox'); const [tripSelect] = screen.getAllByRole('combobox');
const tokyoOption = Array.from(tripSelect.querySelectorAll('option')).find( const tokyoOption = Array.from(tripSelect.querySelectorAll('option')).find(
@@ -159,15 +195,19 @@ describe('DevNotificationsPanel', () => {
await waitFor(() => expect(capturedBody).toBeDefined()); await waitFor(() => expect(capturedBody).toBeDefined());
expect(capturedBody!.targetId).toBe(tokyoId); 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 () => { it('FE-ADMIN-DEVNOTIF-010: Trip-Scoped section absent when no trips', async () => {
server.use( server.use(
http.get('/api/trips', () => HttpResponse.json({ trips: [] })), http.get('/api/trips', () => HttpResponse.json({ trips: [] })),
); );
const lookupsAnswered = trackRequests();
render(<><ToastContainer /><DevNotificationsPanel /></>); render(<><ToastContainer /><DevNotificationsPanel /></>);
// Wait for user data to confirm async effects have settled // Wait for user data to confirm async effects have settled
await screen.findByText('User-Scoped Events'); await screen.findByText('User-Scoped Events');
await lookupsAnswered();
expect(screen.queryByText('Trip-Scoped Events')).not.toBeInTheDocument(); expect(screen.queryByText('Trip-Scoped Events')).not.toBeInTheDocument();
}); });
@@ -180,8 +220,7 @@ describe('DevNotificationsPanel', () => {
}), }),
); );
const user = userEvent.setup(); const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>); await renderSettled();
await screen.findByText('Type Testing');
await user.click(screen.getByText('Boolean → Me').closest('button')!); await user.click(screen.getByText('Boolean → Me').closest('button')!);
await screen.findByText('Sent: boolean-me'); await screen.findByText('Sent: boolean-me');
@@ -216,8 +255,7 @@ describe('DevNotificationsPanel', () => {
}), }),
); );
const user = userEvent.setup(); const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>); await renderSettled();
await screen.findByText('Trip-Scoped Events');
const [tripSelect] = screen.getAllByRole('combobox'); const [tripSelect] = screen.getAllByRole('combobox');
const tripId = Number((tripSelect as HTMLSelectElement).value); const tripId = Number((tripSelect as HTMLSelectElement).value);
@@ -247,8 +285,7 @@ describe('DevNotificationsPanel', () => {
}), }),
); );
const user = userEvent.setup(); const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>); await renderSettled();
await screen.findByText('User-Scoped Events');
const userSelect = screen.getAllByRole('combobox')[1] as HTMLSelectElement; const userSelect = screen.getAllByRole('combobox')[1] as HTMLSelectElement;
const aliceOption = Array.from(userSelect.querySelectorAll('option')).find( 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 () => { 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: [] }))); server.use(http.get('/api/admin/users', () => HttpResponse.json({ users: [] })));
const lookupsAnswered = trackRequests();
render(<><ToastContainer /><DevNotificationsPanel /></>); render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Trip-Scoped Events'); await screen.findByText('Trip-Scoped Events');
await lookupsAnswered();
expect(screen.queryByText('User-Scoped Events')).not.toBeInTheDocument(); expect(screen.queryByText('User-Scoped Events')).not.toBeInTheDocument();
}); });
@@ -288,22 +327,38 @@ describe('DevNotificationsPanel', () => {
server.use( server.use(
http.get('/api/trips', () => HttpResponse.error()), http.get('/api/trips', () => HttpResponse.error()),
http.get('/api/admin/users', () => 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 /></>); render(<><ToastContainer /><DevNotificationsPanel /></>);
expect(await screen.findByText('Type Testing')).toBeInTheDocument(); expect(await screen.findByText('Type Testing')).toBeInTheDocument();
await lookupsAnswered();
await waitFor(() => expect(screen.queryByText('Trip-Scoped Events')).not.toBeInTheDocument()); await waitFor(() => expect(screen.queryByText('Trip-Scoped Events')).not.toBeInTheDocument());
expect(screen.queryByText('User-Scoped Events')).not.toBeInTheDocument(); expect(screen.queryByText('User-Scoped Events')).not.toBeInTheDocument();
expect(screen.getByText('Admin-Scoped Events')).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 () => { it('FE-ADMIN-DEVNOTIF-016: a trigger takes its hover background from CSS, not inline styles', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>); await renderSettled();
await screen.findByText('Type Testing');
const btn = screen.getByText('Simple → Me').closest('button')!; const btn = screen.getByText('Simple → Me').closest('button')!;
fireEvent.mouseEnter(btn); fireEvent.mouseEnter(btn);
expect(btn.style.background).toBe(''); expect(btn.style.background).toBe('');
expect(btn.className).toContain('hover:bg-surface-secondary'); 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> return <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">{children}</div>
} }
export default function DevNotificationsPanel(): React.ReactElement { /**
const ids = useId() * One send button. Declared here, not inside the panel: a component made during
const { * render is a new type on every render, so React would remount every button on
sending, trips, selectedTripId, setSelectedTripId, users, selectedUserId, setSelectedUserId, * each state change and a click could land on one that is already gone.
tripInviteId, vacayInviteId, send, */
} = useDevNotifications() function Btn({
id, label, sub, icon: Icon, onClick, sending,
// ── Helpers ────────────────────────────────────────────────────────────── }: {
id: string; label: string; sub: string; icon: React.ElementType; onClick: () => void; sending: string | null
const Btn = ({ }): React.ReactElement {
id, label, sub, icon: Icon, onClick, return (
}: {
id: string; label: string; sub: string; icon: React.ElementType; onClick: () => void
}) => (
<button type="button" <button type="button"
onClick={onClick} onClick={onClick}
disabled={sending !== null} 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" />} {sending === id && <Loader2 size={15} className="flex-none animate-spin text-content-faint" />}
</button> </button>
) )
}
export default function DevNotificationsPanel(): React.ReactElement {
const ids = useId()
const {
sending, trips, selectedTripId, setSelectedTripId, users, selectedUserId, setSelectedUserId,
tripInviteId, vacayInviteId, send,
} = useDevNotifications()
return ( return (
<div> <div>
@@ -66,16 +71,16 @@ export default function DevNotificationsPanel(): React.ReactElement {
badge={<StatusPill tone="warning">DEV ONLY</StatusPill>} badge={<StatusPill tone="warning">DEV ONLY</StatusPill>}
> >
<ButtonGrid> <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} 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} 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} 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} onClick={send.simpleAdmins}
/> />
</ButtonGrid> </ButtonGrid>
@@ -94,19 +99,19 @@ export default function DevNotificationsPanel(): React.ReactElement {
</SelectBox> </SelectBox>
</EditorField> </EditorField>
<ButtonGrid> <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} 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} 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} 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} 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} onClick={send.packingTagged}
/> />
</ButtonGrid> </ButtonGrid>
@@ -127,6 +132,7 @@ export default function DevNotificationsPanel(): React.ReactElement {
</EditorField> </EditorField>
<ButtonGrid> <ButtonGrid>
<Btn <Btn
sending={sending}
id={tripInviteId} id={tripInviteId}
label="trip_invite" label="trip_invite"
sub="navigate · user" sub="navigate · user"
@@ -134,6 +140,7 @@ export default function DevNotificationsPanel(): React.ReactElement {
onClick={send.tripInvite} onClick={send.tripInvite}
/> />
<Btn <Btn
sending={sending}
id={vacayInviteId} id={vacayInviteId}
label="vacay_invite" label="vacay_invite"
sub="navigate · user" sub="navigate · user"
@@ -147,7 +154,7 @@ export default function DevNotificationsPanel(): React.ReactElement {
{/* ── Admin-Scoped Events ──────────────────────────────────────────── */} {/* ── Admin-Scoped Events ──────────────────────────────────────────── */}
<SettingsCard icon={ShieldCheck} title="Admin-Scoped Events" hint="Fires to all admin users."> <SettingsCard icon={ShieldCheck} title="Admin-Scoped Events" hint="Fires to all admin users.">
<ButtonGrid> <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} onClick={send.versionAvailable}
/> />
</ButtonGrid> </ButtonGrid>
@@ -0,0 +1,76 @@
import { act, renderHook, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { adminApi, authApi } from '../../../api/client';
import { cycleMapAdminApi, hikingMapAdminApi, skiRoutingAdminApi } from '../../../api/tourBaseMaps';
import { wandererAdminApi } from '../../../api/wanderer';
import { useAddonStore } from '../../../store/addonStore';
import { useAuthStore } from '../../../store/authStore';
import { useAddonManager } from './useAddonManager';
// FE-ATLAS2-REST-030 to 032: the Atlas ranking switch the admin flips under the Atlas addon.
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));
vi.mock('../../shared/Toast', () => ({ useToast: () => toast }));
vi.mock('../../../i18n', () => ({ useTranslation: () => ({ t: (k: string) => k }) }));
let loadAddons: ReturnType<typeof vi.fn<() => Promise<void>>>;
beforeEach(() => {
toast.success.mockReset();
toast.error.mockReset();
loadAddons = vi.fn<() => Promise<void>>().mockResolvedValue(undefined);
useAddonStore.setState({ loadAddons });
useAuthStore.setState({ atlasCompareEnabled: true });
vi.spyOn(adminApi, 'addons').mockResolvedValue({ addons: [] });
vi.spyOn(wandererAdminApi, 'get').mockResolvedValue({ enabled: false });
vi.spyOn(hikingMapAdminApi, 'get').mockResolvedValue({ enabled: false });
vi.spyOn(cycleMapAdminApi, 'get').mockResolvedValue({ enabled: false });
vi.spyOn(skiRoutingAdminApi, 'get').mockResolvedValue({ enabled: false });
});
afterEach(() => vi.restoreAllMocks());
async function loaded() {
const hook = renderHook(() => useAddonManager());
await waitFor(() => expect(hook.result.current.loading).toBe(false));
return hook;
}
describe('useAddonManager: Atlas ranking switch', () => {
it('FE-ATLAS2-REST-030: reads the switch from the app config the auth store holds', async () => {
useAuthStore.setState({ atlasCompareEnabled: false });
const { result } = await loaded();
expect(result.current.atlasCompare).toBe(false);
act(() => {
useAuthStore.setState({ atlasCompareEnabled: true });
});
expect(result.current.atlasCompare).toBe(true);
});
it('FE-ATLAS2-REST-031: a flip turns it off at once, saves the app setting, refreshes the addons and toasts', async () => {
const save = vi.spyOn(authApi, 'updateAppSettings').mockResolvedValue({});
const { result } = await loaded();
await act(() => result.current.toggleAtlasCompare());
expect(save).toHaveBeenCalledWith({ atlas_compare_enabled: false });
expect(useAuthStore.getState().atlasCompareEnabled).toBe(false);
expect(result.current.atlasCompare).toBe(false);
expect(loadAddons).toHaveBeenCalledTimes(1);
expect(toast.success).toHaveBeenCalledWith('admin.addons.toast.updated');
// And on again from off.
await act(() => result.current.toggleAtlasCompare());
expect(save).toHaveBeenLastCalledWith({ atlas_compare_enabled: true });
expect(useAuthStore.getState().atlasCompareEnabled).toBe(true);
});
it('FE-ATLAS2-REST-032: a failed save puts the switch back and says so, without refreshing', async () => {
vi.spyOn(authApi, 'updateAppSettings').mockRejectedValue(new Error('down'));
const { result } = await loaded();
await act(() => result.current.toggleAtlasCompare());
expect(useAuthStore.getState().atlasCompareEnabled).toBe(true);
expect(result.current.atlasCompare).toBe(true);
expect(toast.error).toHaveBeenCalledWith('admin.addons.toast.error');
expect(toast.success).not.toHaveBeenCalled();
expect(loadAddons).not.toHaveBeenCalled();
});
});
@@ -2,7 +2,7 @@ import type { AdminFeatureToggleResponse } from '@trek/shared';
import { Bike, Footprints, MountainSnow } from 'lucide-react'; import { Bike, Footprints, MountainSnow } from 'lucide-react';
import { useEffect, useEffectEvent, useState } from '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 { cycleMapAdminApi, hikingMapAdminApi, skiRoutingAdminApi } from '../../../api/tourBaseMaps';
import { wandererAdminApi } from '../../../api/wanderer'; import { wandererAdminApi } from '../../../api/wanderer';
import { useTranslation } from '../../../i18n'; import { useTranslation } from '../../../i18n';
@@ -43,6 +43,9 @@ export function useAddonManager() {
const [toursHikingMap, setToursHikingMap] = useState(false); const [toursHikingMap, setToursHikingMap] = useState(false);
const [toursCycleMap, setToursCycleMap] = useState(false); const [toursCycleMap, setToursCycleMap] = useState(false);
const [toursSkiRouting, setToursSkiRouting] = 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 () => { const loadAddons = async () => {
try { try {
@@ -105,6 +108,11 @@ export function useAddonManager() {
void refreshGlobalAddons(); void refreshGlobalAddons();
toast.success(t('admin.addons.toast.updated')); 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); 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). */ /** The maps and the piste router Tours offers on their operators' terms, one switch each (MAP-01, BIK-06, SKI-02). */
const mapSwitches = [ const mapSwitches = [
@@ -167,5 +175,7 @@ export function useAddonManager() {
wandererOffered, wandererOffered,
toggleToursWanderer, toggleToursWanderer,
mapSwitches, mapSwitches,
atlasCompare,
toggleAtlasCompare,
}; };
} }
@@ -137,19 +137,65 @@ describe('useDefaultUserSettings', () => {
act(() => result.current.pickTilePreset('')); act(() => result.current.pickTilePreset(''));
act(() => result.current.pickStylePreset('')); 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(); expect(update).not.toHaveBeenCalled();
act(() => result.current.pickTilePreset('https://tile.openstreetmap.de/{z}/{x}/{y}.png')); 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(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')); 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.setMapboxStyle('mapbox://styles/not-for-maplibre'));
act(() => result.current.commitStyle()); act(() => result.current.commitStyle());
expect(result.current.mapboxStyle).toBe(OPENFREEMAP_DEFAULT_STYLE); 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)); await waitFor(() => expect(toast.success).toHaveBeenCalledTimes(3));
}); });
it('FE-COMP-DEFAULTSETTINGS-007: a MapLibre keyword default survives loading, a switch, a pick and a typed commit', async () => {
const update = stub({
map_provider: 'maplibre-gl',
maplibre_style: 'trek:template',
mapbox_style: 'mapbox://styles/me/x',
});
const { result } = await loaded();
expect(result.current.mapboxStyle).toBe('trek:template');
// The picker names both keywords after the OpenFreeMap styles.
expect(result.current.glStylePresets.slice(-2)).toEqual([
{ name: 'settings.mapStyleFollowTheme', url: 'trek:ofm-auto', tags: ['OpenFreeMap'] },
{ name: 'settings.mapStyleTemplate', url: 'trek:template' },
]);
act(() => result.current.commitStyle());
await waitFor(() => expect(update).toHaveBeenLastCalledWith({ maplibre_style: 'trek:template' }));
act(() => result.current.saveMapProvider('mapbox-gl'));
await waitFor(() =>
expect(update).toHaveBeenLastCalledWith({ map_provider: 'mapbox-gl', mapbox_style: 'mapbox://styles/me/x' })
);
act(() => result.current.saveMapProvider('maplibre-gl'));
await waitFor(() =>
expect(update).toHaveBeenLastCalledWith({ map_provider: 'maplibre-gl', maplibre_style: 'trek:template' })
);
expect(result.current.mapboxStyle).toBe('trek:template');
act(() => result.current.pickStylePreset('trek:ofm-auto'));
await waitFor(() => expect(update).toHaveBeenLastCalledWith({ maplibre_style: 'trek:ofm-auto' }));
});
it('FE-COMP-DEFAULTSETTINGS-008: a keyword typed for Mapbox is not kept, Mapbox draws neither', async () => {
const update = stub({ map_provider: 'mapbox-gl', mapbox_style: 'trek:template' });
const { result } = await loaded();
expect(result.current.mapboxStyle).toBe(MAPBOX_DEFAULT_STYLE);
expect(result.current.glStylePresets.map((p) => p.url)).not.toContain('trek:template');
act(() => result.current.commitStyle());
await waitFor(() => expect(update).toHaveBeenLastCalledWith({ mapbox_style: MAPBOX_DEFAULT_STYLE }));
});
}); });
@@ -1,21 +1,19 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { adminApi } from '../../api/client'; import { adminApi } from '../../api/client';
import { useWritesInOrder } from '../../hooks/useWritesInOrder';
import { useTranslation } from '../../i18n'; import { useTranslation } from '../../i18n';
import { useAuthStore } from '../../store/authStore'; import { useAuthStore } from '../../store/authStore';
import { useSettingsStore } from '../../store/settingsStore'; import { useSettingsStore } from '../../store/settingsStore';
import type { DateFormat, DistanceUnit, Place, WeekStart } from '../../types'; import type { DateFormat, DistanceUnit, Place, WeekStart } from '../../types';
import { normalizeTileUrl } from '../../utils/tileUrl'; import { normalizeTileUrl } from '../../utils/tileUrl';
import { import { defaultStyleForProvider, styleSettingKey } from '../Map/glProviders';
defaultStyleForProvider,
getStylePresets,
normalizeStyleForProvider,
styleSettingKey,
} from '../Map/glProviders';
import { import {
type MapProvider, type MapProvider,
glStylePresetsFor,
mapboxOffered, mapboxOffered,
mapPresetsFor, mapPresetsFor,
normalizeGlSelection,
normalizeProvider, normalizeProvider,
styleForProvider, styleForProvider,
} from '../Settings/mapSettingsModel'; } from '../Settings/mapSettingsModel';
@@ -87,32 +85,38 @@ export function useDefaultUserSettings({ errorMessage, previewCreatedAt }: Defau
.catch(() => setLoaded(true)); .catch(() => setLoaded(true));
}, []); }, []);
const save = async (patch: Partial<Defaults>) => { // A field's save on blur and the reset clicked right after it reach the server in
try { // that order, or the save landing last would store the old value again.
const updated = await adminApi.updateDefaultUserSettings(patch as Record<string, unknown>); const inOrder = useWritesInOrder();
setDefaults(updated);
toast.success(t('admin.defaultSettings.saved'));
} catch (err: unknown) {
toast.error(errorMessage(err, t('common.error')));
}
};
const reset = async (key: keyof Defaults) => { const save = (patch: Partial<Defaults>) =>
try { inOrder(async () => {
const updated = await adminApi.updateDefaultUserSettings({ [key]: null }); try {
setDefaults(updated); const updated = await adminApi.updateDefaultUserSettings(patch as Record<string, unknown>);
if (key === 'map_tile_url') setMapTileUrl(''); setDefaults(updated);
if (key === 'mapbox_access_token') setMapboxToken(''); toast.success(t('admin.defaultSettings.saved'));
if (key === 'carto_api_key') setCartoKey(''); } catch (err: unknown) {
if (key === 'mapbox_style' || key === 'maplibre_style') { toast.error(errorMessage(err, t('common.error')));
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 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; const isSet = (key: keyof Defaults) => defaults[key] !== undefined;
@@ -120,7 +124,8 @@ export function useDefaultUserSettings({ errorMessage, previewCreatedAt }: Defau
const [mapPreviewPlaces] = useState((): Place[] => [adminPreviewPlace(previewCreatedAt())]); const [mapPreviewPlaces] = useState((): Place[] => [adminPreviewPlace(previewCreatedAt())]);
const mapProvider = normalizeProvider(defaults.map_provider); const mapProvider = normalizeProvider(defaults.map_provider);
const glStylePresets = mapProvider === 'leaflet' ? [] : getStylePresets(mapProvider); // MapLibre also offers its keywords: a default that follows the colour scheme, or the template above.
const glStylePresets = mapProvider === 'leaflet' ? [] : glStylePresetsFor(mapProvider, t);
const styleKey: keyof Defaults = mapProvider === 'maplibre-gl' ? 'maplibre_style' : 'mapbox_style'; const styleKey: keyof Defaults = mapProvider === 'maplibre-gl' ? 'maplibre_style' : 'mapbox_style';
const saveMapProvider = (nextProvider: MapProvider) => { const saveMapProvider = (nextProvider: MapProvider) => {
@@ -151,11 +156,11 @@ export function useDefaultUserSettings({ errorMessage, previewCreatedAt }: Defau
} }
}; };
/** A typed style is normalized for the provider before it is saved. */ /** A typed style is normalized for the provider before it is saved; a MapLibre keyword stays. */
const commitStyle = () => { const commitStyle = () => {
// The style input never renders for leaflet; this only narrows the provider type. // The style input never renders for leaflet; this only narrows the provider type.
if (mapProvider === 'leaflet') return; if (mapProvider === 'leaflet') return;
const nextStyle = normalizeStyleForProvider(mapProvider, mapboxStyle); const nextStyle = normalizeGlSelection(mapProvider, mapboxStyle);
setMapboxStyle(nextStyle); setMapboxStyle(nextStyle);
void save({ [styleKey]: nextStyle }); void save({ [styleKey]: nextStyle });
}; };
@@ -50,7 +50,7 @@ describe('AssistantAskButton', () => {
expect(screen.queryByRole('button')).not.toBeInTheDocument(); expect(screen.queryByRole('button')).not.toBeInTheDocument();
unmount(); unmount();
renderAt('/collections/3'); renderAt('/places/3');
expect(screen.queryByRole('button')).not.toBeInTheDocument(); expect(screen.queryByRole('button')).not.toBeInTheDocument();
}); });
}); });
@@ -54,7 +54,7 @@ describe('collection answer cards', () => {
expect(within(card).getByText('Idea')).toBeInTheDocument(); expect(within(card).getByText('Idea')).toBeInTheDocument();
expect(within(card).getByText('3')).toBeInTheDocument(); expect(within(card).getByText('3')).toBeInTheDocument();
fireEvent.click(within(card).getByRole('button', { name: /Open list/ })); fireEvent.click(within(card).getByRole('button', { name: /Open list/ }));
expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/collections/12' }); expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/places/12' });
}); });
it('FE-AI-COLL-040: the places to revisit have a pill of their own in the head, in the visited tone (#2567)', () => { it('FE-AI-COLL-040: the places to revisit have a pill of their own in the head, in the visited tone (#2567)', () => {
@@ -86,7 +86,7 @@ describe('collection answer cards', () => {
expect(screen.getByText('Spot 4')).toBeInTheDocument(); expect(screen.getByText('Spot 4')).toBeInTheDocument();
expect(screen.queryByText('Spot 5')).toBeNull(); expect(screen.queryByText('Spot 5')).toBeNull();
fireEvent.click(screen.getByRole('button', { name: '7 more in this list' })); fireEvent.click(screen.getByRole('button', { name: '7 more in this list' }));
expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/collections/12' }); expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/places/12' });
}); });
it('FE-AI-COLL-013: a roomy chat shows eight rows', () => { it('FE-AI-COLL-013: a roomy chat shows eight rows', () => {
@@ -144,7 +144,7 @@ describe('collection answer cards', () => {
expect(screen.queryByText('Paris food')).toBeNull(); expect(screen.queryByText('Paris food')).toBeNull();
expect(screen.getByText('Invite from Maya')).toBeInTheDocument(); expect(screen.getByText('Invite from Maya')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /Rome/ })); fireEvent.click(screen.getByRole('button', { name: /Rome/ }));
expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/collections/40' }); expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/places/40' });
}); });
it('FE-AI-COLL-018: where a place is saved reads as its lists with its status in each', () => { it('FE-AI-COLL-018: where a place is saved reads as its lists with its status in each', () => {
@@ -94,7 +94,7 @@ describe('collection change cards', () => {
const view = draw([applied(pending('save_place_to_collection', 'Septime', card), 'collection_place', [77])]); const view = draw([applied(pending('save_place_to_collection', 'Septime', card), 'collection_place', [77])]);
expect(screen.queryByRole('button', { name: 'Show on map' })).toBeNull(); expect(screen.queryByRole('button', { name: 'Show on map' })).toBeNull();
fireEvent.click(screen.getByRole('button', { name: 'Open in Collections' })); fireEvent.click(screen.getByRole('button', { name: 'Open in Collections' }));
expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/collections/12?place=77' }); expect(view.onOpen).toHaveBeenCalledWith({ kind: 'page', path: '/places/12?place=77' });
}); });
it('FE-AI-COLL-023: a save the place matched already says where it is saved', () => { it('FE-AI-COLL-023: a save the place matched already says where it is saved', () => {
@@ -8,6 +8,7 @@ import type {
TrekCard, TrekCard,
} from '@trek/shared'; } from '@trek/shared';
import { placesPath } from '../../../../utils/placesRoutes';
import type { EntityTarget } from '../cardTypes'; import type { EntityTarget } from '../cardTypes';
/** /**
@@ -26,12 +27,12 @@ export const MAX_FACTS = 4;
/** Where a list opens in Collections. */ /** Where a list opens in Collections. */
export function listTarget(listId: number | null): EntityTarget { export function listTarget(listId: number | null): EntityTarget {
return { kind: 'page', path: listId === null ? '/collections' : `/collections/${listId}` }; return { kind: 'page', path: placesPath(listId === null ? 'saved' : listId) };
} }
/** Where a saved place opens: its list, with the place selected. */ /** Where a saved place opens: its list, with the place selected. */
function placeTarget(listId: number, placeId: number | null): EntityTarget { function placeTarget(listId: number, placeId: number | null): EntityTarget {
const path = `/collections/${listId}`; const path = placesPath(listId);
return { kind: 'page', path: placeId === null ? path : `${path}?place=${placeId}` }; return { kind: 'page', path: placeId === null ? path : `${path}?place=${placeId}` };
} }
@@ -62,9 +62,9 @@ describe('collection look', () => {
it('FE-AI-COLL-002: an applied list opens in Collections, unless the change deleted it or declined its invite', () => { it('FE-AI-COLL-002: an applied list opens in Collections, unless the change deleted it or declined its invite', () => {
const look = ENTITY_LOOK.collection; const look = ENTITY_LOOK.collection;
expect(look.openLabelKey).toBe('assistant.card.collection.openList'); expect(look.openLabelKey).toBe('assistant.card.collection.openList');
expect(look.open?.(applied('collection', [12]), null)).toEqual({ kind: 'page', path: '/collections/12' }); expect(look.open?.(applied('collection', [12]), null)).toEqual({ kind: 'page', path: '/places/12' });
const card = listsCard({ lists: [listRow({ id: 13 })] }); const card = listsCard({ lists: [listRow({ id: 13 })] });
expect(look.open?.(applied('collection', []), card)).toEqual({ kind: 'page', path: '/collections/13' }); expect(look.open?.(applied('collection', []), card)).toEqual({ kind: 'page', path: '/places/13' });
for (const change of ['remove', 'decline'] as const) { for (const change of ['remove', 'decline'] as const) {
expect(look.open?.(applied('collection', [12]), listsCard({ lists: [listRow({ change })] }))).toBeNull(); expect(look.open?.(applied('collection', [12]), listsCard({ lists: [listRow({ change })] }))).toBeNull();
} }
@@ -76,10 +76,10 @@ describe('collection look', () => {
const card = placesCard(); const card = placesCard();
expect(look.open?.(applied('collection_place', [34]), card)).toEqual({ expect(look.open?.(applied('collection_place', [34]), card)).toEqual({
kind: 'page', kind: 'page',
path: '/collections/12?place=34', path: '/places/12?place=34',
}); });
const removed = placesCard({ places: [savedPlace({ delta: emptyDelta({ removed: true }) })] }); const removed = placesCard({ places: [savedPlace({ delta: emptyDelta({ removed: true }) })] });
expect(look.open?.(applied('collection_place', [34]), removed)).toEqual({ kind: 'page', path: '/collections/12' }); expect(look.open?.(applied('collection_place', [34]), removed)).toEqual({ kind: 'page', path: '/places/12' });
expect(look.open?.(applied('collection_place', [34]), null)).toBeNull(); expect(look.open?.(applied('collection_place', [34]), null)).toBeNull();
}); });
@@ -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 { FigureBadge } from '../../Tours/paddle/FigureBadge';
import { TourDayRowPill } from '../../Tours/TourDayRowFacts'; import { TourDayRowPill } from '../../Tours/TourDayRowFacts';
import { tourDayRowIcon } from '../../Tours/tourDayRowIcon'; import { tourDayRowIcon } from '../../Tours/tourDayRowIcon';
import { typeIcon, typeLabel, type Translate } from './tourActivityReading'; import { periodLabel, typeIcon, typeLabel } from './tourActivityReading';
import { periodYear, type ActivityPeriod, type ActivityType } from './tourActivityStatsModel'; import { type ActivityType } from './tourActivityStatsModel';
import type { TourActivityStats } from './useTourActivityStats'; 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. */ /** 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 }) { export function ActivityFilters({ stats, quiet = false }: { stats: TourActivityStats; quiet?: boolean }) {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -4,7 +4,7 @@ import { useSettingsStore } from '../../../store/settingsStore';
import type { DistanceUnit } from '../../../types'; import type { DistanceUnit } from '../../../types';
import { formatDistance, formatElevation } from '../../../utils/units'; import { formatDistance, formatElevation } from '../../../utils/units';
import { tourDayRowIcon } from '../../Tours/tourDayRowIcon'; 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; 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 { export function partialHint(sum: TourActivityTotals['distanceKm'], t: Translate): string {
return t('tours.scope.partialBody', { known: sum.known, of: sum.of }); 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));
}
@@ -0,0 +1,151 @@
// FE-ATLAS2-PAINT-301 to FE-ATLAS2-PAINT-318: the tours page figures of the Atlas hub
// and the readings and labels the tour activity views share.
import { act, renderHook } from '@testing-library/react';
import type { TourActivityStatsResponse, TourActivitySum, TourActivitySummary, TourActivityTotals } from '@trek/shared';
import { Bike, Layers, Mountain, Route } from 'lucide-react';
import { afterEach, describe, expect, it } from 'vitest';
import { useSettingsStore } from '../../../store/settingsStore';
import {
distanceReading,
heightReading,
partialHint,
periodLabel,
typeIcon,
typeLabel,
useDistanceUnit,
} from './tourActivityReading';
import { tourHubFigures } from './tourHubFigures';
const echoT = (key: string, params?: Record<string, unknown>): string =>
params ? `${key}:${JSON.stringify(params)}` : key;
function sum(value: number | null, known = 1, of = known): TourActivitySum {
return { value, known, of };
}
function totals(over: Partial<TourActivityTotals> = {}): TourActivityTotals {
return {
count: 3,
distanceKm: sum(42.5, 3),
ascentM: sum(1200, 3),
descentM: sum(1100, 3),
byBasis: { plan: 2, track: 1 },
...over,
};
}
function summary(over: Partial<TourActivitySummary> = {}): TourActivitySummary {
return { totals: totals(), types: [], done: [], upcoming: 0, ...over };
}
const initialSettings = useSettingsStore.getState();
afterEach(() => {
useSettingsStore.setState(initialSettings, true);
});
describe('tourHubFigures', () => {
it('FE-ATLAS2-PAINT-301: leads with the distance split into number and unit, with the climbs beside it', () => {
const figures = tourHubFigures(summary(), null, 'metric');
expect(figures.hero).toEqual({ value: '42.5', unit: 'km' });
expect(figures.ascent).toEqual({ text: '1200 m', partial: false });
expect(figures.descent).toEqual({ text: '1100 m', partial: false });
});
it('FE-ATLAS2-PAINT-302: marks a distance some tours lack as at least that much', () => {
const figures = tourHubFigures(summary({ totals: totals({ distanceKm: sum(10, 1, 3) }) }), null, 'metric');
expect(figures.hero).toEqual({ value: '≥ 10', unit: 'km' });
});
it('FE-ATLAS2-PAINT-303: leads with the tour count when no tour knows its distance', () => {
const figures = tourHubFigures(
summary({ totals: totals({ count: 7, distanceKm: sum(null, 0, 7), ascentM: sum(null, 0, 7) }) }),
null,
'metric'
);
expect(figures.hero).toEqual({ value: '7', unit: '' });
expect(figures.ascent).toBeNull();
});
it('FE-ATLAS2-PAINT-304: reads in miles and feet for imperial', () => {
const figures = tourHubFigures(summary(), null, 'imperial');
expect(figures.hero).toEqual({ value: '26.4', unit: 'mi' });
expect(figures.ascent?.text).toBe('3937 ft');
});
it('FE-ATLAS2-PAINT-305: scales the types to the longest one', () => {
const types = [
{ ...totals({ distanceKm: sum(30) }), type: 'hike' as const },
{ ...totals({ distanceKm: sum(120) }), type: 'bike' as const },
{ ...totals({ distanceKm: sum(null, 0, 1) }), type: 'kayak' as const },
];
const figures = tourHubFigures(summary({ types }), null, 'metric');
expect(figures.types).toBe(types);
expect(figures.maxKm).toBe(120);
});
it('FE-ATLAS2-PAINT-306: never scales against zero, with no types or none with a distance', () => {
expect(tourHubFigures(summary(), null, 'metric').maxKm).toBe(1e-9);
const types = [{ ...totals({ distanceKm: sum(null, 0, 2) }), type: 'run' as const }];
expect(tourHubFigures(summary({ types }), null, 'metric').maxKm).toBe(1e-9);
});
it('FE-ATLAS2-PAINT-307: says which tours are left out of the sums, none before the data loads', () => {
expect(tourHubFigures(summary(), null, 'metric').uncounted).toEqual({ unassigned: 0, undated: 0 });
const data: TourActivityStatsResponse = { entries: [], uncounted: { unassigned: 2, undated: 1 } };
expect(tourHubFigures(summary(), data, 'metric').uncounted).toEqual({ unassigned: 2, undated: 1 });
});
});
describe('tourActivityReading', () => {
it('FE-ATLAS2-PAINT-308: reads the distance unit from the user settings', () => {
useSettingsStore.setState({ settings: { ...initialSettings.settings, distance_unit: 'imperial' } });
const { result } = renderHook(() => useDistanceUnit());
expect(result.current).toBe('imperial');
act(() => {
useSettingsStore.setState({ settings: { ...initialSettings.settings, distance_unit: 'metric' } });
});
expect(result.current).toBe('metric');
});
it('FE-ATLAS2-PAINT-309: falls back to metric when the setting is missing', () => {
useSettingsStore.setState({ settings: { ...initialSettings.settings, distance_unit: undefined } });
const { result } = renderHook(() => useDistanceUnit());
expect(result.current).toBe('metric');
});
it('FE-ATLAS2-PAINT-310: names every type at once apart from a single type', () => {
expect(typeLabel('all', echoT)).toBe('tours.stats.allTypes');
expect(typeLabel('hike', echoT)).toBe('tourTypes.hike');
});
it('FE-ATLAS2-PAINT-311: draws every type at once as a stack and a single type with its own icon', () => {
expect(typeIcon('all')).toBe(Layers);
expect(typeIcon('bike')).toBe(Bike);
expect(typeIcon('hike')).toBe(Mountain);
expect(typeIcon('food')).toBe(Route);
});
it('FE-ATLAS2-PAINT-312: reads a distance, short ones in metres, and none without a value', () => {
expect(distanceReading({ distanceKm: sum(0.3) }, 'metric')).toEqual({ text: '300 m', partial: false });
expect(distanceReading({ distanceKm: sum(5, 2, 4) }, 'metric')).toEqual({ text: '≥ 5 km', partial: true });
expect(distanceReading({ distanceKm: sum(null, 0, 4) }, 'metric')).toBeNull();
});
it('FE-ATLAS2-PAINT-313: reads a height sum in metres or feet', () => {
expect(heightReading(sum(500), 'metric')).toEqual({ text: '500 m', partial: false });
expect(heightReading(sum(500, 1, 2), 'imperial')).toEqual({ text: '≥ 1640 ft', partial: true });
expect(heightReading(sum(null, 0, 2), 'imperial')).toBeNull();
});
it('FE-ATLAS2-PAINT-314: explains a short sum with how many tours know their value', () => {
expect(partialHint(sum(5, 2, 4), echoT)).toBe('tours.scope.partialBody:{"known":2,"of":4}');
});
it('FE-ATLAS2-PAINT-315: names each period of the filter, an earlier year by its number', () => {
expect(periodLabel('all', echoT)).toBe('tours.stats.period.all');
expect(periodLabel('thisYear', echoT)).toBe('tours.stats.period.thisYear');
expect(periodLabel('last12', echoT)).toBe('tours.stats.period.last12');
expect(periodLabel('year:2023', echoT)).toBe('2023');
});
});
@@ -0,0 +1,27 @@
import type { TourActivityStatsResponse, TourActivitySummary } from '@trek/shared';
import type { DistanceUnit } from '../../../types';
import { distanceReading, heightReading } from './tourActivityReading';
import { splitMeasure } from './tourActivityStatsModel';
/**
* What the tours page of the Atlas hub shows above its lists, for the desktop
* and the phone view alike: the headline distance (or the tour count when no
* distance is known), the climbs, the types scaled to the longest, and the
* tours left out of the sums.
*/
export function tourHubFigures(
summary: TourActivitySummary,
data: TourActivityStatsResponse | null,
unit: DistanceUnit
) {
const totals = summary.totals;
const distance = distanceReading(totals, unit);
return {
hero: distance ? splitMeasure(distance.text) : { value: String(totals.count), unit: '' },
ascent: heightReading(totals.ascentM, unit),
descent: heightReading(totals.descentM, unit),
types: summary.types,
maxKm: Math.max(1e-9, ...summary.types.map((x) => x.distanceKm.value ?? 0)),
uncounted: data?.uncounted ?? { unassigned: 0, undated: 0 },
};
}
@@ -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,278 @@
// FE-ATLAS2-RENDER-200 to FE-ATLAS2-RENDER-214: the AtlasGlobe component wiring a (faked) GlobeEngine
// to its props: lifecycle, callbacks, painting, theme, inset and the label overlay.
import { act, render } from '@testing-library/react';
import { createRef, type ComponentProps } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { AtlasMeshManifest, GlobeEngine, GlobeEngineOptions, GlobeHit } from './GlobeEngine';
import type { GlobeTheme } from './GlobeRenderer';
const h = vi.hoisted(() => {
const state = { engines: [] as FakeEngine[], failNext: null as unknown };
class FakeEngine {
opts: GlobeEngineOptions;
manifest: AtlasMeshManifest | null = null;
onRegionLoaded: ((a2: string) => void) | null = null;
themes: GlobeTheme[] = [];
insets: number[] = [];
kicks = 0;
disposed = false;
constructor(opts: GlobeEngineOptions) {
if (state.failNext !== null) {
const err = state.failNext;
state.failNext = null;
throw err;
}
this.opts = opts;
state.engines.push(this);
}
setTheme(theme: GlobeTheme): void {
this.themes.push(theme);
}
setInsetBottom(px: number): void {
this.insets.push(px);
}
kick(): void {
this.kicks++;
}
dispose(): void {
this.disposed = true;
}
}
const placeLabels = vi.fn(
(
_host: HTMLDivElement,
_pool: unknown[],
_engine: GlobeEngine,
_labelFor: (a2: string) => string | null,
_labelRegionsOf?: (a2: string) => boolean
) => undefined
);
return { FakeEngine, state, placeLabels };
});
vi.mock('./GlobeEngine', () => ({ GlobeEngine: h.FakeEngine }));
vi.mock('./globeLabels', () => ({ placeLabels: h.placeLabels }));
import AtlasGlobe, { type AtlasGlobeHandle } from './AtlasGlobe';
type Props = ComponentProps<typeof AtlasGlobe>;
const MANIFEST = {
version: 1,
lods: ['110m'],
regionLods: [],
world: {},
countries: [],
} as unknown as AtlasMeshManifest;
function baseProps(over: Partial<Props> = {}): Props {
return {
fetchJson: vi.fn(async (_path: string) => ({})),
dark: true,
labelFor: (a2: string) => a2,
paint: vi.fn(),
paintKey: 1,
...over,
};
}
function engine(i = 0): InstanceType<typeof h.FakeEngine> {
const e = h.state.engines[i];
if (!e) throw new Error(`no engine ${i}`);
return e;
}
/** The fake as the GlobeEngine the callbacks hand around. */
function asEngine(e: InstanceType<typeof h.FakeEngine>): GlobeEngine {
return e as unknown as GlobeEngine;
}
beforeEach(() => {
h.state.engines.length = 0;
h.state.failNext = null;
h.placeLabels.mockClear();
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('AtlasGlobe', () => {
it('FE-ATLAS2-RENDER-200: renders the canvas as an image named Atlas with a hidden label layer', () => {
const { container, getByRole } = render(<AtlasGlobe {...baseProps({ className: 'globe-host' })} />);
const canvas = getByRole('img', { name: 'Atlas' });
expect(canvas.tagName).toBe('CANVAS');
expect(container.firstElementChild).toHaveClass('globe-host');
expect(container.querySelector('[aria-hidden="true"]')).not.toBeNull();
});
it('FE-ATLAS2-RENDER-201: creates one engine on the canvas with the theme for the mode', () => {
const { getByRole } = render(<AtlasGlobe {...baseProps({ dark: false })} />);
expect(h.state.engines).toHaveLength(1);
expect(engine().opts.canvas).toBe(getByRole('img', { name: 'Atlas' }));
expect(engine().opts.theme.dark).toBe(false);
});
it('FE-ATLAS2-RENDER-202: exposes the engine through the ref and drops it on unmount', () => {
const ref = createRef<AtlasGlobeHandle>();
const { unmount } = render(<AtlasGlobe ref={ref} {...baseProps()} />);
const e = engine();
expect(ref.current?.engine).toBe(e);
unmount();
expect(e.disposed).toBe(true);
});
it('FE-ATLAS2-RENDER-203: reports an engine that cannot start to onError and keeps no engine', () => {
const onError = vi.fn();
const err = new Error('WebGL2 unavailable');
h.state.failNext = err;
const ref = createRef<AtlasGlobeHandle>();
const { unmount } = render(<AtlasGlobe ref={ref} {...baseProps({ onError })} />);
expect(onError).toHaveBeenCalledWith(err);
expect(ref.current?.engine).toBeNull();
expect(() => unmount()).not.toThrow();
});
it('FE-ATLAS2-RENDER-204: an engine failure without onError is swallowed quietly', () => {
h.state.failNext = new Error('nope');
expect(() => render(<AtlasGlobe {...baseProps()} />)).not.toThrow();
expect(h.state.engines).toHaveLength(0);
});
it('FE-ATLAS2-RENDER-205: fetches through the latest fetchJson prop', async () => {
const first = vi.fn(async (_path: string) => 'first');
const second = vi.fn(async (_path: string) => 'second');
const { rerender } = render(<AtlasGlobe {...baseProps({ fetchJson: first })} />);
rerender(<AtlasGlobe {...baseProps({ fetchJson: second })} />);
await expect(engine().opts.fetchJson('manifest')).resolves.toBe('second');
expect(second).toHaveBeenCalledWith('manifest');
expect(first).not.toHaveBeenCalled();
});
it('FE-ATLAS2-RENDER-206: forwards hover, select and error to the current callbacks', () => {
const onHover = vi.fn();
const onSelect = vi.fn();
const onError = vi.fn();
render(<AtlasGlobe {...baseProps({ onHover, onSelect, onError })} />);
const hit: GlobeHit = { kind: 'country', index: 4, a2: 'DE' };
const opts = engine().opts;
opts.onHover?.(hit, 1, 2);
opts.onSelect?.(null, 3, 4);
opts.onError?.('boom');
expect(onHover).toHaveBeenCalledWith(hit, 1, 2);
expect(onSelect).toHaveBeenCalledWith(null, 3, 4);
expect(onError).toHaveBeenCalledWith('boom');
});
it('FE-ATLAS2-RENDER-207: callbacks without handlers do nothing', () => {
render(<AtlasGlobe {...baseProps()} />);
const opts = engine().opts;
expect(() => {
opts.onHover?.(null, 0, 0);
opts.onSelect?.(null, 0, 0);
opts.onError?.(new Error('x'));
opts.onFrame?.(asEngine(engine()));
}).not.toThrow();
});
it('FE-ATLAS2-RENDER-208: when the engine is ready it reports the manifest and paints', () => {
const paint = vi.fn();
const onReady = vi.fn();
render(<AtlasGlobe {...baseProps({ paint, onReady })} />);
const e = engine();
e.manifest = MANIFEST;
act(() => e.opts.onReady?.());
expect(onReady).toHaveBeenCalledWith(MANIFEST);
// Once from onReady, once from the paint effect now that the globe is ready.
expect(paint).toHaveBeenCalledTimes(2);
expect(paint).toHaveBeenCalledWith(e);
expect(e.kicks).toBe(1);
});
it('FE-ATLAS2-RENDER-209: a ready engine without a manifest still paints but reports nothing', () => {
const paint = vi.fn();
const onReady = vi.fn();
render(<AtlasGlobe {...baseProps({ paint, onReady })} />);
act(() => engine().opts.onReady?.());
expect(onReady).not.toHaveBeenCalled();
expect(paint).toHaveBeenCalled();
});
it('FE-ATLAS2-RENDER-210: does not paint before the engine is ready, nor without a paint key', () => {
const paint = vi.fn();
const { rerender } = render(<AtlasGlobe {...baseProps({ paint, paintKey: undefined })} />);
expect(paint).not.toHaveBeenCalled();
act(() => engine().opts.onReady?.());
// onReady paints; the effect stays quiet while paintKey is undefined.
expect(paint).toHaveBeenCalledTimes(1);
expect(engine().kicks).toBe(0);
rerender(<AtlasGlobe {...baseProps({ paint, paintKey: 'k1' })} />);
expect(paint).toHaveBeenCalledTimes(2);
expect(engine().kicks).toBe(1);
});
it('FE-ATLAS2-RENDER-211: repaints and kicks the engine when the paint key changes', () => {
const paint = vi.fn();
const { rerender } = render(<AtlasGlobe {...baseProps({ paint, paintKey: 1 })} />);
act(() => engine().opts.onReady?.());
const before = paint.mock.calls.length;
rerender(<AtlasGlobe {...baseProps({ paint, paintKey: 2 })} />);
expect(paint.mock.calls.length).toBe(before + 1);
rerender(<AtlasGlobe {...baseProps({ paint, paintKey: 2 })} />);
expect(paint.mock.calls.length).toBe(before + 1);
});
it('FE-ATLAS2-RENDER-212: a loaded region repaints through the latest paint prop', () => {
const first = vi.fn();
const second = vi.fn();
const { rerender } = render(<AtlasGlobe {...baseProps({ paint: first })} />);
rerender(<AtlasGlobe {...baseProps({ paint: second })} />);
engine().onRegionLoaded?.('DE');
expect(second).toHaveBeenCalledWith(engine());
expect(first).not.toHaveBeenCalled();
});
it('FE-ATLAS2-RENDER-213: switching dark mode hands the engine the other theme', () => {
const { rerender } = render(<AtlasGlobe {...baseProps({ dark: true })} />);
rerender(<AtlasGlobe {...baseProps({ dark: false })} />);
const themes = engine().themes.map((t) => t.dark);
expect(themes[themes.length - 1]).toBe(false);
expect(themes[0]).toBe(true);
});
it('FE-ATLAS2-RENDER-214: passes the bottom inset on, zero when none is given', () => {
const { rerender } = render(<AtlasGlobe {...baseProps()} />);
expect(engine().insets).toEqual([0]);
rerender(<AtlasGlobe {...baseProps({ insetBottom: 120 })} />);
expect(engine().insets).toEqual([0, 120]);
});
it('FE-ATLAS2-RENDER-215: every frame places the labels with the current label props and reports it', () => {
const onFrame = vi.fn();
const labelFor = (a2: string) => `Land ${a2}`;
const labelRegionsOf = (a2: string) => a2 === 'DE';
const { container } = render(<AtlasGlobe {...baseProps({ onFrame, labelFor, labelRegionsOf })} />);
const e = asEngine(engine());
engine().opts.onFrame?.(e);
engine().opts.onFrame?.(e);
expect(h.placeLabels).toHaveBeenCalledTimes(2);
const [host, pool, eng, lf, lr] = h.placeLabels.mock.calls[0];
expect(host).toBe(container.querySelector('[aria-hidden="true"]'));
expect(Array.isArray(pool)).toBe(true);
// The pool is kept across frames, so labels are reused rather than rebuilt.
expect(h.placeLabels.mock.calls[1][1]).toBe(pool);
expect(eng).toBe(e);
expect(lf).toBe(labelFor);
expect(lr).toBe(labelRegionsOf);
expect(onFrame).toHaveBeenCalledWith(e);
});
it('FE-ATLAS2-RENDER-216: a frame after unmount skips the labels', () => {
const { unmount } = render(<AtlasGlobe {...baseProps()} />);
const e = engine();
unmount();
e.opts.onFrame?.(asEngine(e));
expect(h.placeLabels).not.toHaveBeenCalled();
});
});
@@ -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;
}
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 = '#f4f4f5'; // theme-lint-disable: medal line art
const ACCENT = '#d4d4d8'; // 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(255 255 255 / 0.22)" />
<stop offset="0.55" stopColor="rgb(39 39 42 / 0.82)" />
<stop offset="1" stopColor="rgb(14 14 16 / 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>
);
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,863 @@
/**
* 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,
latLimits,
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. */
const REGION_FADE_START = 5;
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 };
/**
* What one visit to the Atlas loaded and built, kept for the next one in this
* tab: the manifest and the built world meshes, by file name (the name carries
* the content hash). Coming back then puts the globe up at once, instead of
* reading and triangulating the world again behind a loading notice. A new
* page load starts empty, so a deploy's new geometry is read as before.
*/
let keptManifest: Promise<AtlasMeshManifest> | null = null;
const keptWorlds = new Map<string, BuiltLayer>();
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();
/** Countries whose regions show at every zoom, not only once zoomed in (the regions view). */
private pinned: 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 {
keptManifest ??= this.fetchRetrying('manifest') as Promise<AtlasMeshManifest>;
try {
this.manifest = await keptManifest;
} catch (err) {
// A failed read is not kept: the next visit asks again.
keptManifest = null;
throw err;
}
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 file = this.manifest.world[lod];
let layer = keptWorlds.get(file);
if (!layer) {
const topo = (await this.fetchRetrying(`world/${file}`)) as Topology;
layer = await this.build(topo, 'countries', MAX_EDGE[lod], 0);
keptWorlds.set(file, layer);
}
if (!this.alive) return;
this.renderer.setWorld(lod, layer);
this.kick();
} finally {
this.worldLoading.delete(lod);
}
}
/**
* Shows these countries' regions at every zoom instead of only once zoomed
* in, so a country with a few visited regions reads as those regions rather
* than as a whole visited country. An empty list goes back to the usual fade.
*/
setPinnedRegions(a2s: readonly string[]): void {
this.pinned = new Set(a2s);
this.kick();
}
/** The region layers that must stay on the GPU: those in view and the pinned countries' coarse ones. */
private regionsInUse(): ReadonlySet<string> {
if (!this.pinned.size) return this.inViewRegionKeys;
return new Set([...this.inViewRegionKeys, ...[...this.pinned].map((a2) => `${a2}:r0`)]);
}
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.regionsInUse());
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 = this.clampLat(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 = this.clampLat(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);
}
/** A latitude for the view's centre, held where the map's edges stay off screen. */
private clampLat(lat: number): number {
const [south, north] = latLimits(this.cam.zoom, this.vp);
return Math.max(south, Math.min(north, lat));
}
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 = this.clampLat(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;
// Zooming into the flat map narrows how far north and south it may look.
this.cam.lat = this.clampLat(this.cam.lat);
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');
}
}
// The pinned countries' coarse regions, wherever the camera is.
for (const a2 of this.pinned) {
if (!this.manifest?.regions[a2]) continue;
this.renderer.touchRegion(`${a2}:r0`);
void this.loadRegion(a2, 'r0');
}
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,
pinnedRegions: this.pinned,
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[] {
const out: string[] = [];
// Pinned countries draw their regions before the zoom brings the rest in.
for (const a2 of this.pinned) {
if (this.regionAlpha <= 0 && this.renderer.hasRegion(`${a2}:r0`)) out.push(`${a2}:r0`);
}
if (this.regionAlpha <= 0) return out;
const fine = this.cam.zoom >= REGION_FINE_ZOOM;
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,119 @@
// FE-ATLAS2-RENDER-400 to FE-ATLAS2-RENDER-406: wishes pinned on the globe, placed per frame and hidden
// behind the horizon or off screen.
import { act, fireEvent, render, screen } from '@testing-library/react';
import { createRef, type RefObject } from 'react';
import { describe, expect, it, vi } from 'vitest';
import type { GlobeEngine } from './GlobeEngine';
import GlobePins, { type GlobePin, type GlobePinsHandle } from './GlobePins';
import type { ScreenPoint } from './globeMath';
/** An engine whose projection answers from a table keyed by "lon,lat". */
function fakeEngine(points: Record<string, ScreenPoint>, width = 800, height = 600) {
const project = vi.fn((lon: number, lat: number): ScreenPoint => {
const p = points[`${lon},${lat}`];
if (!p) throw new Error(`unexpected point ${lon},${lat}`);
return p;
});
const engine = { vp: { width, height, baseRadius: 1, globeY: 0, flatY: 0 }, project } as unknown as GlobeEngine;
return { engine, project };
}
function handle(ref: RefObject<GlobePinsHandle | null>): GlobePinsHandle {
if (!ref.current) throw new Error('GlobePins handle missing');
return ref.current;
}
const PARIS: GlobePin = { key: 'paris', lon: 2, lat: 49, title: 'Paris' };
const KYOTO: GlobePin = { key: 'kyoto', lon: 136, lat: 35, title: 'Kyoto', reached: true };
describe('GlobePins', () => {
it('FE-ATLAS2-RENDER-400: renders one labelled star button per pin, marking reached wishes', () => {
render(<GlobePins pins={[PARIS, KYOTO]} />);
const paris = screen.getByRole('button', { name: 'Paris' });
const kyoto = screen.getByRole('button', { name: 'Kyoto' });
expect(paris).toHaveAttribute('title', 'Paris');
expect(paris).toHaveAttribute('data-reached', '0');
expect(kyoto).toHaveAttribute('data-reached', '1');
expect(paris).toHaveAttribute('data-no-press');
expect(paris.querySelector('svg')).not.toBeNull();
});
it('FE-ATLAS2-RENDER-401: clicking a pin runs its action', () => {
const onClick = vi.fn();
render(<GlobePins pins={[{ ...PARIS, onClick }]} />);
fireEvent.click(screen.getByRole('button', { name: 'Paris' }));
expect(onClick).toHaveBeenCalledTimes(1);
});
it('FE-ATLAS2-RENDER-402: moves a visible pin to its screen point and makes it clickable', () => {
const ref = createRef<GlobePinsHandle>();
render(<GlobePins ref={ref} pins={[PARIS]} />);
const { engine, project } = fakeEngine({ '2,49': { x: 120.04, y: 80.36, visible: 0.5, shade: 1 } });
act(() => handle(ref).layout(engine));
expect(project).toHaveBeenCalledWith(2, 49);
const pin = screen.getByRole('button', { name: 'Paris' });
expect(pin.style.transform).toBe('translate3d(120.0px, 80.4px, 0) translate(-50%, -50%)');
expect(pin.style.opacity).toBe('1');
expect(pin.style.pointerEvents).toBe('auto');
});
it('FE-ATLAS2-RENDER-403: fades a pin in as it comes over the horizon', () => {
const ref = createRef<GlobePinsHandle>();
render(<GlobePins ref={ref} pins={[PARIS]} />);
const { engine } = fakeEngine({ '2,49': { x: 10, y: 10, visible: 0.1, shade: 0.2 } });
act(() => handle(ref).layout(engine));
const pin = screen.getByRole('button', { name: 'Paris' });
expect(Number(pin.style.opacity)).toBeCloseTo(0.6);
expect(pin.style.pointerEvents).toBe('auto');
});
it('FE-ATLAS2-RENDER-404: hides a pin behind the globe', () => {
const ref = createRef<GlobePinsHandle>();
render(<GlobePins ref={ref} pins={[PARIS]} />);
const { engine } = fakeEngine({ '2,49': { x: 100, y: 100, visible: 0.01, shade: 0 } });
act(() => handle(ref).layout(engine));
const pin = screen.getByRole('button', { name: 'Paris' });
expect(pin.style.opacity).toBe('0');
expect(pin.style.pointerEvents).toBe('none');
});
it('FE-ATLAS2-RENDER-405: hides pins more than 20 px off any edge of the screen', () => {
const ref = createRef<GlobePinsHandle>();
const pins: GlobePin[] = [
{ key: 'l', lon: 1, lat: 0, title: 'Left' },
{ key: 'r', lon: 2, lat: 0, title: 'Right' },
{ key: 't', lon: 3, lat: 0, title: 'Top' },
{ key: 'b', lon: 4, lat: 0, title: 'Bottom' },
{ key: 'edge', lon: 5, lat: 0, title: 'Edge' },
];
render(<GlobePins ref={ref} pins={pins} />);
const { engine } = fakeEngine(
{
'1,0': { x: -21, y: 100, visible: 1, shade: 1 },
'2,0': { x: 821, y: 100, visible: 1, shade: 1 },
'3,0': { x: 100, y: -21, visible: 1, shade: 1 },
'4,0': { x: 100, y: 621, visible: 1, shade: 1 },
'5,0': { x: -19, y: 619, visible: 1, shade: 1 },
},
800,
600
);
act(() => handle(ref).layout(engine));
for (const title of ['Left', 'Right', 'Top', 'Bottom']) {
expect(screen.getByRole('button', { name: title }).style.opacity).toBe('0');
}
expect(screen.getByRole('button', { name: 'Edge' }).style.opacity).toBe('1');
});
it('FE-ATLAS2-RENDER-406: after the pin list changes, layout places the new pins', () => {
const ref = createRef<GlobePinsHandle>();
const { rerender } = render(<GlobePins ref={ref} pins={[PARIS]} />);
rerender(<GlobePins ref={ref} pins={[KYOTO]} />);
expect(screen.queryByRole('button', { name: 'Paris' })).toBeNull();
const { engine, project } = fakeEngine({ '136,35': { x: 5, y: 5, visible: 1, shade: 1 } });
act(() => handle(ref).layout(engine));
expect(project).toHaveBeenCalledTimes(1);
expect(screen.getByRole('button', { name: 'Kyoto' }).style.pointerEvents).toBe('auto');
});
});
@@ -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,700 @@
// FE-ATLAS2-RENDER-001 to FE-ATLAS2-RENDER-040: the WebGL2 renderer of the Atlas globe, driven
// against a hand-written WebGL2 fake that records draws, uniforms and buffer lifetimes.
import { describe, expect, it } from 'vitest';
import { createFakeGl, GL, type FakeGl, type FakeGlOptions } from '../../../tests/helpers/fakeWebGl2';
import { GlobeRenderer, MAX_FEATURES, type ArcLayer, type DrawState, type GlobeTheme } from './GlobeRenderer';
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';
const DARK: GlobeTheme = {
land: [0.19, 0.19, 0.2],
ocean: [0.08, 0.08, 0.09],
oceanDeep: [0.03, 0.03, 0.03],
space0: [0.01, 0.01, 0.01],
space1: [0.04, 0.04, 0.04],
glow: [0.18, 0.18, 0.19],
border: [0.05, 0.05, 0.06, 0.9],
coast: [0.85, 0.85, 0.87, 0.14],
regionBorder: [0.95, 0.95, 0.95, 0.5],
selection: [1, 1, 1, 0.95],
arc: [0.9, 0.9, 0.9, 0.8],
dark: true,
};
const LIGHT: GlobeTheme = { ...DARK, dark: false };
function fill(tris: number): FillMesh {
return {
ll: new Float32Array(6),
ref: new Float32Array(6),
fid: new Float32Array(3),
index: new Uint32Array(tris * 3),
};
}
function lines(count: number): LineMesh {
return { seg: new Float32Array(count * 4), count };
}
function layer(tris: number, coast: number, borders: number): BuiltLayer {
return { fill: fill(tris), coast: lines(coast), borders: lines(borders) };
}
function arc(count: number, width = 2): ArcLayer {
return { data: new Float32Array(count * 8), count, width };
}
function state(over: Partial<DrawState> = {}): DrawState {
return {
frame: { t: 0.25, k: 1, scale: 200, originX: 400, originY: 300, centerLon: 0.1, centerLat: 0.2 },
dpr: 2,
width: 800,
height: 600,
time: 1.5,
revealStart: 0.75,
hover: 3,
selected: 7,
ink: null,
regionAlpha: 0,
theme: DARK,
arcs: [],
arcProgress: 0.6,
regionKeys: [],
worldKey: 'w',
selectedOutline: null,
sun: [1, 0, 0],
night: 0.5,
...over,
};
}
function setup(opts: FakeGlOptions = {}): { fake: FakeGl; r: GlobeRenderer } {
const fake = createFakeGl(opts);
const r = new GlobeRenderer(fake.canvas());
return { fake, r };
}
/** Fill draws with this triangle count. */
function fillDraws(fake: FakeGl, count: number) {
return fake.drawsWith(FILL_FS).filter((d) => d.call === 'drawElements' && d.count === count);
}
function lineDraws(fake: FakeGl, instances: number) {
return fake.drawsWith(LINE_FS).filter((d) => d.call === 'drawArraysInstanced' && d.instances === instances);
}
function deletedBuffers(fake: FakeGl): unknown[] {
return fake.gl.deleteBuffer.mock.calls.map((c) => c[0]);
}
describe('GlobeRenderer setup', () => {
it('FE-ATLAS2-RENDER-001: throws when the canvas has no WebGL2 context', () => {
const canvas = { getContext: () => null } as unknown as HTMLCanvasElement;
expect(() => new GlobeRenderer(canvas)).toThrow('WebGL2 unavailable');
});
it('FE-ATLAS2-RENDER-002: asks for an opaque, antialiased webgl2 context', () => {
const fake = createFakeGl();
const canvas = fake.canvas();
const r = new GlobeRenderer(canvas);
expect(r.gl).toBe(fake.gl);
expect(canvas.getContext).toHaveBeenCalledWith('webgl2', {
antialias: true,
alpha: false,
premultipliedAlpha: false,
preserveDrawingBuffer: false,
});
});
it('FE-ATLAS2-RENDER-003: links the five programs from the right shader pairs', () => {
const { fake } = setup();
expect(fake.programs.map((p) => p.srcs)).toEqual([
[FILL_VS, FILL_FS],
[FILL_VS, PICK_FS],
[LINE_VS, LINE_FS],
[SKY_VS, SKY_FS],
[SKY_VS, RIM_FS],
]);
expect(fake.gl.linkProgram).toHaveBeenCalledTimes(5);
});
it('FE-ATLAS2-RENDER-004: makes two 256x64 nearest-filtered status textures', () => {
const { fake } = setup();
expect(fake.textures).toHaveLength(2);
const sizes = fake.gl.texImage2D.mock.calls.map((c) => [c[3], c[4]]);
expect(sizes).toEqual([
[256, 64],
[256, 64],
]);
expect(fake.gl.texParameteri).toHaveBeenCalledWith(GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER, GL.NEAREST);
expect(fake.gl.texParameteri).toHaveBeenCalledWith(GL.TEXTURE_2D, GL.TEXTURE_MAG_FILTER, GL.NEAREST);
expect(MAX_FEATURES).toBe(256 * 64);
});
it('FE-ATLAS2-RENDER-005: a shader that fails to compile throws with its log and is deleted', () => {
const fake = createFakeGl({ compileOk: (src) => src !== PICK_FS, shaderLog: 'syntax error at 3' });
expect(() => new GlobeRenderer(fake.canvas())).toThrow('Atlas globe shader failed: syntax error at 3');
expect(fake.gl.deleteShader).toHaveBeenCalledTimes(1);
});
it('FE-ATLAS2-RENDER-006: a compile failure without a log says unknown', () => {
const fake = createFakeGl({ compileOk: () => false, shaderLog: null });
expect(() => new GlobeRenderer(fake.canvas())).toThrow('Atlas globe shader failed: unknown');
});
it('FE-ATLAS2-RENDER-007: a program that fails to link throws with its log, or unknown', () => {
const withLog = createFakeGl({ linkOk: false, programLog: 'varying mismatch' });
expect(() => new GlobeRenderer(withLog.canvas())).toThrow('Atlas globe program failed: varying mismatch');
const noLog = createFakeGl({ linkOk: false, programLog: null });
expect(() => new GlobeRenderer(noLog.canvas())).toThrow('Atlas globe program failed: unknown');
});
it('FE-ATLAS2-RENDER-008: binds the full-screen quad for the sky and the rim', () => {
const { fake } = setup();
// a_pos is attribute 0 of both SKY_VS programs, set up once inside the quad VAO each.
const quadAttr = fake.gl.vertexAttribPointer.mock.calls.filter((c) => c[0] === 0 && c[1] === 2 && c[4] === 0);
expect(quadAttr.length).toBeGreaterThanOrEqual(2);
const quadData = fake.buffers.find((b) => b.data instanceof Float32Array && b.data.length === 8);
expect(Array.from(quadData?.data as Float32Array)).toEqual([-1, -1, 1, -1, -1, 1, 1, 1]);
});
it('FE-ATLAS2-RENDER-009: skips attributes a compiler dropped or placed at -1', () => {
const { fake, r } = setup({
attribLocation: (fs, name, i) => {
if (fs === RIM_FS && name === 'a_pos') return null;
if (fs === PICK_FS && name === 'a_ref') return -1;
if (fs === LINE_FS && name === 'a_h') return null;
if (fs === LINE_FS && name === 'a_s') return -1;
return i;
},
});
expect(fake.programWith(RIM_FS).attribs).toEqual([]);
r.setWorld('w', layer(2, 1, 1));
r.draw(state({ arcs: [arc(3)] }));
expect(fake.gl.enableVertexAttribArray.mock.calls.some((c) => c[0] === -1)).toBe(false);
expect(fake.gl.vertexAttribPointer.mock.calls.some((c) => c[0] === -1)).toBe(false);
// Only a_a and a_b get a divisor once a_h and a_s are gone.
const line = fake.programWith(LINE_FS);
const divisorLocs = new Set(fake.gl.vertexAttribDivisor.mock.calls.map((c) => c[0]));
expect(divisorLocs).toEqual(new Set([line.attribLoc.get('a_a'), line.attribLoc.get('a_b')]));
});
});
describe('GlobeRenderer draw', () => {
it('FE-ATLAS2-RENDER-010: sets every uniform it uses on a location its shaders declare', () => {
const { fake, r } = setup();
r.setOcean(fill(5));
r.setWorld('w', layer(2, 1, 1));
r.setRegion('DE', layer(4, 1, 1));
r.draw(
state({
regionAlpha: 1,
regionKeys: ['DE'],
arcs: [arc(2)],
selectedOutline: lines(2),
ink: { id: 1, lon: 0, lat: 0, radius: 1 },
})
);
const methods = [
fake.gl.uniform1f,
fake.gl.uniform1i,
fake.gl.uniform2f,
fake.gl.uniform4f,
fake.gl.uniform3fv,
fake.gl.uniform4fv,
];
for (const m of methods) {
for (const call of m.mock.calls) expect(call[0]).toBeDefined();
}
});
it('FE-ATLAS2-RENDER-011: sizes the viewport in device pixels and draws the sky first', () => {
const { fake, r } = setup();
r.draw(state({ width: 800.4, height: 600, dpr: 2 }));
expect(fake.gl.viewport).toHaveBeenCalledWith(0, 0, 1601, 1200);
expect(fake.enabled.has(GL.BLEND)).toBe(true);
expect(fake.enabled.has(GL.DEPTH_TEST)).toBe(false);
const first = fake.draws[0];
expect(first.program?.srcs[1]).toBe(SKY_FS);
expect(first.call).toBe('drawArrays');
expect(first.mode).toBe(GL.TRIANGLE_STRIP);
expect(first.count).toBe(4);
expect(first.values.u_viewport).toEqual([1601, 1200]);
expect(first.values.u_globe).toEqual([800, 600]);
expect(first.values.u_radius).toBe(400);
expect(first.values.u_t).toBe(0.25);
expect(first.values.u_time).toBe(1.5);
expect(first.values.u_space0).toEqual(DARK.space0);
expect(first.values.u_space1).toEqual(DARK.space1);
expect(first.values.u_dark).toBe(1);
});
it('FE-ATLAS2-RENDER-012: draws the rim last, over the limb, and unbinds the VAO', () => {
const { fake, r } = setup();
r.draw(state());
const last = fake.draws[fake.draws.length - 1];
expect(last.program?.srcs[1]).toBe(RIM_FS);
expect(last.values.u_glow).toEqual(DARK.glow);
expect(last.values.u_radius).toBe(400);
expect(fake.gl.bindVertexArray).toHaveBeenLastCalledWith(null);
});
it('FE-ATLAS2-RENDER-013: passes the projection to the fill program in device pixels', () => {
const { fake, r } = setup();
r.setOcean(fill(5));
r.draw(state());
const [ocean] = fillDraws(fake, 15);
expect(ocean.values.u_center).toEqual([0.1, 0.2]);
expect(ocean.values.u_scale).toBe(400);
expect(ocean.values.u_origin).toEqual([800, 600]);
expect(ocean.values.u_viewport).toEqual([1600, 1200]);
expect(ocean.values.u_status).toBe(0);
expect(ocean.values.u_fx).toBe(1);
expect(ocean.values.u_hover).toBe(3);
expect(ocean.values.u_selected).toBe(7);
expect(ocean.values.u_revealStart).toBe(0.75);
expect(ocean.values.u_sun).toEqual([1, 0, 0]);
expect(ocean.values.u_night).toBe(0.5);
expect(ocean.values.u_dpr).toBe(2);
});
it('FE-ATLAS2-RENDER-014: draws the ocean in mode 1 only once it is set', () => {
const { fake, r } = setup();
r.draw(state());
expect(fake.drawsWith(FILL_FS)).toHaveLength(0);
r.setOcean(fill(5));
r.draw(state());
const ocean = fillDraws(fake, 15);
expect(ocean).toHaveLength(1);
expect(ocean[0].values.u_mode).toBe(1);
expect(ocean[0].mode).toBe(GL.TRIANGLES);
});
it('FE-ATLAS2-RENDER-015: dark mode lights a hovered country up and keeps the limb darker', () => {
const { fake, r } = setup();
r.setOcean(fill(1));
r.draw(state({ theme: DARK }));
const [d] = fillDraws(fake, 3);
expect(d.values.u_shadeMin).toBe(0.42);
expect(d.values.u_hoverTint).toEqual([1, 1, 1, 0.09]);
});
it('FE-ATLAS2-RENDER-016: light mode tints a hovered country blue and keeps the limb bright', () => {
const { fake, r } = setup();
r.setOcean(fill(1));
r.draw(state({ theme: LIGHT }));
const [d] = fillDraws(fake, 3);
expect(d.values.u_shadeMin).toBe(0.82);
expect(d.values.u_hoverTint).toEqual([0.42, 0.56, 0.82, 0.16]);
expect(fake.drawsWith(SKY_FS)[0].values.u_dark).toBe(0);
});
it('FE-ATLAS2-RENDER-017: hands the ink spot over in radians, or a neutral one without ink', () => {
const { fake, r } = setup();
r.setOcean(fill(1));
r.draw(state({ ink: { id: 42, lon: 180, lat: -90, radius: 0.3 } }));
r.draw(state({ ink: null }));
const [withInk, without] = fillDraws(fake, 3);
expect(withInk.values.u_inkId).toBe(42);
const [inkLon, inkLat] = withInk.values.u_inkLL as number[];
expect(inkLon).toBeCloseTo(Math.PI);
expect(inkLat).toBeCloseTo(-Math.PI / 2);
expect(withInk.values.u_inkR).toBe(0.3);
expect(without.values.u_inkId).toBe(-1);
expect(without.values.u_inkLL).toEqual([0, 0]);
expect(without.values.u_inkR).toBe(0);
});
});
describe('GlobeRenderer status textures', () => {
it('FE-ATLAS2-RENDER-018: uploads status and fx once at the first draw, then only when dirty', () => {
const { fake, r } = setup();
r.draw(state());
expect(fake.statusUploads).toHaveLength(2);
r.draw(state());
expect(fake.statusUploads).toHaveLength(2);
});
it('FE-ATLAS2-RENDER-019: writes a feature colour and effects at its four bytes', () => {
const { fake, r } = setup();
r.draw(state());
r.setStatus(3, [10, 20, 30, 40], [1, 2, 3, 4]);
r.draw(state());
const [status, fx] = fake.statusUploads.slice(2);
expect(Array.from(status.slice(12, 16))).toEqual([10, 20, 30, 40]);
expect(Array.from(fx.slice(12, 16))).toEqual([1, 2, 3, 4]);
expect(status.length).toBe(MAX_FEATURES * 4);
});
it('FE-ATLAS2-RENDER-020: leaves the effects empty when only a colour is given', () => {
const { fake, r } = setup();
r.setStatus(5, [9, 9, 9, 255], [7, 7, 7, 7]);
r.setStatus(5, [1, 2, 3, 4]);
r.draw(state());
const [status, fx] = fake.statusUploads;
expect(Array.from(status.slice(20, 24))).toEqual([1, 2, 3, 4]);
expect(Array.from(fx.slice(20, 24))).toEqual([0, 0, 0, 0]);
});
it('FE-ATLAS2-RENDER-021: ignores ids outside the texture without marking it dirty', () => {
const { fake, r } = setup();
r.draw(state());
r.setStatus(-1, [1, 1, 1, 1]);
r.setStatus(MAX_FEATURES, [1, 1, 1, 1]);
r.draw(state());
expect(fake.statusUploads).toHaveLength(2);
});
it('FE-ATLAS2-RENDER-022: clearStatus zeroes a range of ids and re-uploads', () => {
const { fake, r } = setup();
r.setStatus(1, [1, 1, 1, 1], [1, 1, 1, 1]);
r.setStatus(2, [2, 2, 2, 2], [2, 2, 2, 2]);
r.setStatus(4, [4, 4, 4, 4], [4, 4, 4, 4]);
r.draw(state());
r.clearStatus(1, 3);
r.draw(state());
const [status, fx] = fake.statusUploads.slice(2);
expect(Array.from(status.slice(4, 12))).toEqual([0, 0, 0, 0, 0, 0, 0, 0]);
expect(Array.from(fx.slice(4, 12))).toEqual([0, 0, 0, 0, 0, 0, 0, 0]);
expect(Array.from(status.slice(16, 20))).toEqual([4, 4, 4, 4]);
});
});
describe('GlobeRenderer world layers', () => {
it('FE-ATLAS2-RENDER-023: draws the world named by the frame, in mode 0 with its lines', () => {
const { fake, r } = setup();
expect(r.hasWorld('w')).toBe(false);
r.setWorld('w', layer(2, 3, 4));
expect(r.hasWorld('w')).toBe(true);
r.draw(state({ regionAlpha: 0.4 }));
const [world] = fillDraws(fake, 6);
expect(world.values.u_mode).toBe(0);
expect(world.values.u_dimBase).toBe(1);
expect(world.values.u_regionFade).toBe(0.4);
const [borders] = lineDraws(fake, 4);
expect(borders.values.u_color).toEqual(DARK.border);
expect(borders.values.u_width).toBeCloseTo(1.6);
expect(borders.values.u_lift).toBe(0);
expect(borders.values.u_progress).toBe(2);
const [coast] = lineDraws(fake, 3);
expect(coast.values.u_color).toEqual(DARK.coast);
expect(coast.values.u_width).toBeCloseTo(1.8);
expect(coast.count).toBe(6);
});
it('FE-ATLAS2-RENDER-024: draws no world when the frame names one that is not loaded', () => {
const { fake, r } = setup();
r.setWorld('w', layer(2, 3, 4));
r.draw(state({ worldKey: 'w-fine' }));
expect(fillDraws(fake, 6)).toHaveLength(0);
expect(fake.drawsWith(LINE_FS)).toHaveLength(0);
});
it('FE-ATLAS2-RENDER-025: skips a line mesh without segments', () => {
const { fake, r } = setup();
r.setWorld('w', layer(2, 0, 4));
r.draw(state());
const instanced = fake.drawsWith(LINE_FS);
expect(instanced).toHaveLength(1);
expect(instanced[0].instances).toBe(4);
});
it('FE-ATLAS2-RENDER-026: replacing a world frees the old one after the new one is up', () => {
const { fake, r } = setup();
const first = layer(2, 3, 4);
r.setWorld('w', first);
const oldBuffers = [
fake.bufferOf(first.fill.ll),
fake.bufferOf(first.fill.index),
fake.bufferOf(first.coast.seg),
fake.bufferOf(first.borders.seg),
];
const second = layer(1, 1, 1);
r.setWorld('w', second);
const deleted = deletedBuffers(fake);
for (const b of oldBuffers) expect(deleted).toContain(b);
expect(deleted).not.toContain(fake.bufferOf(second.fill.ll));
// fill, pick, coast and border VAOs of the old layer.
expect(fake.gl.deleteVertexArray).toHaveBeenCalledTimes(4);
r.draw(state());
expect(fillDraws(fake, 3)).toHaveLength(1);
});
it('FE-ATLAS2-RENDER-027: uploads fill attributes with the element buffer bound to the VAO', () => {
const { fake, r } = setup();
const l = layer(2, 1, 1);
r.setWorld('w', l);
expect(fake.gl.bufferData).toHaveBeenCalledWith(GL.ELEMENT_ARRAY_BUFFER, l.fill.index, GL.STATIC_DRAW);
expect(fake.gl.bufferData).toHaveBeenCalledWith(GL.ARRAY_BUFFER, l.fill.fid, GL.STATIC_DRAW);
const fillProg = fake.programWith(FILL_FS);
expect(fake.gl.vertexAttribPointer).toHaveBeenCalledWith(fillProg.attribLoc.get('a_fid'), 1, GL.FLOAT, false, 0, 0);
});
});
describe('GlobeRenderer region layers', () => {
it('FE-ATLAS2-RENDER-028: draws loaded regions in mode 2 over the world with faded borders', () => {
const { fake, r } = setup();
r.setWorld('w', layer(1, 0, 0));
r.setRegion('DE', layer(4, 1, 5));
expect(r.hasRegion('DE')).toBe(true);
r.draw(state({ regionAlpha: 0.5, regionKeys: ['FR', 'DE'] }));
const [region] = fillDraws(fake, 12);
expect(region.values.u_mode).toBe(2);
expect(region.values.u_layerAlpha).toBe(0.5);
const [borders] = lineDraws(fake, 5);
expect(borders.values.u_color).toEqual([0.95, 0.95, 0.95, 0.25]);
expect(borders.values.u_width).toBeCloseTo(1.4);
// The theme is not changed by the fade.
expect(DARK.regionBorder[3]).toBe(0.5);
});
it('FE-ATLAS2-RENDER-049: a pinned country draws its regions in full while zoomed out, with faint inner borders', () => {
const { fake, r } = setup();
r.setRegion('DE:r0', layer(4, 1, 5));
r.draw(state({ regionAlpha: 0, regionKeys: ['DE:r0'], pinnedRegions: new Set(['DE']) }));
const [region] = fillDraws(fake, 12);
expect(region.values.u_mode).toBe(2);
expect(region.values.u_layerAlpha).toBe(1);
const [borders] = lineDraws(fake, 5);
expect((borders.values.u_color as number[])[3]).toBeCloseTo(DARK.regionBorder[3] * 0.45);
});
it('FE-ATLAS2-RENDER-029: does not draw regions faded out below the threshold', () => {
const { fake, r } = setup();
r.setRegion('DE', layer(4, 1, 5));
r.draw(state({ regionAlpha: 0.0005, regionKeys: ['DE'] }));
expect(fillDraws(fake, 12)).toHaveLength(0);
expect(lineDraws(fake, 5)).toHaveLength(0);
});
it('FE-ATLAS2-RENDER-030: does not switch to region mode when none of the keys is loaded', () => {
const { fake, r } = setup();
r.setOcean(fill(1));
r.draw(state({ regionAlpha: 1, regionKeys: ['FR'] }));
expect(fake.drawsWith(FILL_FS).every((d) => d.values.u_mode !== 2)).toBe(true);
expect(fake.drawsWith(FILL_FS)[0].values.u_layerAlpha).toBe(1);
});
it('FE-ATLAS2-RENDER-031: replacing a region frees the old layer and keeps one entry', () => {
const { fake, r } = setup();
const first = layer(4, 1, 1);
r.setRegion('DE', first);
r.setRegion('DE', layer(2, 1, 1));
expect(deletedBuffers(fake)).toContain(fake.bufferOf(first.fill.index));
r.draw(state({ regionAlpha: 1, regionKeys: ['DE'] }));
expect(fillDraws(fake, 12)).toHaveLength(0);
expect(fillDraws(fake, 6)).toHaveLength(1);
});
it('FE-ATLAS2-RENDER-032: past 64 region layers drops the one held longest', () => {
const { fake, r } = setup();
const oldest = layer(1, 1, 1);
r.setRegion('r0', oldest);
for (let i = 1; i <= 64; i++) r.setRegion(`r${i}`, layer(1, 1, 1));
expect(r.hasRegion('r0')).toBe(false);
expect(r.hasRegion('r1')).toBe(true);
expect(r.hasRegion('r64')).toBe(true);
expect(deletedBuffers(fake)).toContain(fake.bufferOf(oldest.fill.ll));
});
it('FE-ATLAS2-RENDER-033: never drops a region in use, the next oldest goes instead', () => {
const { r } = setup();
for (let i = 0; i < 64; i++) r.setRegion(`r${i}`, layer(1, 1, 1));
r.setRegion('r64', layer(1, 1, 1), new Set(['r0']));
expect(r.hasRegion('r0')).toBe(true);
expect(r.hasRegion('r1')).toBe(false);
expect(r.hasRegion('r64')).toBe(true);
});
it('FE-ATLAS2-RENDER-034: touching a region makes it the last to go; an unknown key is a no-op', () => {
const { r } = setup();
for (let i = 0; i < 64; i++) r.setRegion(`r${i}`, layer(1, 1, 1));
r.touchRegion('r0');
r.touchRegion('nope');
expect(r.hasRegion('nope')).toBe(false);
r.setRegion('r64', layer(1, 1, 1));
expect(r.hasRegion('r0')).toBe(true);
expect(r.hasRegion('r1')).toBe(false);
});
});
describe('GlobeRenderer outline and arcs', () => {
it('FE-ATLAS2-RENDER-035: draws the selected outline glowing, uploading it once per mesh', () => {
const { fake, r } = setup();
const outline = lines(7);
r.draw(state({ selectedOutline: outline }));
r.draw(state({ selectedOutline: outline }));
const uploads = fake.gl.bufferData.mock.calls.filter((c) => c[1] === outline.seg);
expect(uploads).toHaveLength(1);
const draws = lineDraws(fake, 7);
expect(draws).toHaveLength(2);
expect(draws[0].values.u_glow).toBe(0.55);
expect(draws[0].values.u_color).toEqual(DARK.selection);
expect(draws[0].values.u_width).toBeCloseTo(3.6);
expect(fake.programWith(LINE_FS).values.u_glow).toBe(0);
});
it('FE-ATLAS2-RENDER-036: a new outline frees the buffer of the previous one', () => {
const { fake, r } = setup();
const a = lines(7);
r.draw(state({ selectedOutline: a }));
const aBuffer = fake.bufferOf(a.seg);
expect(deletedBuffers(fake)).not.toContain(aBuffer);
const b = lines(9);
r.draw(state({ selectedOutline: b }));
expect(deletedBuffers(fake)).toContain(aBuffer);
expect(lineDraws(fake, 9)).toHaveLength(1);
});
it('FE-ATLAS2-RENDER-037: draws arcs lifted with their progress, width and glow', () => {
const { fake, r } = setup();
const a = arc(5, 3);
r.draw(state({ arcs: [a], arcProgress: 0.6 }));
const [d] = lineDraws(fake, 5);
expect(d.values.u_lift).toBe(1);
expect(d.values.u_progress).toBe(0.6);
expect(d.values.u_glow).toBe(0.35);
expect(d.values.u_width).toBe(6);
expect(d.values.u_color).toEqual(DARK.arc);
expect(fake.programWith(LINE_FS).values.u_lift).toBe(0);
// An arc carries heights and progress too: stride of eight floats, four attributes per instance.
const line = fake.programWith(LINE_FS);
expect(fake.gl.vertexAttribPointer).toHaveBeenCalledWith(line.attribLoc.get('a_s'), 2, GL.FLOAT, false, 32, 24);
expect(fake.gl.vertexAttribDivisor).toHaveBeenCalledWith(line.attribLoc.get('a_h'), 1);
});
it('FE-ATLAS2-RENDER-038: keeps an arc on the GPU across frames and frees the ones no longer drawn', () => {
const { fake, r } = setup();
const keep = arc(5);
const gone = arc(6);
r.draw(state({ arcs: [keep, gone] }));
r.draw(state({ arcs: [keep] }));
r.draw(state({ arcs: [keep] }));
expect(fake.gl.bufferData.mock.calls.filter((c) => c[1] === keep.data)).toHaveLength(1);
const deleted = deletedBuffers(fake);
expect(deleted).toContain(fake.bufferOf(gone.data));
expect(deleted).not.toContain(fake.bufferOf(keep.data));
expect(lineDraws(fake, 5)).toHaveLength(3);
expect(lineDraws(fake, 6)).toHaveLength(1);
});
});
describe('GlobeRenderer picking', () => {
it('FE-ATLAS2-RENDER-039: returns -1 before any frame was drawn', () => {
const { fake, r } = setup({ pixel: [9, 0, 0, 255] });
expect(r.pick(10, 10, true)).toBe(-1);
expect(fake.framebuffers).toHaveLength(0);
});
it('FE-ATLAS2-RENDER-040: decodes the id under the pointer from the pick pass', () => {
const { fake, r } = setup({ pixel: [5, 1, 0, 255] });
r.setWorld('w', layer(2, 1, 1));
r.draw(state());
expect(r.pick(10.2, 20.4, false)).toBe(5 + 256 - 1);
expect(fake.gl.readPixels).toHaveBeenCalledWith(
20,
1200 - 41 - 1,
1,
1,
GL.RGBA,
GL.UNSIGNED_BYTE,
expect.any(Uint8Array)
);
const picks = fake.drawsWith(PICK_FS);
expect(picks).toHaveLength(1);
expect(picks[0].count).toBe(6);
expect(picks[0].framebuffer).toBe(fake.framebuffers[0]);
expect(picks[0].values.u_scale).toBe(400);
expect(fake.gl.bindFramebuffer).toHaveBeenLastCalledWith(GL.FRAMEBUFFER, null);
expect(fake.enabled.has(GL.BLEND)).toBe(true);
expect(fake.gl.clearColor).toHaveBeenCalledWith(0, 0, 0, 0);
});
it('FE-ATLAS2-RENDER-041: answers -1 on empty sea', () => {
const { r } = setup();
r.draw(state());
expect(r.pick(1, 1, true)).toBe(-1);
});
it('FE-ATLAS2-RENDER-042: reuses the pick target while the size holds and rebuilds it on resize', () => {
const { fake, r } = setup();
r.draw(state());
r.pick(1, 1, false);
r.pick(2, 2, false);
expect(fake.framebuffers).toHaveLength(1);
expect(fake.gl.deleteFramebuffer).not.toHaveBeenCalled();
const firstTex = fake.textures[fake.textures.length - 1];
r.draw(state({ width: 400 }));
r.pick(1, 1, false);
expect(fake.framebuffers).toHaveLength(2);
expect(fake.gl.deleteFramebuffer).toHaveBeenCalledWith(fake.framebuffers[0]);
expect(fake.gl.deleteTexture).toHaveBeenCalledWith(firstTex);
const sized = fake.gl.texImage2D.mock.calls.map((c) => [c[3], c[4]]);
expect(sized).toContainEqual([1600, 1200]);
expect(sized).toContainEqual([800, 1200]);
});
it('FE-ATLAS2-RENDER-043: draws loaded regions into the pick pass only when asked to', () => {
const { fake, r } = setup();
r.setWorld('w', layer(2, 1, 1));
r.setRegion('DE', layer(4, 1, 1));
r.draw(state({ regionKeys: ['DE', 'FR'], regionAlpha: 1 }));
r.pick(1, 1, false);
expect(fake.drawsWith(PICK_FS).map((d) => d.count)).toEqual([6]);
r.pick(1, 1, true);
expect(fake.drawsWith(PICK_FS).map((d) => d.count)).toEqual([6, 6, 12]);
});
it('FE-ATLAS2-RENDER-044: picks without a world when the frame names none that is loaded', () => {
const { fake, r } = setup({ pixel: [3, 0, 0, 255] });
r.draw(state({ worldKey: 'none' }));
expect(r.pick(1, 1, false)).toBe(2);
expect(fake.drawsWith(PICK_FS)).toHaveLength(0);
});
});
describe('GlobeRenderer dispose', () => {
it('FE-ATLAS2-RENDER-045: frees every world and region layer and forgets them', () => {
const { fake, r } = setup();
const w = layer(2, 1, 1);
const reg = layer(3, 1, 1);
r.setWorld('w', w);
r.setRegion('DE', reg);
r.dispose();
expect(r.hasWorld('w')).toBe(false);
expect(r.hasRegion('DE')).toBe(false);
const deleted = deletedBuffers(fake);
expect(deleted).toContain(fake.bufferOf(w.fill.ll));
expect(deleted).toContain(fake.bufferOf(reg.borders.seg));
// World and region: fill, pick, coast and borders each; then the quad.
expect(fake.gl.deleteVertexArray).toHaveBeenCalledTimes(9);
});
it('FE-ATLAS2-RENDER-048: gives back the programs, textures and shared buffers too, so a revisit leaks nothing', () => {
const { fake, r } = setup();
r.dispose();
expect(fake.gl.deleteProgram).toHaveBeenCalledTimes(5);
// The status and fx textures; no pick texture before the first pick.
expect(fake.gl.deleteTexture).toHaveBeenCalledTimes(2);
expect(fake.gl.deleteFramebuffer).not.toHaveBeenCalled();
expect(fake.gl.deleteBuffer).toHaveBeenCalledTimes(2);
});
});
describe('globe shaders', () => {
it('FE-ATLAS2-RENDER-046: every shader is GLSL ES 3.00 with high precision', () => {
for (const src of [FILL_VS, FILL_FS, PICK_FS, LINE_VS, LINE_FS, SKY_VS, SKY_FS, RIM_FS]) {
expect(src.startsWith('#version 300 es\n')).toBe(true);
expect(src).toContain('precision highp float;');
}
});
it('FE-ATLAS2-RENDER-047: the fill and line vertex shaders share the projection the picker relies on', () => {
for (const src of [FILL_VS, LINE_VS]) {
expect(src).toContain('vec4 project(vec2 ll, vec2 ref)');
expect(src).toContain('uniform vec2 u_center;');
}
// pick() subtracts one again: id 0 stays "nothing here".
expect(PICK_FS).toContain('int id = v_fid + 1;');
});
});
@@ -0,0 +1,626 @@
/**
* 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';
const STATUS_TEX_W = 256;
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;
/** Countries whose regions show at full strength at every zoom (the regions view). */
pinnedRegions?: ReadonlySet<string>;
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 quadBuf: WebGLBuffer | null = null;
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();
this.quadBuf = b;
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), regions loaded, visited regions. */
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.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);
}
// A pinned country's regions show whatever the zoom; the rest fade in with it.
const pinnedKey = (k: string) => !!s.pinnedRegions?.has(k.slice(0, k.indexOf(':')));
const fillAlpha = (k: string) => (pinnedKey(k) ? 1 : s.regionAlpha);
const regionsOn = s.regionKeys.some((k) => this.regions.has(k) && fillAlpha(k) > 0.001);
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);
for (const k of s.regionKeys) {
const r = this.regions.get(k);
if (!r) continue;
gl.uniform1f(p.u.u_layerAlpha, fillAlpha(k));
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) {
for (const k of s.regionKeys) {
const r = this.regions.get(k);
if (!r) continue;
// Zoomed out, a pinned country's inner borders stay faint, so it does not turn into a web.
const c = [...th.regionBorder];
c[3] *= pinnedKey(k) ? Math.max(s.regionAlpha, 0.45) : s.regionAlpha;
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;
}
/**
* Gives back everything this renderer put on the GPU. The context itself is
* left alive: React mounts twice in development and the second engine takes
* over the same canvas, so whatever stayed behind here would pile up on it
* with every visit to the Atlas.
*/
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();
const freeLines = (l: GpuLines) => {
for (const b of l.buffers) gl.deleteBuffer(b);
gl.deleteVertexArray(l.vao);
};
if (this.ocean) {
freeLines(this.ocean);
gl.deleteVertexArray(this.ocean.pickVao);
this.ocean = null;
}
for (const a of this.arcs.values()) freeLines(a);
this.arcs.clear();
if (this.outline) freeLines(this.outline.gpu);
this.outline = null;
if (this.pickTex) gl.deleteTexture(this.pickTex);
if (this.pickFbo) gl.deleteFramebuffer(this.pickFbo);
this.pickTex = null;
this.pickFbo = null;
gl.deleteTexture(this.statusTex);
gl.deleteTexture(this.fxTex);
gl.deleteVertexArray(this.quad);
if (this.quadBuf) gl.deleteBuffer(this.quadBuf);
gl.deleteBuffer(this.cornerBuf);
for (const p of [this.fillP, this.pickP, this.lineP, this.skyP, this.rimP]) gl.deleteProgram(p.prog);
}
}
@@ -0,0 +1,212 @@
// FE-ATLAS2-RENDER-300 to FE-ATLAS2-RENDER-312: the sky around the globe, the moon in its phase and the
// shooting stars, on their own timer and on demand.
import { act, render } from '@testing-library/react';
import { createRef, type RefObject } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { GlobeEngine } from './GlobeEngine';
import GlobeSky, { type GlobeSkyHandle } from './GlobeSky';
import { smoothstep } from './globeMath';
const SYNODIC_MS = 29.530588853 * 86400000;
const NEW_MOON = Date.UTC(2000, 0, 6, 18, 14);
/** A moment at this share of a lunation after a known new moon. */
function atPhase(phase: number): Date {
return new Date(NEW_MOON + 300 * SYNODIC_MS + phase * SYNODIC_MS);
}
interface AnimateCall {
el: HTMLElement;
keyframes: Keyframe[];
options: KeyframeAnimationOptions;
animation: { onfinish: (() => void) | null };
}
let animations: AnimateCall[];
let visibility: DocumentVisibilityState;
function fakeEngine(over: { t?: number; scale?: number; width?: number; height?: number } = {}): GlobeEngine {
return {
frame: { t: over.t ?? 0, k: 1, scale: over.scale ?? 100, originX: 400, originY: 300, centerLon: 0, centerLat: 0 },
vp: { width: over.width ?? 800, height: over.height ?? 600, baseRadius: 1, globeY: 0, flatY: 0 },
} as unknown as GlobeEngine;
}
function mount(dark: boolean) {
const ref = createRef<GlobeSkyHandle>();
const utils = render(<GlobeSky ref={ref} dark={dark} />);
const starHost = utils.container.children[0] as HTMLDivElement;
const moon = utils.container.children[1] as HTMLDivElement;
Object.defineProperty(starHost, 'clientWidth', { configurable: true, value: 1000 });
Object.defineProperty(starHost, 'clientHeight', { configurable: true, value: 400 });
return { ...utils, ref, starHost, moon };
}
function handle(ref: RefObject<GlobeSkyHandle | null>): GlobeSkyHandle {
if (!ref.current) throw new Error('GlobeSky handle missing');
return ref.current;
}
beforeEach(() => {
vi.useFakeTimers({ now: atPhase(0.2) });
vi.spyOn(Math, 'random').mockReturnValue(0);
animations = [];
visibility = 'visible';
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => visibility });
Object.defineProperty(HTMLElement.prototype, 'animate', {
configurable: true,
writable: true,
value: function animate(this: HTMLElement, keyframes: Keyframe[], options: KeyframeAnimationOptions) {
const animation = { onfinish: null as (() => void) | null };
animations.push({ el: this, keyframes, options, animation });
return animation;
},
});
});
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
Reflect.deleteProperty(document, 'visibilityState');
Reflect.deleteProperty(HTMLElement.prototype, 'animate');
});
describe('GlobeSky moon', () => {
it('FE-ATLAS2-RENDER-300: draws a waxing crescent as a thin lit sliver', () => {
const { container } = mount(true);
const path = container.querySelector('path');
expect(path?.getAttribute('d')).toBe('M 14 1 A 13 13 0 0 0 14 27 A 4.02 13 0 0 0 14 1 Z');
});
it('FE-ATLAS2-RENDER-301: mirrors the shadow for a waning crescent', () => {
vi.setSystemTime(atPhase(0.8));
const { container } = mount(true);
expect(container.querySelector('path')?.getAttribute('d')).toBe(
'M 14 1 A 13 13 0 0 1 14 27 A 4.02 13 0 0 1 14 1 Z'
);
});
it('FE-ATLAS2-RENDER-302: bulges the shadow ellipse the other way for a gibbous moon', () => {
vi.setSystemTime(atPhase(0.4));
const { container } = mount(true);
expect(container.querySelector('path')?.getAttribute('d')).toBe(
'M 14 1 A 13 13 0 0 0 14 27 A 10.52 13 0 0 1 14 1 Z'
);
});
it('FE-ATLAS2-RENDER-303: hides the moon in light mode', () => {
const { ref, moon } = mount(false);
act(() => handle(ref).layout(fakeEngine()));
expect(moon.style.opacity).toBe('0');
expect(moon.style.transform).toBe('');
});
it('FE-ATLAS2-RENDER-304: places the moon up and to the side of the globe, fully shown on the globe', () => {
const { ref, moon } = mount(true);
act(() => handle(ref).layout(fakeEngine({ t: 0, scale: 100, width: 800, height: 600 })));
const d = Math.max(175, 600 * 0.42);
const x = 400 + Math.cos(-0.65) * d * 1.25;
const y = 300 + Math.sin(-0.65) * d * 0.62;
expect(moon.style.transform).toBe(`translate3d(${x.toFixed(1)}px, ${y.toFixed(1)}px, 0) translate(-50%, -50%)`);
expect(moon.style.opacity).toBe('0.95');
});
it('FE-ATLAS2-RENDER-305: keeps a zoomed-in globe clear of the moon and fades it as the map unrolls', () => {
const { ref, moon } = mount(true);
act(() => handle(ref).layout(fakeEngine({ t: 0.3, scale: 400 })));
const d = 400 * 1.75;
const x = 400 + Math.cos(-0.65) * d * 1.25;
expect(moon.style.transform.startsWith(`translate3d(${x.toFixed(1)}px,`)).toBe(true);
expect(Number(moon.style.opacity)).toBeCloseTo((1 - smoothstep(0.05, 0.6, 0.3)) * 0.95);
act(() => handle(ref).layout(fakeEngine({ t: 1 })));
expect(moon.style.opacity).toBe('0');
});
});
describe('GlobeSky shooting stars', () => {
it('FE-ATLAS2-RENDER-306: a shooting star crosses the upper right of the sky and removes itself', () => {
const { ref, starHost } = mount(true);
act(() => handle(ref).shootingStar());
const star = starHost.querySelector('.ag-shooting-star') as HTMLElement;
expect(star).not.toBeNull();
expect(star.style.left.endsWith('px')).toBe(true);
expect(parseFloat(star.style.left)).toBeCloseTo(550);
expect(parseFloat(star.style.top)).toBeCloseTo(20);
expect(animations).toHaveLength(1);
expect(animations[0].el).toBe(star);
expect(animations[0].options.duration).toBe(1100);
expect(animations[0].keyframes).toHaveLength(3);
animations[0].animation.onfinish?.();
expect(starHost.querySelector('.ag-shooting-star')).toBeNull();
});
it('FE-ATLAS2-RENDER-307: there are no shooting stars in light mode', () => {
const { ref, starHost } = mount(false);
act(() => handle(ref).shootingStar());
expect(starHost.children).toHaveLength(0);
expect(animations).toHaveLength(0);
});
it('FE-ATLAS2-RENDER-308: respects reduced motion', () => {
// Once only: window.matchMedia is the setup's shared mock, and a lasting return value would
// outlive this test (restoreAllMocks does not undo it) and silence every later star.
vi.mocked(window.matchMedia).mockReturnValueOnce({ matches: true } as unknown as MediaQueryList);
const { ref, starHost } = mount(true);
act(() => handle(ref).shootingStar());
expect(starHost.children).toHaveLength(0);
});
/** Catches the sky's own schedule, so a test runs each planned star by hand. */
function scheduled(): Array<{ run: () => void; ms: number }> {
const plans: Array<{ run: () => void; ms: number }> = [];
vi.spyOn(window, 'setTimeout').mockImplementation(((run: () => void, ms?: number) => {
plans.push({ run, ms: ms ?? 0 });
return plans.length;
}) as unknown as typeof window.setTimeout);
return plans;
}
it('FE-ATLAS2-RENDER-309: sends a star of its own now and then while the page is in view', () => {
const plans = scheduled();
const { starHost } = mount(true);
expect(plans).toHaveLength(1);
// Math.random is 0 here: the shortest wait, forty seconds.
expect(plans[0].ms).toBe(40_000);
expect(starHost.children).toHaveLength(0);
act(() => plans[0].run());
expect(starHost.children).toHaveLength(1);
// And the next one is planned right away.
expect(plans).toHaveLength(2);
act(() => plans[1].run());
expect(starHost.children).toHaveLength(2);
});
it('FE-ATLAS2-RENDER-310: skips its own star while the page is hidden but keeps the schedule', () => {
const plans = scheduled();
const { starHost } = mount(true);
visibility = 'hidden';
act(() => plans[0].run());
expect(starHost.children).toHaveLength(0);
expect(plans).toHaveLength(2);
visibility = 'visible';
act(() => plans[1].run());
expect(starHost.children).toHaveLength(1);
});
it('FE-ATLAS2-RENDER-311: schedules nothing in light mode', () => {
mount(false);
expect(vi.getTimerCount()).toBe(0);
});
it('FE-ATLAS2-RENDER-312: stops its timer on unmount and when switching to light mode', () => {
const { rerender, unmount } = mount(true);
expect(vi.getTimerCount()).toBe(1);
rerender(<GlobeSky dark={false} />);
expect(vi.getTimerCount()).toBe(0);
rerender(<GlobeSky dark />);
expect(vi.getTimerCount()).toBe(1);
unmount();
expect(vi.getTimerCount()).toBe(0);
});
});
@@ -0,0 +1,115 @@
import { forwardRef, useCallback, useEffect, 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;
}
/** How long the sky waits between two shooting stars of its own, in ms. */
const STAR_EVERY_MIN = 40_000;
const STAR_EVERY_SPREAD = 60_000;
/**
* What hangs in the sky around the globe: the moon in its real phase, and shooting
* stars, now and then on their own and one whenever 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()), []);
const shootingStar = useCallback(() => {
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]);
// Now and then a shooting star of its own, while the page is in view.
useEffect(() => {
if (!dark) return;
let timer = 0;
const next = () => {
timer = window.setTimeout(
() => {
if (document.visibilityState === 'visible') shootingStar();
next();
},
STAR_EVERY_MIN + Math.random() * STAR_EVERY_SPREAD
);
};
next();
return () => window.clearTimeout(timer);
}, [dark, shootingStar]);
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,
}),
[dark, shootingStar]
);
// 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(235 235 237 / 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(245 245 245)" />
<stop offset="1" stopColor="rgb(176 176 180)" />
</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(8 8 9)" opacity="0.88" />
</svg>
</div>
</>
);
});
export default GlobeSky;
@@ -0,0 +1,142 @@
// FE-ATLAS2-VIEWB-020 to FE-ATLAS2-VIEWB-029: the globe's stat cards, the medal and the Dawarich mark.
import { fireEvent, render, screen } from '@testing-library/react';
import type { BadgeMotif } from '@trek/shared';
import { Flag, Globe } from 'lucide-react';
import { describe, expect, it, vi } from 'vitest';
import BadgeMedal from './BadgeMedal';
import DawarichMark from './DawarichMark';
import GlobeStatsBar from './GlobeStatsBar';
describe('GlobeStatsBar', () => {
it('FE-ATLAS2-VIEWB-020: a stat with an action is a button, one without is plain', () => {
const onClick = vi.fn();
const { container } = render(
<GlobeStatsBar
stats={[
{ key: 'countries', icon: Flag, value: 12, label: 'Countries', onClick },
{ key: 'continents', icon: Globe, value: 3, label: 'Continents' },
]}
/>
);
const btn = screen.getByRole('button');
expect(btn).toHaveTextContent('12');
expect(btn).toHaveTextContent('Countries');
fireEvent.click(btn);
expect(onClick).toHaveBeenCalledTimes(1);
expect(screen.getByText('Continents').closest('button')).toBeNull();
expect(screen.getByText('3')).toBeInTheDocument();
expect(container.firstElementChild?.className).toContain('bottom-[22px]');
});
it('FE-ATLAS2-VIEWB-021: the bar takes a caller position instead of the corner', () => {
const { container } = render(<GlobeStatsBar stats={[]} className="end-0 top-0" />);
expect(container.firstElementChild?.className).toContain('end-0 top-0');
expect(container.firstElementChild?.className).not.toContain('bottom-[22px]');
expect(container.firstElementChild?.children).toHaveLength(0);
});
});
describe('BadgeMedal', () => {
it('FE-ATLAS2-VIEWB-022: an earned medal has a full ring and its gradients are named after its id', () => {
const { container } = render(<BadgeMedal id="x1" motif="first" tier="gold" earned />);
const svg = container.querySelector('svg');
expect(svg).toHaveAttribute('width', '92');
expect(svg).toHaveAttribute('height', '104');
expect(container.querySelector('#bm-x1-r')).not.toBeNull();
const hex = container.querySelector('polygon');
expect(hex).toHaveAttribute('stroke-width', '5');
expect(hex).toHaveAttribute('stroke-opacity', '1');
expect(hex).not.toHaveAttribute('stroke-dasharray');
// No progress ring on an earned medal.
expect(container.querySelectorAll('polygon')).toHaveLength(2);
expect(container.querySelector('g')).toHaveAttribute('opacity', '1');
});
it('FE-ATLAS2-VIEWB-023: a medal not yet earned is dashed, dim and draws its progress', () => {
const { container } = render(
<BadgeMedal id="p" motif="countries" tier="bronze" earned={false} progress={0.42} size={46} />
);
const polys = container.querySelectorAll('polygon');
expect(polys).toHaveLength(3);
expect(polys[0]).toHaveAttribute('stroke-dasharray', '4 3');
expect(polys[0]).toHaveAttribute('stroke-width', '2');
expect(polys[2]).toHaveAttribute('stroke-dasharray', '42 100');
expect(container.querySelector('g')).toHaveAttribute('opacity', '0.38');
expect(container.querySelector('svg')).toHaveAttribute('width', '46');
expect(container.querySelector('svg')).toHaveAttribute('height', '52');
});
it('FE-ATLAS2-VIEWB-024: a medal not earned and without progress draws no progress ring', () => {
const { container } = render(<BadgeMedal id="z" motif="moon" tier="silver" earned={false} />);
expect(container.querySelectorAll('polygon')).toHaveLength(2);
});
it('FE-ATLAS2-VIEWB-025: the seven-continents motif lights seven points', () => {
const { container } = render(<BadgeMedal id="s" motif="seven" tier="aurora" earned />);
expect(container.querySelectorAll('circle[r="2.4"]')).toHaveLength(7);
});
it('FE-ATLAS2-VIEWB-026: a stepped medal carries its label, smaller the longer it is', () => {
const sizes: Array<[string, string]> = [
['5', '15'],
['100', '13'],
['3/12', '11'],
];
for (const [label, size] of sizes) {
const { container, unmount } = render(<BadgeMedal id="l" motif="countries" tier="gold" earned label={label} />);
const text = container.querySelector('text');
expect(text).toHaveTextContent(label);
expect(text).toHaveAttribute('font-size', size);
unmount();
}
});
it('FE-ATLAS2-VIEWB-027: a back side replaces the motif', () => {
const { container } = render(
<BadgeMedal id="b" motif="countries" tier="gold" earned label="5" back={<text data-testid="back">B</text>} />
);
expect(screen.getByTestId('back')).toBeInTheDocument();
expect(container.querySelectorAll('text')).toHaveLength(1);
});
it('FE-ATLAS2-VIEWB-028: every motif draws a symbol', () => {
const motifs: BadgeMotif[] = [
'first',
'countries',
'continents',
'region',
'earth',
'moon',
'flights',
'longhaul',
'airports',
'dateline',
'equator',
'hemispheres',
'tropics',
'polar',
'streak',
'burst',
'wish',
'islands',
];
for (const motif of motifs) {
const { container, unmount } = render(<BadgeMedal id={motif} motif={motif} tier="bronze" earned />);
// The lucide symbol is an svg nested in the medal's own.
expect(container.querySelectorAll('svg').length).toBeGreaterThan(1);
unmount();
}
});
});
describe('DawarichMark', () => {
it('FE-ATLAS2-VIEWB-029: the mark sits two pixels larger than the icon size it stands for', () => {
const { container, rerender } = render(<DawarichMark />);
const box = container.firstElementChild as HTMLElement;
expect(box.style.width).toBe('18px');
expect(container.querySelector('img')).toHaveAttribute('width', '18');
rerender(<DawarichMark size={30} />);
expect((container.firstElementChild as HTMLElement).style.height).toBe('32px');
expect(container.querySelector('img')).toHaveAttribute('src', '/brands/dawarich.svg');
});
});
@@ -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(22 22 24 / 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(244 244 245);
--ag-muted: rgb(161 161 170);
--ag-faint: rgb(113 113 122);
--ag-accent: rgb(244 244 245);
--ag-mint: rgb(161 161 170);
--ag-label: rgb(235 235 237 / 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(4 4 5);
}
html:not(.dark) .ag-btn {
background: rgb(24 24 27 / 0.04);
}
html:not(.dark) .ag-btn[data-on='1'] {
background: rgb(24 24 27 / 0.12);
border-color: rgb(24 24 27 / 0.4);
}
html:not(.dark) .ag-bar {
background: rgb(24 24 27 / 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(255 255 255 / 0.16);
border-color: rgb(255 255 255 / 0.45);
}
.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(255 255 255 / 0.35);
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(255 255 255 / 0) 30%,
rgb(255 255 255 / 0.18) 45%,
rgb(255 255 255 / 0.14) 55%,
rgb(255 255 255 / 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(255 255 255 / 0.7);
}
@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(255 255 255 / 0.3) 0%, rgb(255 255 255 / 0.12) 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,368 @@
// FE-ATLAS2-PAINT-101 to FE-ATLAS2-PAINT-120: the country and region names placed
// over the globe, their collision rules and how their elements are reused.
import { beforeEach, describe, expect, it } from 'vitest';
import type { AtlasMeshManifest, GlobeEngine, RegionIndex } from './GlobeEngine';
import { placeLabels, type GlobeLabel } from './globeLabels';
type ManifestCountry = AtlasMeshManifest['countries'][number];
type Feature = RegionIndex['features'][number];
interface FakeLabelEngine {
manifest: { countries: ManifestCountry[] } | null;
zoom: number;
vp: { width: number; height: number };
regionIndex: Map<string, RegionIndex>;
regionAlpha: number;
focus: string | null;
/** Visibility by "x,y" of the anchor; 1 when not listed. */
visibility: Map<string, number>;
}
/**
* A globe engine whose projection is the identity: an anchor [x, y] lands on
* screen at x, y, so a test places labels in pixels directly.
*/
function fakeEngine(over: Partial<FakeLabelEngine> = {}) {
const state: FakeLabelEngine = {
manifest: { countries: [] },
zoom: 1,
vp: { width: 1000, height: 800 },
regionIndex: new Map(),
regionAlpha: 0,
focus: null,
visibility: new Map(),
...over,
};
const engine = {
get manifest() {
return state.manifest;
},
get zoom() {
return state.zoom;
},
get vp() {
return state.vp;
},
get regionIndex() {
return state.regionIndex;
},
get regionAlpha() {
return state.regionAlpha;
},
focusCountry: () => state.focus,
project: (lon: number, lat: number) => ({
x: lon,
y: lat,
visible: state.visibility.get(`${lon},${lat}`) ?? 1,
shade: 1,
}),
} as unknown as GlobeEngine;
return { engine, state };
}
function mc(a2: string | null, x: number, y: number, area = 1000, anchor = true): ManifestCountry {
return { a2, a3: a2 ?? 'XXX', name: a2 ?? '', anchor: anchor ? [x, y] : null, bbox: [], area };
}
function feat(over: Partial<Feature> = {}): Feature {
return { code: null, name: null, nameEn: null, anchor: null, counted: true, ...over };
}
function index(features: Feature[]): RegionIndex {
return { bbox: [], counted: features.length, features, files: {} };
}
const nameOf = (a2: string) => `Name ${a2}`;
let host: HTMLDivElement;
let pool: GlobeLabel[];
beforeEach(() => {
host = document.createElement('div');
pool = [];
});
/** The labels that show, by text. */
function shownTexts(): string[] {
return pool
.filter((l) => l.el.style.opacity !== '0')
.map((l) => l.el.textContent ?? '')
.sort();
}
function labelOf(text: string): GlobeLabel | undefined {
return pool.find((l) => l.el.textContent === text && l.el.style.opacity !== '0');
}
describe('placeLabels: country names', () => {
it('FE-ATLAS2-PAINT-101: places nothing before the manifest has loaded', () => {
const { engine } = fakeEngine({ manifest: null });
placeLabels(host, pool, engine, nameOf);
expect(host.children).toHaveLength(0);
expect(pool).toHaveLength(0);
});
it('FE-ATLAS2-PAINT-102: names a large country in view at its anchor, in a fresh element on the host', () => {
const { engine } = fakeEngine({ manifest: { countries: [mc('FR', 100, 200)] } });
placeLabels(host, pool, engine, nameOf);
expect(pool).toHaveLength(1);
const el = pool[0].el;
expect(host.firstChild).toBe(el);
expect(pool[0].key).toBe('FR');
expect(el.className).toBe('atlas-globe-label text-caption');
expect(el.textContent).toBe('Name FR');
expect(el.dataset.region).toBe('');
expect(el.style.transform).toBe('translate3d(100.0px, 200.0px, 0) translate(-50%, -50%)');
expect(el.style.opacity).toBe('1');
});
it('FE-ATLAS2-PAINT-103: leaves out countries too small for the zoom, unless they are the user own', () => {
// At zoom 1 a country needs 700 square degrees; one of the user's own needs 30 % of that.
const countries = [mc('BE', 100, 100, 300), mc('LU', 400, 100, 300), mc('MT', 700, 100, 100)];
const { engine } = fakeEngine({ manifest: { countries } });
placeLabels(host, pool, engine, nameOf, (a2) => a2 === 'BE' || a2 === 'MT');
expect(shownTexts()).toEqual(['Name BE']);
});
it('FE-ATLAS2-PAINT-104: zooming in brings smaller countries in', () => {
const { engine, state } = fakeEngine({ manifest: { countries: [mc('BE', 100, 100, 300)] } });
placeLabels(host, pool, engine, nameOf);
expect(shownTexts()).toEqual([]);
state.zoom = 2;
placeLabels(host, pool, engine, nameOf);
expect(shownTexts()).toEqual(['Name BE']);
});
it('FE-ATLAS2-PAINT-105: skips countries without a code, an anchor, a name, or out of view', () => {
const countries = [
mc(null, 100, 100),
mc('AQ', 200, 100, 1000, false),
mc('NO', 300, 100),
// Past the margin left, right, above and below the view.
mc('W1', -50, 300),
mc('E1', 1050, 300),
mc('N1', 500, -30),
mc('S1', 500, 830),
// Behind the limb.
mc('BK', 600, 600),
// Inside the margin: still named.
mc('IN', -30, 400),
];
const { engine } = fakeEngine({ manifest: { countries }, visibility: new Map([['600,600', 0.1]]) });
placeLabels(host, pool, engine, (a2) => (a2 === 'NO' ? null : a2));
expect(shownTexts()).toEqual(['IN']);
});
it('FE-ATLAS2-PAINT-106: fades a name in as it turns from the limb and as region fills take over', () => {
const { engine } = fakeEngine({
manifest: { countries: [mc('FR', 100, 100)] },
visibility: new Map([['100,100', 0.15]]),
regionAlpha: 0.5,
});
placeLabels(host, pool, engine, nameOf);
expect(Number(pool[0].el.style.opacity)).toBeCloseTo(0.6 * (1 - 0.5 * 0.55), 6);
});
it('FE-ATLAS2-PAINT-107: of two overlapping names the larger country wins', () => {
const { engine } = fakeEngine({ manifest: { countries: [mc('SM', 100, 100, 800), mc('IT', 110, 104, 3000)] } });
placeLabels(host, pool, engine, nameOf);
expect(shownTexts()).toEqual(['Name IT']);
expect(pool).toHaveLength(1);
});
it('FE-ATLAS2-PAINT-108: the user own country outranks a larger neighbour', () => {
const { engine } = fakeEngine({ manifest: { countries: [mc('CH', 100, 100, 1000), mc('DE', 110, 104, 3000)] } });
placeLabels(host, pool, engine, nameOf, (a2) => a2 === 'CH');
expect(shownTexts()).toEqual(['Name CH']);
});
it('FE-ATLAS2-PAINT-109: a name on screen keeps its place against a slightly larger one, not a much larger one', () => {
const { engine, state } = fakeEngine({ manifest: { countries: [mc('AA', 100, 100, 1000)] } });
placeLabels(host, pool, engine, nameOf);
const first = pool[0].el;
state.manifest = { countries: [mc('AA', 100, 100, 1000), mc('BB', 104, 100, 1400)] };
placeLabels(host, pool, engine, nameOf);
expect(shownTexts()).toEqual(['Name AA']);
expect(labelOf('Name AA')?.el).toBe(first);
state.manifest = { countries: [mc('AA', 100, 100, 1000), mc('BB', 104, 100, 1600)] };
placeLabels(host, pool, engine, nameOf);
expect(shownTexts()).toEqual(['Name BB']);
});
it('FE-ATLAS2-PAINT-110: a name that stays keeps its element and only moves', () => {
const { engine, state } = fakeEngine({ manifest: { countries: [mc('FR', 100, 100)] } });
placeLabels(host, pool, engine, nameOf);
const el = pool[0].el;
state.manifest = { countries: [mc('FR', 150.04, 120)] };
placeLabels(host, pool, engine, nameOf);
expect(pool).toHaveLength(1);
expect(pool[0].el).toBe(el);
expect(el.style.transform).toBe('translate3d(150.0px, 120.0px, 0) translate(-50%, -50%)');
});
it('FE-ATLAS2-PAINT-111: a name that goes hides its element, and the next new name reuses it', () => {
const { engine, state } = fakeEngine({ manifest: { countries: [mc('FR', 100, 100)] } });
placeLabels(host, pool, engine, nameOf);
const el = pool[0].el;
state.manifest = { countries: [] };
placeLabels(host, pool, engine, nameOf);
expect(el.style.opacity).toBe('0');
expect(shownTexts()).toEqual([]);
state.manifest = { countries: [mc('ES', 300, 300)] };
placeLabels(host, pool, engine, nameOf);
expect(pool).toHaveLength(1);
expect(host.children).toHaveLength(1);
expect(pool[0].key).toBe('ES');
expect(el.textContent).toBe('Name ES');
expect(el.style.opacity).toBe('1');
});
it('FE-ATLAS2-PAINT-112: shows at most 150 names at once', () => {
const countries: ManifestCountry[] = [];
for (let i = 0; i < 170; i++) {
countries.push(mc(`C${i}`, 20 + (i % 20) * 48, 20 + Math.floor(i / 20) * 30, 1000 + i));
}
const { engine } = fakeEngine({ manifest: { countries } });
placeLabels(host, pool, engine, (a2) => a2);
expect(pool).toHaveLength(150);
// The largest win the cut.
expect(labelOf('C169')).toBeDefined();
expect(labelOf('C0')).toBeUndefined();
});
});
describe('placeLabels: region names', () => {
const US = mc('US', 500, 400, 9000);
const usRegions = () =>
index([
feat({ code: 'US-KS', name: 'Kansas', anchor: [300, 300] }),
feat({ code: null, name: 'Texas', nameEn: 'Texas (en)', anchor: [600, 500] }),
feat({ code: 'US-AK', name: 'Alaska', anchor: null }),
feat({ code: 'US-HI', name: 'Hawaii', anchor: [1200, 300] }),
feat({ code: 'US-GU', name: 'Guam', anchor: [-10, 300] }),
feat({ code: 'US-VI', name: 'Virgin', anchor: [300, -5] }),
feat({ code: 'US-AS', name: 'Samoa', anchor: [300, 900] }),
feat({ code: 'US-ME', name: 'Maine', anchor: [800, 100] }),
]);
it('FE-ATLAS2-PAINT-113: from the wide-screen region zoom on, a country with regions names them instead of itself', () => {
const { engine } = fakeEngine({
manifest: { countries: [US, mc('CA', 900, 700, 9000)] },
zoom: 18,
regionIndex: new Map([['US', usRegions()]]),
regionAlpha: 0.8,
visibility: new Map([['800,100', 0.05]]),
});
placeLabels(host, pool, engine, nameOf);
expect(shownTexts()).toEqual(['Kansas', 'Name CA', 'Texas (en)']);
const kansas = labelOf('Kansas');
expect(kansas?.key).toBe('US:US-KS');
expect(kansas?.el.dataset.region).toBe('1');
expect(kansas?.el.style.opacity).toBe('0.8');
expect(labelOf('Texas (en)')?.key).toBe('US:Texas');
expect(labelOf('Name CA')?.el.dataset.region).toBe('');
});
it('FE-ATLAS2-PAINT-114: below the region zoom the country keeps its own name', () => {
const { engine } = fakeEngine({
manifest: { countries: [US] },
zoom: 17,
regionIndex: new Map([['US', usRegions()]]),
});
placeLabels(host, pool, engine, nameOf);
expect(shownTexts()).toEqual(['Name US']);
});
it('FE-ATLAS2-PAINT-115: on a phone-wide view region names start earlier', () => {
const { engine } = fakeEngine({
manifest: { countries: [US] },
zoom: 14,
vp: { width: 600, height: 800 },
regionIndex: new Map([['US', usRegions()]]),
regionAlpha: 1,
});
placeLabels(host, pool, engine, nameOf);
expect(shownTexts()).toEqual(['Kansas', 'Texas (en)']);
});
it('FE-ATLAS2-PAINT-116: a region named by its plain name falls back to it, and one without any name shows empty', () => {
const { engine } = fakeEngine({
manifest: { countries: [] },
zoom: 20,
regionIndex: new Map([
[
'FR',
index([
feat({ code: 'FR-IDF', name: 'Île-de-France', anchor: [100, 100] }),
feat({ code: 'FR-X', anchor: [400, 400] }),
]),
],
]),
regionAlpha: 1,
});
placeLabels(host, pool, engine, nameOf);
expect(pool.map((l) => l.el.textContent).sort()).toEqual(['', 'Île-de-France']);
});
/** Two countries with one region each at nearly the same spot: only one of them can be named. */
function rivals(focus: string | null, countries: ManifestCountry[]) {
return fakeEngine({
manifest: { countries },
zoom: 20,
focus,
regionIndex: new Map([
// Mexico's region is right in the middle of the view.
['MX', index([feat({ code: 'MX-SON', name: 'Sonora', anchor: [500, 400] })])],
['US', index([feat({ code: 'US-AZ', name: 'Arizona', anchor: [510, 404] })])],
]),
regionAlpha: 1,
});
}
it('FE-ATLAS2-PAINT-117: the regions of the country under the middle of the view come first', () => {
const { engine } = rivals('US', [mc('US', 520, 410), mc('MX', 480, 420)]);
placeLabels(host, pool, engine, nameOf);
expect(shownTexts()).toEqual(['Arizona']);
});
it('FE-ATLAS2-PAINT-118: a country under the middle without regions puts no country first, so the nearest region wins', () => {
const { engine } = rivals('ES', [mc('US', 520, 410), mc('MX', 480, 420)]);
placeLabels(host, pool, engine, nameOf);
expect(shownTexts()).toEqual(['Sonora']);
});
it('FE-ATLAS2-PAINT-119: over open water the country with regions whose anchor is nearest the middle comes first', () => {
// US's anchor is the nearer one; Mexico's lies behind the limb.
const near = rivals(null, [mc('US', 520, 410), mc('MX', 501, 401)]);
near.state.visibility.set('501,401', 0);
placeLabels(host, pool, near.engine, nameOf);
expect(shownTexts()).toEqual(['Arizona']);
// No anchor near enough the middle (or none at all): nobody comes first.
pool = [];
const far = rivals(null, [mc('US', 950, 750), mc('MX', 0, 0, 1000, false)]);
placeLabels(host, pool, far.engine, nameOf);
expect(shownTexts()).toEqual(['Sonora']);
});
it('FE-ATLAS2-PAINT-120: shows at most 120 region names, leaving room for country names', () => {
const features: Feature[] = [];
for (let i = 0; i < 130; i++) {
features.push(feat({ code: `R${i}`, name: `R${i}`, anchor: [30 + (i % 13) * 70, 30 + Math.floor(i / 13) * 30] }));
}
const { engine } = fakeEngine({
manifest: { countries: [mc('FR', 500, 700, 5000)] },
zoom: 20,
regionIndex: new Map([['XX', index(features)]]),
regionAlpha: 1,
});
placeLabels(host, pool, engine, nameOf);
const regions = pool.filter((l) => l.el.dataset.region === '1' && l.el.style.opacity !== '0');
expect(regions).toHaveLength(120);
expect(labelOf('Name FR')).toBeDefined();
});
});
@@ -0,0 +1,194 @@
/**
* 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);
// A name on screen keeps its place against a near equal one, so two labels
// that overlap while the globe turns do not take turns frame by frame.
const shown = new Set(pool.filter((l) => l.key && l.el.style.opacity !== '0').map((l) => l.key));
const held = (c: Candidate) => (shown.has(c.key) ? (c.region ? c.rank + 3e5 : c.rank * 1.5) : c.rank);
cands.sort((a, b) => held(b) - held(a));
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++;
}
// Every name keeps its own element while it shows; an element only takes a
// new name once its old one is gone, so no label jumps to another's place.
const wanted = new Set(chosen.map((c) => c.key));
const byKey = new Map(pool.filter((l) => wanted.has(l.key)).map((l) => [l.key, l]));
const free = pool.filter((l) => !wanted.has(l.key));
for (const l of free) {
if (l.el.style.opacity !== '0') l.el.style.opacity = '0';
}
for (const c of chosen) {
let l = byKey.get(c.key);
if (!l) {
l = free.pop();
if (!l) {
const el = document.createElement('div');
el.className = 'atlas-globe-label text-caption';
host.appendChild(el);
l = { el, key: '' };
pool.push(l);
}
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,131 @@
// FE-ATLAS2-PAINT-401 to FE-ATLAS2-PAINT-412: the edges of the globe projection the
// main globeMath tests leave out (clamps, the far side, degenerate arcs).
import { describe, expect, it } from 'vitest';
import {
arcSegments,
frameParams,
interpolateGreatCircle,
latLimits,
moonPhase,
MORPH_END,
morphOf,
projectPoint,
RAD,
smoothstep,
wrapPi,
xSqueeze,
type GlobeViewport,
} from './globeMath';
const VP: GlobeViewport = { width: 1000, height: 800, baseRadius: 300, globeY: 300, flatY: 500 };
describe('globeMath edges', () => {
it('FE-ATLAS2-PAINT-401: smoothstep clamps below and above its range and eases in between', () => {
expect(smoothstep(0, 1, -2)).toBe(0);
expect(smoothstep(0, 1, 3)).toBe(1);
expect(smoothstep(0, 1, 0.5)).toBe(0.5);
expect(smoothstep(0, 1, 0.25)).toBeCloseTo(0.15625);
expect(morphOf(MORPH_END * 4)).toBe(1);
});
it('FE-ATLAS2-PAINT-402: wraps exactly pi onto minus pi and leaves small angles alone', () => {
expect(wrapPi(Math.PI)).toBeCloseTo(-Math.PI);
expect(wrapPi(-Math.PI)).toBeCloseTo(-Math.PI);
expect(wrapPi(1)).toBe(1);
expect(wrapPi(Math.PI * 4 + 0.5)).toBeCloseTo(0.5);
});
it('FE-ATLAS2-PAINT-403: moves the origin from the globe centre to the map centre as it unrolls', () => {
const globe = frameParams({ lon: 20, lat: 10, zoom: 1 }, VP);
expect(globe.t).toBe(0);
expect(globe.k).toBe(1);
expect(globe.originX).toBe(500);
expect(globe.originY).toBe(300);
expect(globe.scale).toBe(300);
expect(globe.centerLon).toBeCloseTo(20 * RAD);
expect(globe.centerLat).toBeCloseTo(10 * RAD);
const flat = frameParams({ lon: 20, lat: 10, zoom: MORPH_END }, VP);
expect(flat.t).toBe(1);
expect(flat.k).toBeCloseTo(0.0005);
expect(flat.originY).toBe(500);
expect(flat.scale).toBeCloseTo(300 * MORPH_END);
});
it('FE-ATLAS2-PAINT-404: hides a point past the antimeridian of its reference on the far side', () => {
const f = frameParams({ lon: 0, lat: 0, zoom: 1 }, VP);
const p = projectPoint(-179, 0, f, 179, 0);
expect(p.visible).toBe(-1);
});
it('FE-ATLAS2-PAINT-405: shades full in the middle, dark at the limb, and evenly once flat', () => {
const globe = frameParams({ lon: 0, lat: 0, zoom: 1 }, VP);
expect(projectPoint(0, 0, globe).shade).toBeCloseTo(1);
expect(projectPoint(89.9, 0, globe).shade).toBeLessThan(0.01);
const flat = frameParams({ lon: 0, lat: 0, zoom: MORPH_END }, VP);
expect(projectPoint(80, 30, flat).shade).toBeCloseTo(1);
});
it('FE-ATLAS2-PAINT-406: never squeezes longitude more than 0.3 near the poles', () => {
const f = frameParams({ lon: 0, lat: 85, zoom: MORPH_END }, VP);
expect(xSqueeze(f)).toBeCloseTo(0.3);
const globe = frameParams({ lon: 0, lat: 85, zoom: 1 }, VP);
expect(xSqueeze(globe)).toBe(1);
});
it('FE-ATLAS2-PAINT-407: a great circle between one point and itself stays on that point', () => {
expect(interpolateGreatCircle(0, 0, 0, 0, 0.5)).toEqual([0, 0]);
const [lon, lat] = interpolateGreatCircle(13.4, 52.5, 13.4, 52.5, 0.5);
expect(lon).toBeCloseTo(13.4);
expect(lat).toBeCloseTo(52.5);
});
it('FE-ATLAS2-PAINT-408: a great circle starts and ends on its airports', () => {
const [lon0, lat0] = interpolateGreatCircle(8.57, 50.03, -73.78, 40.64, 0);
const [lon1, lat1] = interpolateGreatCircle(8.57, 50.03, -73.78, 40.64, 1);
expect(lon0).toBeCloseTo(8.57);
expect(lat0).toBeCloseTo(50.03);
expect(lon1).toBeCloseTo(-73.78);
expect(lat1).toBeCloseTo(40.64);
});
it('FE-ATLAS2-PAINT-409: no routes give no segments, and the default cuts each arc in 48', () => {
const none = arcSegments([]);
expect(none.count).toBe(0);
expect(none.data).toHaveLength(0);
const two = arcSegments([
{ a: [0, 0], b: [10, 0] },
{ a: [20, 0], b: [30, 0] },
]);
expect(two.count).toBe(96);
// The second arc starts at its own first airport.
expect(two.data[48 * 8]).toBeCloseTo(20 * RAD);
});
it('FE-ATLAS2-PAINT-410: a route to the same airport still lifts by the minimum peak', () => {
const { data, count } = arcSegments([{ a: [5, 5], b: [5, 5] }], 2);
expect(count).toBe(2);
// Lift at the middle of the arc is the minimum peak.
expect(data[5]).toBeCloseTo(0.015);
expect(data[0]).toBeCloseTo(5 * RAD);
expect(data[2]).toBeCloseTo(5 * RAD);
});
it('FE-ATLAS2-PAINT-411: knows the moon phase before its reference new moon too', () => {
const old = moonPhase(new Date(Date.UTC(1999, 0, 2)));
expect(old.phase).toBeGreaterThanOrEqual(0);
expect(old.phase).toBeLessThan(1);
expect(old.lit).toBeGreaterThan(0.95);
const ref = moonPhase(new Date(Date.UTC(2000, 0, 6, 18, 14)));
expect(ref.phase).toBe(0);
expect(ref.lit).toBe(0);
});
it('FE-ATLAS2-PAINT-412: an off-centre flat map gets different southern and northern limits', () => {
const [south, north] = latLimits(MORPH_END, VP);
const scale = VP.baseRadius * MORPH_END;
expect(north).toBeCloseTo(90 - VP.flatY / scale / RAD);
expect(south).toBeCloseTo(-90 + (VP.height - VP.flatY) / scale / RAD);
expect(north - south).toBeGreaterThan(0);
});
});
@@ -0,0 +1,141 @@
import { describe, expect, it } from 'vitest';
import {
angularDistance,
arcSegments,
frameParams,
interpolateGreatCircle,
latLimits,
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);
});
describe('latLimits', () => {
it('lets the globe tilt to 80 degrees either way', () => {
expect(latLimits(1, VP)).toEqual([-80, 80]);
});
it('keeps the cut edges of the flat map off the screen', () => {
const zoom = MORPH_END * 2;
const [south, north] = latLimits(zoom, VP);
const scale = VP.baseRadius * zoom;
// At the northern limit the top of the screen shows exactly the pole, and no further.
expect(north + VP.flatY / scale / (Math.PI / 180)).toBeCloseTo(90);
expect(south - (VP.height - VP.flatY) / scale / (Math.PI / 180)).toBeCloseTo(-90);
});
it('holds a flat map lower than the screen in the middle', () => {
const [south, north] = latLimits(MORPH_END, { ...VP, height: 4000, flatY: 2000 });
expect(south).toBeCloseTo(0);
expect(north).toBeCloseTo(0);
});
it('narrows the range as the globe unrolls', () => {
const half = (MORPH_START + MORPH_END) / 2;
const [, mid] = latLimits(half, VP);
const [, flat] = latLimits(MORPH_END, VP);
expect(mid).toBeLessThan(80);
expect(mid).toBeGreaterThan(flat);
});
});
});

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