Compare commits

..

114 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
1305 changed files with 89999 additions and 14947 deletions
+14 -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
@@ -1347,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
@@ -1468,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.
+3
View File
@@ -2,4 +2,7 @@ apiVersion: v2
name: trek name: trek
version: 5.2.2 version: 5.2.2
description: Minimal Helm chart for TREK app description: Minimal Helm chart for TREK app
home: https://github.com/liketrek/TREK
sources:
- https://github.com/liketrek/TREK
appVersion: "5.2.2" 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 }}
+6 -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: ""
+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.
+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);
+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,
+16 -10
View File
@@ -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",
@@ -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/leaflet": "^1.9.23",
"@types/node": "^26.6.11", "@types/node": "^26.6.11",
"@types/react": "^19.3.0", "@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",
@@ -159,13 +165,13 @@
"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"
} }
} }
+23 -24
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": 533, "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": 38, "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."
} }
} }
-22
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",
+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
} }
+4 -5
View File
@@ -5,14 +5,14 @@
"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": 2332, "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,
@@ -20,7 +20,6 @@
"src/pages/JourneyDetailPage.test.tsx": 3886, "src/pages/JourneyDetailPage.test.tsx": 3886,
"src/pages/LoginPage.tsx": 1273, "src/pages/LoginPage.tsx": 1273,
"src/pages/TripPlannerPage.tsx": 1127, "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,
+4 -11
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,
@@ -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,
@@ -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
} }
+13 -1
View File
@@ -1,4 +1,3 @@
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, onTestFinished, vi } from 'vitest' import { describe, it, expect, beforeEach, onTestFinished, vi } from 'vitest'
@@ -457,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.
+56 -21
View File
@@ -1,7 +1,9 @@
import React, { useEffect, useLayoutEffect, 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'
@@ -97,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
@@ -313,14 +335,14 @@ function RouteFallback() {
if (isAppBoot()) return <AppBootScreen /> 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()
@@ -351,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)
@@ -359,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)
@@ -383,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()
@@ -427,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')
@@ -607,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
@@ -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,
}; };
} }
@@ -158,4 +158,44 @@ describe('useDefaultUserSettings', () => {
await waitFor(() => 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 }));
});
}); });
@@ -7,16 +7,13 @@ 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';
@@ -127,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) => {
@@ -158,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);
});
});
});
@@ -0,0 +1,251 @@
/**
* The Atlas globe projection, in plain numbers. The vertex shaders in
* globeShaders.ts run the same formula on the GPU; this copy places labels,
* hit-tests the camera and is what the unit tests pin.
*
* One parameter `t` morphs an orthographic globe (t = 0) into an
* equirectangular map (t = 1) without a cut: the sphere first turns so the
* centre latitude sits on the equator by (1 - t), then the hemisphere unrolls
* with x = sin(k·λ)/k, which is the globe at k = 1 and the flat map as k → 0.
*/
export const RAD = Math.PI / 180;
const TAU = Math.PI * 2;
/** Zoom where the globe starts to unroll and where it lies flat. */
export const MORPH_START = 1.35;
export const MORPH_END = 2.6;
export const MIN_ZOOM = 0.85;
export const MAX_ZOOM = 32;
export interface GlobeCamera {
/** Centre longitude and latitude in degrees. */
lon: number;
lat: number;
/** 1 = the whole globe fits; higher zooms in. */
zoom: number;
}
export interface GlobeViewport {
/** Size in CSS pixels. */
width: number;
height: number;
/** Globe radius at zoom 1, CSS pixels. */
baseRadius: number;
/** Screen position of the globe centre at t = 0 and of the map centre at t = 1. */
globeY: number;
flatY: number;
}
export function smoothstep(a: number, b: number, x: number): number {
const t = Math.max(0, Math.min(1, (x - a) / (b - a)));
return t * t * (3 - 2 * t);
}
export function morphOf(zoom: number): number {
return smoothstep(MORPH_START, MORPH_END, zoom);
}
export function wrapPi(a: number): number {
return a - TAU * Math.floor((a + Math.PI) / TAU);
}
export interface FrameParams {
t: number;
k: number;
scale: number;
originX: number;
originY: number;
centerLon: number;
centerLat: number;
}
export function frameParams(cam: GlobeCamera, vp: GlobeViewport): FrameParams {
const t = morphOf(cam.zoom);
return {
t,
k: 1 - t * 0.9995,
scale: vp.baseRadius * cam.zoom,
originX: vp.width / 2,
originY: vp.globeY + (vp.flatY - vp.globeY) * t,
centerLon: cam.lon * RAD,
centerLat: cam.lat * RAD,
};
}
/**
* How far south and north the view's centre may go, in degrees. On the globe a
* fixed 80; as it unrolls into the flat map, as far as keeps the map's cut
* edges at the poles off the screen (the middle when the map is lower than the
* screen, where nothing hides them).
*/
export function latLimits(zoom: number, vp: GlobeViewport): [number, number] {
const t = morphOf(zoom);
if (t <= 0) return [-80, 80];
const scale = vp.baseRadius * zoom;
let north = 90 - vp.flatY / scale / RAD;
let south = -90 + (vp.height - vp.flatY) / scale / RAD;
if (south > north) north = south = (north + south) / 2;
return [-80 + (south + 80) * t, 80 + (north - 80) * t];
}
export interface ScreenPoint {
x: number;
y: number;
/** Positive while the point is on the visible side; larger is further from the edge. */
visible: number;
/** 1 facing the viewer, 0 at the limb (globe); 1 everywhere once flat. */
shade: number;
}
/**
* Projects a point given in degrees. `refLon/refLat` is the point the
* longitude is unwrapped against (the polygon or segment it belongs to), so a
* shape that crosses the back of the globe never tears across the screen.
*/
export function projectPoint(
lonDeg: number,
latDeg: number,
f: FrameParams,
refLonDeg = lonDeg,
refLatDeg = latDeg
): ScreenPoint {
const lon = lonDeg * RAD;
const lat = latDeg * RAD;
const refLon = refLonDeg * RAD;
const refLat = refLatDeg * RAD;
const phiR = f.centerLat * (1 - f.t);
const cphi = Math.cos(phiR);
const sphi = Math.sin(phiR);
const dlr = wrapPi(refLon - f.centerLon);
const dl = dlr + wrapPi(lon - f.centerLon - dlr);
const cl = Math.cos(lat);
const px = cl * Math.sin(dl);
const py = Math.sin(lat);
const pz = cl * Math.cos(dl);
const qy = py * cphi - pz * sphi;
const qz = py * sphi + pz * cphi;
let lam = Math.atan2(px, qz);
const phi = Math.asin(Math.max(-1, Math.min(1, qy)));
const cr = Math.cos(refLat);
const rx = cr * Math.sin(dlr);
const rz = Math.sin(refLat) * sphi + cr * Math.cos(dlr) * cphi;
const lamR = Math.atan2(rx, rz);
lam = lamR + wrapPi(lam - lamR);
const x = (Math.sin(f.k * lam) / f.k) * (Math.cos(phi) * (1 - f.t) + f.t) * xSqueeze(f);
const y = Math.sin(phi) * (1 - f.t) + phi * f.t;
const c = Math.acos(Math.max(-1, Math.min(1, Math.cos(phi) * Math.cos(lam))));
const lim = Math.min(Math.PI, (0.5 * Math.PI) / f.k);
return {
x: f.originX + x * f.scale,
y: f.originY - (y - f.centerLat * f.t) * f.scale,
visible: Math.abs(lam) <= Math.PI ? lim - c : -1,
shade: Math.max(0, Math.cos(c)) * (1 - f.t) + f.t,
};
}
/** How much the flat map squeezes longitude: the cosine of the centre latitude. */
export function xSqueeze(f: FrameParams): number {
return 1 + (Math.max(0.3, Math.cos(f.centerLat)) - 1) * f.t;
}
/** Great-circle distance in radians between two points given in degrees. */
export function angularDistance(lon1: number, lat1: number, lon2: number, lat2: number): number {
const a1 = lat1 * RAD;
const a2 = lat2 * RAD;
const d = (lon2 - lon1) * RAD;
const c = Math.sin(a1) * Math.sin(a2) + Math.cos(a1) * Math.cos(a2) * Math.cos(d);
return Math.acos(Math.max(-1, Math.min(1, c)));
}
/** Point along the great circle from a to b at fraction s (degrees in, degrees out). */
export function interpolateGreatCircle(
lon1: number,
lat1: number,
lon2: number,
lat2: number,
s: number
): [number, number] {
const p1 = [
Math.cos(lat1 * RAD) * Math.cos(lon1 * RAD),
Math.cos(lat1 * RAD) * Math.sin(lon1 * RAD),
Math.sin(lat1 * RAD),
];
const p2 = [
Math.cos(lat2 * RAD) * Math.cos(lon2 * RAD),
Math.cos(lat2 * RAD) * Math.sin(lon2 * RAD),
Math.sin(lat2 * RAD),
];
const d = angularDistance(lon1, lat1, lon2, lat2);
if (d < 1e-9) return [lon1, lat1];
const a = Math.sin((1 - s) * d) / Math.sin(d);
const b = Math.sin(s * d) / Math.sin(d);
const x = a * p1[0] + b * p2[0];
const y = a * p1[1] + b * p2[1];
const z = a * p1[2] + b * p2[2];
return [Math.atan2(y, x) / RAD, Math.atan2(z, Math.hypot(x, y)) / RAD];
}
/**
* Unit vector to the sun in earth-fixed coordinates (x towards 0°/0°, z north)
* for a moment in time. Low-precision solar position, good to a fraction of a
* degree, which is plenty for a day/night line.
*/
export function sunVector(date: Date): [number, number, number] {
const d = date.getTime() / 86400000 - 10957.5; // days since J2000
const g = (357.529 + 0.98560028 * d) * RAD;
const q = 280.459 + 0.98564736 * d;
const L = (q + 1.915 * Math.sin(g) + 0.02 * Math.sin(2 * g)) * RAD;
const e = (23.439 - 0.00000036 * d) * RAD;
const decl = Math.asin(Math.sin(e) * Math.sin(L));
const ra = Math.atan2(Math.cos(e) * Math.sin(L), Math.cos(L));
const gmst = ((280.46061837 + 360.98564736629 * d) % 360) * RAD;
const lon = ra - gmst;
return [Math.cos(decl) * Math.cos(lon), Math.cos(decl) * Math.sin(lon), Math.sin(decl)];
}
/** Moon phase 0..1 (0 new, 0.5 full) and illuminated share, for a moment in time. */
export function moonPhase(date: Date): { phase: number; lit: number } {
const synodic = 29.530588853;
const ref = Date.UTC(2000, 0, 6, 18, 14);
const days = (date.getTime() - ref) / 86400000;
const phase = (((days % synodic) + synodic) % synodic) / synodic;
return { phase, lit: (1 - Math.cos(phase * 2 * Math.PI)) / 2 };
}
/**
* A flight arc as instanced segments for the line shader: per segment
* a.lon, a.lat, b.lon, b.lat (radians), lift at a and b, and the share of the
* arc reached at a and b (so the arc can draw itself in).
*/
export function arcSegments(
routes: Array<{ a: [number, number]; b: [number, number] }>,
steps = 48
): { data: Float32Array; count: number } {
const out = new Float32Array(routes.length * steps * 8);
let o = 0;
for (const r of routes) {
const d = angularDistance(r.a[0], r.a[1], r.b[0], r.b[1]);
const peak = 0.015 + d * 0.06;
let prev = interpolateGreatCircle(r.a[0], r.a[1], r.b[0], r.b[1], 0);
for (let i = 1; i <= steps; i++) {
const s0 = (i - 1) / steps;
const s1 = i / steps;
const next = interpolateGreatCircle(r.a[0], r.a[1], r.b[0], r.b[1], s1);
out[o++] = prev[0] * RAD;
out[o++] = prev[1] * RAD;
out[o++] = next[0] * RAD;
out[o++] = next[1] * RAD;
out[o++] = peak * Math.sin(Math.PI * s0);
out[o++] = peak * Math.sin(Math.PI * s1);
out[o++] = s0;
out[o++] = s1;
prev = next;
}
}
return { data: out, count: o / 8 };
}
@@ -0,0 +1,218 @@
// FE-ATLAS2-PAINT-501 to FE-ATLAS2-PAINT-510: the branches of the mesh builder the main
// globeMesh tests leave out (each split direction, holes, multipolygons, growth).
import type { Topology } from 'topojson-specification';
import { describe, expect, it } from 'vitest';
import { buildLayer, densify, tessellate } from './globeMesh';
const RAD = Math.PI / 180;
/** A square with a hole, a two-part country, a sliver too thin to fill and a feature without geometry. */
const SHAPES: Topology = {
type: 'Topology',
arcs: [
[
[0, 0],
[10, 0],
[10, 10],
[0, 10],
[0, 0],
],
[
[3, 3],
[3, 7],
[7, 7],
[7, 3],
[3, 3],
],
[
[20, 0],
[22, 0],
[22, 2],
[20, 2],
[20, 0],
],
[
[30, 0],
[32, 0],
[32, 2],
[30, 2],
[30, 0],
],
[
[40, 0],
[41, 1],
[40, 0],
],
],
objects: {
countries: {
type: 'GeometryCollection',
geometries: [
{ type: 'Polygon', id: 0, arcs: [[0], [1]] },
{ type: 'MultiPolygon', id: 1, arcs: [[[2]], [[3]]] },
{ type: 'Polygon', id: 2, arcs: [[4]] },
{ type: null, id: 3 },
],
},
},
};
/** Many small squares, apart from each other: enough vertices to make every buffer grow. */
const GRID_SIDE = 95;
const GRID: Topology = {
type: 'Topology',
arcs: Array.from({ length: GRID_SIDE * GRID_SIDE }, (_, k) => {
const x = (k % GRID_SIDE) * 2 - 100;
const y = Math.floor(k / GRID_SIDE) * 1.5 - 70;
return [
[x, y],
[x + 0.5, y],
[x + 0.5, y + 0.5],
[x, y + 0.5],
[x, y],
];
}),
objects: {
grid: {
type: 'GeometryCollection',
geometries: [
{ type: 'MultiPolygon', id: 0, arcs: Array.from({ length: GRID_SIDE * GRID_SIDE }, (_, k) => [[k]]) },
],
},
},
};
function edgeLengths(coords: number[], tris: number[]): number[] {
const out: number[] = [];
for (let i = 0; i < tris.length; i += 3) {
const t = [tris[i], tris[i + 1], tris[i + 2]];
for (const [p, q] of [
[t[0], t[1]],
[t[1], t[2]],
[t[2], t[0]],
]) {
out.push(Math.hypot(coords[p * 2] - coords[q * 2], coords[p * 2 + 1] - coords[q * 2 + 1]));
}
}
return out;
}
describe('tessellate', () => {
it('FE-ATLAS2-PAINT-501: keeps a triangle that is already small enough as it is', () => {
const coords = [0, 0, 1, 0, 0, 1];
expect(tessellate(coords, [0, 1, 2], 5)).toEqual([0, 1, 2]);
expect(coords).toHaveLength(6);
});
it('FE-ATLAS2-PAINT-502: splits the first edge when it is the longest', () => {
const coords = [0, 0, 10, 0, 5, 1];
expect(tessellate(coords, [0, 1, 2], 9)).toEqual([3, 1, 2, 0, 3, 2]);
expect(coords.slice(6)).toEqual([5, 0]);
});
it('FE-ATLAS2-PAINT-503: splits the second edge when it is the longest', () => {
const coords = [0, 0, 1, 0, 0, 10];
expect(tessellate(coords, [0, 1, 2], 10.01)).toEqual([0, 3, 2, 0, 1, 3]);
expect(coords.slice(6)).toEqual([0.5, 5]);
});
it('FE-ATLAS2-PAINT-504: splits the closing edge when it is the longest', () => {
const coords = [0, 0, 5, 1, 10, 0];
expect(tessellate(coords, [0, 1, 2], 9)).toEqual([3, 1, 2, 0, 1, 3]);
expect(coords.slice(6)).toEqual([5, 0]);
});
it('FE-ATLAS2-PAINT-505: two triangles sharing a long edge share its midpoint', () => {
const coords = [0, 0, 10, 0, 10, 10, 0, 10];
const tris = tessellate(coords, [0, 1, 2, 0, 2, 3], 12);
expect(tris).toHaveLength(12);
// One new vertex for the shared diagonal, not one per triangle.
expect(coords).toHaveLength(10);
expect(coords.slice(8)).toEqual([5, 5]);
expect(Math.max(...edgeLengths(coords, tris))).toBeLessThanOrEqual(12);
});
});
describe('densify', () => {
it('FE-ATLAS2-PAINT-506: leaves a short line and a single point alone and cuts a diagonal evenly', () => {
expect(
densify(
[
[0, 0],
[1, 1],
],
5
)
).toEqual([
[0, 0],
[1, 1],
]);
expect(densify([[3, 4]], 1)).toEqual([[3, 4]]);
const d = densify(
[
[0, 0],
[3, 4],
],
2
);
expect(d).toEqual([
[0, 0],
[1, 4 / 3],
[2, 8 / 3],
[3, 4],
]);
});
});
describe('buildLayer', () => {
const layer = buildLayer(SHAPES, 'countries', 100, (n) => 10 + n);
it('FE-ATLAS2-PAINT-507: draws fill for every nondegenerate polygon part', () => {
const { fid, index, ll, ref } = layer.fill;
// A degenerate ring can contribute vertices, but no fill triangle may reference them.
const drawnVertices = Array.from(new Set(index));
expect(new Set(drawnVertices.map((vertex) => fid[vertex]))).toEqual(new Set([10, 11]));
expect(new Set(drawnVertices.map((vertex) => Math.round(ref[vertex * 2] / RAD)))).toEqual(new Set([5, 21, 31]));
expect(ll).toHaveLength(fid.length * 2);
expect(ref).toHaveLength(fid.length * 2);
expect(index.length % 3).toBe(0);
});
it('FE-ATLAS2-PAINT-508: the hole stays empty and every vertex refers to the centre of its own outline', () => {
const idx = Array.from(layer.fill.index.slice(0, 24));
// The hole's own vertices (4 to 7) never make up one triangle together.
for (let i = 0; i < idx.length; i += 3) {
expect(idx.slice(i, i + 3).every((v) => v >= 4)).toBe(false);
}
expect(layer.fill.ref[0]).toBeCloseTo(5 * RAD);
expect(layer.fill.ref[1]).toBeCloseTo(5 * RAD);
expect(layer.fill.ref[8 * 2]).toBeCloseTo(21 * RAD);
expect(layer.fill.ref[12 * 2]).toBeCloseTo(31 * RAD);
expect(layer.fill.ll[8 * 2]).toBeCloseTo(20 * RAD);
});
it('FE-ATLAS2-PAINT-509: draws every outline as coast when no border is shared', () => {
expect(layer.borders.count).toBe(0);
expect(layer.borders.seg).toHaveLength(0);
// Outer square, hole, two parts (four sides each) and the sliver's two sides.
expect(layer.coast.count).toBe(18);
expect(layer.coast.seg).toHaveLength(18 * 4);
});
it('FE-ATLAS2-PAINT-510: grows its buffers for a country of many parts and keeps every part', () => {
const grid = buildLayer(GRID, 'grid', 5, () => 7);
const vertices = grid.fill.fid.length;
// Four corners a square, past the 32768 the id buffer starts with.
expect(vertices).toBe(GRID_SIDE * GRID_SIDE * 4);
expect(vertices).toBeGreaterThan(1 << 15);
expect(grid.fill.ll).toHaveLength(vertices * 2);
expect(grid.fill.ref).toHaveLength(vertices * 2);
expect(grid.fill.fid.every((v) => v === 7)).toBe(true);
// Two triangles a square; reduce, since spread would overflow the argument list.
expect(grid.fill.index.length).toBe(GRID_SIDE * GRID_SIDE * 6);
expect(grid.fill.index.reduce((m, v) => Math.max(m, v), 0)).toBe(vertices - 1);
// Every side of every square is coast: no two parts share one.
expect(grid.coast.count).toBe(GRID_SIDE * GRID_SIDE * 4);
expect(grid.borders.count).toBe(0);
});
});
@@ -0,0 +1,85 @@
import type { Topology } from 'topojson-specification';
import { describe, expect, it } from 'vitest';
import { buildLayer, buildOcean, densify, tessellate } from './globeMesh';
/** Two squares sharing one edge, as TopoJSON with that edge stored once. */
const TWO_SQUARES: Topology = {
type: 'Topology',
arcs: [
[
[10, 0],
[10, 10],
], // shared
[
[10, 10],
[0, 10],
[0, 0],
[10, 0],
],
[
[10, 0],
[20, 0],
[20, 10],
[10, 10],
],
],
objects: {
countries: {
type: 'GeometryCollection',
geometries: [
{ type: 'Polygon', id: 0, arcs: [[0, 1]] },
{ type: 'Polygon', id: 1, arcs: [[~0, 2]] },
],
},
},
};
describe('globeMesh', () => {
it('splits triangles until every edge is short enough', () => {
const coords = [0, 0, 40, 0, 0, 40];
const tris = tessellate(coords, [0, 1, 2], 8);
for (let i = 0; i < tris.length; i += 3) {
const [a, b, c] = [tris[i], tris[i + 1], tris[i + 2]];
for (const [p, q] of [
[a, b],
[b, c],
[c, a],
]) {
expect(Math.hypot(coords[p * 2] - coords[q * 2], coords[p * 2 + 1] - coords[q * 2 + 1])).toBeLessThanOrEqual(
8 + 1e-9
);
}
}
expect(tris.length / 3).toBeGreaterThan(10);
});
it('densifies lines without moving their ends', () => {
const d = densify(
[
[0, 0],
[10, 0],
],
2
);
expect(d).toHaveLength(6);
expect(d[0]).toEqual([0, 0]);
expect(d[5]).toEqual([10, 0]);
});
it('builds fills with the right ids and the shared border once', () => {
const layer = buildLayer(TWO_SQUARES, 'countries', 100, (n) => 40 + n);
const ids = new Set(Array.from(layer.fill.fid));
expect(ids).toEqual(new Set([40, 41]));
expect(layer.fill.index.length % 3).toBe(0);
// The shared edge is one border segment, the outline is the coast.
expect(layer.borders.count).toBe(1);
expect(layer.coast.count).toBeGreaterThanOrEqual(6);
// Everything leaves in radians.
expect(Math.max(...Array.from(layer.fill.ll))).toBeLessThanOrEqual((20 * Math.PI) / 180 + 1e-6);
});
it('covers the whole sphere with the ocean grid', () => {
const o = buildOcean(30);
expect(o.index.length).toBe((360 / 30) * (180 / 30) * 6);
});
});
@@ -0,0 +1,220 @@
/**
* Turns a TopoJSON level of detail into GPU-ready arrays: triangles for the
* fills, segments for the borders. Pure, so the worker and the tests share it.
*
* Coordinates leave here in radians. Each fill vertex carries the centre of its
* polygon as the reference the shader unwraps longitude against, so a polygon
* that crosses the back of the globe stays in one piece.
*/
import earcut from 'earcut';
import type { LineString, MultiLineString, MultiPolygon, Polygon, Position } from 'geojson';
import { feature, mesh } from 'topojson-client';
import type { GeometryCollection, Topology } from 'topojson-specification';
const RAD = Math.PI / 180;
export interface FillMesh {
/** lon, lat per vertex (radians) */
ll: Float32Array;
/** reference lon, lat per vertex (radians) */
ref: Float32Array;
/** feature id per vertex */
fid: Float32Array;
index: Uint32Array;
}
export interface LineMesh {
/** per segment: a.lon, a.lat, b.lon, b.lat (radians) */
seg: Float32Array;
count: number;
}
export interface BuiltLayer {
fill: FillMesh;
coast: LineMesh;
borders: LineMesh;
}
/** Splits triangles until no edge is longer than maxEdge degrees, so they bend with the sphere. */
export function tessellate(coords: number[], tris: number[], maxEdge: number): number[] {
const out: number[] = [];
const mid = new Map<string, number>();
const midpoint = (a: number, b: number): number => {
const key = a < b ? `${a}:${b}` : `${b}:${a}`;
let m = mid.get(key);
if (m === undefined) {
m = coords.length / 2;
coords.push((coords[a * 2] + coords[b * 2]) / 2, (coords[a * 2 + 1] + coords[b * 2 + 1]) / 2);
mid.set(key, m);
}
return m;
};
const len = (a: number, b: number): number =>
Math.hypot(coords[a * 2] - coords[b * 2], coords[a * 2 + 1] - coords[b * 2 + 1]);
const stack: Array<[number, number, number]> = [];
for (let i = 0; i < tris.length; i += 3) stack.push([tris[i], tris[i + 1], tris[i + 2]]);
while (stack.length) {
const [a, b, c] = stack.pop() as [number, number, number];
const ab = len(a, b);
const bc = len(b, c);
const ca = len(c, a);
const m = Math.max(ab, bc, ca);
if (m <= maxEdge) {
out.push(a, b, c);
} else if (m === ab) {
const d = midpoint(a, b);
stack.push([a, d, c], [d, b, c]);
} else if (m === bc) {
const d = midpoint(b, c);
stack.push([a, b, d], [a, d, c]);
} else {
const d = midpoint(c, a);
stack.push([a, b, d], [d, b, c]);
}
}
return out;
}
/** Inserts points so no segment is longer than maxEdge degrees. */
export function densify(line: Position[], maxEdge: number): Position[] {
const out: Position[] = [line[0]];
for (let i = 1; i < line.length; i++) {
const [x0, y0] = line[i - 1];
const [x1, y1] = line[i];
const n = Math.max(1, Math.ceil(Math.hypot(x1 - x0, y1 - y0) / maxEdge));
for (let k = 1; k <= n; k++) out.push([x0 + ((x1 - x0) * k) / n, y0 + ((y1 - y0) * k) / n]);
}
return out;
}
function polygonsOf(g: Polygon | MultiPolygon | null): Position[][][] {
if (!g) return [];
return g.type === 'Polygon' ? [g.coordinates] : g.coordinates;
}
function centreOf(ring: Position[]): [number, number] {
let w = Infinity;
let e = -Infinity;
let s = Infinity;
let n = -Infinity;
for (const [x, y] of ring) {
if (x < w) w = x;
if (x > e) e = x;
if (y < s) s = y;
if (y > n) n = y;
}
return [(w + e) / 2, (s + n) / 2];
}
class Grow {
data: Float32Array;
length = 0;
constructor(n = 4096) {
this.data = new Float32Array(n);
}
push(...v: number[]): void {
if (this.length + v.length > this.data.length) {
const next = new Float32Array(Math.max(this.data.length * 2, this.length + v.length));
next.set(this.data);
this.data = next;
}
for (const x of v) this.data[this.length++] = x;
}
done(): Float32Array {
return this.data.slice(0, this.length);
}
}
function linesOf(ml: MultiLineString | LineString, maxEdge: number): LineMesh {
const seg = new Grow();
const parts = ml.type === 'MultiLineString' ? ml.coordinates : [ml.coordinates];
for (const part of parts) {
if (part.length < 2) continue;
const d = densify(part, maxEdge);
for (let i = 1; i < d.length; i++) seg.push(d[i - 1][0] * RAD, d[i - 1][1] * RAD, d[i][0] * RAD, d[i][1] * RAD);
}
const arr = seg.done();
return { seg: arr, count: arr.length / 4 };
}
/**
* Builds one layer. `ids` maps a topology feature's numeric id to the id the
* status texture knows it by (countries: their manifest index; regions: a block
* reserved for that country).
*/
export function buildLayer(
topo: Topology,
objectName: string,
maxEdge: number,
ids: (topoId: number) => number
): BuiltLayer {
const obj = topo.objects[objectName] as GeometryCollection;
const fc = feature(topo, obj);
const ll = new Grow(1 << 16);
const ref = new Grow(1 << 16);
const fid = new Grow(1 << 15);
let index: number[] = [];
let vbase = 0;
for (const f of fc.features) {
const id = ids(Number(f.id));
for (const poly of polygonsOf(f.geometry as Polygon | MultiPolygon)) {
if (!poly.length || poly[0].length < 4) continue;
const flat: number[] = [];
const holes: number[] = [];
poly.forEach((ring, ri) => {
if (ri > 0) holes.push(flat.length / 2);
for (let i = 0; i < ring.length - 1; i++) flat.push(ring[i][0], ring[i][1]);
});
const tris = tessellate(flat, earcut(flat, holes, 2), maxEdge);
const [cx, cy] = centreOf(poly[0]);
for (let i = 0; i < flat.length; i += 2) {
ll.push(flat[i] * RAD, flat[i + 1] * RAD);
ref.push(cx * RAD, cy * RAD);
fid.push(id);
}
for (const t of tris) index.push(vbase + t);
vbase += flat.length / 2;
}
if (index.length > 1 << 20) index = index.slice();
}
const coast = mesh(topo, obj, (a, b) => a === b) as MultiLineString;
const borders = mesh(topo, obj, (a, b) => a !== b) as MultiLineString;
return {
fill: { ll: ll.done(), ref: ref.done(), fid: fid.done(), index: Uint32Array.from(index) },
coast: linesOf(coast, maxEdge),
borders: linesOf(borders, maxEdge),
};
}
/** A latitude/longitude grid over the whole sphere, the ocean the land sits on. */
export function buildOcean(step = 6): FillMesh {
const ll: number[] = [];
const ref: number[] = [];
const fid: number[] = [];
const index: number[] = [];
let v = 0;
for (let lon = -180; lon < 180; lon += step) {
for (let lat = -90; lat < 90; lat += step) {
const cx = (lon + step / 2) * RAD;
const cy = (lat + step / 2) * RAD;
for (const [x, y] of [
[lon, lat],
[lon + step, lat],
[lon + step, lat + step],
[lon, lat + step],
]) {
ll.push(x * RAD, Math.min(90, y) * RAD);
ref.push(cx, cy);
fid.push(0);
}
index.push(v, v + 1, v + 2, v, v + 2, v + 3);
v += 4;
}
}
return {
ll: Float32Array.from(ll),
ref: Float32Array.from(ref),
fid: Float32Array.from(fid),
index: Uint32Array.from(index),
};
}
@@ -0,0 +1,119 @@
// FE-ATLAS2-RENDER-500 to FE-ATLAS2-RENDER-503: the mesh worker, building a layer off the main thread and
// answering each job with the layer (buffers transferred) or the error.
import type { Topology } from 'topojson-specification';
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import type { MeshRequest, MeshResponse } from './globeMesh.worker';
const h = vi.hoisted(() => ({ fail: null as unknown }));
vi.mock('./globeMesh', async (importOriginal) => {
const actual = await importOriginal<typeof import('./globeMesh')>();
return {
...actual,
buildLayer: (...args: Parameters<typeof actual.buildLayer>) => {
if (h.fail !== null) throw h.fail;
return actual.buildLayer(...args);
},
};
});
/** Two squares sharing one edge. */
const TWO_SQUARES: Topology = {
type: 'Topology',
arcs: [
[
[10, 0],
[10, 10],
],
[
[10, 10],
[0, 10],
[0, 0],
[10, 0],
],
[
[10, 0],
[20, 0],
[20, 10],
[10, 10],
],
],
objects: {
countries: {
type: 'GeometryCollection',
geometries: [
{ type: 'Polygon', id: 0, arcs: [[0, 1]] },
{ type: 'Polygon', id: 1, arcs: [[~0, 2]] },
],
},
},
};
type Posted = [MeshResponse, Transferable[] | undefined];
let posted: Posted[];
function send(req: MeshRequest): void {
const handler = self.onmessage;
if (!handler) throw new Error('worker installed no message handler');
handler.call(self, { data: req } as MessageEvent<MeshRequest>);
}
beforeAll(async () => {
await import('./globeMesh.worker');
});
beforeEach(() => {
h.fail = null;
posted = [];
vi.spyOn(self, 'postMessage').mockImplementation(((msg: MeshResponse, transfer?: Transferable[]) => {
posted.push([msg, transfer]);
}) as typeof self.postMessage);
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('globeMesh.worker', () => {
it('FE-ATLAS2-RENDER-500: answers a job with the built layer, ids offset by idBase', () => {
send({ job: 7, topo: TWO_SQUARES, object: 'countries', maxEdge: 4, idBase: 100 });
expect(posted).toHaveLength(1);
const [msg] = posted[0];
expect(msg.job).toBe(7);
expect(msg.error).toBeUndefined();
const fid = Array.from(msg.layer?.fill.fid ?? []);
expect(new Set(fid)).toEqual(new Set([100, 101]));
expect(msg.layer?.fill.index.length).toBeGreaterThan(0);
// The shared edge is a border, the outer ring the coast.
expect(msg.layer?.borders.count).toBeGreaterThan(0);
expect(msg.layer?.coast.count).toBeGreaterThan(0);
});
it('FE-ATLAS2-RENDER-501: transfers the six array buffers instead of copying them', () => {
send({ job: 1, topo: TWO_SQUARES, object: 'countries', maxEdge: 8, idBase: 0 });
const [msg, transfer] = posted[0];
const layer = msg.layer;
if (!layer) throw new Error('no layer');
expect(transfer).toEqual([
layer.fill.ll.buffer,
layer.fill.ref.buffer,
layer.fill.fid.buffer,
layer.fill.index.buffer,
layer.coast.seg.buffer,
layer.borders.seg.buffer,
]);
});
it('FE-ATLAS2-RENDER-502: answers a failing job with its error message', () => {
h.fail = new Error('bad topology');
send({ job: 3, topo: TWO_SQUARES, object: 'countries', maxEdge: 8, idBase: 0 });
expect(posted).toEqual([[{ job: 3, error: 'bad topology' }, undefined]]);
});
it('FE-ATLAS2-RENDER-503: turns a thrown non-error into text', () => {
h.fail = 'out of memory';
send({ job: 4, topo: TWO_SQUARES, object: 'countries', maxEdge: 8, idBase: 0 });
expect(posted).toEqual([[{ job: 4, error: 'out of memory' }, undefined]]);
});
});
@@ -0,0 +1,43 @@
/// <reference lib="webworker" />
/**
* Builds globe layers off the main thread. The main thread fetches the
* topology (it owns auth and the API base) and hands it over; this worker
* triangulates and sends the arrays back as transferables.
*/
import type { Topology } from 'topojson-specification';
import { buildLayer, type BuiltLayer } from './globeMesh';
export interface MeshRequest {
job: number;
topo: Topology;
object: string;
maxEdge: number;
/** Status-texture id of topology feature 0; feature n gets idBase + n. */
idBase: number;
}
export interface MeshResponse {
job: number;
layer?: BuiltLayer;
error?: string;
}
const scope = self as unknown as DedicatedWorkerGlobalScope;
scope.onmessage = (e: MessageEvent<MeshRequest>) => {
const { job, topo, object, maxEdge, idBase } = e.data;
try {
const layer = buildLayer(topo, object, maxEdge, (n) => idBase + n);
const transfer = [
layer.fill.ll.buffer,
layer.fill.ref.buffer,
layer.fill.fid.buffer,
layer.fill.index.buffer,
layer.coast.seg.buffer,
layer.borders.seg.buffer,
];
scope.postMessage({ job, layer } satisfies MeshResponse, transfer);
} catch (err) {
scope.postMessage({ job, error: err instanceof Error ? err.message : String(err) } satisfies MeshResponse);
}
};
@@ -0,0 +1,430 @@
/**
* GLSL for the Atlas globe. PROJECT is the GPU twin of projectPoint() in
* globeMath.ts; a change to one belongs in the other.
*/
/**
* The flat map has edges at the poles, where the sphere was cut open. While the
* globe unrolls, land, sea and lines fade into the sky towards them, so the map
* ends in a haze instead of a hard rim. Needs u_t.
*/
const POLAR = /* glsl */ `
float polarFade(float lat) { return 1.0 - u_t * smoothstep(1.36, 1.5708, abs(lat)); }
`;
const PROJECT = /* glsl */ `
uniform vec2 u_center; // centre lon, lat in radians
uniform float u_t; // 0 globe .. 1 flat map
uniform float u_scale; // device px per radian
uniform vec2 u_origin; // device px of the centre
uniform vec2 u_viewport; // device px
const float PI = 3.14159265;
float wrapPi(float a) { return a - 2.0 * PI * floor((a + PI) / (2.0 * PI)); }
// xy: screen px, z: visibility (> 0 visible), w: shade
vec4 project(vec2 ll, vec2 ref) {
float k = 1.0 - u_t * 0.9995;
float phiR = u_center.y * (1.0 - u_t);
float cphi = cos(phiR), sphi = sin(phiR);
float dlr = wrapPi(ref.x - u_center.x);
float dl = dlr + wrapPi(ll.x - u_center.x - dlr);
float cl = cos(ll.y);
vec3 p = vec3(cl * sin(dl), sin(ll.y), cl * cos(dl));
float qy = p.y * cphi - p.z * sphi;
float qz = p.y * sphi + p.z * cphi;
float lam = atan(p.x, qz);
float phi = asin(clamp(qy, -1.0, 1.0));
float cr = cos(ref.y);
float lamR = atan(cr * sin(dlr), sin(ref.y) * sphi + cr * cos(dlr) * cphi);
lam = lamR + wrapPi(lam - lamR);
// Flat, longitude is squeezed by the cosine of the centre latitude, so shapes keep
// their proportions where the user looks instead of widening towards the poles.
float xs = mix(1.0, max(0.3, cos(u_center.y)), u_t);
float x = sin(k * lam) / k * (cos(phi) * (1.0 - u_t) + u_t) * xs;
float y = sin(phi) * (1.0 - u_t) + phi * u_t;
vec2 s = u_origin + vec2(x, -(y - u_center.y * u_t)) * u_scale;
float c = acos(clamp(cos(phi) * cos(lam), -1.0, 1.0));
float lim = min(PI, 0.5 * PI / k);
float vis = abs(lam) <= PI ? lim - c : -1.0;
float shade = max(0.0, cos(c)) * (1.0 - u_t) + u_t;
return vec4(s, vis, shade);
}
vec4 toClip(vec2 s) {
return vec4(s.x / u_viewport.x * 2.0 - 1.0, 1.0 - s.y / u_viewport.y * 2.0, 0.0, 1.0);
}
`;
export const FILL_VS = /* glsl */ `#version 300 es
precision highp float;
${PROJECT}
in vec2 a_ll; // radians
in vec2 a_ref; // radians
in float a_fid;
out float v_vis;
out float v_shade;
out vec2 v_ll;
flat out int v_fid;
void main() {
vec4 p = project(a_ll, a_ref);
v_vis = p.z;
v_shade = p.w;
v_ll = a_ll;
v_fid = int(a_fid + 0.5);
gl_Position = toClip(p.xy);
}
`;
export const FILL_FS = /* glsl */ `#version 300 es
precision highp float;
precision highp usampler2D;
in float v_vis;
in float v_shade;
in vec2 v_ll;
flat in int v_fid;
uniform sampler2D u_status; // rgb colour, a strength
uniform sampler2D u_fx; // r hatch, g reveal order, b regions loaded, a visited regions
uniform int u_mode; // 0 land, 1 ocean, 2 region layer
uniform vec3 u_land;
uniform vec3 u_ocean;
uniform vec3 u_oceanDeep;
uniform float u_layerAlpha;
uniform float u_time;
uniform float u_revealStart;
uniform int u_hover;
uniform int u_selected;
uniform int u_inkId;
uniform vec2 u_inkLL;
uniform float u_inkR;
uniform float u_dpr;
uniform float u_scale; // device px per radian, as in PROJECT
uniform float u_t;
uniform float u_dimBase;
uniform float u_regionFade;
uniform vec3 u_sun; // unit vector to the sun, earth-fixed
uniform float u_night; // how strongly the night side darkens
uniform float u_shadeMin; // brightness at the limb (light mode keeps it high)
uniform vec4 u_hoverTint; // rgb + strength; selection uses 1.8x the strength
out vec4 outColor;
vec4 fetch(sampler2D tex, int id) { return texelFetch(tex, ivec2(id % 256, id / 256), 0); }
${POLAR}
void main() {
if (v_vis < 0.0) discard;
float edge = smoothstep(0.0, 0.004, v_vis);
float light = mix(u_shadeMin, 1.0, pow(v_shade, 0.65));
vec3 nrm = vec3(cos(v_ll.y) * cos(v_ll.x), cos(v_ll.y) * sin(v_ll.x), sin(v_ll.y));
float sunDot = dot(nrm, u_sun);
float day = smoothstep(-0.12, 0.1, sunDot);
float nightMul = mix(1.0 - u_night, 1.0, day);
if (u_mode == 1) {
vec3 col = mix(u_oceanDeep, u_ocean, pow(v_shade, 0.9));
col *= mix(1.0 - u_night * 0.7, 1.0, day);
// A faint glint where the sun stands over the sea.
col += vec3(0.45) * pow(max(0.0, sunDot), 40.0) * 0.25 * (1.0 - u_t) * v_shade;
outColor = vec4(col, edge * polarFade(v_ll.y));
return;
}
vec4 st = fetch(u_status, v_fid);
vec4 fx = fetch(u_fx, v_fid);
float reveal = clamp((u_time - u_revealStart - fx.g * 1.6) / 0.45, 0.0, 1.0);
float a = st.a * reveal;
if (v_fid == u_inkId) {
vec3 p1 = vec3(cos(v_ll.y) * cos(v_ll.x), cos(v_ll.y) * sin(v_ll.x), sin(v_ll.y));
vec3 p2 = vec3(cos(u_inkLL.y) * cos(u_inkLL.x), cos(u_inkLL.y) * sin(u_inkLL.x), sin(u_inkLL.y));
float d = acos(clamp(dot(p1, p2), -1.0, 1.0));
a *= 1.0 - smoothstep(u_inkR - 0.01, u_inkR, d);
}
// A country whose regions are on screen steps back so its regions read; one with
// visited regions (fx.a) all but disappears behind them, as in the regions view,
// so only the regions really visited carry its colour.
if (u_mode == 0 && fx.b > 0.5) a *= 1.0 - (fx.a > 0.5 ? 0.96 : 0.32) * u_regionFade;
vec3 base = u_land * (u_mode == 2 ? 1.0 : u_dimBase);
vec3 col = mix(base, st.rgb, a);
if (fx.r > 0.5) {
// The stripes are slices through the globe itself, so they stay on the land
// while it turns; their spacing steps with the zoom to stay about 7 px.
vec3 p3 = vec3(cos(v_ll.y) * cos(v_ll.x), cos(v_ll.y) * sin(v_ll.x), sin(v_ll.y));
float per = exp2(floor(log2(7.0 * u_dpr / u_scale)));
float sl = dot(p3, vec3(0.6, 0.6, 0.53)) / per;
float w = max(fwidth(sl), 1e-4);
float h = 1.0 - smoothstep(0.115 - w * 0.5, 0.115 + w * 0.5, abs(fract(sl) - 0.115));
col = mix(col, st.rgb, h * 0.9 * reveal);
a = max(a, h * 0.9 * reveal);
}
if (v_fid == u_selected) col = mix(col, u_hoverTint.rgb, u_hoverTint.a * 1.8);
else if (v_fid == u_hover) col = mix(col, u_hoverTint.rgb, u_hoverTint.a);
col *= light;
// Night darkens the land; what you marked keeps most of its colour, like lights on.
col *= mix(nightMul, 1.0, a * 0.75);
float alpha = edge * polarFade(v_ll.y);
if (u_mode == 2) alpha *= u_layerAlpha * max(a, (v_fid == u_hover || v_fid == u_selected) ? 0.25 : 0.0);
outColor = vec4(col, alpha);
}
`;
export const PICK_FS = /* glsl */ `#version 300 es
precision highp float;
in float v_vis;
in float v_shade;
in vec2 v_ll;
flat in int v_fid;
uniform int u_idBase;
out vec4 outColor;
void main() {
if (v_vis < 0.0) discard;
int id = v_fid + 1;
outColor = vec4(float(id & 255) / 255.0, float((id >> 8) & 255) / 255.0, float((id >> 16) & 255) / 255.0, 1.0);
}
`;
/** Instanced screen-space lines: borders, coasts, outlines and flight arcs. */
export const LINE_VS = /* glsl */ `#version 300 es
precision highp float;
${PROJECT}
in vec2 a_corner; // x: 0 start .. 1 end, y: -1 .. 1 across
in vec2 a_a; // radians
in vec2 a_b; // radians
in vec2 a_h; // lift of a and b (arcs), share of the radius
in vec2 a_s; // position along the whole line, 0..1, at a and b
uniform float u_width; // device px
uniform float u_lift; // 1 lifts arcs above the surface
out float v_vis;
out float v_across;
out float v_s;
out float v_shade;
out float v_lat;
vec2 lifted(vec4 p, float h) {
vec2 d = p.xy - u_origin;
vec2 globe = u_origin + d * (1.0 + h);
vec2 flat2 = p.xy - vec2(0.0, h * u_scale * 0.35);
return mix(globe, flat2, u_t);
}
void main() {
vec2 mid = (a_a + a_b) * 0.5;
if (abs(a_a.x - a_b.x) > PI) mid.x = a_a.x;
vec4 pa = project(a_a, mid);
vec4 pb = project(a_b, mid);
vec2 sa = u_lift > 0.5 ? lifted(pa, a_h.x) : pa.xy;
vec2 sb = u_lift > 0.5 ? lifted(pb, a_h.y) : pb.xy;
vec2 dir = sb - sa;
float len = length(dir);
dir = len > 1e-5 ? dir / len : vec2(1.0, 0.0);
vec2 n = vec2(-dir.y, dir.x);
vec2 s = mix(sa, sb, a_corner.x) + n * a_corner.y * (u_width * 0.5 + 1.0) + dir * (a_corner.x * 2.0 - 1.0) * 0.5;
float hv = mix(a_h.x, a_h.y, a_corner.x);
v_vis = mix(pa.z, pb.z, a_corner.x) + (u_lift > 0.5 ? hv * 0.6 : 0.0);
v_across = a_corner.y * (u_width * 0.5 + 1.0);
v_s = mix(a_s.x, a_s.y, a_corner.x);
v_shade = mix(pa.w, pb.w, a_corner.x);
v_lat = mix(a_a.y, a_b.y, a_corner.x);
gl_Position = toClip(s);
}
`;
export const LINE_FS = /* glsl */ `#version 300 es
precision highp float;
in float v_vis;
in float v_across;
in float v_s;
in float v_shade;
in float v_lat;
uniform vec4 u_color;
uniform float u_width;
uniform float u_t;
uniform float u_progress; // draws the line up to this share (arcs drawing in)
uniform float u_glow;
out vec4 outColor;
${POLAR}
void main() {
if (v_vis < 0.0 || v_s > u_progress) discard;
float d = abs(v_across);
float core = 1.0 - smoothstep(u_width * 0.5 - 0.5, u_width * 0.5 + 0.5, d);
float a = core;
if (u_glow > 0.0) a = max(core, exp(-d * d / (u_width * u_width * 1.2)) * u_glow);
float limb = smoothstep(0.0, 0.03, v_vis);
outColor = vec4(u_color.rgb, u_color.a * a * limb * mix(0.55, 1.0, v_shade) * polarFade(v_lat));
}
`;
/** Full-screen quad for the backdrop: deep space, stars, atmosphere. */
export const SKY_VS = /* glsl */ `#version 300 es
precision highp float;
in vec2 a_pos;
out vec2 v_uv;
void main() {
v_uv = a_pos * 0.5 + 0.5;
gl_Position = vec4(a_pos, 0.0, 1.0);
}
`;
export const SKY_FS = /* glsl */ `#version 300 es
precision highp float;
in vec2 v_uv;
uniform vec2 u_viewport; // device px
uniform vec2 u_globe; // device px of the globe centre
uniform float u_radius; // device px
uniform float u_t;
uniform float u_time;
uniform vec3 u_space0;
uniform vec3 u_space1;
uniform vec3 u_glow;
uniform float u_dark;
out vec4 outColor;
float hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
// Three constellations from their stars' real places (a gnomonic view around
// each figure's middle, north up): the Big Dipper, Orion and Cassiopeia. Each
// star is x, y in units of the view's height and its magnitude.
const vec3 CST[20] = vec3[20](
vec3(0.1807, 0.0977, 1.8),
vec3(0.21, 0.0111, 2.4),
vec3(0.0945, -0.0566, 2.4),
vec3(0.0403, -0.0038, 3.3),
vec3(-0.0494, -0.0169, 1.8),
vec3(-0.1232, -0.0213, 2.2),
vec3(-0.21, -0.0977, 1.9),
vec3(-0.0874, 0.1263, 0.5),
vec3(0.0415, 0.1075, 1.6),
vec3(-0.0255, -0.0354, 1.8),
vec3(-0.0061, -0.0226, 1.7),
vec3(0.0121, -0.0072, 2.2),
vec3(-0.0557, -0.17, 2.1),
vec3(0.0874, -0.1445, 0.1),
vec3(-0.0015, 0.17, 3.4),
vec3(0.13, -0.0137, 2.3),
vec3(0.0514, -0.0792, 2.2),
vec3(0.0035, 0.0053, 2.2),
vec3(-0.0711, -0.0018, 2.7),
vec3(-0.13, 0.0792, 3.4)
);
// Their colour: warm for the cool giants (Betelgeuse, Dubhe, Schedar), blue white for the hot ones.
const vec3 CST_TINT[20] = vec3[20](
vec3(1.0, 0.9, 0.78),
vec3(0.94, 0.96, 1.0),
vec3(0.94, 0.96, 1.0),
vec3(0.95, 0.97, 1.0),
vec3(0.95, 0.97, 1.0),
vec3(0.95, 0.97, 1.0),
vec3(0.9, 0.94, 1.0),
vec3(1.0, 0.78, 0.6),
vec3(0.9, 0.94, 1.0),
vec3(0.9, 0.94, 1.0),
vec3(0.9, 0.94, 1.0),
vec3(0.9, 0.94, 1.0),
vec3(0.9, 0.94, 1.0),
vec3(0.86, 0.92, 1.0),
vec3(0.92, 0.95, 1.0),
vec3(1.0, 0.97, 0.9),
vec3(1.0, 0.88, 0.74),
vec3(0.9, 0.94, 1.0),
vec3(0.96, 0.97, 1.0),
vec3(0.9, 0.94, 1.0)
);
const ivec2 CSL[19] = ivec2[19](
ivec2(0, 1), ivec2(1, 2), ivec2(2, 3), ivec2(3, 0), ivec2(3, 4), ivec2(4, 5),
ivec2(5, 6), ivec2(7, 14), ivec2(14, 8), ivec2(7, 9), ivec2(8, 11), ivec2(9, 10),
ivec2(10, 11), ivec2(9, 12), ivec2(11, 13), ivec2(15, 16), ivec2(16, 17), ivec2(17, 18),
ivec2(18, 19)
);
/** Where a constellation's star stands on the screen, in device px. */
vec2 cstAt(int i) {
float h = u_viewport.y;
float w = u_viewport.x / h;
// px runs downwards from the top, the figures are drawn upwards.
vec2 at = i < 7 ? vec2(w - 0.36, 0.2) : i < 15 ? vec2(0.24, 0.74) : vec2(0.2, 0.2);
return (at + vec2(CST[i].x, -CST[i].y)) * h;
}
/** The share of a hairline between two stars at p, with a gap around each star. */
float cstLine(vec2 p, vec2 a, vec2 b, float gap, float width) {
vec2 ba = b - a;
float len = length(ba);
float h = dot(p - a, ba) / (len * len);
float g = gap / len;
if (h < g || h > 1.0 - g) return 0.0;
float d = length(p - a - ba * h);
// The line thins out towards its ends, so it reads as drawn, not as a wire.
float ends = smoothstep(g, g + 0.12, h) * smoothstep(1.0 - g, 1.0 - g - 0.12, h);
return (1.0 - smoothstep(width * 0.5, width, d)) * ends;
}
/** The figures: hairlines first, then their stars, sized and tinted by brightness, each with a soft halo. */
vec3 constellations(vec2 px) {
float unit = max(1.0, u_viewport.y / 1000.0);
float line = 0.0;
for (int i = 0; i < 19; i++) {
line = max(line, cstLine(px, cstAt(CSL[i].x), cstAt(CSL[i].y), 6.0 * unit, 1.1 * unit));
}
vec3 col = vec3(0.86, 0.88, 0.92) * line * 0.11;
for (int i = 0; i < 20; i++) {
float d = length(px - cstAt(i));
// Magnitude 0 is the brightest here, 3.5 the faintest that still shows.
float bright = clamp(1.0 - CST[i].z / 4.2, 0.18, 1.0);
float r = mix(0.7, 2.1, bright) * unit;
float tw = 0.86 + 0.14 * sin(u_time * (0.7 + float(i) * 0.13) + float(i) * 1.7);
float core = 1.0 - smoothstep(r * 0.4, r, d);
float halo = exp(-d / (r * 2.2)) * 0.35 * bright;
col += CST_TINT[i] * (core * bright + halo) * tw;
}
return col;
}
float stars(vec2 px, float cell, float density, float size) {
vec2 g = floor(px / cell);
vec2 f = fract(px / cell);
float h = hash(g);
if (h > density) return 0.0;
vec2 c = vec2(hash(g + 3.1), hash(g + 7.7)) * 0.8 + 0.1;
float d = length(f - c) * cell;
float tw = 0.65 + 0.35 * sin(u_time * (0.6 + h * 2.0) + h * 40.0);
return smoothstep(size, 0.0, d) * tw * (0.4 + 0.6 * hash(g + 1.3));
}
void main() {
vec2 px = v_uv * u_viewport;
px.y = u_viewport.y - px.y;
float r = length(px - u_globe);
vec3 col = mix(u_space1, u_space0, smoothstep(0.0, max(u_viewport.x, u_viewport.y) * 0.8, r));
float sky = (1.0 - u_t * 0.9) * u_dark;
// Milky way: a soft band across the sky. The stars are endlessly far away, so
// they stand still while the Earth turns in front of them.
vec2 q = px / u_viewport.y;
float band = exp(-pow((q.y - 0.35 - 0.45 * q.x + 0.25) * 3.2, 2.0));
float dust = hash(floor(px * 0.5)) * 0.5 + 0.5;
col += vec3(0.27, 0.27, 0.28) * band * 0.10 * sky * dust;
vec2 sp = px;
float s = stars(sp, 38.0, 0.20, 1.6) + stars(sp * 1.7 + 13.0, 31.0, 0.12, 1.1) * 0.7 + band * stars(sp * 2.3 + 5.0, 17.0, 0.35, 0.9) * 0.8;
col += vec3(0.93, 0.93, 0.94) * s * sky;
col += constellations(px) * sky;
// Atmosphere: a glow hugging the globe, gone once the map lies flat.
float atm = (1.0 - smoothstep(0.0, 0.7, u_t));
float outside = smoothstep(u_radius * 0.985, u_radius * 1.0, r);
float glow = exp(-max(0.0, r - u_radius) / (u_radius * 0.075)) * outside;
col += u_glow * glow * 0.55 * atm;
outColor = vec4(col, 1.0);
}
`;
/** A thin bright rim on the limb, drawn over the globe. */
export const RIM_FS = /* glsl */ `#version 300 es
precision highp float;
in vec2 v_uv;
uniform vec2 u_viewport;
uniform vec2 u_globe;
uniform float u_radius;
uniform float u_t;
uniform vec3 u_glow;
out vec4 outColor;
void main() {
vec2 px = v_uv * u_viewport;
px.y = u_viewport.y - px.y;
float r = length(px - u_globe);
float inner = smoothstep(u_radius * 0.82, u_radius, r) * (1.0 - smoothstep(u_radius, u_radius * 1.004, r));
float a = pow(inner, 3.0) * 0.55 * (1.0 - smoothstep(0.0, 0.5, u_t));
outColor = vec4(u_glow, a);
}
`;
@@ -0,0 +1,75 @@
// FE-ATLAS2-RENDER-100 to FE-ATLAS2-RENDER-109: the globe's paint, light and dark, and the accent it reads.
import { afterEach, describe, expect, it, vi } from 'vitest';
import { globeTheme, hexToRgb, rgbToBytes } from './globeTheme';
/** What the live stylesheet answers for --accent. */
function accentToken(value: string): void {
const read = vi.fn((name: string) => (name === '--accent' ? value : ''));
vi.stubGlobal('getComputedStyle', () => ({ getPropertyValue: read }) as unknown as CSSStyleDeclaration);
}
afterEach(() => {
vi.unstubAllGlobals();
});
describe('hexToRgb', () => {
it('FE-ATLAS2-RENDER-100: reads a six-digit hex colour into 0..1 channels', () => {
expect(hexToRgb('#ff8000')).toEqual([1, 128 / 255, 0]);
});
it('FE-ATLAS2-RENDER-101: expands the three-digit short form', () => {
expect(hexToRgb('#0f8')).toEqual([0, 1, 136 / 255]);
});
it('FE-ATLAS2-RENDER-102: ignores an alpha channel and surrounding space', () => {
expect(hexToRgb(' #11223380 ')).toEqual([0x11 / 255, 0x22 / 255, 0x33 / 255]);
});
it('FE-ATLAS2-RENDER-103: falls back to mid grey for something that is no hex colour', () => {
expect(hexToRgb('#zzzzzz')).toEqual([0.5, 0.5, 0.5]);
});
});
describe('rgbToBytes', () => {
it('FE-ATLAS2-RENDER-104: rounds channels to bytes', () => {
expect(rgbToBytes([1, 0.5, 0])).toEqual([255, 128, 0]);
expect(rgbToBytes(hexToRgb('#123456'))).toEqual([0x12, 0x34, 0x56]);
});
});
describe('globeTheme', () => {
it('FE-ATLAS2-RENDER-105: dark mode is a dark globe with white selection and arcs', () => {
const th = globeTheme(true);
expect(th.dark).toBe(true);
expect(th.selection).toEqual([1, 1, 1, 0.95]);
expect(th.arc).toEqual([0.95, 0.95, 0.95, 0.95]);
expect(Math.max(...th.land)).toBeLessThan(0.3);
expect(Math.max(...th.space0)).toBeLessThan(0.05);
});
it('FE-ATLAS2-RENDER-106: dark mode does not take the accent for the selection', () => {
accentToken('#ff0000');
expect(globeTheme(true).selection).toEqual([1, 1, 1, 0.95]);
});
it('FE-ATLAS2-RENDER-107: light mode is a bright globe whose selection is the default accent', () => {
const th = globeTheme(false);
expect(th.dark).toBe(false);
expect(Math.min(...th.land)).toBeGreaterThan(0.9);
const [r, g, b] = hexToRgb('#111827');
expect(th.selection).toEqual([r, g, b, 0.95]);
});
it('FE-ATLAS2-RENDER-108: light mode follows the live --accent token', () => {
accentToken('#4f46e5');
const [r, g, b] = hexToRgb('#4f46e5');
expect(globeTheme(false).selection).toEqual([r, g, b, 0.95]);
});
it('FE-ATLAS2-RENDER-109: an accent token that is no hex colour keeps the default', () => {
accentToken('rgb(1 2 3)');
const [r, g, b] = hexToRgb('#111827');
expect(globeTheme(false).selection).toEqual([r, g, b, 0.95]);
});
});
@@ -0,0 +1,65 @@
/**
* Map paint for the Atlas globe. These are rendering colours for WebGL, not UI
* surfaces, so they are numbers here rather than appearance tokens; the accent
* is read from the live --accent token so the globe follows the user's scheme.
*/
import type { GlobeTheme, Rgb } from './GlobeRenderer';
export function hexToRgb(hex: string): Rgb {
const h = hex.replace('#', '').trim();
const full =
h.length === 3
? h
.split('')
.map((c) => c + c)
.join('')
: h.slice(0, 6);
const n = parseInt(full, 16);
if (Number.isNaN(n)) return [0.5, 0.5, 0.5];
return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
}
export function rgbToBytes(c: Rgb): [number, number, number] {
return [Math.round(c[0] * 255), Math.round(c[1] * 255), Math.round(c[2] * 255)];
}
function readCssColor(name: string, fallback: string): string {
if (typeof document === 'undefined') return fallback;
const v = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
return /^#[0-9a-f]{3,8}$/i.test(v) ? v : fallback;
}
export function globeTheme(dark: boolean): GlobeTheme {
const accent = hexToRgb(readCssColor('--accent', dark ? '#e4e4e7' : '#111827'));
if (dark) {
return {
land: [0.19, 0.19, 0.2],
ocean: [0.085, 0.085, 0.09],
oceanDeep: [0.03, 0.03, 0.032],
space0: [0.006, 0.006, 0.007],
space1: [0.035, 0.035, 0.038],
glow: [0.18, 0.18, 0.185],
border: [0.05, 0.05, 0.055, 0.9],
coast: [0.85, 0.85, 0.87, 0.14],
regionBorder: [0.95, 0.95, 0.95, 0.3],
selection: [1, 1, 1, 0.95],
arc: [0.95, 0.95, 0.95, 0.95],
dark: true,
};
}
// Daylight: a clear sky, a bright sea, warm grey land and white borders.
return {
land: [0.985, 0.985, 0.98],
ocean: [0.72, 0.84, 0.96],
oceanDeep: [0.55, 0.7, 0.88],
space0: [0.88, 0.93, 0.98],
space1: [0.75, 0.85, 0.96],
glow: [0.62, 0.8, 1.0],
border: [0.72, 0.78, 0.86, 0.9],
coast: [0.3, 0.45, 0.65, 0.3],
regionBorder: [0.75, 0.8, 0.88, 0.75],
selection: [accent[0], accent[1], accent[2], 0.95],
arc: [0.16, 0.32, 0.72, 0.9],
dark: false,
};
}
@@ -16,7 +16,7 @@ import type { CostsSettlementResponse } from './costsModel';
import { useCostsLedger } from './useCostsLedger'; import { useCostsLedger } from './useCostsLedger';
import { useFreezeMissingRates } from './useFreezeMissingRates'; import { useFreezeMissingRates } from './useFreezeMissingRates';
// FE-BUDGET-LEDGER-001 to FE-BUDGET-LEDGER-023 // FE-BUDGET-LEDGER-001 to FE-BUDGET-LEDGER-024
const fx = vi.hoisted(() => ({ const fx = vi.hoisted(() => ({
// One stable converter, the way useExchangeRates hands out a memoised one: USD is half a euro. // One stable converter, the way useExchangeRates hands out a memoised one: USD is half a euro.
@@ -183,6 +183,28 @@ describe('useCostsLedger: loading', () => {
expect(result.current.settlement).toEqual(SETTLEMENT); expect(result.current.settlement).toEqual(SETTLEMENT);
}); });
it('FE-BUDGET-LEDGER-024: a settlement answer that lands after the ledger is gone changes no state', async () => {
let fail: (reason: Error) => void = () => undefined;
settlementMock().mockImplementation(
() =>
new Promise<CostsSettlementResponse>((_resolve, reject) => {
fail = reject;
})
);
const { unmount } = setup();
await waitFor(() => expect(settlementMock()).toHaveBeenCalled());
unmount();
// React reads window.event when a state update is scheduled, and a test
// environment that is already torn down has no window.
vi.stubGlobal('window', undefined);
try {
fail(new Error('gone'));
await new Promise((resolve) => setTimeout(resolve, 20));
} finally {
vi.unstubAllGlobals();
}
});
it('FE-BUDGET-LEDGER-006: hands the unconverted rows to the rate freeze, which reads the settlement again once healed', async () => { it('FE-BUDGET-LEDGER-006: hands the unconverted rows to the rate freeze, which reads the settlement again once healed', async () => {
const { result } = setup(); const { result } = setup();
await waitFor(() => expect(result.current.settlement).not.toBeNull()); await waitFor(() => expect(result.current.settlement).not.toBeNull());
@@ -120,6 +120,13 @@ export function useCostsLedger({
// Only the latest read may land: an answer for the currency picked before would // Only the latest read may land: an answer for the currency picked before would
// otherwise overwrite the one for the currency shown now. // otherwise overwrite the one for the currency shown now.
const latestRead = useRef(0); const latestRead = useRef(0);
// An answer that lands after the ledger is gone has nobody to show it to.
useEffect(() => {
const reads = latestRead;
return () => {
reads.current += 1;
};
}, []);
// The browser's own figure for the display currency goes along, for the server to // The browser's own figure for the display currency goes along, for the server to
// answer in it when it cannot fetch a quote itself. // answer in it when it cannot fetch a quote itself.
@@ -346,7 +346,8 @@ describe('useCollabChatData on a box that changes size', () => {
it('FE-COLLAB-CHATDATA-017: a list at its newest message stays there when a rotation or a fold resizes it', async () => { it('FE-COLLAB-CHATDATA-017: a list at its newest message stays there when a rotation or a fold resizes it', async () => {
vi.stubGlobal('ResizeObserver', Observer); vi.stubGlobal('ResizeObserver', Observer);
const { list, grow } = await mountList(400); const { list, grow } = await mountList(400);
expect(observed).toContain(list); // The observer starts in an effect after the list is drawn; under load that comes a tick later.
await waitFor(() => expect(observed).toContain(list));
grow(900); grow(900);
report(); report();
expect(list.scrollTop).toBe(900); expect(list.scrollTop).toBe(900);

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