Compare commits

..

210 Commits

Author SHA1 Message Date
Maurice 61378559ca chore(deps): runtime security floors and the CI action updates
- sharp 0.35.5 (librsvg CVE), with the musl pins that ship in the image.
- follow-redirects 1.16.2, postcss-selector-parser 6.1.5 and
  serialize-javascript 7.1.3, from the open advisories.
- GitHub Actions: github-script 9 and the minor-and-patch group.
- plugin-sdk: @types/update-notifier 6.0.9.

The grouped npm update is left out: with it the server build runs out of
memory in tsc, and the culprit is not found yet.
2026-11-02 21:58:16 +01:00
Maurice 84df69c18a Revert "chore(deps): take the safe updates from the open Dependabot PRs"
The server build runs out of memory in tsc with the grouped updates. Back to
the previous dependencies until the update that causes it is found.
2026-11-02 21:56:33 +01:00
Maurice 6194a658d9 chore(deps): take the safe updates from the open Dependabot PRs
- The npm minor-and-patch group (#2952) without mapbox-gl: 3.34 drops
  setRTLTextPlugin from its typings, and the RTL plugin is what joins Arabic,
  Hebrew and Persian labels. react and react-dom move to 19.3.1 together,
  overrides included, so the workspace keeps one React.
- Security floors from the open alerts: sharp 0.35.5, vite 8.3.5,
  follow-redirects 1.16.2 (#2927), postcss-selector-parser 6.1.5 (#2865) and
  serialize-javascript 7.1.3.
- GitHub Actions: github-script 9 (#2951) and the minor-and-patch group (#2950).
- plugin-sdk: @types/update-notifier 6.0.9 (#2948).
2026-11-02 21:30:17 +01:00
Maurice 97188c16d1 fix(place-contrib): mark the independent writes and use TREK's OSM id form in the catch-up test 2026-11-02 14:11:27 +01:00
Maurice 247d5fc519 feat(services): get the key at startup and share earlier place details
An installation now asks for its TREK services key a few minutes after
it starts, and the daily check registers a missing key as well as
renewing a due one. Until now nothing happened before someone searched
for a place or opened the admin settings, so "Share place details"
stayed unavailable on a fresh or updated instance.

When an admin agrees to share place details, what users typed into
places since TREK 5.1.0 goes out too, not only what they type from then
on. The origin of every field is recorded since 5.1.0 whatever the
decision, so a catch-up walks those places page by page before each
send run: only values that are still the ones a user typed, only for
fields switched on, only for places the service can key, and only
while the queue holds fewer than 200 values. It goes on where it
stopped after a restart, never replaces a newer value a save queued,
and ends on switching off, declining or withdrawing everything. A field
switched on later catches up as well, under an agreement given with the
new prompt sentence that says so; an agreement from 5.1.0 does not.

Queuing moves into PlaceContribQueue so a save and the catch-up take
the same path.
2026-11-02 13:56:32 +01:00
Maurice 8659262e59 fix(services): let slow handshakes reach the TREK services
Node gives each address of a dual-stack name 250 ms before it moves on.
From Australia that is shorter than one round trip to Europe, so on a
network without IPv6 the IPv4 handshake to places.liketrek.com was cut
off, the IPv6 attempt failed at once and every request ended in
ETIMEDOUT. The installation never got its services key, sharing place
details stayed unavailable and searches fell back to OpenStreetMap.

Raise the per-address attempt timeout to 2 s at startup, keeping a
larger value an operator already set, and log the reason behind
undici's bare "fetch failed" for each address tried.
2026-11-02 12:12:48 +01:00
Maurice 327ebc354f fix(push): accept Google's jmt17.google.com push endpoints
Chrome on Android increasingly hands out push subscriptions on
jmt17.google.com, which the push service allowlist did not know, so
turning push on failed with a 400. The host is added as an exact entry,
next to the two FCM hosts.

Closes #2939
2026-11-01 22:51:27 +01:00
roopesh 1625a10424 fix(server): refuse unwritable database in maintenance scripts (#2933) 2026-11-01 22:26:40 +01:00
Raz Erlich 94c2ef35b5 fix(planner): keep places selection bar visible with long lists 2026-11-01 22:08:45 +01:00
Maurice bf8e04741d test(storage): follow the release queue in the tests that pinned an immediate delete
Replacing a cover or an avatar and deleting a note file now hand the old
bytes to the release queue instead of deleting them in the request; the
integration tests check the queue row and that the bytes are still
there. Release mocks answer with a count, the reclaim e2e sends its
refused bodies one after another, and a stale-count reload that fails is
told to the admin instead of swallowed.
2026-11-01 18:46:58 +01:00
Maurice 0b598680ec test(storage): spell the pending-reset case title without a stray quote 2026-11-01 18:32:43 +01:00
Maurice 13332cf06b fix(storage): a pass on a database this installation does not recognise only reports
While a restore's reset is still pending, or the database names another
installation, the nightly pass judges and reports but deletes nothing,
whatever the restored switch says.
2026-11-01 18:32:33 +01:00
Maurice e6d52cb061 docs(wiki): say every restore resets the cleanup state and what the release queue gives up
A restore of this installation's own backup now resets it too, through the .trek-reclaim-reset file. Files dropped from the release queue after 30 days, or refused by a full queue, are only removed by the nightly cleanup once deletion is on.
2026-11-01 18:31:45 +01:00
Maurice bef8fc20f1 fix(storage): reset reclaim state after any restore, re-check owners often, share release ticks
- A restore (admin panel or RESTORE_FROM_BACKUP) now leaves
  data/.trek-reclaim-reset before it swaps the database in. Boot reconcile
  resets the reclaim state when it finds the file, whatever install id the
  database names, and removes it afterwards; a successful reopen removes it
  too. A restart after a failed reopen, or a boot restore of this
  installation's own backup, no longer keeps the old switch, marks and
  confirmations. The id mismatch reset stays.
- The release job skips a tick (install_mismatch) while the database names
  another installation or a reset is still pending.
- An allowed owner verdict is cached for 15 minutes, a refusal for 26 hours.
  The local driver reads a list prefix as a folder, so the category root is
  still listed whole, at most once per category per window.
- Each tick reads every allowed category's due rows separately, an equal
  share of the 200 each, so a category whose deletes keep failing cannot
  starve the others.
- Rows dropped after 30 days overdue and releases refused by a full queue
  are logged at warn with their counts.
2026-11-01 18:31:41 +01:00
Maurice 9d2ffc91af feat(storage): confirm the count shown, and say a backup or a missing install id held the cleanup
Confirm sends the count the admin saw and waits for its answer; a stale
count reloads the state. A running backup is named as a skip reason, a
missing installation id and a stale count as errors, and the switch's
hint no longer promises removal right away: deleted files go a day
later, once no undo can bring them back. Strings in all 28 languages.
2026-11-01 18:14:49 +01:00
Maurice 10ad64d170 docs(wiki): describe the day-later release, the install id file and the confirmation margin
Covers what a clone must do (its own data dir, or delete .trek-install-id),
that an older TREK writes no owner marker and cannot be detected, and the
new backup_running reason.
2026-11-01 18:11:47 +01:00
Maurice 1c6a175ebc fix(storage): queue what a delete left unnamed past every undo, and tell a copied database apart
A delete or a replace no longer deletes inside the request. The owner's call
queues the keys in storage_release_queue, due after RELEASE_DELAY_MS (26 h:
the assistant's 24 h approval window plus a margin), and StorageReleaseJob
takes the due rows every ten minutes, at most 200 a tick and 50 keys a
question, asks every reference source again and deletes what none names.
It refuses what the nightly pass refuses (StorageReclaimGuardService: the
ledger, the required sources, a shared location, another installation's
owner marker, cached per category), and waits while a restore or a backup
runs or another storage job holds the slot. An assistant undo or a late
write that names the old value again keeps its object.

The install id lives in data/.trek-install-id, outside any backup and never
written by a restore. At boot and after every reopen the database is
reconciled with it: a database naming another installation (a boot restore,
a restart after a failed restore, a copied travel.db) loses its switch,
confirmations, reports, marks and queue before anything reads them.

A confirmation now stores the count the admin was shown and when; it covers
up to one and a half times that count (at least 100 more) for 14 days, is
used up once the share is back under a fifth, and a count the last report
no longer holds is refused as reclaim_confirm_stale. The admin state folds
a live confirmation in, so the prompt goes at once.

A pass reads each source once for every category and drops each category's
keys once judged; right before a batch it reads the category's sources
again, whole and in memory, instead of a LIKE per key. A narrowed read holds
at most 50 LIKE terms. A pass held off by a backup reports backup_running,
and a category the ledger never reclaims reports not_reclaimed even after a
stop.
2026-11-01 18:11:43 +01:00
Maurice 0a25de2c6d feat(storage): confirm the reclaim count the admin was shown, name a running backup as a skip, bound a trip cover
The confirm request now carries the unreferenced count the admin saw, so the
server can refuse a count its last report no longer holds. A pass that found
objects due while a backup read the uploads reports backup_running for them.
A trip cover is bounded to 2048 characters on REST, RPC and the MCP tool, as a
place image already is, since a replaced cover is queued for release by every
upload path it spells out.
2026-11-01 18:11:25 +01:00
Maurice 59a6d92cea fix(storage): type the key search run, split the reclaim view per category
The longest-run helper typed its reduce as never, reclaimView grew past
the complexity limit (one function per category line now), and a test
read a promise as a boolean.
2026-11-01 16:37:00 +01:00
Maurice e0982e708f feat(storage): show running checks, confirmations and the nightly result in Admin > Storage
The panels follow the reworked reclaim state: Check now starts a check
in the background and the panel polls until it is done, a category with
an unusually large share of unused files offers Confirm, Freed comes
from the last run that deleted, a stopped check says why and no longer
reads as nothing found, the switch waits for its answer and a poll that
was in flight cannot flip it back, and refusals name their reason in
the operator's language. Strings updated in all 28 languages.
2026-11-01 16:25:38 +01:00
Maurice d17457de56 fix(storage): delete what a delete or a replace left unnamed right away again
Leaving every replaced cover, place image and deleted journey photo to the
nightly pass kept them publicly fetchable by URL for a week at least, and
for good while deletion was off. Owners now hand the values a delete or a
replace left behind to StorageReleaseService once their write committed.
It asks every registered reference source, with the same parser as the
nightly pass, and deletes at once what no row names any more: an object a
trip copy, a journey or a saved place still shows stays, which the old
inline deletes got wrong.

The release holds the pass's guards (reclaimable categories at their root
only, never an owner marker, never while a restore runs, never with a
required source missing or an overlapping location), never fails the
request and logs at debug. It runs for trip covers (update, upload, trip
delete), collection covers and saved-place images, place images (update,
bulk update, delete), journey covers and journey or gallery photos
(their thumbnail goes with a file that went), avatars (change, delete,
account deletion), trip files (permanent delete, empty trash) and collab
note and chat attachments. A trip file row now goes before its bytes, so a
failing backend no longer fails the delete. The objects of a deleted trip's
places and files are left to the nightly pass: their rows are other
domains'.

PlacesService drops the collection places repository nothing read any
more. Size, warning and boundary baselines follow the shrunk files.
2026-11-01 16:18:21 +01:00
Maurice 790fccb92c fix(storage): judge unreferenced files without a brake anyone can trip
The 20 % brake skipped a category and wiped its marks every night once a
fifth of it looked unreferenced. Any user could push a small install over
that line, a backlog from #2924 started braked, and a second install on the
same bucket below the line was not caught at all. It is gone:

- Each pass leaves a trek-owner-<install id> marker at the root of every
  category it judges. A category holding another install's marker is
  skipped as foreign_install, one where the marker cannot be written as
  owner_unknown. Backups leave the markers out.
- The install id lives in app_settings outside the storage.* prefix. The
  switch is stored as that id, so a database from another install reads as
  off, and every reopen (a restore) writes this install's id back, turns
  deletion off and drops the marks, confirmations and reports.
- More than a fifth unreferenced still marks and reports, but deletes only
  after an admin confirmed the count shown (POST .../reclaim/confirm). A
  larger count later waits again.

A skip no longer touches the marks, so a failed listing or lookup does not
restart the week. Check now runs in the background and answers 202; the
admin state says running and keeps the last deleting report apart, so a
report-only check never resets what was freed. A pass that deletes writes a
system audit entry, a pass that stops or fails keeps its partial counts and
marks the rest interrupted, a backend error stops deleting in its category,
and deleting stops for the rest of the pass once the switch is off or a
backup is reading the uploads. The usage scan waits for a pass still
running.

Sources read each category once per pass and answer the pre-delete
re-check with a query narrowed to the keys' plain runs. Bare names keep
their raw spelling (a '#', '?' or trailing blank is part of an upload's
name), and local roots are resolved through their symlinks before the
overlap check. A pass lists only a category's root.
2026-11-01 16:18:08 +01:00
Maurice e59992d56d chore(ci): lower the knip baseline the reclaim branch shrank
storage-registry.service.ts no longer exports a type nothing uses.
2026-11-01 14:55:54 +01:00
Maurice 382797febc fix(storage): let the app boot with the reclaim routes and keep the ratchets where they were
The two admin routes go on the managed allow list, without which buildApp
refused to start. The reclaim calls move to their own api module so
client.ts stays at its size, the phone card sizes its text through the
type tiers, and the tests drop a hand-built service, a non-null assertion
and a promise read as a boolean.
2026-11-01 14:44:53 +01:00
Maurice a1d9cdc8f2 feat(storage): show unreferenced files in Admin > Storage, with the switch and a check
Desktop and phone show what the last check found (can be freed, unused for
less than a week, freed), why a category was skipped, the switch that lets
the nightly run delete and a report-only check on demand, through the
shared storage panel hook. All 28 languages, and the Admin-Storage wiki
page explains the check, the week's wait and when to leave it off.
2026-11-01 14:30:01 +01:00
Maurice b31666d1c9 fix(storage): re-check a batch right before its delete, and drop reads nothing calls
The last question to the sources now comes after the object's own check,
so nothing slower than the delete sits between the answer and the delete,
and it is asked once per batch instead of once per object: a pass read
every source's columns for each object it was about to remove. The
collection reads the removed inline reclaims used are gone with them.
2026-11-01 14:23:04 +01:00
Maurice 19e4f0dadf fix(storage): keep the reclaim pass and a backup restore apart
A restore wipes and rehydrates the uploads under a swapped database, but it
never took the storage job slot, so a reclaim pass could start or carry on
beside it, and a delete already past the generation check could land on an
object the restore had just put back. BackupService now marks a restore as
running on StorageJobsService and waits for a pass in flight to let go; a
pass refuses to start while a restore runs and stops at its next check when
one begins. Backfills and migrations are not affected. The service test also
reads its fake source sets through a helper instead of non-null assertions.
2026-11-01 14:20:11 +01:00
Maurice 8fde643347 fix(storage): make the reclaim state on the admin storage state nullable
The shared contract made reclaim a required field, so every client fixture
typed StorageAdminState stopped compiling. It is nullable now, as planned,
and the five base fixtures carry reclaim: null.
2026-11-01 14:20:11 +01:00
Maurice f44dd92ee0 test(storage): run the reclaim e2e and source check on the whole app
The reclaim e2e and the source-registration check mocked src/db/database,
which lint:test-mocks holds at zero for new files; both now boot buildApp
against the worker's snapshot db. The key parser drops its non-null
assertions (the indexed reads are typed string already), and the e2e sends
its refused bodies at once instead of awaiting inside a loop, so the eslint
ratchet stays where it was.
2026-11-01 14:20:10 +01:00
Maurice db0fbc1ccd fix(storage): stop deleting covers, place images and journey photos another row may still show
Replacing a trip or list cover, changing or deleting a place or saved-place
image and deleting a journey photo removed the bytes at once, without asking
whether a trip copy, a journey, a saved place or another photo row still
named them (#2924). Those paths now leave the object in place and the reclaim
job removes it once no row names it. A journey photo the user deletes takes
its local photo row with it when nothing else links it, so its bytes become
reclaimable instead of being kept by a row nobody sees.

A place image copied from a trip file is still dropped at once when the
update that would name it fails: that copy was never anyone else's.

Size and warning baselines follow the shrunk files.
2026-11-01 13:59:28 +01:00
Maurice 095bed2db8 feat(storage): let every owner of an upload column tell the reclaim pass what it still names
Trips, collections, places, the contribution queue, journeys, photos, trip
files and users each register a reference source from their own domain. A
source reads its own columns and parses every spelling they hold through the
storage helpers, and the free-form columns claim every reclaimable category,
since a cover or an image can point into any of them. The contribution queue
joins the ledger as its own source, because place-contrib owns that table.
2026-11-01 13:59:19 +01:00
Maurice fb2429ebb2 feat(storage): find and reclaim upload objects no row names any more
Domains whose rows name stored objects register a reference source with
StorageReclaimRegistryService; storage never imports them. A ledger in
storage decides per category whether it is reclaimed at all and which
sources must have answered first, and a category whose resolved location
overlaps another one is left alone.

A nightly pass at 04:05 lists the root level of files, journey, covers,
avatars and places, skips objects younger than a day or without a
modification time, asks every source in pages of 500 and marks the rest.
Only with deletion switched on, and only for marks a week old, it asks every
source about the single key again and deletes through StorageService. A
category is skipped and its marks start over when a source is missing or
fails, the listing fails, or more than a fifth of its objects look
unreferenced. A pass shares the one-job slot with backfills and migrations,
never runs on a demo instance and stops when the database is reopened.

Admins switch deletion and run a pass on demand under
/api/admin/storage/reclaim; both are audited, and GET /api/admin/storage
carries the switch and the last report. Deletion is off after install and
upgrade.
2026-11-01 13:37:53 +01:00
Maurice 29298dcfe5 feat(storage): keep a mark per stored object no row names
storage_reclaim_marks records since when the reclaim pass has seen an object
unreferenced, keyed by category and key. A mark is never moved forward, so
its age is how long the object has been unreferenced without a break; it goes
once the object is named again or gone. Owned by the storage domain.
2026-11-01 13:37:44 +01:00
Maurice 630f15b5ea feat(storage): describe the reclaim report, its switch and the run request in the shared contract
The admin state now carries the reclaim switch and the last pass's report.
A report covers every served category, the legacy photos folder included,
with the objects a pass looked at, the unreferenced, eligible and deleted
counts and bytes, and the reason a category was skipped.
2026-11-01 13:37:37 +01:00
Maurice 04debce79e fix(planner): keep the lint and size ratchets where they were
The zone helpers of the day order take the merged row's own type instead
of an explicit any, and the day list's size baseline follows it down.
2026-11-01 11:41:56 +01:00
Maurice 4003769a5c fix(planner): keep the date whole and rename the title where it stands with the date first
With "date first in day headings" a long day title squeezed the date in
the day list to "Th…" (#2920); the name now gives way and the date stays
whole. The day panel and the mobile day sheet kept the rename pencil on
the heading, which then is the date, and the input replaced it (#2921);
pencil and input now go with the title line under the date.
2026-11-01 11:41:56 +01:00
Maurice 7faf771f9c fix(docker): look at the volume roots only, and say when chown is refused
The ownership check still read every inode of the volumes on each start.
It now looks at the dirs and what sits directly in them, hands a volume
over once when it is not node's, and logs a warning instead of walking a
volume that refuses chown (NFS with root_squash).
2026-11-01 11:41:56 +01:00
Maurice 51b991f851 fix(docker): the container starts on large volumes and under runAsUser 1000
The entrypoint no longer runs chown -R over data and uploads on every start;
it only hands over files that are not node's yet, and logs when it does.
Started as a non-root user, it skips chown and gosu and runs Node directly.
The chart exposes podSecurityContext and securityContext for that setup.
2026-11-01 11:41:56 +01:00
Maurice 8692b8790c fix(planner): judge a move by the order a day is drawn in across time zones
The checks behind a drag and the up/down buttons read each booking's raw
clock, so on a day whose flights were put in the order they happen every
move of a timed stop asked to change its time (desktop) or was refused
(mobile). They now read the same key the day is ordered by.
2026-11-01 11:41:56 +01:00
Maurice 1b6a156969 fix(planner): order flights across time zones by when they actually leave
A booking's time is local to its own airport, so a flight leaving
Auckland at 20:20 and landing in Los Angeles at 12:25 the same date
was drawn below the 17:00 flight on from Los Angeles. Bookings whose
dated time has a known zone now take their clock slots in real order.
2026-11-01 11:41:55 +01:00
Maurice f076cb82da docs(readme): link dataforest cloud wherever the sponsor section names it 2026-11-01 10:20:21 +01:00
Maurice 073db83421 fix(assistant): answer the calls of a stopped step and ask for the words behind wordless follow-ups
A step stopped while its calls ran (the user left the page) kept the
provider's whole record of it but answers only for the calls that ran, so
Anthropic and the Responses API refused that thread with HTTP 400 from then
on. Replaying the thread now answers every recorded call that never ran,
which also mends threads already stuck that way.

Claude Sonnet 5.5 at times ends a turn on suggest_follow_ups alone, without
writing its answer, and the turn failed as empty_answer. That step now goes
back to the model whole, its follow-ups answered that the user saw nothing
yet, and their chips come under the answer it then writes. The prompts no
longer say the call goes alone in its step.
2026-11-01 10:18:27 +01:00
Maurice cafc8dd46e fix: link dataforest cloud with /en again
The 5.1.0 popup, the sponsor panel in Settings > About and the README had
switched to https://cloud.dataforest.net/?mtm_campaign=trek. The link stays
https://cloud.dataforest.net/en?mtm_campaign=trek everywhere.
2026-10-31 12:26:36 +01:00
github-actions[bot] dc36c21c08 chore: bump version to 5.1.0 [skip ci] 2026-10-31 11:12:52 +00:00
Maurice 175413b3c1 ci(release): take ci-ok from an earlier commit when main only changed workflows [skip ci]
A fix to a release workflow changes nothing that the tests cover, yet the
gate wanted a full new test run on it. With ci_from the release takes ci-ok
from the commit main's code comes from, provided that commit is an ancestor
of main, everything outside .github/ is identical, and one of its ci-ok runs
is green.
2026-10-31 12:10:35 +01:00
Maurice 030918cfa9 ci(release): check the dialect with node's types
TypeScript 6 includes no @types unless a file imports from them, and the
issued dialect imports nothing from node. Type-checked on its own it did
not know Buffer, so the 5.1.0 release threw away a valid dialect as one
that does not type-check. The check config names node now.
2026-10-31 12:09:32 +01:00
Maurice 75d65ccb1b test(release-notes): build the new cases without non-null assertions
The four cases added with the 5.1.0 popup patched the fixture through
n.release! and read the support card through card!, six warnings over the
tests baseline of the eslint ratchet. They go through a withRelease()
helper and optional chaining instead.
2026-10-31 11:31:13 +01:00
Maurice def8b8a24d release notes: the 5.1.0 popup, and dataforest cloud in Settings > About
The release popup now shows 5.1.0: place search, shared place details
and faster routing as three cards side by side, each with its own
drawing. The support band is set as a card like the promise above it
(optional supportLabelKey; a release without it keeps the plain line),
and the two support buttons get the same glass look in their colours.

Settings > About gets a full-width panel for dataforest cloud, who
sponsor the servers behind place search, address search and routing.
Both logos ship in client/public/brands, so opening Settings reaches no
third party. Wherever a line names dataforest cloud it links to
https://cloud.dataforest.net/?mtm_campaign=trek, the link dataforest
gave us; the README moves to it too.

All 28 locales carry the new copy, and the old 5.0 card keys are gone.
2026-10-31 11:04:19 +01:00
Maurice f4e524f3c3 place-enrichment: the details lookup is a standalone cache fill
The service reads a community place's details before the result cache and
every other place's after it, so the lookup has two call sites of which one
runs. It only fills the details row cache and turns a failure into no
details, so it is tagged @txStandalone and the enrich baseline drops to the
four writes it holds without it.
2026-10-31 06:45:13 +00:00
Maurice 682ae19143 test(place-enrichment): a cached OSM place still reads its details for the community version
An OSM element can hold community values, so the service reads its details
before the cache to learn the version it is served under. The second request
reads them once and then answers from the row cache without another lookup.
2026-10-31 06:27:31 +00:00
Maurice 255607b750 place-contrib: format the settle filters of the outbox repository
The id and cid lists the settle writes match on come from two small helpers,
which keeps each filter on one line in Prettier's layout.
2026-10-31 06:27:31 +00:00
Maurice ce7437a46f i18n: translate the place sharing, services card and refresh pill strings into Hebrew
The Hebrew locale arrived on dev while this branch was open, so its 80 new
admin.contribute, admin.servicesCard and places.refresh keys were missing
there.
2026-10-31 03:25:56 +00:00
Maurice 36d8cc2e7b wiki: the New place details pill offers the description too 2026-10-31 03:25:56 +00:00
Maurice dc76efc418 admin: a withdrawal that went through is reported even when the state re-read fails 2026-10-31 03:25:56 +00:00
Maurice 314b087f98 planner: the refresh pill compares with the place picked anew in the search box
After another place was picked while editing, the pill still offered the
saved place's details and would have written them onto the new one.
2026-10-31 03:25:56 +00:00
Maurice 2f689ea9ca maps: stop reading a community picture at its size cap
An answer without a content-length was buffered whole before its size was
checked. The read now stops at the cap.
2026-10-31 03:25:56 +00:00
Maurice 41edbcf67a maps: validate the community values and OSM elements the TREK Places API answers
Both answers were taken as typed. A value outside the published shape, such
as hours that are no text, reached the hours parser and failed the details
request. A place outside the shape is now left out of /v1/community, and an
element outside it sends the lookup to Overpass.
2026-10-31 03:25:56 +00:00
Maurice 6945b53c10 place-enrichment: a community summary the request carried stays out of the shared cache
Like an OpenStreetMap summary, a summary credited to the community is read
straight off the request's details, so any caller could have it served to
every user of the instance for a week under the community's name.
2026-10-31 03:25:56 +00:00
Maurice 7ade99c8ce place-contrib: audit a switch-off whose withdrawal the service did not confirm
Switching sharing off commits before the withdrawal asks the service. When
the service did not confirm, the decision had taken effect but left no audit
row. It is now audited with withdrawFailed, and the admin still gets the
error.
2026-10-31 03:25:56 +00:00
Maurice 593df53993 places: a picture route records the origin of the picture only
The upload and the trip-file routes vouched for every field that changed
between their read and their answer. A website the assistant or a
collaborator changed while a large picture uploaded was then recorded as
typed by the user and queued for the TREK Places API. Those writers now name
the one field they write, and other changes keep the origin their own writer
recorded.
2026-10-31 03:25:56 +00:00
Maurice aa41c67a20 place-contrib: settle a sent value only while its queue row still holds it
A value saved while the request for its predecessor was out rewrote the same
outbox row with a new cid; the answer for the old value then deleted the row,
or charged it an attempt, and the newer value was never sent. The settle
writes now match the cid that was sent as well as the id, so such a row stays
queued for the next run. A replaced value also counts its age from the
replacement, so a long pause cannot expire a value queued days ago.
2026-10-31 03:25:56 +00:00
Maurice c10a698b9f planner: keep a place's enrichment in the tab for ten minutes, not for good
A saved place reopened for editing has no community version in its key, so
the answer the tab kept the first time stayed until the tab closed: a picture
another installation contributed since never showed. Kept answers now carry
when they were fetched and are asked again after ten minutes, the same span
the server keeps an empty answer. The key version moves to 5 so open tabs drop
what they kept in the old shape.
2026-10-31 03:25:56 +00:00
Maurice e2756dab22 places: a picture another installation contributed shows on the next edit
Two gaps kept it out. The service writes absolute picture URLs on its own
host, and the community service only took relative paths, so every picture
was dropped; it now takes the path of a URL on the configured service and
nothing from another host. And a saved place opened for editing sends no
details, so no community version, and the cached answer kept for a week; for
an index or OSM place the details are now read before the cache, so a new
version is a new answer.
2026-10-31 03:25:56 +00:00
Maurice 330644e88b places: show the community's published pictures first in Pick a picture
The service delivers the pictures review approved for a place, but TREK never
read them. A new TrekCommunityService in the maps domain asks the TREK Places
API for them (the index row for a gers place, /v1/community for an OSM one),
accepts only paths of the service's picture store, and fetches the bytes with
the installation's key, capped at 4 MB. Enrichment puts them ahead of Google
and Commons, through the same photo cache, credited as TREK Community under
CC BY 4.0. The enrichment cache now follows the community version for OSM
places too, so a newly approved picture shows on the next open.

Also lowers the client's no-non-null-assertion baseline to 380: moving Use
this text into the description card removed two.
2026-10-31 03:25:56 +00:00
Maurice 0b86a13b51 admin: fold the transmission log to its newest five rows
A busy log pushed the rest of the card down. It shows the newest five rows,
a Show more toggle opens the rest, and the page buttons appear once it is
open.
2026-10-31 03:25:56 +00:00
Maurice 8d8629516b places: offer a newer description in the refresh pill
The pill compared website, phone, e-mail and hours only, so a description
the community published never showed up on a saved place. It now reads the
index description or the OSM summary, compares it as plain words against
the editor's markup, and shows it clamped to three lines.
2026-10-31 03:25:56 +00:00
Maurice 5822910f40 places: put Use this text right under the description it copies
The button was pinned to the foot of the details column, away from the text
it adopts. It now sits inside the description card, under the source line,
with the reason it is blocked directly beneath it.
2026-10-31 03:25:56 +00:00
Maurice ce5ec7132f places: a description the community shared is credited to the TREK community
A community description laid over OSM details or an index row showed up as
OpenStreetMap under ODbL, or as the place's own website. It now has a source of
its own, community, credited as TREK Community under CC BY 4.0, like the
service publishes it.
2026-10-31 03:25:56 +00:00
Maurice 7f2a3b6039 planner: keep REFRESH_FIELDS inside its module; docker: leave shared/node_modules out of the build context
A checkout where npm install ran once carried shared/node_modules into the
image build, and its stale packages broke the client build with a vite that
lacked vite/internal.
2026-10-31 03:25:56 +00:00
Maurice 3e860dd9ca place-contrib: tag enqueue's send run as independent of its queue write 2026-10-31 03:25:56 +00:00
Maurice c28604b891 planner: the details refresh reads through a repository, and the form drops what moved out
The fresh lookup behind New place details goes through placeDetailsRepo
(online-only, like the service identity) instead of api/ directly. The form
loses the Translate type and the comment that moved with the head band's
pills, which takes it under its line limit and out of the size baseline; the
maps service suite's test-size entry follows its shorter count.
2026-10-31 03:25:56 +00:00
Maurice aba329b1b1 planner: a saved place offers newer details from its provider, field by field
Editing a saved place looks it up again. Where the lookup has a website,
phone, e-mail or opening hours that differ from the place, a New place details
pill in the form's head band shows how many, and opens what the place holds
beside what the lookup has. Empty fields are ticked, filled ones are left to
the person and say they would replace; Take over writes only the ticked
fields, with the provider as their origin, and nothing the lookup does not
know is ever emptied.

The head band's pills move to PlaceFormHeaderPills.tsx, which brings the form
from 1157 to 1002 lines.
2026-10-31 03:25:56 +00:00
Maurice 04458bee12 place-contrib: community hours in the details' own shape, and no origin rows for collection copies
Community opening hours laid over OSM details now go through the same parser
as OSM's own, so they arrive as one line per day with open-now and the periods,
and a community description lands in the details' summary. A place copied from
a collection no longer records its values as an import: without an origin row a
value is never sent anyway, and a later edit marks only the fields it changes.
2026-10-31 03:25:56 +00:00
Maurice f01ffc2c67 maps: OSM details come from TREK's own copy of OpenStreetMap first
Opening an OSM place asked the public Overpass servers for its tags, which
took five seconds and more and answered nothing while they were down. Where
the TREK services are in use, the details now come from the Places API's
details layer (/v1/osm), with the community values in the same answer, and
Overpass is asked only for an element the layer does not hold.
2026-10-31 03:25:56 +00:00
Maurice 5cfe925b78 place-contrib: no promise in the job's condition; the OSM details test counts the community call 2026-10-31 03:25:55 +00:00
Maurice a2414685ad wiki: what the API Keys card still saves 2026-10-31 03:25:55 +00:00
Maurice a1ca1aae44 admin: place search and routing get a card of their own, the keys keep theirs
The TREK API, the transit provider, the place search provider and the search
log move out of API Keys into a card of their own, which keeps them together
and saves as they change. API Keys holds only Google Maps, Unsplash and Amap,
and is not shown on a managed install, where the keys are the operator's.
Allowed File Types moves to the left column, which had room for it.
2026-10-31 03:25:55 +00:00
Maurice 56536ae803 admin: the allowance and the sharing blocks take the settings' own card head
Both blocks in the TREK API card now use SettingsCard like Single Sign-On and
two-factor: an icon tile, the title with its state as a badge, the note under
it and the switch or badges on the right, with a flush variant for a card
inside a card. A figure badge no longer cuts the last pixels of its value, and
the withdrawal toast names how many values it took back.
2026-10-31 03:25:55 +00:00
Maurice 59154b34c9 maps: OSM details carry the values installations published for the element
A place found through Photon or Overpass, a relation or a way, is no row of the
TREK index, so the community values the index lays over its own rows never
reached it. Opening its details now asks /v1/community for the element and
lays what is published over the record, with the version, where the TREK index
is in use. No answer leaves the details as they were.
2026-10-31 03:25:55 +00:00
Maurice b64f4535fd admin: set the service card's state and its one action apart from the figures
The state and its badges sit in a head band, the new-identity button in a foot
band, each with a rule and the card's own surface, so neither reads as part of
the allowance tiles between them.
2026-10-31 03:25:55 +00:00
Maurice ad2916903c place-contrib: send a queued value at once instead of minutes later
A value is due the moment it is queued, and the save starts a send run right
away; the two-minute tick stays for the retries. One run goes at a time, and a
run asked for meanwhile follows right after it. Only where the schedules run, so
tests and replicas send nothing.
2026-10-31 03:25:55 +00:00
Maurice 71cd6c2de4 place-contrib: record origins for collection copies and booking imports
A place copied from a collection and a venue a booking import creates now
record their details as an import, so a later edit compares against what was
really written. Dawarich and the background enrichment write none of the
shareable fields, so they need nothing.

The admin panel asks again for a few seconds while a fresh installation is
still fetching its key, so the prompt appears without a reload.
2026-10-31 03:25:55 +00:00
Maurice 3f2dec6c47 place-contrib: sort the request id's parts with an explicit code-unit compare 2026-10-31 03:25:55 +00:00
Maurice 668df8c62e place-contrib: seed the repository tests through the row factories, not raw SQL 2026-10-31 03:25:55 +00:00
Maurice 294ba0a4fe place-contrib: repository tests for the log, the outbox and the field origins
Every method of the three new repositories, the empty-list shortcuts and the
filters included, so the repositories keep their 99 % floor.
2026-10-31 03:25:55 +00:00
Maurice 36c1599a09 place-contrib: settle the second CI round
- The plugin RPC fallback tests build PlacesRpc with its origin bookkeeping.
- The e2e guard and contract cases send their requests one after another; the
  test server reset connections opened all at once.
- The job's two cron registrations are tagged @txIndependent: neither writes.
- The panel draws its fold head itself instead of importing it from pages/.
2026-10-31 03:25:55 +00:00
Maurice 65abea6910 place-contrib: settle the first CI round
- The pause setting's type comes from its schema, so nullable fields read the
  same under the server's compiler settings.
- The place form passes the origin of a field through to the hook.
- Serial steps run through inOrder (src/nest/common/in-order.ts) and
  independent ones through Promise.all, instead of an await inside a loop. The
  bulk update in places.mcp.ts goes the same way, so its baseline drops by one.
- The status a call without a key gets is a named constant, not an envelope
  literal.
- A picture test no longer inherits the previous test's mock answer.
- The entity counts include the three new tables.
- The log keeps its failure per query instead of resetting it in the effect,
  and usePlaceForm sets its picture through one helper.
2026-10-31 03:25:55 +00:00
Maurice 18dc121132 wiki: sharing place details with the TREK Places API
What is sent and when, what never is, how values are checked before anyone
sees them, and where an admin switches it off or takes it back. The new
TREK_PLACES_CONTRIBUTE variable is listed with the compose file and the chart.
2026-10-31 03:25:55 +00:00
Maurice 013aa3954d admin: ask once, then show and steer what is shared of place details
The first time an admin opens the settings on an installation that can share,
a dialog asks for the whole installation, with every field switched on and a
plain list of what never goes along. Nothing is sent before Agree; Not now
asks again in 14 days, No keeps the question away until the terms change, and
closing it decides nothing.

Inside the TREK Places API card, Share place details then holds the switch for
the installation and one per field, the figures of the last 30 days, the
transmission log and the way to withdraw everything sent. The place form
reports for each field whether the user typed it or a provider filled it.
2026-10-31 03:25:55 +00:00
Maurice 182ed56fa4 places: let an admin share the details users typed with the TREK Places API
Every shareable field of a place now records where its value came from: typed
by a user, filled by a provider, written by the assistant, a plugin or an
import. Only values a user typed are ever sent, and only after an admin agreed
to the current terms for the whole installation, field by field.

The new place-contrib domain keeps the decision in app settings, queues values
in an outbox a cron job sends from, logs what the service made of each one and
can withdraw everything this installation sent. Development, test and demo
instances, an own TREK_PLACES_URL, TREK_SERVICES=off and
TREK_PLACES_CONTRIBUTE=off never send anything. Index results carry the
community version, so the details caches refresh when it changes.
2026-10-31 03:25:55 +00:00
Vini f56f6ae11e perf(atlas): keep the admin0 country index as Int16 arrays and send countries/geo from disk 2026-10-31 03:25:13 +00:00
Vini c94ff7421a keep looked-up regions as packed Int32 arrays under a 16 MiB budget 2026-10-31 03:25:12 +00:00
Maurice 2dbcc39832 chore(lint): lower the no-explicit-any baseline after the typed region lookup 2026-10-31 03:25:09 +00:00
Maurice 47dad114df test(atlas): cover the per-country region route in the e2e suite 2026-10-31 00:40:23 +00:00
Vini 7277e35a96 serve each country's regions from its own file, so the server no longer holds them all
The Atlas server no longer keeps the admin-1 regions of every country in memory. Each country's regions are now a pre-gzipped file of their own, sent to the map as they are.

**Why:** `GET /addons/atlas/regions/geo?countries=…` built `admin1Store` (every country's region text, kept until restart), then joined the requested countries, `JSON.parse`d them, and Nest stringified them again. On the 512 MB – 1 GB boxes TREK runs on, the first z≥5 view could OOM the server (same shape as #1576).

**What changes:**
- `server/assets/atlas/admin1/<ISO_A2>.geojson.gz`: 198 files, 14.85 MB, the same 3,447 features as `admin1.geojson.gz`.
- New `GET /addons/atlas/regions/geo/:code` with a Zod contract (`regionGeoParamsSchema` in `@trek/shared`: two letters, any case). It sends the country's file as it is, with `Content-Encoding: gzip` and the current 1-day `Cache-Control`, as `countries/geo` does. A country without regions gets an empty FeatureCollection. Anything that is not two letters gets a 400.
- `useAtlas.ts` fetches one URL per uncached country and still rebuilds the layer once. Each country has a stable URL, so a country evicted by `REGION_CACHE_MAX` comes back from the browser cache.
- `getRegionFeatures` reads only the country it needs. `admin1Store` is removed.
- `?countries=` keeps working for cached PWA clients. It joins the per-country files as bytes, without a parse.
- The migrations are untouched. `admin1.geojson.gz` still ships, only for `Migration20200101021500` and `Migration20200101031500`. This costs ~15 MB of disk in the image and no RAM. `build-atlas-geo.mjs` writes both, and ATLAS-BUNDLE-008 keeps them equal.

**Memory** (real `atlas-geo` module, first z≥5 view over Europe = 49 country codes, JS heap + Buffers):

| | peak | kept after |
|---|---|---|
| before, first view (builds the store) | +372 MB | +61 MB |
| before, later views | +115 MB | 0 |
| after, `/regions/geo/:code` | +4.7 MB | 0 |
| after, legacy `?countries=` | +59 MB | 0 |

**Tests:**
- New: `atlas-region-files.test.ts` (moved from `atlas.service.test.ts`, plus join and dedupe cases), the `regionGeoParamsSchema` spec, ATLAS-BUNDLE-007 (the file format the byte join depends on), ATLAS-BUNDLE-008 (bundle and per-country files are equal), ATLAS-016/017/018 (the new route over HTTP, including the 400).
- The `getVisitedRegions` tests (ATLAS-UNIT-019..024) used to pass only when `getRegionGeo`'s `beforeAll` had built the store first. They now also pass on their own.
- The shared, server and client gates pass. Baselines go down only where this change removed code (`no-console`, `no-explicit-any`, `no-swallowed-catch`, file sizes).

**Trade-offs:**
- A first zoom over Europe sends ~49 small parallel requests instead of 1. Over HTTP/1.1 the browser queues them 6 at a time. The total bytes are the same (4.4 MB gz).
- The per-country URLs are unversioned and cached for a day, like `countries/geo`. After an upgrade that changes a country's regions, a browser can show the old shapes for up to 24 h.

Approved on Discord in #github-pr: <paste the thread link here>
Related: #1576, #2559

- [x] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update

- [ ] I have read the [Contributing Guidelines](https://github.com/liketrek/TREK/wiki/Contributing)
- [ ] My branch is [up to date with `dev`](https://github.com/liketrek/TREK/wiki/Development-environment#3-keep-your-fork-up-to-date)
- [x] This PR targets the `dev` branch, not `main` *(wiki-only PRs are exempt)*
- [x] I have tested my changes locally
- [x] I have added/updated tests that prove my fix is effective or that my feature works
- [x] I have updated documentation if needed
2026-10-31 00:40:23 +00:00
Maurice 70f27085b9 feat(i18n): bring the Hebrew locale up to date with dev and list it in the docs
Translate the 55 keys dev added since the branch was cut (TREK services
allowance, Valhalla routing service, PDF routing progress, overview
distances, Unsplash key hint, tour day limit) and drop the two reservation
toasts dev removed, so he matches en key for key again. Refresh the two
admin strings and the Valhalla hint whose English changed.

Check he in the placeholder spec and the RTL test, and count 28 languages
with Hebrew in the README and the Languages, Environment Variables,
Contributing and Help Center wiki pages.
2026-10-31 00:40:23 +00:00
Dolev Benezri 156dc4a6c2 feat(i18n): complete Hebrew locale for dev
Fill in every domain added since the first Hebrew pass (help, tours,
assistant*, studio*, wanderer*, journey, demo, ferratas and the rest),
retranslate strings whose English changed, and give every count group
its Hebrew one/two forms. Register he as a non-Latin locale for the
untranslated ratchet, add the Hebrew 429 message, and count 28 locales
in the tours locale spec.
2026-10-31 00:40:23 +00:00
Dolev Benezri d159aec78b feat(i18n): add Hebrew (he) locale with RTL support
Full Hebrew translation of every UI domain plus email/notification
templates. Registered in SUPPORTED_LANGUAGES, marked right-to-left,
wired into the client locale loader and the rate-limit message table.
2026-10-31 00:40:23 +00:00
bear 547f0b84b0 fix(mcp): file a transit fare under the transport cost category
transit is not one of the fixed Costs categories, so typeToCostCategory
would put an uncategorised fare under other. Default to transport, the
category every rail and bus booking maps to.
2026-10-31 00:40:23 +00:00
bear 8d10bff616 feat(mcp): price on create_transit_journey, reservation_id on create_budget_item
- create_transit_journey takes price / budget_category, as create_transport
  does: a fare > 0 files the linked expense in the booking's own transaction
  and rides along in metadata.price. The tool now writes through
  ReservationWritesService.createBooking, so its events and booking notice are
  the ones every other booking write sends
- create_budget_item and create_budget_item_with_members take reservation_id,
  the field POST /budget already accepts; create_budget_item now runs
  BudgetWritesService.createItem like its sibling, so a linked booking's
  mirrored price is worked out again before budget:created goes out
- bookingPriceSchema / bookingBudgetCategorySchema in @trek/shared back the
  price fields of all three booking tools (mcp-inline-zod baseline lowered)
- wiki: MCP-Tools-and-Resources describes the new params
2026-10-31 00:40:23 +00:00
Maurice e5048643f8 test(assistant): pin the clock in FE-AI-PICK-004
Trip 7 ran until 2026-10-30, so from 2026-10-31 on the hook ranked it as
past and the test failed. Pin the date to the file's TODAY.
2026-10-31 00:39:38 +00:00
Maurice a156f5be32 fix(chart): keep a blank line before the HTTPRoute section in NOTES.txt
The trimming if swallowed the blank line, so the HTTPRoute note ran
straight on from the Persistence section. Move the blank line inside
the conditional so it only appears with the section.
2026-10-30 23:32:43 +00:00
Demisu 431122d253 refactor(README): remove HTTPRoute configuration section for clarity 2026-10-30 23:32:43 +00:00
Demisu bbc8f141e3 feat(helm): add optional Gateway API HTTPRoute support
Add disabled-by-default HTTPRoute support with configurable parent references,
hostnames, paths, annotations and optional timeouts. Route to the existing TREK
Service and keep Ingress support unchanged, including simultaneous use.

Document configuration and extend the existing Helm Chart & Compose job with
HTTPRoute render variants and strict validation using a pinned CRDs catalog.

Approved on Discord:
https://discord.com/channels/1488298068427411591/1553537637455761500

Validation: strict Helm lint, 37 manifests validated without errors or skipped
resources, and both Compose configuration checks passed locally.
Live Gateway WebSocket and streamed assistant response checks were not performed
because no Kubernetes test cluster was configured.
2026-10-30 23:32:43 +00:00
Maurice 01681f57c7 docs(chart): document extraVolumes and extraVolumeMounts in the Helm install guide
The install guide lists extraEnv and extraEnvFrom but had no word on the
new volume values. Add a Further volumes section with the KItinerary
extractor example and point the Reservations-and-Bookings page at it.
2026-10-30 23:30:54 +00:00
aaronspruit 553808eb83 feat(chart): add extraVolumes and extraVolumeMounts
The chart mounts only the data and uploads volumes, and no value adds
another one. Add two lists that go into the Deployment as written:
extraVolumes for the pod, and extraVolumeMounts for the trek container,
next to the data and uploads mounts. Both lists are empty by default,
so the default render does not change.

The values file shows one use: a ConfigMap of KItinerary extractor
scripts, mounted at /usr/local/share/kitinerary/extractors. The chart
README and the Reservations-and-Bookings wiki page tell Helm and Compose
users how to mount extractors there.

The variants render in the Helm Chart & Compose job sets both values,
so kubeconform checks them.
2026-10-30 23:30:54 +00:00
Maurice 324ee69151 fix(transit): mark the plan fallback's quota counts as independent writes
The empty-result fallback can call Google after Transitous, so lint:tx now sees two googleQuota.record() calls in TransitService.plan. Only one of them runs per request, and each is a call counter written after its own upstream request, so it cannot share a transaction with it.
2026-10-30 23:36:35 +01:00
Maurice c4c63ffd62 docs(transit): describe the empty-result fallback between transit providers
Admin settings, transport, environment and MCP pages still said Transitous
is the only fallback and that Google is billed only when picked. Document
that an empty plan asks the other backend, that the Google fallback uses
only an instance key within the daily limit, and mention it in the
search_transit_routes tool description.
2026-10-30 23:01:17 +01:00
Raz Erlich 209f8fe5cc feat(transit): fall back between configured public transit providers 2026-10-28 08:01:53 +02:00
Maurice 9f155a3191 fix(airports): refresh the bundled airports from OurAirports without dropping shipped codes
Logroño-Agoncillo (RJL) and fifteen other airports gained their IATA code in
OurAirports after the bundled list was built, so the airport search and the
code lookup of create_transport could not find them. The list is rebuilt from
the current data. The build now keeps every code the previous list carried
that upstream no longer lists (a scheduled-service flag flipped back, PBI moved
to a new record), since bookings and MCP calls still name them.

Refs #2897
2026-10-30 22:06:07 +01:00
Maurice 067ab89430 fix(calendar): give transport events a LOCATION and GEO from their endpoints
A car or other transport booking carried its route only in the description, so
a calendar app had no place to navigate to. Without a location of its own, a
transport event now takes the endpoint the traveller has to get to: the
destination of a drive of their own (car, bicycle) and the departure of a ride
they board, the side the per-leg events already use. A car's pickup and
drop-off events are located at their own endpoints. A location the booking
states keeps winning.

Closes #2909
2026-10-30 21:54:19 +01:00
Maurice 019c668744 fix(llm-parse): ask Anthropic models for the extraction tool instead of forcing it
Claude Sonnet 5.5, Opus 5.5 and Fable 5.1 reject tool_choice type "tool" and
"any" with a 400, so every booking import through the Anthropic provider failed
on them. The request now sends tool_choice auto with parallel tool use off,
which every Anthropic model and Messages-compatible gateway accepts, and the
system prompt tells the model to answer through the emit tool exactly once. A
model that still answers in text is reported as before.

Closes #2902
2026-10-30 21:54:19 +01:00
Maurice b953ece4b3 fix(journey): stop the entry views from shifting while photos and providers load
Opening an entry on the share page showed the hero at no height until the
original arrived, then pushed the story down, and the lightbox stayed black
until the full photo had loaded. The hero now reserves the photo's proportions
(4:3 when none were recorded) with its thumbnail behind it, and the lightbox
shows the thumbnail and a spinner until the original is in.

The phone entry sheet probed the photo providers again on every open and added
the External photos button once the answer came, squeezing the icons of the
other two buttons. The journey screen already knows the connected providers, so
it hands them to the sheet, and the icons keep their size.

The picked neutral mood was a grey tint on a grey sheet; a picked mood is now
framed in its full colour and announced as pressed.

Closes #2907
Closes #2908
Closes #2905
2026-10-30 21:15:38 +01:00
Maurice 94a9cbf070 fix(journey): draw the live Dawarich trail in the colour of its day
The live trail arrived in Dawarich's own day palette, counted from the first
recorded day, while a journey colours its days by the entries. A day's line and
its pins therefore wore different colours. The trail of a day that has entries
now takes that day's colour, the way the kept recordings already did.

Closes #2906
2026-10-30 21:15:37 +01:00
Maurice 8eebcea9f5 fix(journey): keep GL photo markers absolutely positioned so thumbnails sit on their coordinates
The journey map's photo thumbnails set position:relative inline on the marker
element. That overrides the engine's .mapboxgl-marker/.maplibregl-marker
position:absolute, so every thumbnail entered the normal flow below the ones
drawn before it and the engine's translate was added on top: the further down
the list, the further the photo drifted from its spot. The location dot had the
same inline position. Both now leave position to the engine's class.

Closes #2910
2026-10-30 21:15:37 +01:00
Maurice 5e00282309 maps: drop indexHitsOnly, which the search no longer needs, and keep isHit inside its module 2026-10-30 17:26:56 +01:00
Maurice 3b675eed60 airports: publish the airport of a code as a contract the place search reads
The search turned an airport code into its airport by reaching into the
airports domain's data module. airports.contract.ts publishes that lookup
instead, as the import boundaries ask.
2026-10-30 17:14:55 +01:00
Maurice 51bbd337c9 i18n: format the admin strings of the TREK API card 2026-10-30 16:57:52 +01:00
Maurice 4203dcd91f maps: keep the merge and Photon's geocoding in modules of their own
maps.helpers.ts and osm.client.ts had grown past the 1000-line limit. The
merge behind the search and suggestion lists, with its lead rules, moves to
maps-merge.helpers.ts; the search records and Photon's half of the
OpenStreetMap geocoding (search, suggestions, airport codes, identity,
reverse, element details) move to osm-geocoding.ts. OsmClient keeps the
same methods and hands them on, so no caller changes.
2026-10-30 16:52:12 +01:00
Maurice 1e5314d847 maps, routing, i18n: settle what the checks found
- The lead is Photon's own row first; a row of its name inside the lead
  only stands in where Photon's row went as the same place. Rows without a
  line below the name are never folded as reading the same.
- A miss of Photon where it is the geocoder no longer asks it a second time
  on the way to an empty answer.
- The transport words of the identity match use a Unicode word boundary
  (straße, estación) and match 駅 anywhere.
- Opening an OSM place reads the coordinate it was placed at explicitly.
- The ferry spans of a Valhalla leg move to valhallaFerries.ts, and a day
  cut into pieces is asked with one options object.
- "Limit" on the allowance tiles is "Daily limit", which no locale left
  as an English copy.
- Tests follow the new behaviour: no Nominatim behind Photon, zoom 13,
  and the expectations of the merge and edit-distance cases.
2026-10-30 16:36:22 +01:00
Maurice b98e530ffc wiki: describe the address search, the merged result list and the routing of the TREK services 2026-10-30 16:16:10 +01:00
Maurice deb125bedc admin: show the TREK API as its three services
The card names place search, address search and routing with what each
answers and what is left of today's allowance. Each service is a tile with
what is left as its figure, the day's use as a bar and used and limit as
badges; the state, the kind of installation, a key from the environment
and the time the count starts again sit as badges in the header. The
sources add the terrain tiles the routes take their heights from.
2026-10-30 16:16:09 +01:00
Maurice c508bb9758 routing: a slow route is not a down relay, and the relay takes whole days
A request to the TREK Valhalla that runs out its deadline (a long bike
route) is answered 504 and no longer rests the relay for every user or a
tab for ten minutes; that one day goes to OSRM. Only an unreachable host
or a server error rests it.

A day goes to the relay with up to twenty stops per request and no pause
between pieces; a request that ends up at the public FOSSGIS Valhalla is
cut to ten and paced, as before. The 1.1 s spacing of the server applies
to the public hosts only, not to an admin's own OSRM or Valhalla. The
relay keeps its connections open and asks for maneuvers only, which the
relay contract now accepts.
2026-10-30 16:16:09 +01:00
Maurice a55d4e786f maps: lead with the place a name stands for, and leave Nominatim to installs without the services
The suggestions and the full search now share one merge. Photon's hits are
ranked with places that have a Wikidata link before their unlinked
namesakes, and its context bias is narrower (zoom 13). The list opens on a
lead where Photon's answer has one: a country or region always; a town,
island or sight when it is called what was typed (or a near typo of it),
lies within 1000 km of where the traveller is looking and no place of that
name ranks above it. Rows of the lead's name inside it, the same element
under two ids and rows that read the same are shown once. A three-letter
code in capitals is asked for as the airport of the bundled list.

Where Photon is the geocoder it answers alone: an empty answer and a miss
are the answer for search and imports, the reverse lookup asks again
within 50 km, a Google place is matched inside a box through Photon, and
an opened OpenStreetMap place is placed by Overpass and named by Photon.
Nominatim stays the search of installations without the TREK services or
with an operator's own Nominatim.

Measured on 5000 places from Wikidata: the right place first while typing
48 % before, 65 % now; full search 53 % to 68 %; no repeated rows.
2026-10-30 16:15:59 +01:00
Maurice 5a270abc05 fix(booking-import): give the fare keeper reduce an initial value 2026-10-29 21:40:03 +01:00
Maurice f50a1dabe5 chore(ci): lower the knip baseline for the kitinerary types 2026-10-29 21:25:13 +01:00
Maurice 1058849388 test(booking-import): read the endpoints without a non-null assertion and lower the any baseline 2026-10-29 21:12:58 +01:00
Maurice 299beb65b1 fix(roadtrip): hand a hire car without a return day back on its pick-up day
A car booking without an end day is a one-day booking everywhere else in
the plan, but the road trip read it as a car never handed back: only its
pick-up desk stood on the road. Two one-way car bookings on one day
(Bologna to Villach, then Villach to Klagenfurt) therefore drove from the
first pick-up to the second and on to whatever came before, counting the
road between the two cities twice and never reaching Klagenfurt. This
applies to the planner, the phone and calculate_roadtrip alike, since all
three seat the desks through the shared carrierSeam.

Such a car now has its return desk on the pick-up day. A return without a
time goes back before the next car of that day is collected rather than
closing the day behind it, so each one-way car drives its own road once.
Bookings with a return day and cars without a located return desk are
unchanged.

Closes #2894
2026-10-29 20:51:28 +01:00
Maurice 23b7f6d71c fix(bookings): count a multi-segment rail ticket's fare once
A rail, bus or ferry ticket with changes arrived as one booking per
segment, each with a linked cost for the full fare, so the trip total
was the fare times the number of segments.

Import: the KItinerary mapper now groups consecutive train segments
under one booking reference that connect (same station by name or
within 500 m, no return, within a day) into one train booking with
stops and metadata.legs, the way connecting flights already were. The
connection rule is shared between flights and ground transport, and a
stop carries the onward departure for flights as for trains, as the
planner form and the MCP tools write it. The three copied ground
mappers are folded into one.

Within one such booking a fare repeated on every segment is booked
once, and fares that differ per segment are added in whole cents. That
summing now applies to connecting flights too, which used to keep the
first leg's price only.

Segments of one order that do not join into one booking (an outward
and a return trip, a gap, a change of station named two ways without
coordinates, bus and boat tickets, Rail&Fly) are compared across the
document: when every priced transport booking of a reference carries
the same amount in the same currency, the first to depart keeps it and
the others lose it. Amounts that differ stay. This runs on what
KItinerary extracted only.

AI import: the repeated-total safety net from #2651 now covers train,
bus and ferry tickets and any mix of them with flights, still only
when the document prints that amount on a total line.

MCP and assistant: create_transport says that a ticket with several
segments is one booking with endpoints[] and legs[], and the price
fields say they hold the whole booking's cost. When a new booking
repeats the price an earlier booking with the same confirmation number
already carries in the trip's currency (its own currency, or the
trip's when it names none), create_transport and create_reservation
still save it and return a warning naming the earlier booking. REST is
unchanged.

Existing duplicated costs are left alone: they cannot be told apart
from two tickets that really cost the same, and deleting expenses
automatically would change settled balances. They can be removed in
the Costs tab.

Closes #2895
2026-10-29 20:51:28 +01:00
Maurice f85b9dc3ff fix(service-identity): call the dialect self-check's scrypt input inputSha256
A field named passwordSha256 next to a hex literal reads as a hard-coded
password to static analysis.
2026-10-29 20:04:40 +01:00
Maurice 3c38a87271 chore(knip): treat the registration dialect as an entry, the release job loads it by path 2026-10-29 20:04:40 +01:00
Maurice 12e22c258a ci(release): stop on a stale dialect, check it like CI would, give prereleases their own
A stable release without a dialect of its own now ships the one on main only while that one has 90 days left; dialect 0 or less stops the run before anything is committed, unless allow_stale_dialect is ticked. Fetching and checking moved into registration-dialect.yml, which never fails its caller and also type-checks the module under the strict config and lints it with --max-warnings 0, since the bump commit skips CI. The bump and everything after it run whatever became of the dialect job. Prereleases ask the issuer for a dialect of their -pre.N version and build it into the image without committing it. The release check reads the module token by token against an allowlist of keywords, globals and member names, refuses any assignment to a property, computed access and regular expressions, and names Object, JSON and defineProperty among the forbidden. The issuer's kitchen-sink sample is gone; the tests use a hand-written dialect instead.
2026-10-29 20:04:40 +01:00
Maurice cd5ce4b1d9 docs(wiki): say how long a key renews and what a new registration needs 2026-10-29 20:04:40 +01:00
Maurice 6d245ab4da ci(release): ship the registration dialect with the version bump
The stable release asks the issuer for the registration dialect of the
version it cuts and commits it in the bump commit. Fetching and checking run
in a job of their own that holds no write token and keeps no git
credentials: scripts/ci/check-registration-dialect.mjs refuses a file that
imports or names anything beyond hashing, then runs it on its self-check
inputs. Only a file that passes reaches the bump as an artifact. When the
issuer is unreachable or its answer fails the check, the release goes ahead
with the dialect already on main and says so in the log and the summary.

Prereleases get no dialect of their own; dev takes the stable one through
the merge of main into dev after a release, and docker-dev.yml warns while
dev still speaks the original registration or a dialect older than 150 days.
2026-10-29 20:04:40 +01:00
Maurice 3ca73d432b feat(service-identity): register through the dialect of the running release
Registration now goes through a registration dialect module: the paths of
the challenge and the registration, the bytes scrypt runs over and the body
and headers of the request. Each stable release will carry the dialect the
TREK services issuer writes for it; until the first such release the module
speaks the original registration, so nothing changes on the wire.

An issuer that no longer takes the release's dialect answers 410. TREK then
says so once per process, waits a day (or what Retry-After asks) and keeps
searching through the shared pool. The issuer client only lets a dialect
register at the issuer's own paths, with X-TREK-* headers that are not the
gate's and a body of registration size.

Renewal needs no dialect, and an expired key may now be renewed for a year
instead of 30 days, the same period the issuer allows, so an installation
that was offline for long comes back without an update. The key format
ignores the new optional dialect claim; the shared vectors gain one key that
carries it.
2026-10-29 20:04:40 +01:00
Maurice e6c8fee3e5 fix(journey): keep the card-click ref in JourneyMap and type the pin event test
The marker effect reads the card handler through the component's own ref
again, so exhaustive-deps sees a ref it knows, and the card hook takes it
alongside the map's other refs. The pin event assertion types the mock
calls it maps under strict mode.
2026-10-29 17:50:43 +01:00
Maurice 2dbaf6b029 fix(journey): hold the client gates on the journey map changes
The phone card logic moves out of JourneyMap into useEntryCard, which brings
the component back under the line limit. The new card tests reach the
card element through a guard instead of non-null assertions, the public
hook test reads the hook through renderHook, the GL card tests use
mock.lastCall where Array#at is outside the client's lib, and the
complexity baseline drops to the count the branch now holds.
2026-10-29 17:39:37 +01:00
Maurice c14b572038 refactor(server): read the share link's journey entries through Kysely
listPublicEntries changed for #2886, and the repository rules move a
touched QueryBuilder call to the entity methods or Kysely. Kysely keeps
the method's answer what it was, the stored row as SELECT * reads it,
which the entity methods would hand back as entities with a journey
reference in place of journey_id. The query-api baseline drops to 8.
2026-10-29 17:26:51 +01:00
Maurice c0e951fc8e chore(journey): keep the map stop and connection types to their files
ConnectionStop, EntryConnections and JourneyMapStop are only used in the
signatures of their own modules, and knip counts an export nothing
imports. The connection tests take the FE- prefix and header the other
journey tests carry.
2026-10-29 17:26:51 +01:00
Maurice c71ecc8f76 fix(journey): drive the phone's Leaflet card from the active pin
The card a phone host opens its entry from was still a tooltip bound to
the pin, so Leaflet opened and closed it on the pin's hover and focus. A
tap on the card reaches a phone browser as the pointer leaving the pin
first: the pin's mouseout closed the card between the tap and its click,
and on iOS a content change in that phase can drop the click entirely.

Where a host wires onMarkerCardClick, the pins now bind no tooltip. One
card per map stands over the active pin, the way the GL popup does: it
follows highlightMarker, leaves when no entry is active or the entry
pins are switched off, and only a change of entry moves it. A press on
it never reaches the map. Desktop hosts keep the hover label on each pin.

The card tests run against the handlers the pins really get and the
card the map really adds, and the file parses again: two test names held
an unescaped apostrophe.
2026-10-29 17:26:51 +01:00
Maurice a1c7ea209b fix(journey): open the entry when its marker card is tapped on the phone
On the phone journey screen and the public share page on a phone, a tap on
a numbered pin brings up the entry's card above it, but the card could not
be tapped: the GL popup and the Leaflet tooltip both let the pointer fall
through to the map, and no phone host gave the card anything to do.

The map now takes onMarkerCardClick, and both renderers make the card open
that entry once a host wires it. The GL popup handles it in its delegated
listener next to the photo strip, which keeps opening the photos where the
desktop asks for that. Leaflet handles it on the tooltip element itself:
a press that reached the map container let Leaflet focus the map, which
blurred the pin and closed the card before its click landed. The phone
screen and the timeline open the entry through the carousel hook, the
same way a tap on the active card does. The desktop asides keep the card
as a hover label.

The unused hideMarkerTooltip prop goes, together with the docs that still
said the phone hides the card.

Closes #2885
2026-10-29 17:26:51 +01:00
Maurice fe24dd03c5 fix(journey): number map stops the same way in the journal and on the share link
The share link has counted its map stops through the whole journey since
#1962, while the owner's journal still restarted the count every day, so
the same stop read 66 on the link and 6 in the journal.

Both views now take their stops from one helper, journeyMapStops: located,
non-skeleton entries in the server's reading order (date, sort_order, id),
numbered across the journey. A draft keeps its pin in the journal but gets
no number, so the published stops after it carry exactly the numbers the
share link shows. The public entry query gains the id tiebreak the owner
query already had, so entries sharing a sort_order come back in the same
order on both sides.

Closes #2886
2026-10-29 17:26:51 +01:00
Maurice 66bff5c342 fix(journey): drop the entry connection where a recorded day shows the way
The journey map joins every located entry with a faint dashed line in the
order of its pins. It drew that line through everything, also across days
whose real route is on the map as a kept recording or the live Dawarich
trail, so straight guesses fanned out over the recorded track. The phone
has no layer switches, so the line could not even be hidden there.

A recorded track now carries the day it belongs to (an optional `date` on
the track contract, set by every builder of recorded lines: kept days, the
shared page's recordings, the live Dawarich trail and the day import
preview). A pure model splits the connection into the stretches still open
and those whose days were all recorded, the night between two recorded days
included. Both renderers draw only the open stretches with the entries; the
covered ones sit on a layer of their own that shows while the reader hides
what was recorded, so the guess comes back exactly where nothing else
explains the way.

The live trail is now matched to a kept day by that date instead of reading
the track name as one.

Closes #2888
2026-10-29 17:26:50 +01:00
Maurice 55b11f792a fix(journey): keep map photo and mark clusters stable while panning
The journey map grouped its photo thumbnails and its plan and stay marks
on a grid laid over container pixels. Every pan shifted that grid against
the map, so photos near a cell edge changed groups after each move: the
count badges jumped and the thumbnail switched to another photo, although
the zoom never changed.

Both renderers now bucket in world pixels at the current zoom, Leaflet
through its own CRS (so GCJ-02 basemaps stay right) and GL through a
plain Web Mercator projection that ignores centre, bearing and pitch.
Panning keeps every group as it is; only a zoom regroups.

Closes #2889
2026-10-29 17:26:50 +01:00
Maurice e8fbba236d refactor(bookings): hand the notes and link to the shared lower part as form fields
The booking and transport dialogs each spelled out the notes and the link
as four value and change props, and with the saving flag the two calls
became one copied block. The shared lower part now takes the form and its
setter, as the dialogs hold them, and writes the two fields itself.
2026-10-29 15:50:09 +01:00
Maurice 97455da6ca test: type the follow-up steps and the Atlas visit filter as they are used
The editor follow-up always hands the planner an afterSave, and its type now
says so, so the hook test calls it under strictNullChecks. The travel stats
test reads a country without a status as visited, as the standing helper
does for the hand-marked list. The client baseline holds the one non-null
assertion the count missed.
2026-10-29 15:36:37 +01:00
Maurice 2a51a1a842 test: hold the branch's tests to the type and lint gates
The booking save helper answers a Reservation the way the dialogs' onSave
does, and takes the payload the sheets read back. The export tests resolve
their routing promise without non-null assertions, the autocomplete test
reads its own console spy, and the Photon tally test asks its five dropped
questions together instead of awaiting in a loop. The Photon address line
falls back to empty when a feature has none.

The repair test now expects the dashboard to place the cleared beach in
Germany through the borders, as the Atlas map does since #2875. The client
lint baseline follows the counts this branch lowered.
2026-10-29 15:24:49 +01:00
Maurice 724857fc73 docs(atlas): say what the country resolver costs the dashboard, and why
The resolver's comment claimed the places of a city trip share their
coordinates, which they do not. It now says what an uncached place costs
per count and why the dashboard does not queue the Atlas region lookup:
that lookup falls back to Nominatim, and a dashboard load must not send a
user's places to a third party.

The #2875 cases continue the file's AUTH-DB numbering.
2026-10-29 15:11:39 +01:00
Maurice 28a577df5e fix(maps): keep a slow Photon from holding back the suggestions
The suggestions waited for Photon beside the index for up to its full
2.5 s deadline on every keystroke, and their misses and spent allowance
paused Photon for the search and the reverse lookup as well.

Once the index has answered, Photon now gets 300 ms more and is then
called off; with nothing from the index it is still waited for. The
keystroke question has a shorter deadline and its own tally of misses and
pauses, a question called off by the list counts as no miss, and a pause
of the search still holds the suggestions back.

Refs #2877
2026-10-29 15:11:39 +01:00
Maurice 64f370fd0e fix(pdf): give up a routing export once its dialog or sheet is gone
A PDF of a long trip routes for minutes, and only the skip button could
stop it. Closing the export dialog, hiding the phone sheet or leaving the
trip left the legs going out and opened the document later on whatever
page the user was on. Closing now stops the routing and the document never
opens; skipping still prints without the remaining legs.

The plan filter moves from TripPDF to pdfScope beside the other plan
predicate, which keeps TripPDF under its size entry. The routing test name
gets its quotes back, and the export dialog and sheet tests cover the leg
count, the skip button and closing while routing.
2026-10-29 15:11:32 +01:00
Maurice 00ac889139 fix(bookings): add the next imported booking instead of writing over the last one
The follow-up kept the booking a save stored until the editor session
changed, and on the phone the session was only the open flag. The import
review swaps the draft without closing the sheet, so the second booking of
the same kind went out as an update of the first and lost its linked cost.

The stored booking now lives only as long as a failed try needs it, and
the phone sheets name their session the way the desktop dialogs do, by the
booking or draft they hold. The sheets also seed their form from that
session, so the next draft of the review shows its own fields.

The follow-up hook gets its own test, the notes block test passes the
saving flag the component now takes, and the swallowed-catch baseline
follows the one catch the save merge removed.
2026-10-29 15:11:25 +01:00
Maurice 9ab2fc30ff fix(atlas): count a place's country on the dashboard the way the Atlas map does
The passport card and the last/next trip countries read place countries
from the place_regions cache alone, while the Atlas map falls back to the
bundled borders for a place without a cached region. A place in Vatican
City never gets a region row (the region bundle has no VA features and
Nominatim names no region there), so the map counted VA and the card did
not. The same gap hid any country whose place was still waiting for its
background lookup, or whose lookup had failed.

Both views now resolve each place through one helper: the cached country
first, the borders otherwise, once per location. The dashboard reads every
place of a started trip with its cached country instead of the distinct
cached codes, and the trip countries count resolved places the same way.
The MCP travel stats tool and the public stats API use the same service
methods and are fixed with it.

Closes #2875
2026-10-29 14:52:47 +01:00
Maurice 3238fbc517 fix(pdf): route every leg of the trip map and mark what is left unrouted
The PDF export routed the whole trip under an 8 s deadline while the router
is asked one leg at a time, a second apart. A cold month-long trip got about
seven legs routed per export; the rest printed as straight lines at "0 m"
under a total that looked final, and every further export routed a few more
days from the device cache.

The export now waits for every leg, bounded by the request pacing, the
rate-limit retries and a per-leg timeout. The export dialog and the phone
sheet count the legs while they route and offer to print without the rest.
Any leg left without a road is marked in the document: the day reads "not
routed" or "at least ...", the total says it is a floor, and a note names
how many legs are missing. The planner overview shares the same wording.

The PDF also routes what the planner map routes now: the road trip's vias,
the multi-day tour stages and the reader's distance unit.

Closes #2876
2026-10-29 14:48:13 +01:00
Maurice c03c40d287 fix(mobile): line the day rail up on today once the trip splash lifts
The opening day is seeded while the loading splash still covers the shell,
so the rail's auto-scroll ran before any chip existed and never ran again:
its dependencies did not change when the rail first mounted. A trip opened
mid-way showed today's day below a rail stuck at day 1.

The rail element is now a dependency of the alignment, so the active chip
is brought into view when the rail appears, including after re-entering
the trip. The first alignment jumps instead of gliding across a rail
nobody has seen yet, and runs before paint; later day changes still glide.

Closes #2880
2026-10-29 14:28:22 +01:00
Maurice b06e3e6266 fix(bookings): keep the editor open until a booking's files are uploaded
Saving a booking or a transport closed the editor and reported success
before the travellers and picked files were written. A failed upload left
a booking without some of its PDFs, no list to retry from, and a create
form that would add a duplicate when saved again. On desktop a file picked
on an existing booking went up at once and vanished when that failed.

The planner's save now takes the editor's follow-up as a step it waits
for: it stores the booking, runs the traveller write and the uploads, and
only then says so and closes. Each file that lands leaves the list, so a
failure leaves exactly the files still to send, and the editor keeps the
stored booking so the retry updates it instead of creating another one,
without a second linked cost or stay. All four editors (desktop booking
and transport dialogs, both phone sheets) share this through
useBookingFollowUp, an import review only moves on once an item's files
are up, and desktop files picked on a saved booking wait for Update like
on the phone.

Closes #2883
2026-10-29 14:20:57 +01:00
Maurice 7d669cb5c3 feat(maps): ask Photon beside the index for search-as-you-type suggestions
The suggestion list asked only the TREK index and its OpenStreetMap layer,
because Nominatim's usage policy rules out autocomplete. The layer is a slice
of OpenStreetMap, so many places showed up only once the full search was sent
(#2877). Photon is built for this keystroke: the suggestions now ask it in
parallel with the index and interleave its rows, dropping any the list
already holds, by OSM id or by the search list's same-place rule.

Without Photon (services off, an operator's own Nominatim, a paused or failed
answer) the list reads exactly as before. A failing index no longer throws
away what Photon found, and the Google-only switch skips Photon as it skips
the index.

Refs #2877
2026-10-29 13:50:37 +01:00
Maurice 81b3657528 fix(mcp): name the tuple check for what it holds, describe a restored map point as [lat, lng]
MCP-SCHEMA-005 finds tuple keywords, it does not validate against the 2020-12 metaschema, so the name now says that. A restored map point lost its range and order to the tuple fix; the description keeps the order visible to a model that builds a page itself.
2026-10-29 13:49:41 +01:00
Maurice 6f4d7d9066 fix(mcp): keep restore_book_page free of tuples so ChatGPT accepts the tool list
With the Journey addon on, ChatGPT refused every TREK tool: restore_book_page
took a map's path and roads as [lat, lng] tuples, which the SDK writes as the
draft-07 array form of items, and JSON Schema 2020-12 refuses that form.

The restore now takes a map point as two numbers and parses each page as a
spread before it is put back, so lat and lng stay checked and a point out of
range is an invalid_op instead of a thrown parse. MCP-SCHEMA-005 holds every
tool's input schema free of tuple keywords.

Closes #2879
2026-10-29 13:45:53 +01:00
Maurice 00684f4202 chore(client): lower the complexity baseline to the 219 the source holds 2026-10-29 13:34:28 +01:00
Maurice c4a39171f2 fix(client): narrow the route profile and Valhalla answer types, keep the stop check reading the whole log
The built-in profile check returned the open profile key and the run request
returned an unnarrowed answer, both of which the client typecheck refused. The
new road trip tests asserted with non-null assertions where optional calls do.

The graceful stop step piped docker logs into grep -q under pipefail, so grep
leaving early after its match could fail the step with SIGPIPE although the
server had logged SIGTERM.
2026-10-29 13:34:28 +01:00
Maurice 10e0e59c3f fix(server): keep no OSRM stand-in for a day the TREK Valhalla routes
A road trip day OSRM drew while the relay could not answer was cached for five
minutes, and a key added or removed kept serving the old engine's answer. The
stand-in is no longer cached and the key's availability is part of the cache
key. A walk kept off the boats may still go to FOSSGIS, which is now said and
tested.
2026-10-29 13:34:28 +01:00
Maurice e3a8c6fb8a fix(server): tell a user over the routing allowance when to ask the relay again
The per-user 429 carried no Retry-After, so the planner left the relay alone for
its full ten minutes and routed every day with OSRM meanwhile. It now answers
like the installation limit does, with the minute the window takes.
2026-10-29 13:34:28 +01:00
Maurice 7dc313c567 fix(maps): say which engine drew a day and keep Valhalla days found while the relay rests
The route cache key followed the relay's rest, so after one failed relay request
(always the case offline) every day the device held only from Valhalla missed
the cache for ten minutes. The key now follows the configured provider, and a
resting relay only stops the question from going out.

A route now names the engine that drew it. A day OSRM drew because Valhalla
could not answer is OSRM's on the rail, and its other ways are asked of OSRM,
instead of being labelled Valhalla's and compared with Valhalla offers.

An own Valhalla gets the relay's twelve second deadline, and a day that runs it
out goes to OSRM without a second wait. A day that avoids something keeps its
old cache key, so the days a device already holds stay found. The leg segment
and the offer types move to modules both engines import.
2026-10-29 13:34:28 +01:00
Maurice e3f542c8b7 docs(wiki): describe Valhalla routing every day and OSRM taking over a day it cannot answer 2026-10-29 13:34:28 +01:00
Maurice ba6428d7f1 feat(admin): say that the routing service calculates every route with OSRM taking over
The hint under Routing service now explains that the TREK services and an
own Valhalla calculate every route, that OSRM calculates a day they cannot
answer, and that FOSSGIS keeps Valhalla to what OSRM cannot do. In all 27
languages.
2026-10-29 13:34:28 +01:00
Maurice 29dc967d29 feat(server): route the road trip days through Valhalla on the server as the planner does
Where the TREK services or an own Valhalla route the days, the MCP road trip
router asks Valhalla for a day that avoids nothing, through the relay alone,
and OSRM routes the whole day when it cannot answer. Requests carry twenty
locations unless they may end up at FOSSGIS, which keeps ten.
2026-10-29 13:34:28 +01:00
Maurice 8fd025e003 feat(client): route every day through Valhalla where the TREK services or an own Valhalla answer
With the TREK services or an own Valhalla, the day plan, the road trip and
the other ways of a leg are routed by Valhalla on foot, by bike and by car,
twenty locations a request. A day it cannot answer (relay refusal, time out,
no way for a leg) goes to OSRM whole and without a word; it is never handed
to FOSSGIS unless it avoids something only Valhalla can avoid. With FOSSGIS
nothing changes: OSRM routes the days and Valhalla the avoidances.

A Valhalla answer is cached under its own key beside the OSRM one, so
switching engines never serves a day from the other engine. The Valhalla
day routing moves out of RouteCalculator into valhallaDayRoute.ts.
2026-10-29 13:34:28 +01:00
Maurice ec8df01f85 feat(shared): name the Valhalla costing of each profile and the providers that route every day
VALHALLA_COSTING maps driving, walking and cycling to auto, pedestrian and
bicycle once for the planner and the server. valhallaRoutesEveryDay says
whether the resolved provider carries every day: the TREK services and an
own Valhalla do, FOSSGIS and no Valhalla leave the days to OSRM.
2026-10-29 13:34:28 +01:00
Maurice 79260ad737 fix: name the routing and allowance labels where the key check finds them and keep the new tests within the lint baselines 2026-10-29 13:34:28 +01:00
Maurice 0426ce7f01 docs(server): name TREK_PHOTON_URL in the services config and the alternates limit of the TREK Valhalla 2026-10-29 13:34:28 +01:00
Maurice f76b8d5d9c fix(server): put a Photon house number before its street as Nominatim does 2026-10-29 13:34:28 +01:00
Maurice 8c11833fb1 fix(server): ask Nominatim when Photon finds nothing and keep bulk lookups off Photon
An empty Photon search, or one without a hit that has an OpenStreetMap id, is asked again at Nominatim as the reverse lookup already was. The background lane goes to Nominatim alone, a reverse lookup leaves Nominatim half of the caller's deadline, and a 429 with Retry-After pauses Photon for that long.
2026-10-29 13:34:28 +01:00
Maurice 45727b3d3b fix(client): ask FOSSGIS when the routing relay times out, refuses the body or is missing
A route or height question through the relay now gives up after 12 s. A 400 without Valhalla's error_code and a 404 or 405 count as the relay unable to answer instead of no way or no Valhalla, and a Retry-After sets how long the tab leaves the relay alone.
2026-10-29 13:34:28 +01:00
Maurice 686592437a fix(server): rest the routing relay after a failure and keep it under the installation's minute
A hung TREK Valhalla cost every leg, height chunk and trace the full 30 s before FOSSGIS answered. The relay now waits 10 s for a route or heights, rests a minute after an error or timeout and answers 503 at once meanwhile, follows a 429's Retry-After (an hour at most), passes that header on to the browser, and holds the installation to 100 questions a minute below the gate's 120 (60 per user).
2026-10-29 13:34:28 +01:00
Maurice 1da7d0627a fix(server): judge the address search in the admin status by TREK_PHOTON_URL and an own NOMINATIM_URL
The status asked a fixed Photon origin and compared NOMINATIM_URL with the public address, so a moved Photon or an explicitly set public Nominatim showed the wrong service as in use. It now reads the same photonUrl and nominatimOwn the Photon client decides by. TREK_VALHALLA_URL joins the commented compose variables.
2026-10-29 13:34:28 +01:00
Maurice bc62eb0d6f feat(admin): show the allowance of place search, address search and routing in the TREK API card
GET /api/admin/service-identity lists places, photon and valhalla, each with
today's allowance read fresh from /v1/quota of its own host (cached for 20
seconds per host) and whether this instance asks it right now: Photon only
beside the public Nominatim, the TREK Valhalla only where the routing choice
comes to it. Photon and Valhalla are asked only with a key and only while
TREK_SERVICES_HOSTS lists them. The last allowance an answer stated is kept
per host for when a host does not answer.

The card lists the three services under each other in the look it had,
a service this instance does not ask dimmed and named as such.
2026-10-29 13:34:28 +01:00
Maurice 091ebed8e4 feat(routing): let the admin pick FOSSGIS, the TREK services or an own Valhalla
routing_valhalla_provider (fossgis, trek or custom) sits beside the routing
URLs under Admin, Default user settings, admin only and locked on a managed
install. Without a choice an own Valhalla is custom, an own OSRM alone asks
no Valhalla, and otherwise the TREK services answer.

The planner asks them through the same-origin relay, so no connect-src
changes. A relay that answers 401 (a shared page without a sign-in), 403,
413, 429 or 5xx sends the question to FOSSGIS without a word and is left
alone for ten minutes. A long line to describe goes as a polyline.
2026-10-29 13:34:28 +01:00
Maurice 80183bc986 feat(server): relay Valhalla routing to the TREK services with the installation key
POST /api/routing/valhalla/route, /trace_attributes and /height ask the
Valhalla at TREK_VALHALLA_URL (default https://valhalla.liketrek.com) for a
signed-in user. The body is held to the shared contract (64 KB, at most 20
locations), every question counts against 120 a minute per user, and the
installation key goes along only to a host TREK_SERVICES_HOSTS lists.
Valhalla's answer is passed on as it came, refusals included.

The road trip router asks the same relay when the routing choice lands on
the TREK services, so the MCP road trip, city walk and hike tools share its
limits, and hands a question it cannot answer to FOSSGIS.
2026-10-29 13:34:28 +01:00
Maurice 250a7d4eb7 docs(wiki): describe the Photon address search and TREK_PHOTON_URL 2026-10-29 13:34:28 +01:00
Maurice 256f8c08e2 feat(server): ask the TREK services' Photon before Nominatim for search and reverse lookups
An installation that holds a key for the TREK services and has no
NOMINATIM_URL of its own now sends the OpenStreetMap search and the
reverse lookups to photon.liketrek.com first. The answers are read into
Nominatim's shape, so the place records stay the same, and every miss
(refused key, allowance spent, timeout, error, foreign body) falls back
to Nominatim, with a one minute pause after four misses in a row.

TREK_PHOTON_URL points at another copy, and the default of
TREK_SERVICES_HOSTS now lists photon.liketrek.com and
valhalla.liketrek.com beside places.liketrek.com.
2026-10-29 13:34:28 +01:00
Maurice 4ab3244f8f fix(server): mark the identity reset as writing its new key on its own
Regenerating clears the stored key at once and writes the new one only after the issuer answered in the background, so the two writes cannot share a transaction.
2026-10-29 13:34:28 +01:00
Maurice cb546e4a72 refactor(server): move the identified Places request into a file of its own
The instance token and the request that carries the installation key leave trek-places.client.ts, which had grown past the 1000-line limit.
2026-10-29 13:34:28 +01:00
Maurice eeae904867 fix(server): solve the proof of work and read the revocation notice without awaiting in a loop
The proof of work and the bounded read of a 403 body recurse instead of looping, the background-work checks compare against null instead of testing a promise, and the tests repeat their requests through oneByOne. The renewal test loads the stored key before its first request, and the panel test picks the last confirm button without Array.prototype.at.
2026-10-29 13:34:28 +01:00
Maurice 414a7ad98f fix(server): fetch a refused registration challenge once more instead of backing off 2026-10-29 13:34:28 +01:00
Maurice 58e006cfd9 docs(wiki): say that requests are counted per installation and per network 2026-10-29 13:34:28 +01:00
Maurice 476dbef7dc fix(server): renew service keys on the next request and stop sending expired ones
An expired key is no longer sent; the request goes through the shared pool
while a due key, or an expired one within its grace, is renewed in the
background. Refusals in one burst count once, a refused renewal counts like
a refused search, and a Places request whose key is refused is sent once
more without it.
2026-10-29 13:34:28 +01:00
Maurice b53751344b fix(server): ask the issuer for the allowance of a key only when TREK_SERVICES_HOSTS lists it 2026-10-29 13:34:28 +01:00
Maurice 01c0f8b64c fix(server): rotate the stored service key with ENCRYPTION_KEY and pin every encrypted app setting 2026-10-29 13:34:28 +01:00
Maurice 44add57109 fix(client): hide the new identity action on a managed install 2026-10-29 13:34:28 +01:00
Maurice afacf00c9f docs: document TREK_SERVICES, TREK_SERVICES_KEY and the daily allowance
docker-compose.yml and the Helm chart name the switch and the key (the key in the Secret, never the ConfigMap), and the wiki explains the installation key, what it carries, where it goes and the admin view of the allowance.
2026-10-29 13:34:28 +01:00
Maurice baf69da27f feat(client): show the TREK services allowance on the TREK API card
A calm panel under the card's facts: a dot with the state, the tier, a bar of today's use against the limit, what is left and the local time the count starts again. It reads when the card comes into view and every 30 seconds while it stays there and the tab is in front, says why when the services are off, revoked or cannot be read, and offers a new identity behind a confirmation unless the key comes from the environment.
2026-10-29 13:34:28 +01:00
Maurice 01ae91c939 feat(server): give each installation a key for the TREK services and report its allowance
A new service-identity domain registers the installation with places.liketrek.com on its first Places request, in the background and behind a light scrypt proof of work, keeps the key encrypted in app_settings, renews it from day 60 through a daily job, drops it after three 401s in a row with up to six hours of jitter, and freezes it on a revocation until an admin starts over. TREK_SERVICES_KEY wins and turns registration off; TREK_SERVICES=off sends no key; a mirror set with TREK_PLACES_URL never registers and never sees the key, which goes only to the hosts in TREK_SERVICES_HOSTS over https.

The Places client takes its headers from the identity port, sends a TREK/<version> User-Agent and keeps the instance token. A 401 or 403 does not open its breaker. GET /api/admin/service-identity reports the state, tier and today's allowance, asking the issuer at most every 20 seconds; POST .../regenerate starts a new identity.
2026-10-29 13:34:28 +01:00
Maurice f19f0a33b2 feat(shared): add the service identity contract and the allowance texts of the TREK API card
Zod schemas for what the key issuer answers (challenge, key grant, quota) and for GET /api/admin/service-identity. The card no longer claims there is no quota: every locale now says there is no key to enter, a fair daily allowance per installation, and that only the number of requests is counted.
2026-10-29 13:34:28 +01:00
Maurice e5fc735e13 docs(readme): close the gap above the sponsor line 2026-10-29 11:38:54 +01:00
Maurice d2ec9eabde docs(readme): describe TREK as the trip ecosystem it has become 2026-10-29 11:38:54 +01:00
Maurice 9128039c38 docs(readme): let the four status badges continue the badge row 2026-10-29 11:38:54 +01:00
Maurice dd6f41f768 docs(readme): give the license, release, pulls and stars badges the style of the row above 2026-10-29 11:38:54 +01:00
Maurice 1a73b22810 docs(readme): show the TREK logo alone at the top 2026-10-29 11:38:54 +01:00
Maurice c1d413f31a docs(readme): set the sponsor logo right under its line and the server hint right under the button 2026-10-29 11:38:54 +01:00
Maurice 8316119293 docs(readme): thank dataforest cloud as infrastructure sponsor, drop the third showcase and the star history 2026-10-29 11:38:54 +01:00
Maurice 74abaa9d7c test(unsplash): check both refusals without awaiting in a loop 2026-10-28 16:30:54 +01:00
Maurice 091505d17c fix(unsplash): tell a server Unsplash turns away that the free key helps
Without an Access Key the image search goes through Unsplash's web endpoint,
which refuses datacenter addresses with a 401 or 403 or answers with a
challenge page. The search then said only "Unsplash search unavailable",
although an admin can already enter a free key in the settings. Such a
refusal now answers 502 with that hint and the code unsplash_key_needed, and
the cover search shows it in the user's language.

Closes #1449
2026-10-28 16:30:54 +01:00
Maurice aee275e2b0 fix(places): read an imported row for the dedup set in one helper
The candidate a GPX or KML row is checked as is built in lineCandidate, so
places.service.ts stays within its size baseline, and the atomic import test
imports the same Ridge line it later expects to be skipped.
2026-10-28 15:43:52 +01:00
Maurice ef86bf2660 fix(places): keep two different tracks of the same name apart on import
Two GPX tracks a watch named alike (two "Afternoon Hike"s) were taken for one:
the import compared a track only by its name, so the second was skipped as
already in the trip. A track now matches a track of that name only when it
also starts, ends and reaches as far as that one, to about a hundred metres,
so the same file imported again is still skipped. The GPX, KML and tour
imports and the tour preview all read the same rule.

Closes #2870
2026-10-28 15:43:52 +01:00
Maurice 0139c46fb4 test(i18n): count the new planned total key in the tours locales 2026-10-28 15:18:07 +01:00
Maurice a0a7fcdbb9 fix(tours): say why a tour over a day cannot be saved
A tour whose walking time and breaks came to more than 24 hours a stage
only greyed out Save, with nothing saying why. The planner now marks the
planned total and says what to do: make it a multi-day tour by ending a
stage at a stop, or enter a shorter planned total. The details section
opens by itself so the reason is in sight.

Closes #2869
2026-10-28 14:52:01 +01:00
Maurice 186dd94b61 fix(assistant): chat with an own server entered without /v1 at /v1
The assistant sent an own server's chat to the address as entered plus
/chat/completions. Ollama, entered as http://host:11434 the way its own docs
write it, answers that with a 404, so every message ended in "something went
wrong" while connecting had worked: the model list is found under the root
at /api/tags. A bare server address now chats under /v1, where Ollama, LM
Studio, vLLM, llama.cpp and LiteLLM all answer; an address with a path, such
as https://api.groq.com/openai/v1, is used as entered.
2026-10-28 12:17:54 +01:00
Maurice ad721a1ac6 test(studio): the auto layout lays out a long journey whole 2026-10-28 12:26:06 +01:00
Maurice 87441f269d fix(studio): lay out a book as long as its journey, with no page limit
A book held at most 150 spreads. The auto layout cut everything past that
without a word, so a long journey's book ended about three quarters of the
way through, with its last page and back cover gone, and adding, copying or
applying a designed page to a full book was refused.

The spread cap is gone from the book schema, the page operations, the
design composer and its apply, the assistant's book card and the design tool
contracts. A design's own page budget (pages.max) still bounds what it lays
out. The save route's 8 MB body still bounds a book's size, which at two to
five kilobytes an auto laid page is a few thousand pages.

The templated design digests move because their counter ids shift by two;
the pages, their order and their elements are unchanged.
2026-10-28 12:06:50 +01:00
github-actions[bot] a0943f8226 chore: bump version to 5.0.1 [skip ci] 2026-10-28 10:43:52 +00:00
1259 changed files with 63754 additions and 4857 deletions
+1
View File
@@ -1,6 +1,7 @@
node_modules
client/node_modules
server/node_modules
shared/node_modules
client/dist
shared/dist
data
@@ -14,7 +14,7 @@ jobs:
timeout-minutes: 45
steps:
- name: Close stale invalid-title issues
uses: actions/github-script@v8
uses: actions/github-script@v9
with:
script: |
const badTitles = [
@@ -15,7 +15,7 @@ jobs:
timeout-minutes: 45
steps:
- name: Close stale wrong-base-branch PRs
uses: actions/github-script@v8
uses: actions/github-script@v9
with:
script: |
const { data: pulls } = await github.rest.pulls.list({
+1 -1
View File
@@ -14,7 +14,7 @@ jobs:
timeout-minutes: 45
steps:
- name: Flag or redirect issue
uses: actions/github-script@v8
uses: actions/github-script@v9
with:
script: |
const title = context.payload.issue.title.trim();
+66 -3
View File
@@ -5,6 +5,13 @@ name: Build & Push Docker Image (Prerelease)
# :latest-pre, and tags the commit. Nothing moves :latest. Like the stable
# release it refuses a commit whose ci-ok is not green. docker.yml with
# bump=auto later finalizes the line once main carries it.
#
# A prerelease asks the TREK services issuer for a registration dialect of its
# own -pre.N version (registration-dialect.yml, as the stable release does)
# and builds it into the image; nothing of it is committed, dev keeps the
# module of the last stable release, which it gets when main is merged back
# into dev. Without one the image carries dev's module, with a warning when
# that is the original one or old.
on:
workflow_dispatch:
@@ -89,10 +96,23 @@ jobs:
echo "VERSION=$NEW_VERSION" >> "$GITHUB_OUTPUT"
echo "$STABLE to $NEW_VERSION"
# The registration dialect of this prerelease, fetched and checked in a job
# without write access. It never fails the build.
dialect:
needs: version-bump
uses: ./.github/workflows/registration-dialect.yml
with:
version: ${{ needs.version-bump.outputs.version }}
ref: ${{ needs.version-bump.outputs.sha }}
secrets:
TREK_DIALECT_TOKEN: ${{ secrets.TREK_DIALECT_TOKEN }}
build:
runs-on: ${{ matrix.runner }}
timeout-minutes: 120
needs: version-bump
needs: [version-bump, dialect]
# Whatever became of the dialect job: without its artifact the image carries dev's module.
if: ${{ !cancelled() && needs.version-bump.result == 'success' }}
strategy:
fail-fast: false
matrix:
@@ -111,9 +131,51 @@ jobs:
with:
ref: ${{ needs.version-bump.outputs.sha }}
- name: Take over the prerelease's dialect
id: take
uses: actions/download-artifact@v7
continue-on-error: true
with:
name: registration-dialect
path: ${{ runner.temp }}/dialect
# Into the build context only; the commit stays as it is. Without a
# dialect of its own the image speaks dev's module, which the issuer
# takes for new installations for 180 days after it was made (longer
# while it is the newest stable release's). That is warned about, never
# stopped on, and a date that cannot be read only warns as well.
- name: Place the dialect
env:
VERSION: ${{ needs.version-bump.outputs.version }}
TAKEN: ${{ steps.take.outcome }}
REPORT: ${{ matrix.platform == 'linux/amd64' }}
run: |
set -u
target=server/src/nest/service-identity/registration-dialect.ts
fetched="$RUNNER_TEMP/dialect/registration-dialect.ts"
if [ "$TAKEN" = success ] && [ -f "$fetched" ]; then
cp "$fetched" "$target"
echo "$VERSION registers in dialect $(sed -n "s/^const DIALECT = '\(.*\)';$/\1/p" "$target") of its own."
exit 0
fi
[ "$REPORT" = true ] || exit 0
id="$(sed -n "s/^const DIALECT = '\(.*\)';$/\1/p" "$target")"
created="$(sed -n "s/^ createdAt: '\(.*\)',$/\1/p" "$target")"
if [ "$id" = 0 ]; then
message="$VERSION got no dialect of its own and registers in the original one, which the issuer accepts only for a transition period."
elif made="$(date -u -d "$created" +%s 2>/dev/null)"; then
age=$(( ($(date -u +%s) - made) / 86400 ))
message="$VERSION got no dialect of its own and registers in dev's dialect $id from $created, $age days old."
[ "$age" -gt 150 ] || { echo "$message"; exit 0; }
else
message="$VERSION got no dialect of its own, and the date of dev's dialect cannot be read from $target."
fi
echo "::warning::$message"
printf '### Registration dialect\n%s\n' "$message" >> "$GITHUB_STEP_SUMMARY"
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
- uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
- uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
@@ -156,6 +218,7 @@ jobs:
runs-on: ubuntu-24.04
timeout-minutes: 120
needs: [version-bump, build]
if: ${{ !cancelled() && needs.build.result == 'success' }}
steps:
- uses: actions/checkout@v6
with:
@@ -173,7 +236,7 @@ jobs:
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
- uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
- uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
+182 -23
View File
@@ -2,17 +2,29 @@ name: Build & Push Docker Image
# The stable release. Dispatched by hand on main, it:
# 1. refuses to run unless ci-ok passed on the main commit it releases,
# 2. works out the version from the tags and the bump input, commits the
# bump to package.json, the lockfile and Chart.yaml, tags it and pushes,
# 3. builds both platforms from exactly that bump commit (never from
# 2. works out the version from the tags and the bump input,
# 3. asks the TREK services issuer for the registration dialect of that
# version and checks it, in a job without write access
# (registration-dialect.yml); without one the release ships the dialect
# already on main, but only while that one still has 90 days to run,
# 4. commits the bump to package.json, the lockfile, Chart.yaml and the
# dialect, tags it and pushes,
# 5. builds both platforms from exactly that bump commit (never from
# whatever main points to by then) and publishes :VERSION,
# :MAJOR.MINOR, :MAJOR and :latest,
# 4. publishes the Helm chart from the same commit.
# 6. publishes the Helm chart from the same commit.
#
# Big or risky changes go out as a prerelease first (docker-dev.yml, tagged
# :latest-pre and :<next>-pre.N); bump=auto here then finalizes that line.
# Without a prerelease in flight there is no default: the run stops until
# someone picks patch, minor or major.
#
# Each stable release registers new installations in a dialect of its own,
# which the issuer accepts for 180 days, and for as long as it is the newest
# release's; renewing a key needs none. dev gets the module when main is merged
# back into dev after the release; a prerelease asks the issuer for one of its
# own (docker-dev.yml). The issuer's side, and what to set up before the first
# release with a dialect, is in the operations guide of the TREK services.
on:
workflow_dispatch:
@@ -26,6 +38,14 @@ on:
description: "Type MAJOR (all caps) to confirm a major release"
type: string
default: ''
ci_from:
description: 'Take ci-ok from this earlier commit instead of the one on main, when main differs from it only under .github/ (a fix to a release workflow needs no second test run)'
type: string
default: ''
allow_stale_dialect:
description: 'Ship without a dialect of its own even if the one on main is the original one or has under 90 days left'
type: boolean
default: false
permissions:
contents: write
@@ -36,13 +56,16 @@ concurrency:
cancel-in-progress: false
jobs:
version-bump:
version:
if: github.repository == 'liketrek/TREK'
runs-on: ubuntu-24.04
timeout-minutes: 120
timeout-minutes: 30
permissions:
contents: read
checks: read
outputs:
version: ${{ steps.bump.outputs.VERSION }}
sha: ${{ steps.bump.outputs.SHA }}
base: ${{ steps.base.outputs.SHA }}
steps:
- name: Release from main only
if: github.ref != 'refs/heads/main'
@@ -50,17 +73,17 @@ jobs:
echo "::error::Dispatch this workflow on main, not on $GITHUB_REF."
exit 1
- uses: actions/create-github-app-token@v3
id: app-token
with:
app-id: ${{ secrets.RELEASE_APP_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
- uses: actions/checkout@v6
with:
fetch-depth: 0
fetch-tags: true
token: ${{ steps.app-token.outputs.token }}
persist-credentials: false
# The bump job checks out exactly this commit, so what ci-ok was checked
# on is what gets released, however long the dialect takes.
- name: Note the commit being released
id: base
run: echo "SHA=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
# The dev push, the main push and any manual run each leave a ci-ok on
# this commit. scripts/ci/ci-ok-verdict.mjs counts the newest attempt of
@@ -68,6 +91,7 @@ jobs:
# finished last to be green, so a later green run supersedes a flaky or
# cancelled one. It prints the link of every run it counted.
- name: Require a green ci-ok on the commit being released
if: inputs.ci_from == ''
env:
GH_TOKEN: ${{ github.token }}
run: |
@@ -77,14 +101,43 @@ jobs:
gh api "repos/$GITHUB_REPOSITORY/commits/$sha/check-runs?check_name=ci-ok&filter=all&per_page=100" > "$runs"
node scripts/ci/ci-ok-verdict.mjs "$runs" "$sha"
- name: Determine bump type and update version
# ci_from: main carries only workflow changes on top of a commit that
# already passed. That commit must be an ancestor of main, everything
# outside .github/ must be identical, and one of its ci-ok runs must be
# green (its dev push, typically).
- name: Require a green ci-ok on the commit main's code comes from
if: inputs.ci_from != ''
env:
GH_TOKEN: ${{ github.token }}
CI_FROM: ${{ inputs.ci_from }}
run: |
set -euo pipefail
from="$(git rev-parse --verify "$CI_FROM^{commit}")"
if ! git merge-base --is-ancestor "$from" HEAD; then
echo "::error::$from is not an ancestor of main."
exit 1
fi
outside="$(git diff --name-only "$from" HEAD -- . ':(exclude).github/**')"
if [ -n "$outside" ]; then
echo "::error::main differs from $from outside .github/:"
echo "$outside"
exit 1
fi
green="$(gh api "repos/$GITHUB_REPOSITORY/commits/$from/check-runs?check_name=ci-ok&filter=all&per_page=100" \
--jq '[.check_runs[] | select(.status == "completed" and .conclusion == "success")] | length')"
if [ "$green" -lt 1 ]; then
echo "::error::$from has no green ci-ok."
exit 1
fi
echo "main differs from $from only under .github/, and $from has $green green ci-ok run(s)."
- name: Determine bump type and version
id: bump
env:
BUMP_INPUT: ${{ inputs.bump || 'auto' }}
CONFIRM_MAJOR: ${{ inputs.confirm_major }}
run: |
set -eu
git fetch --tags
# Derive version from git tags, no package.json dependency
STABLE_TAG=$(git tag -l 'v[0-9]*.[0-9]*.[0-9]*' | grep -v '\-pre\.' | sort -V | tail -1)
@@ -143,6 +196,107 @@ jobs:
echo "VERSION=$NEW_VERSION" >> "$GITHUB_OUTPUT"
echo "$STABLE to $NEW_VERSION ($BUMP)"
# The registration dialect of this version, fetched and checked in a job
# without write access. It never fails; without an artifact from it the
# bump decides below whether the dialect on main may ship.
dialect:
needs: version
uses: ./.github/workflows/registration-dialect.yml
with:
version: ${{ needs.version.outputs.version }}
ref: ${{ needs.version.outputs.base }}
secrets:
TREK_DIALECT_TOKEN: ${{ secrets.TREK_DIALECT_TOKEN }}
# Runs whatever became of the dialect job, a timeout or a lost runner
# included: no artifact means the dialect on main, if it may still ship.
version-bump:
needs: [version, dialect]
if: ${{ !cancelled() && needs.version.result == 'success' }}
runs-on: ubuntu-24.04
timeout-minutes: 120
outputs:
sha: ${{ steps.commit.outputs.SHA }}
steps:
- uses: actions/create-github-app-token@v3
id: app-token
with:
app-id: ${{ secrets.RELEASE_APP_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
- uses: actions/checkout@v6
with:
ref: ${{ needs.version.outputs.base }}
fetch-depth: 0
fetch-tags: true
token: ${{ steps.app-token.outputs.token }}
- name: Take over the checked dialect
id: take
uses: actions/download-artifact@v7
continue-on-error: true
with:
name: registration-dialect
path: ${{ runner.temp }}/dialect
# Without a dialect of its own the release ships the one on main, but
# only while the issuer takes new registrations in it for 90 more days:
# dialect 0 closes on the issuer's transition date, and a dialect with
# little left would shut out new installations of this release soon after
# it is out. Then this stops before anything is committed, unless
# allow_stale_dialect says to ship anyway. The issuer keeps the newest
# release's dialect open past its date, so the date here is the least it
# has, not the most.
- name: Place the dialect
env:
VERSION: ${{ needs.version.outputs.version }}
TAKEN: ${{ steps.take.outcome }}
ALLOW_STALE: ${{ inputs.allow_stale_dialect }}
run: |
set -u
target=server/src/nest/service-identity/registration-dialect.ts
fetched="$RUNNER_TEMP/dialect/registration-dialect.ts"
dialect_id() { sed -n "s/^const DIALECT = '\(.*\)';$/\1/p" "$1"; }
report() {
echo "$2$1"
printf '### Registration dialect\n%s\n' "$1" >> "$GITHUB_STEP_SUMMARY"
}
if [ "$TAKEN" = success ] && [ -f "$fetched" ]; then
cp "$fetched" "$target"
report "$VERSION registers in dialect $(dialect_id "$target"), written by the issuer for it." ""
exit 0
fi
id="$(dialect_id "$target")"
created="$(sed -n "s/^ createdAt: '\(.*\)',$/\1/p" "$target")"
left=""
if [ -n "$id" ] && [ "$id" != 0 ] && made="$(date -u -d "$created" +%s 2>/dev/null)"; then
left=$(( (made + 180 * 86400 - $(date -u +%s)) / 86400 ))
fi
if [ -n "$left" ] && [ "$left" -ge 90 ]; then
report "$VERSION ships without a dialect of its own and registers in dialect $id from $created, which the issuer takes for new installations for $left more days at least. Its operator can write one by hand for the next patch." "::warning::"
exit 0
fi
if [ "$id" = 0 ]; then
what="the original registration, which the issuer accepts only until the end of its transition period"
elif [ -n "$left" ]; then
what="dialect $id from $created, which has $left days left"
else
what="a dialect whose id or date cannot be read from $target"
fi
if [ "$ALLOW_STALE" = true ]; then
report "$VERSION ships without a dialect of its own and registers in $what, as allow_stale_dialect asked." "::warning::"
exit 0
fi
report "$VERSION got no dialect of its own and would register in $what. Nothing was committed or pushed. Make sure the issuer runs with its dialect seed and release token and that TREK_DIALECT_TOKEN is set, then run the release again, or tick allow_stale_dialect to ship anyway." "::error::"
exit 1
- name: Update the version, commit, tag and push
id: commit
env:
NEW_VERSION: ${{ needs.version.outputs.version }}
run: |
set -eu
# Update all workspace + root package.json files and the root lockfile in one shot
npm version "$NEW_VERSION" --workspaces --include-workspace-root --no-git-tag-version
sed -i "s/^version: .*/version: $NEW_VERSION/" charts/trek/Chart.yaml
@@ -153,7 +307,8 @@ jobs:
# landed on main in the meantime.
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git add package.json package-lock.json server/package.json client/package.json shared/package.json charts/trek/Chart.yaml
git add package.json package-lock.json server/package.json client/package.json shared/package.json \
charts/trek/Chart.yaml server/src/nest/service-identity/registration-dialect.ts
git commit -m "chore: bump version to $NEW_VERSION [skip ci]"
git tag -a "v$NEW_VERSION" -m "v$NEW_VERSION"
git push origin HEAD:main --follow-tags
@@ -164,7 +319,9 @@ jobs:
build:
runs-on: ${{ matrix.runner }}
timeout-minutes: 120
needs: version-bump
needs: [version, version-bump]
# version-bump may run after a failed dialect job; that alone must not skip what follows it.
if: ${{ !cancelled() && needs.version-bump.result == 'success' }}
strategy:
fail-fast: false
matrix:
@@ -185,7 +342,7 @@ jobs:
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
- uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
- uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
@@ -205,7 +362,7 @@ jobs:
outputs: type=image,name=mauriceboe/trek,push-by-digest=true,name-canonical=true,push=true
no-cache: true
build-args: |
APP_VERSION=${{ needs.version-bump.outputs.version }}
APP_VERSION=${{ needs.version.outputs.version }}
labels: |
org.opencontainers.image.revision=${{ steps.meta.outputs.revision }}
org.opencontainers.image.created=${{ steps.meta.outputs.created }}
@@ -227,7 +384,8 @@ jobs:
merge:
runs-on: ubuntu-24.04
timeout-minutes: 120
needs: [version-bump, build]
needs: [version, version-bump, build]
if: ${{ !cancelled() && needs.build.result == 'success' }}
steps:
- uses: actions/checkout@v6
with:
@@ -243,7 +401,7 @@ jobs:
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
- uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
- uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
@@ -252,7 +410,7 @@ jobs:
working-directory: /tmp/digests
run: |
set -euo pipefail
VERSION="${{ needs.version-bump.outputs.version }}"
VERSION="${{ needs.version.outputs.version }}"
MAJOR_TAG="$(echo "$VERSION" | cut -d. -f1)"
# :MAJOR.MINOR takes the patches of one minor line and nothing else,
# the conservative pin for an install that wants to wait out a
@@ -292,6 +450,7 @@ jobs:
runs-on: ubuntu-24.04
timeout-minutes: 120
needs: version-bump
if: ${{ !cancelled() && needs.version-bump.result == 'success' }}
steps:
- name: Checkout
uses: actions/checkout@v6
+1 -1
View File
@@ -16,7 +16,7 @@ jobs:
steps:
- name: Flag or clear wrong base branch
uses: actions/github-script@v8
uses: actions/github-script@v9
with:
script: |
const base = context.payload.pull_request.base.ref;
+1 -1
View File
@@ -36,7 +36,7 @@ jobs:
- name: Comment on PR if checks failed
if: steps.checks.outcome == 'failure'
uses: actions/github-script@v8
uses: actions/github-script@v9
with:
script: |
await github.rest.issues.createComment({
+144
View File
@@ -0,0 +1,144 @@
name: Registration dialect
# Asks the TREK services issuer for the registration dialect of one version and
# checks it, for docker.yml (a stable release commits it with the version bump)
# and docker-dev.yml (a prerelease only builds it into its image).
#
# The issuer's answer runs here, in a job that holds no write token and keeps
# no git credentials; the token for the issuer is in the environment of the
# one step that fetches. The answer is held to what a dialect is
# (scripts/ci/check-registration-dialect.mjs), then type-checked and linted
# the way TREK's CI would see it once it is on main and dev. Only a module that
# passes all of it goes on, as the artifact `registration-dialect`; without
# one the caller decides what ships. This workflow never fails its caller.
on:
workflow_call:
inputs:
version:
description: 'The version the dialect is for, X.Y.Z or X.Y.Z-pre.N'
type: string
required: true
ref:
description: 'The commit whose checker, types and lint config the dialect is checked with'
type: string
required: true
secrets:
TREK_DIALECT_TOKEN:
required: false
permissions:
contents: read
jobs:
dialect:
runs-on: ubuntu-24.04
timeout-minutes: 20
# A failed or timed-out run leaves no artifact, which the caller already
# handles; it must not fail the release around it.
continue-on-error: true
steps:
- uses: actions/checkout@v6
with:
ref: ${{ inputs.ref }}
persist-credentials: false
- uses: actions/setup-node@v6
with:
node-version-file: .nvmrc
cache: npm
cache-dependency-path: package-lock.json
# The only step that sees the token. The URL is fixed; the answer is
# bounded in time and size and goes to a file nothing runs yet.
- name: Fetch the dialect from the issuer
id: fetch
timeout-minutes: 3
env:
TREK_DIALECT_TOKEN: ${{ secrets.TREK_DIALECT_TOKEN }}
VERSION: ${{ inputs.version }}
run: |
set -uo pipefail
out="$RUNNER_TEMP/registration-dialect.ts"
if [ -z "${TREK_DIALECT_TOKEN:-}" ]; then
echo "::warning::TREK_DIALECT_TOKEN is not set; the issuer was not asked for a dialect for $VERSION."
exit 0
fi
status=$(curl --silent --show-error --proto '=https' --tlsv1.2 --max-time 30 --retry 2 --retry-delay 5 \
--max-filesize 262144 -H "Authorization: Bearer $TREK_DIALECT_TOKEN" -H 'Content-Type: application/json' \
--data "{\"version\":\"$VERSION\"}" -o "$out" -w '%{http_code}' https://places.liketrek.com/v1/dialects) \
|| status=000
if [ "$status" != 200 ] && [ "$status" != 201 ]; then
echo "::warning::The issuer handed out no registration dialect for $VERSION (HTTP $status)."
rm -f "$out"
exit 0
fi
if [ "$(wc -c < "$out")" -gt 262144 ]; then
echo "::warning::The issuer's registration dialect for $VERSION is larger than a dialect."
rm -f "$out"
exit 0
fi
echo "file=$out" >> "$GITHUB_OUTPUT"
# A module that computes for long is refused by the clock as well.
- name: Check the dialect
id: check
if: steps.fetch.outputs.file != ''
timeout-minutes: 2
env:
FILE: ${{ steps.fetch.outputs.file }}
VERSION: ${{ inputs.version }}
run: |
set -uo pipefail
if ! node scripts/ci/check-registration-dialect.mjs "$FILE" "$VERSION"; then
echo "::warning::The issuer's registration dialect for $VERSION failed its check."
exit 0
fi
echo "What changes against the dialect in the tree:"
git diff --no-index -- server/src/nest/service-identity/registration-dialect.ts "$FILE" || true
echo "ok=true" >> "$GITHUB_OUTPUT"
- name: Install the toolchain
if: steps.check.outputs.ok == 'true'
timeout-minutes: 8
run: |
npm ci --ignore-scripts --no-audit --no-fund
npm run build --workspace=shared
# The bump commit skips CI, so this is where the module meets the strict
# config (lint:strict lets a new file have no strict errors) and ESLint
# with --max-warnings 0 (lint:warnings starts a new file at none) before
# it lands on main.
- name: Type-check and lint the dialect
id: types
if: steps.check.outputs.ok == 'true'
timeout-minutes: 5
working-directory: server
env:
FILE: ${{ steps.fetch.outputs.file }}
VERSION: ${{ inputs.version }}
run: |
set -uo pipefail
cp "$FILE" src/nest/service-identity/registration-dialect.ts
# TypeScript 6 includes no @types by default and the dialect imports nothing
# from node, so checked on its own it would not know Buffer: name node here.
printf '%s\n' '{"extends": "./tsconfig.strict.json", "compilerOptions": {"types": ["node"]}, "include": [],' \
'"files": ["src/nest/service-identity/registration-dialect.ts"]}' > tsconfig.dialect-check.json
if ! npx tsc -p tsconfig.dialect-check.json --noEmit --pretty false; then
echo "::warning::The issuer's registration dialect for $VERSION does not type-check under the strict config."
exit 0
fi
if ! npx eslint --max-warnings 0 src/nest/service-identity/registration-dialect.ts; then
echo "::warning::The issuer's registration dialect for $VERSION does not pass ESLint."
exit 0
fi
echo "ok=true" >> "$GITHUB_OUTPUT"
- name: Hand the dialect on
if: steps.types.outputs.ok == 'true'
uses: actions/upload-artifact@v6
with:
name: registration-dialect
path: ${{ steps.fetch.outputs.file }}
if-no-files-found: error
retention-days: 1
+2 -2
View File
@@ -74,12 +74,12 @@ jobs:
load: true
tags: trek:scan
- uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
- uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- uses: docker/scout-action@221e7f4860634eeb1579e3bd7ca232e577bd1864 # v1.26.0
- uses: docker/scout-action@e7e2a72bf1485d10a58f30696b6c513b261ce4fa # v1.29.0
with:
command: cves
image: trek:scan
+31 -3
View File
@@ -1100,7 +1100,7 @@ jobs:
path: plugin-sdk/coverage/
- name: Scan
uses: SonarSource/sonarqube-scan-action@d209202bc7d53ff1cc128f7f907dac145c9d6ae9 # v8.3.0
uses: SonarSource/sonarqube-scan-action@4d1dc0c91ee400dcf8a6dddf2f705ac36542e304 # v8.4.0
env:
# SonarQube Cloud is the scan action's default host, so no
# SONAR_HOST_URL — the token is a sonarcloud.io token for the
@@ -1202,7 +1202,7 @@ jobs:
docker stop -t 30 trek-ci >/dev/null
code="$(docker inspect -f '{{.State.ExitCode}}' trek-ci)"
[ "$code" = "0" ] || { echo "::error::docker stop ended with exit code $code, not a graceful shutdown"; exit 1; }
docker logs trek-ci 2>&1 | grep -q 'SIGTERM received' \
docker logs trek-ci 2>&1 | grep 'SIGTERM received' >/dev/null \
|| { echo "::error::the server never saw SIGTERM"; exit 1; }
- name: Container log
@@ -1263,11 +1263,39 @@ jobs:
--set 'extraEnv[0].name=SESSION_DURATION' \
--set 'extraEnv[0].value=7d' \
--set 'extraEnvFrom[0].secretRef.name=trek-smtp' \
--set 'extraVolumes[0].name=kitinerary-extractors' \
--set 'extraVolumes[0].configMap.name=trek-kitinerary-extractors' \
--set 'extraVolumeMounts[0].name=kitinerary-extractors' \
--set 'extraVolumeMounts[0].mountPath=/usr/local/share/kitinerary/extractors' \
--set 'extraVolumeMounts[0].readOnly=true' \
--set probes.liveness=null \
> "$out/variants.yaml"
helm template trek charts/trek \
--set httpRoute.enabled=true \
--set 'httpRoute.parentRefs[0].name=gateway' \
> "$out/http-route.yaml"
helm template trek charts/trek \
--set podSecurityContext.runAsUser=1000 \
--set podSecurityContext.runAsGroup=1000 \
--set podSecurityContext.runAsNonRoot=true \
--set podSecurityContext.seccompProfile.type=RuntimeDefault \
--set securityContext.allowPrivilegeEscalation=false \
--set 'securityContext.capabilities.drop[0]=ALL' \
> "$out/non-root.yaml"
helm template trek charts/trek \
--set ingress.enabled=true \
--set fullnameOverride=custom-trek \
--set service.port=8080 \
--set-json 'httpRoute={"enabled":true,"parentRefs":[{"name":"gateway","namespace":"gateway-system","sectionName":"https"}],"hostnames":["trek.example.com"],"paths":["/","/api"],"annotations":{"example.com/note":"custom route"},"timeouts":{"request":"0s","backendRequest":"0s"}}' \
> "$out/http-route-variants.yaml"
- name: Check the manifests against the Kubernetes schemas
run: kubeconform -strict -summary "$RUNNER_TEMP"/rendered/*.yaml
# The pinned Gateway API schema adds HTTPRoute validation without skipping unknown resources.
run: >-
kubeconform -strict -summary
-schema-location default
-schema-location 'https://raw.githubusercontent.com/datreeio/CRDs-catalog/041baf4c1d3740ca21461cab765e7432ecd073ef/{{.Group}}/{{.ResourceKind}}_{{.ResourceAPIVersion}}.json'
"$RUNNER_TEMP"/rendered/*.yaml
- name: Check every compose file
run: |
+2 -1
View File
@@ -91,7 +91,8 @@ ENV KITINERARY_EXTRACTOR_PATH=/usr/local/bin/kitinerary-extractor
COPY --chown=node:node --from=server-builder /app/server/dist ./server/dist
# Runtime data assets read from server/assets at runtime: airports.json (flight
# transport search) and atlas/*.geojson.gz (Atlas country/region map). The build
# transport search) and atlas/*.geojson.gz + atlas/admin1/*.geojson.gz (Atlas
# country/region map). The build
# only emits dist, so these must be copied explicitly or the features silently
# degrade to empty in the image.
COPY --chown=node:node --from=server-builder /app/server/assets ./server/assets
+3 -2
View File
@@ -5,8 +5,9 @@ TREK bundles and uses third-party data that requires attribution.
## geoBoundaries — country & sub-national boundaries
The Atlas map's administrative boundaries (admin-0 countries and admin-1
provinces/counties), shipped at `server/assets/atlas/admin0.geojson.gz` and
`server/assets/atlas/admin1.geojson.gz` and generated by
provinces/counties), shipped at `server/assets/atlas/admin0.geojson.gz`,
`server/assets/atlas/admin1.geojson.gz` and `server/assets/atlas/admin1/<ISO_A2>.geojson.gz`
(the same regions, one file per country) and generated by
`server/scripts/build-atlas-geo.mjs`, are derived from **geoBoundaries**.
> Runfola, D. et al. (2020) geoBoundaries: A global database of political
+49 -24
View File
@@ -6,14 +6,9 @@
<img src="docs/logo-trek-dark.svg" alt="TREK" height="96" />
</picture>
<br />
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/subtitle-light.png" />
<source media="(prefers-color-scheme: light)" srcset="docs/subtitle-dark.png" />
<img src="docs/subtitle-dark.png" alt="your trip. your plan." height="28" />
</picture>
### Every part of your trip. One app you own.
A self-hosted, real-time collaborative travel planner — with maps, budgets, packing lists, a journal, and AI built in.
TREK has grown from a travel planner into a whole ecosystem for trips: plan together in real time on a live map, build hikes, tours and road trips, keep bookings and shared costs in order, pack, write the journal, lay out the photo book and hand the busy work to the built-in AI. Self-hosted, on the web, on your phone and offline.
<br />
@@ -32,11 +27,16 @@ A self-hosted, real-time collaborative travel planner — with maps, budgets, pa
<a href="https://ko-fi.com/mauriceboe"><img alt="Ko-fi" src="https://img.shields.io/badge/Ko--fi-support-FF5E5B?style=for-the-badge" /></a>
&nbsp;
<a href="https://www.buymeacoffee.com/mauriceboe"><img alt="BMAC" src="https://img.shields.io/badge/BMAC-support-FFDD00?style=for-the-badge" /></a>
<br />
<a href="LICENSE"><img alt="License" src="https://img.shields.io/badge/license-AGPL_v3-6B7280?style=flat-square" /></a>
<a href="https://github.com/liketrek/TREK/releases"><img alt="Latest Release" src="https://img.shields.io/github/v/release/liketrek/trek?include_prereleases&style=flat-square&color=6B7280" /></a>
<a href="https://hub.docker.com/r/mauriceboe/trek"><img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/mauriceboe/trek?style=flat-square&color=6B7280" /></a>
<a href="https://github.com/liketrek/TREK"><img alt="Stars" src="https://img.shields.io/github/stars/liketrek/trek?style=flat-square&color=6B7280" /></a>
&nbsp;
<a href="LICENSE"><img alt="License" src="https://img.shields.io/badge/License-AGPL_v3-6B7280?style=for-the-badge" /></a>
&nbsp;
<a href="https://github.com/liketrek/TREK/releases"><img alt="Latest Release" src="https://img.shields.io/github/v/release/liketrek/trek?include_prereleases&style=for-the-badge&label=Release&color=6B7280" /></a>
&nbsp;
<a href="https://hub.docker.com/r/mauriceboe/trek"><img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/mauriceboe/trek?style=for-the-badge&label=Docker%20pulls&color=6B7280" /></a>
&nbsp;
<a href="https://github.com/liketrek/TREK"><img alt="Stars" src="https://img.shields.io/github/stars/liketrek/trek?style=for-the-badge&label=Stars&color=6B7280" /></a>
<sub>PUBLIC SERVICES PROUDLY SPONSORED BY</sub><br /><a href="https://cloud.dataforest.net/en?mtm_campaign=trek"><picture><source media="(prefers-color-scheme: dark)" srcset="docs/sponsors/dataforest-light.svg" /><source media="(prefers-color-scheme: light)" srcset="docs/sponsors/dataforest-dark.svg" /><img src="docs/sponsors/dataforest-dark.svg" alt="dataforest cloud" height="30" /></picture></a>
</div>
---
@@ -200,7 +200,7 @@ Most of what follows is an addon an admin switches on or off. Lists, Costs, Docu
- **Admin panel**: users and the permission matrix, defaults for new users, categories and templates, addons, plugins, storage, notifications, MCP tokens, backups, audit log and releases
- **Backups and storage**: scheduled backups with retention that restore their own secrets, and local or S3-compatible storage per content category with replicas
- **Appearance**: light, dark or follow the OS, seven colour schemes plus a custom accent, transparency, density, reduced motion and text size
- **27 languages**: en, de, es, fr, it, nl, hu, ru, zh, zh-TW, pl, cs, ar (right to left), br, id, tr, ja, ko, uk, gr, sv, vi, ca, az, et, sk, th
- **28 languages**: en, de, es, fr, it, nl, hu, ru, zh, zh-TW, pl, cs, ar (right to left), he (right to left), br, id, tr, ja, ko, uk, gr, sv, vi, ca, az, et, sk, th
- **Help center**: a ? in the top bar with 381 step-by-step guides with screenshots, searched together with the wiki that ships in the image
</td>
@@ -214,7 +214,39 @@ Most of what follows is an addon an admin switches on or off. Lists, Costs, Docu
<div align="center">
<a href="docs/screenshots/showcase-desktop-1.webp"><img src="docs/screenshots/showcase-desktop-1.webp" alt="Atlas · dashboard · trip planner" width="100%" /></a>
<a href="docs/screenshots/showcase-mobile.webp"><img src="docs/screenshots/showcase-mobile.webp" alt="Mobile PWA · dashboard, day plan, map, costs" width="100%" /></a>
<a href="docs/screenshots/showcase-desktop-2.webp"><img src="docs/screenshots/showcase-desktop-2.webp" alt="Collections · journey journal · costs" width="100%" /></a>
</div>
<br />
## Powered by [dataforest cloud](https://cloud.dataforest.net/en?mtm_campaign=trek)
<div align="center">
<br />
<a href="https://cloud.dataforest.net/en?mtm_campaign=trek">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/sponsors/dataforest-light.svg" />
<source media="(prefers-color-scheme: light)" srcset="docs/sponsors/dataforest-dark.svg" />
<img src="docs/sponsors/dataforest-dark.svg" alt="dataforest cloud" height="60" />
</picture>
</a>
<br />
<br />
**Every TREK installation in the world searches through servers that [dataforest cloud](https://cloud.dataforest.net/en?mtm_campaign=trek) sponsors.**
The place index with over 88 million places, the address search in every TREK language and the planet-wide routing all run on [dataforest cloud](https://cloud.dataforest.net/en?mtm_campaign=trek) in Frankfurt, Germany, free of charge for everyone who self-hosts TREK. Without this sponsorship, these services would not exist in this form.
Thank you, [dataforest](https://cloud.dataforest.net/en?mtm_campaign=trek), for backing open source this generously. 💚
<br />
<a href="https://cloud.dataforest.net/en?mtm_campaign=trek"><img alt="Visit dataforest cloud" src="https://img.shields.io/badge/Visit-dataforest_cloud-02C382?style=for-the-badge" /></a>
Looking for a server for your own TREK? [dataforest cloud](https://cloud.dataforest.net/en?mtm_campaign=trek) is where TREK's own services live.
</div>
<br />
@@ -244,6 +276,9 @@ Open `http://localhost:3000`, or `http://<server-ip>:3000` from another machine.
`COOKIE_SECURE=false` is only for trying TREK over plain HTTP: without it the browser drops the session cookie and the login does not stick. Once TREK sits behind HTTPS (see [Reverse Proxy](#reverse-proxy)), remove it.
> [!TIP]
> **No server yet?** TREK's own public services run on [**dataforest cloud**](https://cloud.dataforest.net/en?mtm_campaign=trek), our infrastructure sponsor. A small seed is plenty for a TREK instance and is ready within a minute.
<div align="center">
<a href="#docker-compose-production">Docker Compose</a>&nbsp;&nbsp;·&nbsp;&nbsp;<a href="#helm-kubernetes">Helm / Kubernetes</a>&nbsp;&nbsp;·&nbsp;&nbsp;<a href="#install-as-app-pwa">Install as PWA</a>&nbsp;&nbsp;·&nbsp;&nbsp;<a href="#reverse-proxy">Reverse Proxy</a>
@@ -398,16 +433,6 @@ Caddy handles TLS and WebSockets automatically.
Every variable, its default and what it does: see
[Environment Variables](https://github.com/liketrek/TREK/wiki/Environment-Variables).
## Star History
<a href="https://www.star-history.com/?repos=liketrek%2FTREK&type=date&legend=bottom-right">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=liketrek/TREK&type=date&theme=dark&legend=bottom-right&sealed_token=tW9agibKugOyPk0yPURgSdnizM7K72zbJENGD9iyk24ZcwYHtCUn-hk9jh1gdacO0O7xJ3Io7LaNrwYD3mChzcpzZIqDC8_HevYG1qnT0XNTmN6Ez4UZrQ" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=liketrek/TREK&type=date&legend=bottom-right&sealed_token=tW9agibKugOyPk0yPURgSdnizM7K72zbJENGD9iyk24ZcwYHtCUn-hk9jh1gdacO0O7xJ3Io7LaNrwYD3mChzcpzZIqDC8_HevYG1qnT0XNTmN6Ez4UZrQ" />
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=liketrek/TREK&type=date&legend=bottom-right&sealed_token=tW9agibKugOyPk0yPURgSdnizM7K72zbJENGD9iyk24ZcwYHtCUn-hk9jh1gdacO0O7xJ3Io7LaNrwYD3mChzcpzZIqDC8_HevYG1qnT0XNTmN6Ez4UZrQ" />
</picture>
</a>
## Data sources
The Atlas map's country and sub-national (province/county) boundaries come from
+6 -3
View File
@@ -5,9 +5,10 @@ This is a minimal Helm chart for deploying the TREK app.
## Features
- Deploys the TREK container
- Exposes port 3000 via Service
- Optional persistent storage for `/app/data` and `/app/uploads`
- Optional persistent storage for `/app/data` and `/app/uploads`, plus extra volumes and mounts
- Configurable environment variables and secrets
- Optional generic Ingress support
- Optional Gateway API HTTPRoute support
- Configurable health checks (liveness/readiness probes) on `/api/health`
## Helm Repository
@@ -27,7 +28,7 @@ helm install trek trek/trek
Or install directly from the local chart:
```sh
helm install trek ./chart \
helm install trek ./charts/trek \
--set ingress.enabled=true \
--set ingress.hosts[0].host=yourdomain.com
```
@@ -47,7 +48,7 @@ See `values.yaml` for more options.
- `JWT_SECRET` is managed entirely by the server — auto-generated into the data PVC on first start and rotatable via the admin panel (Settings → Danger Zone). No Helm configuration needed.
- `ENCRYPTION_KEY` encrypts stored secrets (API keys, MFA, SMTP, OIDC) at rest. Recommended: set via `secretEnv.ENCRYPTION_KEY` or `existingSecret`. If left empty, the server falls back automatically: existing installs use `data/.jwt_secret` (no action needed on upgrade); fresh installs auto-generate a key persisted to the data PVC.
- Liveness and readiness probes are configurable under `probes`. Overrides are merged over the defaults, so `--set probes.liveness.initialDelaySeconds=60` keeps the `httpGet` handler. When switching to `exec` or `tcpSocket`, clear `httpGet` in the same override. Set `probes.liveness: null` to remove a probe.
- If using ingress, you must manually keep `env.ALLOWED_ORIGINS` and `ingress.hosts` in sync to ensure CORS works correctly. The chart does not sync these automatically.
- If exposing TREK through an Ingress or HTTPRoute, set `env.ALLOWED_ORIGINS` and `env.APP_URL` to the public URL. The chart does not sync these automatically.
- Set `env.ALLOW_INTERNAL_NETWORK: "true"` if Immich or other integrated services are hosted on a private/RFC-1918 address (e.g. a pod on the same cluster or a NAS on your LAN). Loopback (`127.x`) and link-local/metadata addresses (`169.254.x`) remain blocked regardless.
- Set `env.ALLOW_LINK_LOCAL_IPS` to a single link-local address (e.g. `"169.254.1.2"`) only when a service TREK needs sits behind one, such as a host gateway. Cloud metadata addresses (`169.254.169.x`, `169.254.170.x`) cannot be listed.
- `FORCE_HTTPS` is optional. Set `env.FORCE_HTTPS: "true"` only when ingress (or another proxy) terminates TLS. It enables HTTPS redirects, HSTS, CSP `upgrade-insecure-requests`, and forces the session cookie `secure` flag. Requires `TRUST_PROXY` to be set.
@@ -55,3 +56,5 @@ See `values.yaml` for more options.
- `COOKIE_SECURE` is auto-derived (on when `NODE_ENV=production` or `FORCE_HTTPS=true`). Set `env.COOKIE_SECURE: "false"` only during local testing without TLS. **Not recommended for production.**
- Web Push needs no chart settings: TREK generates its key pair on first start and keeps it in the database on the data PVC. To bring your own pair, set `env.VAPID_PUBLIC_KEY` and `secretEnv.VAPID_PRIVATE_KEY` together (and optionally `env.VAPID_SUBJECT`); changing the pair later means every device has to turn push on again.
- Set `env.OIDC_DISCOVERY_URL` to override the auto-constructed OIDC discovery endpoint. Required for providers (e.g. Authentik) that expose it at a non-standard path.
- `podSecurityContext` defaults to `fsGroup: 1000` with `fsGroupChangePolicy: OnRootMismatch`, and `securityContext` (the container's) is empty. The container then starts as root, hands any file under `/app/data` and `/app/uploads` that is not owned by `node` yet to `node`, and drops to `node`. To run as `node` from the start, for example under the `restricted` Pod Security Standard, set `podSecurityContext.runAsUser: 1000` and `runAsGroup: 1000`; the image then skips that step and the privilege drop. See the example in `values.yaml`.
- Use `extraVolumes` and `extraVolumeMounts` to add your own volumes to the pod. To give the booking import more KItinerary extractors, mount a ConfigMap at `/usr/local/share/kitinerary/extractors`, with one `.json` and one `.js` key for each extractor; see the example in `values.yaml`.
+2 -2
View File
@@ -1,5 +1,5 @@
apiVersion: v2
name: trek
version: 5.0.0
version: 5.1.0
description: Minimal Helm chart for TREK app
appVersion: "5.0.0"
appVersion: "5.1.0"
+9
View File
@@ -31,3 +31,12 @@
The other values for that volume (size, storageClassName, annotations) are then ignored.
- With `persistence.enabled=false` the volumes use an emptyDir — storage is ephemeral and is lost
when the pod restarts. Use only for testing.
{{- if .Values.httpRoute.enabled }}
6. HTTPRoute:
- The chart creates an HTTPRoute v1 to the existing TREK Service. The Gateway, GatewayClass,
listeners, TLS certificates and allowedRoutes are managed by your cluster operator.
- Ingress and HTTPRoute may be enabled together.
- Timeout fields are Standard Channel in Gateway API v1.2, but controller support varies. Omit
them to use controller defaults; `0s` disables the corresponding timeout where supported.
{{- end }}
+15
View File
@@ -112,6 +112,21 @@ data:
{{- if .Values.env.TREK_PLACES_URL }}
TREK_PLACES_URL: {{ .Values.env.TREK_PLACES_URL | quote }}
{{- end }}
{{- if .Values.env.TREK_PLACES_CONTRIBUTE }}
TREK_PLACES_CONTRIBUTE: {{ .Values.env.TREK_PLACES_CONTRIBUTE | quote }}
{{- end }}
{{- if .Values.env.TREK_SERVICES }}
TREK_SERVICES: {{ .Values.env.TREK_SERVICES | quote }}
{{- end }}
{{- if .Values.env.TREK_SERVICES_HOSTS }}
TREK_SERVICES_HOSTS: {{ .Values.env.TREK_SERVICES_HOSTS | quote }}
{{- end }}
{{- if .Values.env.TREK_PHOTON_URL }}
TREK_PHOTON_URL: {{ .Values.env.TREK_PHOTON_URL | quote }}
{{- end }}
{{- if .Values.env.TREK_VALHALLA_URL }}
TREK_VALHALLA_URL: {{ .Values.env.TREK_VALHALLA_URL | quote }}
{{- end }}
{{- if .Values.env.GOOGLE_LIST_DATA_BASE }}
GOOGLE_LIST_DATA_BASE: {{ .Values.env.GOOGLE_LIST_DATA_BASE | quote }}
{{- end }}
+19 -1
View File
@@ -29,12 +29,18 @@ spec:
- name: {{ .name }}
{{- end }}
{{- end }}
{{- with .Values.podSecurityContext }}
securityContext:
fsGroup: 1000
{{- toYaml . | nindent 8 }}
{{- end }}
containers:
- name: trek
image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
imagePullPolicy: {{ .Values.image.pullPolicy }}
{{- with .Values.securityContext }}
securityContext:
{{- toYaml . | nindent 12 }}
{{- end }}
{{- with .Values.resources }}
resources:
{{- toYaml . | nindent 12 }}
@@ -85,6 +91,12 @@ spec:
name: {{ default (printf "%s-secret" (include "trek.fullname" .)) .Values.existingSecret }}
key: PLACES_API_KEY
optional: true
- name: TREK_SERVICES_KEY
valueFrom:
secretKeyRef:
name: {{ default (printf "%s-secret" (include "trek.fullname" .)) .Values.existingSecret }}
key: TREK_SERVICES_KEY
optional: true
- name: AMAP_API_KEY
valueFrom:
secretKeyRef:
@@ -135,6 +147,9 @@ spec:
mountPath: /app/data
- name: uploads
mountPath: /app/uploads
{{- with .Values.extraVolumeMounts }}
{{- toYaml . | nindent 12 }}
{{- end }}
{{- with (default dict .Values.probes).startup }}
startupProbe:
{{- toYaml . | nindent 12 }}
@@ -162,3 +177,6 @@ spec:
{{- else }}
emptyDir: {}
{{- end }}
{{- with .Values.extraVolumes }}
{{- toYaml . | nindent 8 }}
{{- end }}
+39
View File
@@ -0,0 +1,39 @@
{{- if .Values.httpRoute.enabled -}}
{{- if not .Values.httpRoute.parentRefs }}
{{- fail "httpRoute.parentRefs must include at least one parent" }}
{{- end }}
{{- if not .Values.httpRoute.paths }}
{{- fail "httpRoute.paths must include at least one path" }}
{{- end }}
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
name: {{ include "trek.fullname" . }}
labels:
app: {{ include "trek.name" . }}
{{- with .Values.httpRoute.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
parentRefs:
{{- toYaml .Values.httpRoute.parentRefs | nindent 4 }}
{{- with .Values.httpRoute.hostnames }}
hostnames:
{{- toYaml . | nindent 4 }}
{{- end }}
rules:
{{- range $path := .Values.httpRoute.paths }}
- matches:
- path:
type: PathPrefix
value: {{ $path | quote }}
backendRefs:
- name: {{ include "trek.fullname" $ }}
port: {{ $.Values.service.port }}
{{- with $.Values.httpRoute.timeouts }}
timeouts:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- end }}
{{- end }}
+6
View File
@@ -23,6 +23,9 @@ data:
{{- if .Values.secretEnv.PLACES_API_KEY }}
PLACES_API_KEY: {{ .Values.secretEnv.PLACES_API_KEY | b64enc | quote }}
{{- end }}
{{- if .Values.secretEnv.TREK_SERVICES_KEY }}
TREK_SERVICES_KEY: {{ .Values.secretEnv.TREK_SERVICES_KEY | b64enc | quote }}
{{- end }}
{{- if .Values.secretEnv.AMAP_API_KEY }}
AMAP_API_KEY: {{ .Values.secretEnv.AMAP_API_KEY | b64enc | quote }}
{{- end }}
@@ -77,6 +80,9 @@ stringData:
{{- if .Values.secretEnv.PLACES_API_KEY }}
PLACES_API_KEY: {{ .Values.secretEnv.PLACES_API_KEY | quote }}
{{- end }}
{{- if .Values.secretEnv.TREK_SERVICES_KEY }}
TREK_SERVICES_KEY: {{ .Values.secretEnv.TREK_SERVICES_KEY | quote }}
{{- end }}
{{- if .Values.secretEnv.AMAP_API_KEY }}
AMAP_API_KEY: {{ .Values.secretEnv.AMAP_API_KEY | quote }}
{{- end }}
+84 -3
View File
@@ -10,6 +10,34 @@ image:
# processes on one host, which network filesystems do not provide.
updateStrategy: Recreate
# Pod-level security context. fsGroup gives the node user (uid/gid 1000) group access
# to the data and uploads volumes; OnRootMismatch lets the kubelet skip its recursive
# permission walk once the volume root already matches, so a big PVC does not hold up
# every start.
#
# By default the container starts as root, hands any files that are not node's yet to
# node, and then drops to node itself. To start it as node straight away (needed under
# the "restricted" Pod Security Standard), add the user here and lock the container
# down below; the image then skips the ownership step and the privilege drop:
# podSecurityContext:
# fsGroup: 1000
# fsGroupChangePolicy: OnRootMismatch
# runAsUser: 1000
# runAsGroup: 1000
# runAsNonRoot: true
# seccompProfile:
# type: RuntimeDefault
# securityContext:
# allowPrivilegeEscalation: false
# capabilities:
# drop: [ALL]
podSecurityContext:
fsGroup: 1000
fsGroupChangePolicy: OnRootMismatch
# Security context of the trek container itself. Empty by default.
securityContext: {}
# Optional image pull secrets for private registries
imagePullSecrets: []
# - name: my-registry-secret
@@ -36,7 +64,7 @@ env:
# Browser/OS language is auto-detected first; this is the fallback when no match is found.
# Supported: ar, az, br, ca, cs, de, en, es, et, fr, gr, hu, id, it, ja, ko, nl, pl, ru, sk, sv, th, tr, uk, vi, zh, zh-TW
# ALLOWED_ORIGINS: ""
# NOTE: If using ingress, ensure env.ALLOWED_ORIGINS matches the domains in ingress.hosts for proper CORS configuration.
# NOTE: If using ingress or HTTPRoute, ensure env.ALLOWED_ORIGINS matches the public domains for proper CORS configuration.
# APP_URL: "https://trek.example.com"
# Public base URL of this instance. Required when OIDC is enabled — must match the redirect URI registered with your IdP.
# Also used as the base URL for links in email notifications and other external links.
@@ -92,7 +120,8 @@ env:
# Custom Nominatim base URL for every geocoding call the server makes (place search, reverse lookup, Atlas region
# fill). When set it REPLACES the public OpenStreetMap service, with no fallback, so the instance behind it needs
# the coverage you expect and has to speak the Nominatim API. TREK keeps its ~1 request per second spacing either
# way. Defaults to https://nominatim.openstreetmap.org.
# way, and search and reverse lookups no longer go to the TREK services' Photon. Defaults to
# https://nominatim.openstreetmap.org.
# OVERPASS_URL: ""
# Custom Overpass endpoint(s) for the map POI "explore" search, comma-separated. When set, REPLACES the bundled
# public mirrors — point it at an internal/self-hosted Overpass instance when the public mirrors are unreachable
@@ -112,6 +141,24 @@ env:
# Base URL of a copy of the Places API you run yourself; it has to answer the same /v1 API. Read from
# configuration rather than typed by a user, so an in-cluster address works without ALLOW_INTERNAL_NETWORK.
# Defaults to https://places.liketrek.com.
# TREK_PLACES_CONTRIBUTE: "off"
# Whether an admin may let this installation send the place details its users typed in (website, phone, e-mail,
# opening hours, description, picture) to the TREK Places API. "admin" leaves the choice to the admin panel, where
# it stays off until an admin agrees; "off" takes it away. Defaults to admin.
# TREK_SERVICES: "off"
# Places search identifies this installation with a key it registers by itself on first use and keeps in the
# database. "off" sends no key; searches then use the shared pool. A key issued to you goes under
# secretEnv.TREK_SERVICES_KEY. Defaults to auto.
# TREK_SERVICES_HOSTS: ""
# Comma-separated hosts that receive the installation key over https. Defaults to
# places.liketrek.com,photon.liketrek.com,valhalla.liketrek.com.
# TREK_PHOTON_URL: ""
# The address search (Photon) of the TREK services. With a key, search and reverse lookups ask it before
# Nominatim and fall back to Nominatim when it does not answer. Never asked when NOMINATIM_URL is set.
# Defaults to https://photon.liketrek.com.
# TREK_VALHALLA_URL: ""
# The Valhalla of the TREK services, which this server relays routing to unless the admin picks another
# routing service. The browser never talks to it. Defaults to https://valhalla.liketrek.com.
# AMAP_API_BASE: ""
# 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
@@ -164,6 +211,9 @@ secretEnv:
# with signing enabled, because such a key rejects every unsigned request. Leave empty
# otherwise. The endpoint itself is not a secret and is set under env.AMAP_API_BASE.
AMAP_API_SECRET: ""
# Optional key issued for this installation by the TREK services. Wins over the key TREK
# registers by itself and turns that registration off. Leave empty to let TREK register.
TREK_SERVICES_KEY: ""
# Optional Web Push key pair, private half (base64url, 32 bytes). Only used together with
# env.VAPID_PUBLIC_KEY; a pair whose halves do not belong together, or only one half, turns
# push off with an error in the log until it is fixed, and every device stays registered.
@@ -179,7 +229,7 @@ generateEncryptionKey: false
# If set, the chart renders no Secret of its own and instead reads every secret env
# var from this existing Kubernetes secret. Expected keys: ENCRYPTION_KEY (rename via
# existingSecretKey), ADMIN_EMAIL, ADMIN_PASSWORD, OIDC_CLIENT_SECRET,
# UNSPLASH_ACCESS_KEY, PLACES_API_KEY, AMAP_API_KEY, AMAP_API_SECRET,
# UNSPLASH_ACCESS_KEY, PLACES_API_KEY, AMAP_API_KEY, AMAP_API_SECRET, TREK_SERVICES_KEY,
# VAPID_PRIVATE_KEY, SMTP_PASS, MAPBOX_ACCESS_TOKEN, CARTO_API_KEY, DEMO_ADMIN_PASS.
# Missing keys are simply left unset (they are optional), so only provide the ones your
# setup needs.
@@ -242,6 +292,20 @@ extraEnv: []
# name: trek-smtp
extraEnvFrom: []
# Further volumes for the pod. The chart does not create the objects they name.
# extraVolumes:
# - name: kitinerary-extractors
# configMap:
# name: trek-kitinerary-extractors
extraVolumes: []
# Where the trek container mounts them. For example, KItinerary
# loads extractors for the booking import from this path:
# extraVolumeMounts:
# - name: kitinerary-extractors
# mountPath: /usr/local/share/kitinerary/extractors
# readOnly: true
extraVolumeMounts: []
resources:
requests:
cpu: 100m
@@ -262,3 +326,20 @@ ingress:
# - secretName: chart-example-tls
# hosts:
# - chart-example.local
httpRoute:
enabled: false
annotations: {}
parentRefs: []
# - name: gateway
# namespace: gateway-system
# sectionName: https
hostnames: []
# - trek.example.com
paths:
- /
# Timeout fields are Standard Channel in Gateway API v1.2; controller support varies.
# Leave empty for controller defaults. Use "0s" to disable the corresponding timeout.
timeouts: {}
# request: "0s"
# backendRequest: "0s"
+110
View File
@@ -0,0 +1,110 @@
import { expect, test, type Locator } from '@playwright/test';
// A visible DOM node can still be clipped by a panel. Check the whole bar
// before interacting: Playwright's automatic scroll-into-view could mask it.
async function expectBarInsidePanel(bar: Locator, panel: Locator) {
await expect(bar).toBeInViewport({ ratio: 1 });
await expect
.poll(async () => {
const bounds = await bar.boundingBox();
const parent = await panel.boundingBox();
return (
!!bounds &&
!!parent &&
bounds.y >= parent.y &&
bounds.y + bounds.height <= parent.y + parent.height + 1 &&
bounds.x >= parent.x &&
bounds.x + bounds.width <= parent.x + parent.width + 1
);
})
.toBe(true);
}
for (const layout of [
{ name: 'desktop', viewport: { width: 1440, height: 900 }, hasTouch: false },
{ name: 'tablet', viewport: { width: 834, height: 1112 }, hasTouch: true },
{ name: 'short desktop', viewport: { width: 1280, height: 600 }, hasTouch: false },
]) {
test.describe(layout.name, () => {
test.use({
viewport: layout.viewport,
hasTouch: layout.hasTouch,
});
for (const tours of [false, true]) {
for (const count of [10, 27, 190]) {
test(`${count} places, Tours ${tours ? 'on' : 'off'}: selection bar stays reachable`, async ({ page }) => {
test.setTimeout(90_000);
const activate = (button: Locator) => (layout.hasTouch ? button.tap() : button.click());
const addonsResponse = await page.request.get('/api/admin/addons');
expect(addonsResponse.ok()).toBeTruthy();
const { addons } = await addonsResponse.json();
const originalTours = addons.find((addon: { id: string }) => addon.id === 'tours');
expect(originalTours).toBeDefined();
let tripId: number | undefined;
try {
expect((await page.request.put('/api/admin/addons/tours', { data: { enabled: tours } })).ok()).toBeTruthy();
const tripResponse = await page.request.post('/api/trips', {
data: {
title: `Selection bar ${layout.name} ${count}`,
start_date: '2027-01-01',
end_date: '2027-01-02',
},
});
expect(tripResponse.ok()).toBeTruthy();
tripId = (await tripResponse.json()).trip.id;
for (let i = 1; i <= count; i++) {
const response = await page.request.post(`/api/trips/${tripId}/places`, {
data: { name: `Selection place ${i}`, lat: 48.85, lng: 2.35 },
});
expect(response.ok(), `seed place ${i}`).toBeTruthy();
}
await page.goto(`/trips/${tripId}`);
if (layout.name === 'tablet') await page.locator('button[aria-label="Places"]').click();
const sidebar = page
.locator('[data-touch-drag]')
.filter({ has: page.getByRole('button', { name: 'Select', exact: true }) });
const panel = sidebar.locator('..');
const rows = sidebar.getByRole('option');
await expect(rows).toHaveCount(count);
await expect(panel.getByRole('tab', { name: 'Tours', exact: true })).toHaveCount(tours ? 1 : 0);
await activate(sidebar.getByRole('button', { name: 'Select', exact: true }));
const bar = sidebar.getByRole('status').locator('../..');
await expectBarInsidePanel(bar, panel);
const list = sidebar.locator('.trek-stagger');
const before = await bar.boundingBox();
// Only the list scrolls; the bar must remain at the panel's foot.
await list.evaluate((el) => {
el.scrollTop = el.scrollHeight;
});
if (count >= 27) await expect.poll(() => list.evaluate((el) => el.scrollTop)).toBeGreaterThan(0);
await expectBarInsidePanel(bar, panel);
expect((await bar.boundingBox())?.y).toBe(before?.y);
await activate(sidebar.getByRole('button', { name: 'Select all', exact: true }));
await expect(sidebar.getByRole('status')).toHaveText(String(count));
await activate(sidebar.getByRole('button', { name: 'Done', exact: true }));
await expect(sidebar.getByRole('status')).toHaveCount(0);
await activate(sidebar.getByRole('button', { name: 'Select', exact: true }));
await list.evaluate((el) => {
el.scrollTop = 0;
});
await expectBarInsidePanel(bar, panel);
await activate(sidebar.getByRole('button', { name: 'Select all', exact: true }));
await activate(sidebar.getByRole('button', { name: 'Delete selected', exact: true }));
await activate(page.getByRole('button', { name: 'Delete', exact: true }));
await expect(rows).toHaveCount(0);
} finally {
if (tripId !== undefined) expect((await page.request.delete(`/api/trips/${tripId}`)).ok()).toBeTruthy();
expect(
(await page.request.put('/api/admin/addons/tours', { data: { enabled: !!originalTours.enabled } })).ok()
).toBeTruthy();
}
});
}
}
});
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@trek/client",
"version": "5.0.0",
"version": "5.1.0",
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
},
@@ -138,7 +138,7 @@
"prettier-plugin-organize-imports": "^4.3.0",
"prettier-plugin-tailwindcss": "^0.8.1",
"rollup-plugin-visualizer": "^7.1.1",
"sharp": "^0.35.4",
"sharp": "^0.35.5",
"tailwindcss": "^3.4.19",
"typescript": "^6.0.3",
"typescript-eslint": "^8.70.0",
@@ -0,0 +1,23 @@
<svg width="310" height="48" viewBox="0 0 310 48" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M39.9361 44.5592H37.3496V40.5946H38.7949C39.6016 40.5946 40.1393 40.0905 40.1393 38.9477V32.7663C40.1393 30.1462 41.3157 28.7345 43.4989 28.0302C41.3157 27.3243 40.1393 25.9142 40.1393 23.2941V17.1127C40.1393 15.9699 39.6016 15.4673 38.7949 15.4673H37.3496V11.5027H39.9361C42.8252 11.5027 44.8403 13.2825 44.8403 16.1059V22.5898C44.8403 24.8738 46.2184 26.0166 48.5696 26.0166V30.0484C46.2184 30.0484 44.8403 31.1912 44.8403 33.4752V39.9591C44.8403 42.7809 42.8252 44.5607 39.9361 44.5607V44.5592Z" fill="white"/>
<path d="M0 30.0453V26.0135C2.35125 26.0135 3.72931 24.8708 3.72931 22.5867V16.1028C3.72931 13.281 5.74445 11.4996 8.63347 11.4996H11.22V15.4642H9.77472C8.96806 15.4642 8.43028 15.9684 8.43028 17.1096V23.291C8.43028 25.9112 7.25389 27.3228 5.07069 28.0271C7.25389 28.733 8.43028 30.1431 8.43028 32.7633V38.9446C8.43028 40.0874 8.96806 40.5916 9.77472 40.5916H11.22V44.5562H8.63347C5.74445 44.5562 3.72931 42.7763 3.72931 39.9545V33.4706C3.72931 31.1866 2.35125 30.0438 0 30.0438V30.0453Z" fill="white"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M24.2855 0.076416L32.7769 8.5678L28.8169 12.5263L24.284 7.99336L19.7511 12.5263L15.7926 8.5678L24.284 0.076416H24.2855Z" fill="#02C382"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M24.2855 11.7119L34.4055 21.8319L30.4471 25.7904L24.2855 19.6289L18.124 25.7904L14.1655 21.8319L24.2855 11.7119Z" fill="#02C382"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M24.2856 23.3475L36.0342 35.0961L32.0757 39.0561L24.2871 31.2675L16.4985 39.0561L12.54 35.0961L24.2887 23.3475H24.2856Z" fill="#02C382"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M21.4867 47.8958V37.3129H27.086V47.8958H21.4867Z" fill="white"/>
<path d="M216.808 36.4329H211.635V23.9357H208.444V19.635H211.635V14.4283H216.808V19.635H220V23.9357H216.808V36.4329Z" fill="white"/>
<path d="M192.671 31.1239H197.575C197.643 32.3003 198.516 33.0046 200.095 33.0046C201.673 33.0046 202.446 32.4332 202.446 31.5593C202.446 31.0552 202.177 30.5174 200.933 30.2485L197.843 29.5763C194.752 28.904 193.241 27.5611 193.241 24.6049C193.241 21.1108 196.231 19.0957 200.263 19.0957C204.294 19.0957 206.881 21.3797 206.881 24.7729H201.977C201.977 23.6302 201.271 22.8586 200.029 22.8586C198.853 22.8586 198.115 23.4636 198.115 24.3711C198.115 25.1442 198.753 25.5811 199.928 25.85L203.052 26.5222C205.807 27.1272 207.319 28.4029 207.319 31.0918C207.319 34.6867 204.262 36.8699 199.894 36.8699C195.527 36.8699 192.671 34.5186 192.671 31.1254V31.1239Z" fill="white"/>
<path d="M182.351 36.8699C177.279 36.8699 173.65 33.1742 173.65 28.0011C173.65 22.8281 177.178 19.0988 182.25 19.0988C187.322 19.0988 190.816 22.5592 190.816 28.0347V29.3456L178.622 29.4128C178.924 31.6296 180.168 32.6715 182.452 32.6715C184.4 32.6715 185.778 31.9657 186.147 30.7572H190.884C190.279 34.4865 186.953 36.8714 182.351 36.8714V36.8699ZM182.284 23.2971C180.235 23.2971 179.092 24.2046 178.689 26.2197H185.677C185.677 24.4383 184.366 23.2971 182.284 23.2971Z" fill="white"/>
<path d="M172.433 19.6351V24.5056H170.787C167.831 24.5056 166.051 25.8164 166.051 29.1424V36.433H160.878V19.6687H165.749L166.017 22.1544C166.723 20.5074 168.201 19.3998 170.453 19.3998C171.058 19.3998 171.728 19.467 172.434 19.6351H172.433Z" fill="white"/>
<path d="M139.367 28.0011C139.367 22.6936 143.264 19.1323 148.639 19.1323C154.014 19.1323 157.878 22.6936 157.878 28.0011C157.878 33.3086 153.98 36.8362 148.639 36.8362C143.298 36.8362 139.367 33.3086 139.367 28.0011ZM144.574 27.9675C144.574 30.5204 146.219 32.2009 148.639 32.2009C151.059 32.2009 152.671 30.5219 152.671 27.9675C152.671 25.413 151.025 23.7676 148.639 23.7676C146.253 23.7676 144.574 25.4466 144.574 27.9675Z" fill="white"/>
<path d="M126.917 19.635H129.235V18.2906C129.235 13.2856 131.855 11.1008 136.122 11.1008C136.828 11.1008 137.634 11.1681 138.44 11.3025V15.7376H136.994C134.878 15.7376 134.408 16.8468 134.408 18.2906V19.635H138.44V23.9357H134.408V36.4329H129.235V23.9357H126.917V19.635Z" fill="white"/>
<path d="M114.606 36.8699C111.045 36.8699 108.828 34.7875 108.828 31.4951C108.828 28.4045 111.011 26.4901 115.043 26.1876L119.746 25.8179V25.549C119.746 23.9021 118.737 23.0297 116.89 23.0297C114.707 23.0297 113.531 23.87 113.531 25.381H109.23C109.23 21.5844 112.354 19.0988 117.158 19.0988C121.961 19.0988 124.783 21.8197 124.783 26.6246V36.4344H120.215L119.879 34.2176C119.341 35.7622 117.124 36.8714 114.605 36.8714L114.606 36.8699ZM116.42 33.0397C118.401 33.0397 119.779 32.065 119.779 30.1507V29.2432L117.159 29.4785C114.909 29.6801 114.102 30.1843 114.102 31.2583C114.102 32.4683 114.842 33.0382 116.42 33.0382V33.0397Z" fill="white"/>
<path d="M104.017 36.4329H98.8441V23.9357H95.6526V19.635H98.8441V14.4283H104.017V19.635H107.209V23.9357H104.017V36.4329Z" fill="white"/>
<path d="M83.5052 36.8699C79.944 36.8699 77.7272 34.7875 77.7272 31.4951C77.7272 28.4045 79.9104 26.4901 83.9422 26.1876L88.6462 25.8179V25.549C88.6462 23.9021 87.6379 23.0297 85.7908 23.0297C83.6076 23.0297 82.4312 23.87 82.4312 25.381H78.1305C78.1305 21.5844 81.2548 19.0988 86.0581 19.0988C90.8615 19.0988 93.6833 21.8197 93.6833 26.6246V36.4344H89.1137L88.7776 34.2176C88.2398 35.7622 86.023 36.8714 83.5037 36.8714L83.5052 36.8699ZM85.3187 33.0397C87.3002 33.0397 88.6783 32.065 88.6783 30.1507V29.2432L86.0581 29.4785C83.8077 29.6801 83.0011 30.1843 83.0011 31.2583C83.0011 32.4683 83.7405 33.0382 85.3187 33.0382V33.0397Z" fill="white"/>
<path d="M63.9986 36.8699C59.1617 36.8699 56.0374 33.4431 56.0374 28.1356C56.0374 22.8281 59.2289 19.0988 64.3347 19.0988C66.4171 19.0988 68.4001 19.9391 69.3733 21.1812V11.1024H74.5464V36.433H69.6758L69.4069 34.2834C68.4994 35.828 66.4171 36.8699 63.9986 36.8699ZM65.2407 32.1323C67.6592 32.1323 69.3397 30.4533 69.3397 27.9324C69.3397 25.4116 67.6607 23.7326 65.2407 23.7326C62.8207 23.7326 61.2425 25.4452 61.2425 27.9324C61.2425 30.4196 62.7871 32.1323 65.2407 32.1323Z" fill="white"/>
<path d="M228.377 28.3024C228.377 26.6 228.702 25.1104 229.351 23.8336C230.023 22.5344 230.942 21.5264 232.107 20.8096C233.294 20.0704 234.671 19.7008 236.239 19.7008C238.121 19.7008 239.7 20.2048 240.977 21.2128C242.276 22.2208 243.083 23.5648 243.396 25.2448H241.078C240.764 24.1248 240.171 23.2624 239.297 22.6576C238.423 22.0528 237.415 21.7504 236.273 21.7504C235.198 21.7504 234.235 22.0192 233.383 22.5568C232.532 23.0944 231.86 23.856 231.367 24.8416C230.897 25.8048 230.662 26.9472 230.662 28.2688C230.662 29.568 230.886 30.6992 231.334 31.6624C231.782 32.6256 232.409 33.376 233.215 33.9136C234.044 34.4512 235.007 34.72 236.105 34.72C237.337 34.72 238.401 34.4176 239.297 33.8128C240.193 33.1856 240.798 32.3456 241.111 31.2928H243.463C243.217 32.3904 242.747 33.3536 242.052 34.1824C241.358 35.0112 240.495 35.6608 239.465 36.1312C238.457 36.5792 237.337 36.8032 236.105 36.8032C234.559 36.8032 233.204 36.456 232.039 35.7616C230.897 35.0448 230.001 34.048 229.351 32.7712C228.702 31.4944 228.377 30.0048 228.377 28.3024Z" fill="white"/>
<path d="M249.395 36.4H247.076V11.9056H249.395V36.4Z" fill="white"/>
<path d="M253.183 28.2688C253.183 26.5888 253.542 25.1104 254.258 23.8336C254.975 22.5568 255.961 21.5488 257.215 20.8096C258.47 20.0704 259.881 19.7008 261.449 19.7008C263.039 19.7008 264.45 20.0704 265.682 20.8096C266.937 21.5488 267.922 22.5568 268.639 23.8336C269.356 25.1104 269.714 26.5888 269.714 28.2688C269.714 29.904 269.356 31.3712 268.639 32.6704C267.922 33.9472 266.937 34.9552 265.682 35.6944C264.45 36.4336 263.039 36.8032 261.449 36.8032C259.881 36.8032 258.47 36.4336 257.215 35.6944C255.961 34.9552 254.975 33.9472 254.258 32.6704C253.542 31.3712 253.183 29.904 253.183 28.2688ZM255.535 28.2352C255.535 29.512 255.782 30.6432 256.274 31.6288C256.79 32.592 257.484 33.3536 258.358 33.9136C259.254 34.4512 260.284 34.72 261.449 34.72C262.614 34.72 263.633 34.4512 264.506 33.9136C265.402 33.3536 266.097 32.592 266.59 31.6288C267.105 30.6432 267.362 29.512 267.362 28.2352C267.362 26.9808 267.105 25.872 266.59 24.9088C266.097 23.9456 265.402 23.184 264.506 22.624C263.633 22.064 262.614 21.784 261.449 21.784C260.284 21.784 259.254 22.064 258.358 22.624C257.484 23.184 256.79 23.9456 256.274 24.9088C255.782 25.872 255.535 26.9808 255.535 28.2352Z" fill="white"/>
<path d="M284.453 20.1376H286.771V36.4H284.755L284.453 33.6448C284.005 34.5856 283.254 35.3472 282.202 35.9296C281.171 36.512 280.018 36.8032 278.741 36.8032C276.837 36.8032 275.37 36.1984 274.339 34.9888C273.331 33.7792 272.827 32.1888 272.827 30.2176V20.104H275.179V29.4784C275.179 31.4048 275.571 32.76 276.355 33.544C277.162 34.328 278.203 34.72 279.48 34.72C281.048 34.72 282.269 34.216 283.142 33.208C284.016 32.1776 284.453 30.6992 284.453 28.7728V20.1376Z" fill="white"/>
<path d="M297.656 36.8032C296.088 36.8032 294.744 36.4336 293.624 35.6944C292.504 34.9552 291.642 33.9472 291.037 32.6704C290.432 31.3712 290.13 29.9152 290.13 28.3024C290.13 26.6672 290.432 25.2 291.037 23.9008C291.642 22.6016 292.504 21.5824 293.624 20.8432C294.767 20.0816 296.144 19.7008 297.757 19.7008C299.101 19.7008 300.288 19.992 301.319 20.5744C302.372 21.1568 303.178 22.0416 303.738 23.2288V11.9056H306.056V36.4H304.04L303.805 33.0736C303.223 34.328 302.394 35.2688 301.319 35.896C300.244 36.5008 299.023 36.8032 297.656 36.8032ZM298.06 34.6864C299.269 34.6864 300.288 34.4176 301.117 33.88C301.946 33.32 302.584 32.5584 303.032 31.5952C303.48 30.6096 303.704 29.4896 303.704 28.2352C303.704 26.9808 303.48 25.872 303.032 24.9088C302.584 23.9456 301.946 23.184 301.117 22.624C300.288 22.064 299.269 21.784 298.06 21.784C296.895 21.784 295.887 22.064 295.036 22.624C294.207 23.184 293.568 23.9456 293.12 24.9088C292.695 25.872 292.482 26.9808 292.482 28.2352C292.482 29.4896 292.695 30.6096 293.12 31.5952C293.568 32.5584 294.207 33.32 295.036 33.88C295.887 34.4176 296.895 34.6864 298.06 34.6864Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 9.7 KiB

+23
View File
@@ -0,0 +1,23 @@
<svg width="258" height="40" viewBox="0 0 258 40" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M33.28 37.1326H31.1245V33.8288H32.3289C33.0011 33.8288 33.4493 33.4087 33.4493 32.4564V27.3052C33.4493 25.1218 34.4296 23.9454 36.2489 23.3584C34.4296 22.7703 33.4493 21.5951 33.4493 19.4117V14.2605C33.4493 13.3082 33.0011 12.8894 32.3289 12.8894H31.1245V9.58553H33.28C35.6875 9.58553 37.3668 11.0688 37.3668 13.4215V18.8248C37.3668 20.7281 38.5151 21.6804 40.4745 21.6804V25.0403C38.5151 25.0403 37.3668 25.9926 37.3668 27.896V33.2992C37.3668 35.6507 35.6875 37.1339 33.28 37.1339V37.1326Z" fill="#1E302D"/>
<path d="M0 25.0377V21.6779C1.95937 21.6779 3.10775 20.7256 3.10775 18.8222V13.419C3.10775 11.0675 4.78704 9.58298 7.19456 9.58298H9.35V12.8868H8.1456C7.47338 12.8868 7.02523 13.3069 7.02523 14.258V19.4091C7.02523 21.5926 6.04491 22.769 4.22558 23.3559C6.04491 23.9441 7.02523 25.1192 7.02523 27.3027V32.4538C7.02523 33.4061 7.47338 33.8263 8.1456 33.8263H9.35V37.1301H7.19456C4.78704 37.1301 3.10775 35.6469 3.10775 33.2954V27.8921C3.10775 25.9888 1.95937 25.0365 0 25.0365V25.0377Z" fill="#1E302D"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M20.2381 0.063694L27.3142 7.13985L24.0142 10.4386L20.2368 6.66115L16.4594 10.4386L13.1606 7.13985L20.2368 0.063694H20.2381Z" fill="#02C382"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M20.238 9.75996L28.6714 18.1933L25.3726 21.492L20.238 16.3574L15.1034 21.492L11.8047 18.1933L20.238 9.75996Z" fill="#02C382"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M20.2382 19.4563L30.0287 29.2468L26.7299 32.5468L20.2394 26.0562L13.7489 32.5468L10.4502 29.2468L20.2407 19.4563H20.2382Z" fill="#02C382"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M17.9058 39.9132V31.0941H22.5718V39.9132H17.9058Z" fill="#1E302D"/>
<path d="M180.674 30.3608H176.363V19.9464H173.703V16.3625H176.363V12.0236H180.674V16.3625H183.333V19.9464H180.674V30.3608Z" fill="#1E302D"/>
<path d="M160.559 25.9366H164.646C164.702 26.9169 165.43 27.5038 166.745 27.5038C168.06 27.5038 168.705 27.0277 168.705 26.2994C168.705 25.8793 168.481 25.4311 167.444 25.2071L164.869 24.6469C162.293 24.0867 161.034 22.9676 161.034 20.5041C161.034 17.5924 163.526 15.9131 166.885 15.9131C170.245 15.9131 172.401 17.8164 172.401 20.6441H168.314C168.314 19.6918 167.726 19.0488 166.691 19.0488C165.71 19.0488 165.095 19.553 165.095 20.3093C165.095 20.9535 165.627 21.3176 166.607 21.5417L169.21 22.1019C171.506 22.606 172.766 23.6691 172.766 25.9098C172.766 28.9056 170.218 30.7249 166.579 30.7249C162.939 30.7249 160.559 28.7655 160.559 25.9378V25.9366Z" fill="#1E302D"/>
<path d="M151.959 30.7249C147.732 30.7249 144.708 27.6451 144.708 23.3343C144.708 19.0234 147.648 15.9156 151.875 15.9156C156.102 15.9156 159.014 18.7993 159.014 23.3623V24.4546L148.851 24.5107C149.103 26.358 150.14 27.2263 152.043 27.2263C153.666 27.2263 154.815 26.6381 155.123 25.631H159.07C158.565 28.7388 155.794 30.7262 151.959 30.7262V30.7249ZM151.903 19.4142C150.196 19.4142 149.243 20.1705 148.907 21.8498H154.731C154.731 20.3653 153.638 19.4142 151.903 19.4142Z" fill="#1E302D"/>
<path d="M143.694 16.3625V20.4213H142.323C139.859 20.4213 138.376 21.5137 138.376 24.2853V30.3608H134.065V16.3905H138.124L138.348 18.4619C138.936 17.0895 140.167 16.1664 142.044 16.1664C142.548 16.1664 143.107 16.2225 143.695 16.3625H143.694Z" fill="#1E302D"/>
<path d="M116.139 23.3343C116.139 18.9113 119.387 15.9436 123.866 15.9436C128.345 15.9436 131.565 18.9113 131.565 23.3343C131.565 27.7572 128.317 30.6969 123.866 30.6969C119.415 30.6969 116.139 27.7572 116.139 23.3343ZM120.478 23.3062C120.478 25.4337 121.849 26.8341 123.866 26.8341C125.883 26.8341 127.226 25.435 127.226 23.3062C127.226 21.1775 125.855 19.8064 123.866 19.8064C121.877 19.8064 120.478 21.2056 120.478 23.3062Z" fill="#1E302D"/>
<path d="M105.764 16.3625H107.696V15.2421C107.696 11.0713 109.879 9.2507 113.435 9.2507C114.023 9.2507 114.695 9.30672 115.366 9.41875V13.1147H114.162C112.399 13.1147 112.006 14.039 112.006 15.2421V16.3625H115.366V19.9464H112.006V30.3608H107.696V19.9464H105.764V16.3625Z" fill="#1E302D"/>
<path d="M95.505 30.7249C92.5373 30.7249 90.6899 28.9896 90.6899 26.246C90.6899 23.6704 92.5093 22.0751 95.8691 21.823L99.7879 21.5149V21.2909C99.7879 19.9184 98.9476 19.1914 97.4083 19.1914C95.589 19.1914 94.6087 19.8917 94.6087 21.1508H91.0248C91.0248 17.987 93.6284 15.9156 97.6311 15.9156C101.634 15.9156 103.985 18.1831 103.985 22.1872V30.362H100.179L99.8986 28.5147C99.4505 29.8019 97.6031 30.7262 95.5037 30.7262L95.505 30.7249ZM97.0162 27.5331C98.6675 27.5331 99.8159 26.7208 99.8159 25.1256V24.3693L97.6324 24.5654C95.7571 24.7335 95.0848 25.1536 95.0848 26.0486C95.0848 27.0569 95.7011 27.5318 97.0162 27.5318V27.5331Z" fill="#1E302D"/>
<path d="M86.6809 30.3608H82.37V19.9464H79.7104V16.3625H82.37V12.0236H86.6809V16.3625H89.3405V19.9464H86.6809V30.3608Z" fill="#1E302D"/>
<path d="M69.5875 30.7249C66.6198 30.7249 64.7725 28.9896 64.7725 26.246C64.7725 23.6704 66.5918 22.0751 69.9516 21.823L73.8716 21.5149V21.2909C73.8716 19.9184 73.0314 19.1914 71.4921 19.1914C69.6728 19.1914 68.6925 19.8917 68.6925 21.1508H65.1086C65.1086 17.987 67.7122 15.9156 71.7149 15.9156C75.7177 15.9156 78.0692 18.1831 78.0692 22.1872V30.362H74.2612L73.9811 28.5147C73.533 29.8019 71.6857 30.7262 69.5862 30.7262L69.5875 30.7249ZM71.0987 27.5331C72.75 27.5331 73.8984 26.7208 73.8984 25.1256V24.3693L71.7149 24.5654C69.8396 24.7335 69.1674 25.1536 69.1674 26.0486C69.1674 27.0569 69.7836 27.5318 71.0987 27.5318V27.5331Z" fill="#1E302D"/>
<path d="M53.3321 30.7249C49.3013 30.7249 46.6978 27.8692 46.6978 23.4463C46.6978 19.0234 49.3574 15.9156 53.6122 15.9156C55.3475 15.9156 57.0001 16.6159 57.8111 17.6509V9.25197H62.1219V30.3608H58.0631L57.8391 28.5695C57.0828 29.8566 55.3475 30.7249 53.3321 30.7249ZM54.3672 26.7769C56.3826 26.7769 57.7831 25.3777 57.7831 23.277C57.7831 21.1763 56.3839 19.7771 54.3672 19.7771C52.3505 19.7771 51.0354 21.2043 51.0354 23.277C51.0354 25.3497 52.3225 26.7769 54.3672 26.7769Z" fill="#1E302D"/>
<path d="M190.314 23.5854C190.314 22.1667 190.585 20.9254 191.126 19.8614C191.686 18.7787 192.451 17.9387 193.422 17.3414C194.411 16.7254 195.559 16.4174 196.866 16.4174C198.434 16.4174 199.75 16.8374 200.814 17.6774C201.897 18.5174 202.569 19.6374 202.83 21.0374H200.898C200.637 20.104 200.142 19.3854 199.414 18.8814C198.686 18.3774 197.846 18.1254 196.894 18.1254C195.998 18.1254 195.195 18.3494 194.486 18.7974C193.777 19.2454 193.217 19.88 192.806 20.7014C192.414 21.504 192.218 22.456 192.218 23.5574C192.218 24.64 192.405 25.5827 192.778 26.3854C193.151 27.188 193.674 27.8134 194.346 28.2614C195.037 28.7094 195.839 28.9334 196.754 28.9334C197.781 28.9334 198.667 28.6814 199.414 28.1774C200.161 27.6547 200.665 26.9547 200.926 26.0774H202.886C202.681 26.992 202.289 27.7947 201.71 28.4854C201.131 29.176 200.413 29.7174 199.554 30.1094C198.714 30.4827 197.781 30.6694 196.754 30.6694C195.466 30.6694 194.337 30.38 193.366 29.8014C192.414 29.204 191.667 28.3734 191.126 27.3094C190.585 26.2454 190.314 25.004 190.314 23.5854Z" fill="#1E302D"/>
<path d="M207.829 30.3334H205.897V9.92135H207.829V30.3334Z" fill="#1E302D"/>
<path d="M210.986 23.5574C210.986 22.1574 211.285 20.9254 211.882 19.8614C212.479 18.7974 213.301 17.9574 214.346 17.3414C215.391 16.7254 216.567 16.4174 217.874 16.4174C219.199 16.4174 220.375 16.7254 221.402 17.3414C222.447 17.9574 223.269 18.7974 223.866 19.8614C224.463 20.9254 224.762 22.1574 224.762 23.5574C224.762 24.92 224.463 26.1427 223.866 27.2254C223.269 28.2894 222.447 29.1294 221.402 29.7454C220.375 30.3614 219.199 30.6694 217.874 30.6694C216.567 30.6694 215.391 30.3614 214.346 29.7454C213.301 29.1294 212.479 28.2894 211.882 27.2254C211.285 26.1427 210.986 24.92 210.986 23.5574ZM212.946 23.5294C212.946 24.5934 213.151 25.536 213.562 26.3574C213.991 27.16 214.57 27.7947 215.298 28.2614C216.045 28.7094 216.903 28.9334 217.874 28.9334C218.845 28.9334 219.694 28.7094 220.422 28.2614C221.169 27.7947 221.747 27.16 222.158 26.3574C222.587 25.536 222.802 24.5934 222.802 23.5294C222.802 22.484 222.587 21.56 222.158 20.7574C221.747 19.9547 221.169 19.32 220.422 18.8534C219.694 18.3867 218.845 18.1534 217.874 18.1534C216.903 18.1534 216.045 18.3867 215.298 18.8534C214.57 19.32 213.991 19.9547 213.562 20.7574C213.151 21.56 212.946 22.484 212.946 23.5294Z" fill="#1E302D"/>
<path d="M237.044 16.7814H238.976V30.3334H237.296L237.044 28.0374C236.67 28.8214 236.045 29.456 235.168 29.9414C234.309 30.4267 233.348 30.6694 232.284 30.6694C230.697 30.6694 229.474 30.1654 228.616 29.1574C227.776 28.1494 227.356 26.824 227.356 25.1814V16.7534H229.316V24.5654C229.316 26.1707 229.642 27.3 230.296 27.9534C230.968 28.6067 231.836 28.9334 232.9 28.9334C234.206 28.9334 235.224 28.5134 235.952 27.6734C236.68 26.8147 237.044 25.5827 237.044 23.9774V16.7814Z" fill="#1E302D"/>
<path d="M248.047 30.6694C246.74 30.6694 245.62 30.3614 244.687 29.7454C243.754 29.1294 243.035 28.2894 242.531 27.2254C242.027 26.1427 241.775 24.9294 241.775 23.5854C241.775 22.2227 242.027 21 242.531 19.9174C243.035 18.8347 243.754 17.9854 244.687 17.3694C245.639 16.7347 246.787 16.4174 248.131 16.4174C249.251 16.4174 250.24 16.66 251.099 17.1454C251.976 17.6307 252.648 18.368 253.115 19.3574V9.92135H255.047V30.3334H253.367L253.171 27.5614C252.686 28.6067 251.995 29.3907 251.099 29.9134C250.203 30.4174 249.186 30.6694 248.047 30.6694ZM248.383 28.9054C249.391 28.9054 250.24 28.6814 250.931 28.2334C251.622 27.7667 252.154 27.132 252.527 26.3294C252.9 25.508 253.087 24.5747 253.087 23.5294C253.087 22.484 252.9 21.56 252.527 20.7574C252.154 19.9547 251.622 19.32 250.931 18.8534C250.24 18.3867 249.391 18.1534 248.383 18.1534C247.412 18.1534 246.572 18.3867 245.863 18.8534C245.172 19.32 244.64 19.9547 244.267 20.7574C243.912 21.56 243.735 22.484 243.735 23.5294C243.735 24.5747 243.912 25.508 244.267 26.3294C244.64 27.132 245.172 27.7667 245.863 28.2334C246.572 28.6814 247.412 28.9054 248.383 28.9054Z" fill="#1E302D"/>
</svg>

After

Width:  |  Height:  |  Size: 9.7 KiB

+8 -8
View File
@@ -1,15 +1,15 @@
{
"src": {
"@typescript-eslint/no-non-null-assertion": 382,
"@typescript-eslint/no-misused-promises": 848,
"@typescript-eslint/no-non-null-assertion": 380,
"@typescript-eslint/no-misused-promises": 847,
"no-console": 88,
"complexity": 220,
"@typescript-eslint/no-explicit-any": 146,
"trek/no-swallowed-catch": 130,
"complexity": 218,
"@typescript-eslint/no-explicit-any": 144,
"trek/no-swallowed-catch": 128,
"max-params": 32,
"trek/store-without-selector": 67,
"react-hooks/refs": 555,
"react-hooks/set-state-in-effect": 194,
"react-hooks/set-state-in-effect": 193,
"@typescript-eslint/no-floating-promises": 164,
"react-hooks/exhaustive-deps": 116,
"@typescript-eslint/no-unused-vars": 124,
@@ -35,11 +35,11 @@
},
"tests": {
"@typescript-eslint/no-explicit-any": 490,
"@typescript-eslint/no-non-null-assertion": 1927,
"@typescript-eslint/no-non-null-assertion": 1915,
"@typescript-eslint/no-misused-promises": 22,
"@typescript-eslint/no-unused-vars": 51,
"@typescript-eslint/no-floating-promises": 33,
"trek/no-window-globals": 331,
"trek/no-window-globals": 325,
"trek/no-swallowed-catch": 14,
"react-hooks/globals": 5,
"react-hooks/refs": 22,
+10
View File
@@ -130,6 +130,15 @@
"src/mobile/screens/trip/sheets/MTransportFormSheet.tsx"
]
},
{
"feature": "Booking save follow-up: travellers and files before the editor closes",
"hooks": ["src/components/Planner/useBookingFollowUp.ts"],
"desktop": ["src/components/Planner/ReservationModal.tsx", "src/components/Planner/TransportModal.tsx"],
"mobile": [
"src/mobile/screens/trip/sheets/MReservationSheet.tsx",
"src/mobile/screens/trip/sheets/MTransportFormSheet.tsx"
]
},
{
"feature": "Bookings and transports lists",
"hooks": ["src/components/Planner/bookings/bookingsModel.ts"],
@@ -976,6 +985,7 @@
"mobileOnly": {
"src/mobile/screens/admin/MAdminResetMfaSheet.tsx": "Markup only; the 2FA reset confirm that MAdminSheets opens, with the reset handed in through props from its useAdminUserActions.",
"src/mobile/screens/admin/MAdminUi.tsx": "Phone only admin UI primitives (button, card, field, input, secret input, sheet frame).",
"src/mobile/screens/admin/MStorageReclaimCard.tsx": "Markup only; renders the reclaim view and handlers that MAdminStoragePanel takes from useStoragePanel, the twin of StorageReclaimSection.",
"src/mobile/screens/atlas/MAtlasSearch.tsx": "Phone full screen country search overlay; options, suggestions and selection come through props from MAtlas.",
"src/mobile/screens/atlas/MAtlasStatsCard.tsx": "Markup only; renders the AtlasStats that MAtlas passes in.",
"src/mobile/screens/collections/MCollCategoryPicker.tsx": "Phone only category dropdown; value and categories come through props from the collection sheets.",
-4
View File
@@ -899,7 +899,6 @@
"src/components/Roadtrip/useVehicleRange.test.ts",
"src/components/Roadtrip/useVehicleRange.ts",
"src/components/Roadtrip/vehicleRange.ts",
"src/components/Settings/AboutTab.tsx",
"src/components/Settings/AccountTab.test.tsx",
"src/components/Settings/AccountTab.tsx",
"src/components/Settings/AirTrailConnectionSection.test.tsx",
@@ -991,9 +990,6 @@
"src/components/Studio/useBookPresence.ts",
"src/components/Studio/useBookStore.ts",
"src/components/Studio/useSpreadInteraction.ts",
"src/components/SystemNotices/ReleaseNoticeModal.test.tsx",
"src/components/SystemNotices/ReleaseNoticeModal.tsx",
"src/components/SystemNotices/ReleaseNoticeVisuals.tsx",
"src/components/SystemNotices/SystemNoticeBanner.extra.test.tsx",
"src/components/SystemNotices/SystemNoticeBanner.test.tsx",
"src/components/SystemNotices/SystemNoticeBanner.tsx",
+3 -5
View File
@@ -8,13 +8,11 @@
"src/components/Map/MapView.tsx": 1385,
"src/components/Map/MapViewGL.test.tsx": 2919,
"src/components/Map/MapViewGL.tsx": 2218,
"src/components/Map/RouteCalculator.ts": 1063,
"src/components/PDF/TripPDF.tsx": 1082,
"src/components/PDF/TripPDF.tsx": 1039,
"src/components/Planner/DayDetailPanel.test.tsx": 2333,
"src/components/Planner/DayPlanSidebar.test.tsx": 5349,
"src/components/Planner/DayPlanSidebar.tsx": 2936,
"src/components/Planner/DayPlanSidebar.tsx": 2929,
"src/components/Planner/PlaceFormModal.test.tsx": 2836,
"src/components/Planner/PlaceFormModal.tsx": 1157,
"src/components/Planner/PlaceInspector.tsx": 1290,
"src/components/Studio/TravelElements.tsx": 1559,
"src/components/Studio/countryShapes.ts": 2595,
@@ -23,7 +21,7 @@
"src/pages/JourneyDetailPage.test.tsx": 4030,
"src/pages/LoginPage.tsx": 1348,
"src/pages/TripPlannerPage.tsx": 1128,
"src/pages/atlas/useAtlas.ts": 1211,
"src/pages/atlas/useAtlas.ts": 1210,
"src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx": 3518,
"src/pages/tripPlanner/useTripPlanner.test.tsx": 3270,
"src/styles/studio.css": 1918
+1 -1
View File
@@ -35,7 +35,7 @@
"components/Roadtrip/dayColors.ts": 8,
"components/Roadtrip/nightBookend.ts": 1,
"components/Roadtrip/stopKinds.ts": 1,
"components/Settings/AboutTab.tsx": 3,
"components/Settings/AboutTab.tsx": 5,
"components/Settings/AccountTab.tsx": 2,
"components/Settings/AppearanceSettingsTab.tsx": 1,
"components/Settings/PasskeysSection.tsx": 1,
+14
View File
@@ -0,0 +1,14 @@
import type { PlaceContribDecisionRequest, PlaceContribLogQuery } from '@trek/shared';
import apiClient from './client';
/** /api/admin/places-contribute: sharing place details with the TREK Places API. Admin only. */
export const placeContribApi = {
state: (signal?: AbortSignal): Promise<unknown> =>
apiClient.get('/admin/places-contribute', { signal }).then((r) => r.data),
decide: (body: PlaceContribDecisionRequest): Promise<unknown> =>
apiClient.put('/admin/places-contribute/decision', body).then((r) => r.data),
log: (query: Partial<PlaceContribLogQuery>, signal?: AbortSignal): Promise<unknown> =>
apiClient.get('/admin/places-contribute/log', { params: query, signal }).then((r) => r.data),
withdraw: (): Promise<unknown> =>
apiClient.post('/admin/places-contribute/withdraw', { confirm: true }).then((r) => r.data),
};
+1
View File
@@ -22,6 +22,7 @@ const RATE_LIMIT_MESSAGES: Record<string, string> = {
tr: 'Çok fazla deneme. Lütfen daha sonra tekrar deneyin.',
ar: 'محاولات كثيرة جدًا. يرجى المحاولة لاحقًا.',
az: 'Həddindən çox cəhd edildi. Bir az sonra yenidən cəhd edin.',
he: 'יותר מדי ניסיונות. נסו שוב מאוחר יותר.',
id: 'Terlalu banyak percobaan. Coba lagi nanti.',
ja: '試行回数が多すぎます。時間をおいて再度お試しください。',
ko: '시도 횟수가 너무 많습니다. 잠시 후 다시 시도해 주세요.',
+8
View File
@@ -0,0 +1,8 @@
import apiClient from './client';
/** /api/admin/service-identity: how this installation stands with the TREK services. Admin only. */
export const serviceIdentityApi = {
status: (signal?: AbortSignal): Promise<unknown> =>
apiClient.get('/admin/service-identity', { signal }).then((r) => r.data),
regenerate: (): Promise<unknown> => apiClient.post('/admin/service-identity/regenerate').then((r) => r.data),
};
+15
View File
@@ -0,0 +1,15 @@
import type { StorageReclaimConfirmRequest, StorageReclaimState } from '@trek/shared';
import { apiClient } from './client';
/** Admin > Storage, unreferenced files: the nightly deletion switch, a check on demand, and the large-share confirmation. */
export const storageReclaimApi = {
setDelete: (deleteEnabled: boolean): Promise<StorageReclaimState> =>
apiClient.put('/admin/storage/reclaim', { deleteEnabled }).then((r) => r.data),
/** Starts a report-only check in the background (202); its report arrives through the admin state. */
check: (): Promise<{ started: true }> => apiClient.post('/admin/storage/reclaim/run').then((r) => r.data),
/** `unreferenced` is the count the admin was shown: the server refuses when its own count has moved on. */
confirm: (request: StorageReclaimConfirmRequest): Promise<StorageReclaimState> =>
apiClient
.post('/admin/storage/reclaim/confirm', request satisfies StorageReclaimConfirmRequest)
.then((r) => r.data),
};
+19
View File
@@ -0,0 +1,19 @@
import type { ValhallaRelayAction } from '@trek/shared';
/**
* POST /api/routing/valhalla/:action: a question for the TREK services'
* Valhalla, which this server asks with the installation key. The answer is
* Valhalla's own, its status included, so it is handed back as a Response and
* read like the answer of any other Valhalla. Plain fetch on purpose: the
* shared client would turn a 401 into a sign-in redirect and a 429 into a
* toast, where the planner only wants to ask FOSSGIS instead.
*/
export function postValhallaRelay(action: ValhallaRelayAction, body: unknown, signal?: AbortSignal): Promise<Response> {
return fetch(`/api/routing/valhalla/${action}`, {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
signal,
});
}
@@ -0,0 +1,80 @@
// FE-ADMIN-CONTRIB-LOG-001 to FE-ADMIN-CONTRIB-LOG-004
import userEvent from '@testing-library/user-event';
import type { PlaceContribLogEntry } from '@trek/shared';
import { http, HttpResponse } from 'msw';
import { describe, expect, it, vi } from 'vitest';
import { server } from '../../../tests/helpers/msw/server';
import { render, screen, waitFor } from '../../../tests/helpers/render';
import PlaceContribLog from './PlaceContribLog';
vi.mock('../../i18n', async (importOriginal) => ({
...(await importOriginal<typeof import('../../i18n')>()),
useTranslation: () => ({ t: (key: string) => key, locale: 'en-US' }),
}));
const ENTRY: PlaceContribLogEntry = {
id: 1,
day: '2026-10-29',
key: 'osm:n123',
placeName: 'Café Luitpold',
field: 'phone',
valueSummary: '+49 89 242 8750',
result: 'accepted',
reason: null,
};
function serve(entries: PlaceContribLogEntry[], total = entries.length) {
const queries: URLSearchParams[] = [];
server.use(
http.get('/api/admin/places-contribute/log', ({ request }) => {
queries.push(new URL(request.url).searchParams);
return HttpResponse.json({
entries,
total,
page: Number(new URL(request.url).searchParams.get('page') ?? 1),
perPage: 20,
});
})
);
return queries;
}
describe('PlaceContribLog', () => {
it('FE-ADMIN-CONTRIB-LOG-001: lists the place, the value, the field and the result', async () => {
serve([ENTRY]);
render(<PlaceContribLog />);
expect(await screen.findByText('Café Luitpold')).toBeInTheDocument();
expect(screen.getByText('+49 89 242 8750')).toBeInTheDocument();
expect(screen.getByText('admin.contribute.field.phone')).toBeInTheDocument();
expect(screen.getByText('admin.contribute.result.accepted')).toBeInTheDocument();
});
it('FE-ADMIN-CONTRIB-LOG-002: an empty log says nothing was sent', async () => {
serve([]);
render(<PlaceContribLog />);
expect(await screen.findByText('admin.contribute.log.empty')).toBeInTheDocument();
});
it('FE-ADMIN-CONTRIB-LOG-003: pages through a long log', async () => {
const queries = serve([ENTRY], 45);
render(<PlaceContribLog />);
await userEvent.click(await screen.findByRole('button', { name: /common\.showMore/ }));
expect(await screen.findByText('1 / 3')).toBeInTheDocument();
await userEvent.click(screen.getByRole('button', { name: 'admin.contribute.log.next' }));
await waitFor(() => expect(queries[queries.length - 1]?.get('page')).toBe('2'));
expect(queries[queries.length - 1]?.get('perPage')).toBe('20');
});
it('FE-ADMIN-CONTRIB-LOG-004: shows the newest five until the list is opened', async () => {
serve(Array.from({ length: 8 }, (_, i) => ({ ...ENTRY, id: i + 1, placeName: `Place ${i + 1}` })));
render(<PlaceContribLog />);
expect(await screen.findByText('Place 5')).toBeInTheDocument();
expect(screen.queryByText('Place 6')).not.toBeInTheDocument();
const toggle = screen.getByRole('button', { name: 'common.showMore (3)' });
expect(toggle).toHaveAttribute('aria-expanded', 'false');
await userEvent.click(toggle);
expect(screen.getByText('Place 8')).toBeInTheDocument();
await userEvent.click(screen.getByRole('button', { name: 'common.showLess' }));
expect(screen.queryByText('Place 8')).not.toBeInTheDocument();
});
});
@@ -0,0 +1,187 @@
import {
PLACE_CONTRIB_FIELDS,
type PlaceContribField,
type PlaceContribLogResponse,
type PlaceContribLogResult,
} from '@trek/shared';
import { ChevronDown, ChevronLeft, ChevronRight } from 'lucide-react';
import { useEffect, useState } from 'react';
import { useTranslation } from '../../i18n';
import { placeContribRepo } from '../../repo/placeContribRepo';
import { PillSelect } from '../shared/dialogParts';
import { fs } from '../shared/DialogShell';
import { fieldLabel } from './placeContribModel';
const PER_PAGE = 20;
/** Rows shown before the list is opened; a busy log should not push the page down. */
const FOLDED = 5;
const RESULTS: PlaceContribLogResult[] = ['accepted', 'duplicate', 'rejected', 'withheld', 'retracted'];
const RESULT_LOOK: Record<PlaceContribLogResult, string> = {
accepted: 'bg-success-soft text-success',
duplicate: 'bg-surface-tertiary text-content-muted',
rejected: 'bg-danger-soft text-danger',
withheld: 'bg-surface-tertiary text-content-muted',
retracted: 'bg-warning-soft text-warning',
};
/**
* What this installation sent, newest first: the place, the field, a short
* form of the value and what the service made of it. Read only while the fold
* is open, a page at a time, and only the newest FOLDED rows until opened.
*/
export default function PlaceContribLog() {
const { t, locale } = useTranslation();
const [page, setPage] = useState(1);
const [result, setResult] = useState<PlaceContribLogResult | 'all'>('all');
const [field, setField] = useState<PlaceContribField | 'all'>('all');
const [data, setData] = useState<PlaceContribLogResponse | null>(null);
const [open, setOpen] = useState(false);
// The query that failed to load, so a new page or filter clears the message by itself.
const query = `${page}|${result}|${field}`;
const [failedQuery, setFailedQuery] = useState<string | null>(null);
const failed = failedQuery === query;
useEffect(() => {
const controller = new AbortController();
placeContribRepo
.log(
{
page,
perPage: PER_PAGE,
...(result === 'all' ? {} : { result }),
...(field === 'all' ? {} : { field }),
},
controller.signal
)
.then(setData, () => {
if (!controller.signal.aborted) setFailedQuery(`${page}|${result}|${field}`);
});
return () => controller.abort();
}, [page, result, field]);
const pages = data ? Math.max(1, Math.ceil(data.total / PER_PAGE)) : 1;
const foldable = !!data && (data.entries.length > FOLDED || pages > 1);
const rows = data ? (open || !foldable ? data.entries : data.entries.slice(0, FOLDED)) : [];
const day = new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'short' });
return (
<div className="flex flex-col gap-2.5">
<div className="flex flex-wrap gap-2">
<PillSelect<PlaceContribLogResult | 'all'>
quiet
label={t('admin.contribute.log.result')}
value={result}
onChange={(v) => {
setResult(v);
setPage(1);
}}
options={[
{ value: 'all', label: t('admin.contribute.log.allResults') },
...RESULTS.map((r) => ({ value: r, label: t(`admin.contribute.result.${r}`) })),
]}
/>
<PillSelect<PlaceContribField | 'all'>
quiet
label={t('admin.contribute.log.field')}
value={field}
onChange={(v) => {
setField(v);
setPage(1);
}}
options={[
{ value: 'all', label: t('admin.contribute.log.allFields') },
...PLACE_CONTRIB_FIELDS.map((f) => ({ value: f, label: fieldLabel(t, f) })),
]}
/>
</div>
{failed && (
<p className="m-0 text-danger" style={fs(12, 'body')}>
{t('admin.contribute.log.failed')}
</p>
)}
{data && data.entries.length === 0 && (
<p className="m-0 py-3 text-center text-content-faint" style={fs(12, 'body')}>
{t('admin.contribute.log.empty')}
</p>
)}
{data && data.entries.length > 0 && (
<ul className="m-0 list-none divide-y divide-edge-faint overflow-hidden rounded-[12px] border border-edge-faint bg-surface-card p-0">
{rows.map((e) => (
<li key={e.id} className="flex flex-wrap items-center gap-x-2.5 gap-y-1 px-3 py-2">
<span className="w-12 flex-none tabular-nums text-content-faint" style={fs(11.5)}>
{day.format(new Date(`${e.day}T12:00:00`))}
</span>
<span className="min-w-0 flex-1">
<span className="block truncate font-medium text-content" style={fs(12.5, 'body')}>
{e.placeName}
</span>
{e.valueSummary && (
<span className="block truncate text-content-muted" style={fs(11.5)}>
{e.valueSummary}
</span>
)}
</span>
<span
className="inline-flex flex-none items-center rounded-full bg-surface-secondary px-2 py-[2px] text-content-secondary"
style={fs(11)}
>
{fieldLabel(t, e.field)}
</span>
<span
className={`inline-flex flex-none items-center rounded-full px-2 py-[2px] font-semibold ${RESULT_LOOK[e.result]}`}
style={fs(11)}
title={e.reason ?? undefined}
>
{t(`admin.contribute.result.${e.result}`)}
</span>
</li>
))}
</ul>
)}
{foldable && (
<button
type="button"
aria-expanded={open}
onClick={() => setOpen((o) => !o)}
className="inline-flex items-center gap-1 self-start font-medium text-content-muted hover:text-content"
style={fs(12, 'body')}
>
<ChevronDown
size={14}
aria-hidden="true"
className={open ? 'rotate-180 transition-transform' : 'transition-transform'}
/>
{open ? t('common.showLess') : `${t('common.showMore')} (${(data?.total ?? 0) - FOLDED})`}
</button>
)}
{data && open && pages > 1 && (
<div className="flex items-center justify-end gap-2 text-content-muted" style={fs(12, 'body')}>
<button
type="button"
disabled={page <= 1}
onClick={() => setPage((p) => p - 1)}
aria-label={t('admin.contribute.log.previous')}
className="grid h-7 w-7 place-items-center rounded-lg border border-edge-faint bg-surface-card disabled:opacity-40"
>
<ChevronLeft size={14} aria-hidden="true" />
</button>
<span className="tabular-nums">
{page} / {pages}
</span>
<button
type="button"
disabled={page >= pages}
onClick={() => setPage((p) => p + 1)}
aria-label={t('admin.contribute.log.next')}
className="grid h-7 w-7 place-items-center rounded-lg border border-edge-faint bg-surface-card disabled:opacity-40"
>
<ChevronRight size={14} aria-hidden="true" />
</button>
</div>
)}
</div>
);
}
@@ -0,0 +1,204 @@
// FE-ADMIN-CONTRIB-001 to FE-ADMIN-CONTRIB-011
import userEvent from '@testing-library/user-event';
import type { PlaceContribDecisionRequest, PlaceContribState } from '@trek/shared';
import { http, HttpResponse } from 'msw';
import { describe, expect, it, vi } from 'vitest';
import { server } from '../../../tests/helpers/msw/server';
import { render, screen, waitFor, within } from '../../../tests/helpers/render';
import PlaceContribPanel from './PlaceContribPanel';
// The keys themselves, so a test fails on a missing or renamed key rather than on wording.
vi.mock('../../i18n', async (importOriginal) => ({
...(await importOriginal<typeof import('../../i18n')>()),
useTranslation: () => ({ t: (key: string) => key, locale: 'en-US' }),
}));
const ON = { website: true, phone: true, email: true, opening_hours: true, description: true, image: true };
const UNDECIDED: PlaceContribState = {
termsVersion: 1,
ceiling: 'admin',
eligible: true,
ineligibleReason: null,
consent: { enabled: false, fields: ON, termsVersion: null, decision: null, decidedBy: null, decidedAt: null },
showPrompt: true,
snoozedUntil: null,
active: false,
counts: { accepted: 0, duplicate: 0, rejected: 0, withheld: 0, retracted: 0 },
lastSuccessDay: null,
queue: { size: 0, cap: 5000, full: false },
pauseReason: null,
registrationOpen: false,
};
const AGREED: PlaceContribState = {
...UNDECIDED,
showPrompt: false,
active: true,
consent: {
enabled: true,
fields: ON,
termsVersion: 1,
decision: 'agreed',
decidedBy: 1,
decidedAt: '2026-10-30T10:00:00Z',
},
counts: { accepted: 42, duplicate: 3, rejected: 1, withheld: 5, retracted: 0 },
lastSuccessDay: '2026-10-29',
queue: { size: 7, cap: 5000, full: false },
};
/** Serves `state`, records every decision and answers it with `answer`. */
function serve(
state: PlaceContribState,
answer: (body: PlaceContribDecisionRequest) => PlaceContribState = () => state
) {
const decisions: PlaceContribDecisionRequest[] = [];
server.use(
http.get('/api/admin/places-contribute', () => HttpResponse.json(state)),
http.put('/api/admin/places-contribute/decision', async ({ request }) => {
const body = (await request.json()) as PlaceContribDecisionRequest;
decisions.push(body);
return HttpResponse.json(answer(body));
}),
http.get('/api/admin/places-contribute/log', () =>
HttpResponse.json({ entries: [], total: 0, page: 1, perPage: 20 })
)
);
return decisions;
}
describe('PlaceContribPanel', () => {
it('FE-ADMIN-CONTRIB-001: an undecided admin gets the prompt with every field switched on', async () => {
serve(UNDECIDED);
render(<PlaceContribPanel />);
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByText('admin.contribute.prompt.title')).toBeInTheDocument();
for (const field of Object.keys(ON)) {
expect(within(dialog).getByRole('button', { name: `admin.contribute.field.${field}` })).toHaveAttribute(
'aria-pressed',
'true'
);
}
expect(within(dialog).getByText('admin.contribute.never.notes')).toBeInTheDocument();
expect(within(dialog).getByText('admin.contribute.never.providers')).toBeInTheDocument();
});
it('FE-ADMIN-CONTRIB-002: nothing is decided until a button is pressed, and Agree sends the switches it shows', async () => {
const decisions = serve(UNDECIDED, () => AGREED);
render(<PlaceContribPanel />);
const dialog = await screen.findByRole('dialog');
expect(decisions).toHaveLength(0);
await userEvent.click(within(dialog).getByRole('button', { name: 'admin.contribute.field.image' }));
await userEvent.click(within(dialog).getByRole('button', { name: 'admin.contribute.prompt.agree' }));
await waitFor(() => expect(decisions).toHaveLength(1));
expect(decisions[0]).toEqual({ action: 'agree', termsVersion: 1, fields: { ...ON, image: false } });
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
expect(screen.getByText('admin.contribute.status.active')).toBeInTheDocument();
});
it('FE-ADMIN-CONTRIB-003: Agree is unavailable with every field off', async () => {
serve(UNDECIDED);
render(<PlaceContribPanel />);
const dialog = await screen.findByRole('dialog');
for (const field of Object.keys(ON)) {
await userEvent.click(within(dialog).getByRole('button', { name: `admin.contribute.field.${field}` }));
}
expect(within(dialog).getByRole('button', { name: 'admin.contribute.prompt.agree' })).toBeDisabled();
});
it('FE-ADMIN-CONTRIB-004: "not now" snoozes and "no" declines for the current terms', async () => {
const decisions = serve(UNDECIDED, () => ({ ...UNDECIDED, showPrompt: false }));
const { unmount } = render(<PlaceContribPanel />);
await userEvent.click(
within(await screen.findByRole('dialog')).getByRole('button', { name: 'admin.contribute.prompt.snooze' })
);
await waitFor(() => expect(decisions).toEqual([{ action: 'snooze' }]));
unmount();
render(<PlaceContribPanel />);
await userEvent.click(
within(await screen.findByRole('dialog')).getByRole('button', { name: 'admin.contribute.prompt.decline' })
);
await waitFor(() => expect(decisions[1]).toEqual({ action: 'decline', termsVersion: 1 }));
});
it('FE-ADMIN-CONTRIB-005: closing the prompt decides nothing', async () => {
const decisions = serve(UNDECIDED);
render(<PlaceContribPanel />);
await screen.findByRole('dialog');
await userEvent.keyboard('{Escape}');
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
expect(decisions).toHaveLength(0);
});
it('FE-ADMIN-CONTRIB-006: an agreement shows its figures and a switch per field', async () => {
serve(AGREED);
render(<PlaceContribPanel />);
expect(await screen.findByText('admin.contribute.status.active')).toBeInTheDocument();
expect(screen.getByText('42')).toBeInTheDocument();
expect(screen.getByText('7')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'admin.contribute.field.phone' })).toHaveAttribute(
'aria-pressed',
'true'
);
expect(screen.queryByRole('dialog')).toBeNull();
});
it('FE-ADMIN-CONTRIB-007: switching a field off sends the new switches', async () => {
const decisions = serve(AGREED);
render(<PlaceContribPanel />);
await userEvent.click(await screen.findByRole('button', { name: 'admin.contribute.field.description' }));
await waitFor(() => expect(decisions).toEqual([{ action: 'fields', fields: { ...ON, description: false } }]));
});
it('FE-ADMIN-CONTRIB-008: the master switch asks before it stops sharing', async () => {
const decisions = serve(AGREED, () => ({
...AGREED,
active: false,
consent: { ...AGREED.consent, enabled: false, decision: 'off' },
}));
render(<PlaceContribPanel />);
await userEvent.click(await screen.findByRole('button', { name: 'admin.contribute.title' }));
expect(decisions).toHaveLength(0);
await userEvent.click(screen.getByRole('button', { name: 'admin.contribute.offConfirm' }));
await waitFor(() => expect(decisions).toEqual([{ action: 'off' }]));
});
it('FE-ADMIN-CONTRIB-009: an installation that cannot share says why and has no prompt', async () => {
serve({ ...UNDECIDED, eligible: false, ineligibleReason: 'custom_places_url', showPrompt: false });
render(<PlaceContribPanel />);
expect(await screen.findByText('admin.contribute.ineligible.custom_places_url')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'admin.contribute.title' })).toBeDisabled();
expect(screen.queryByRole('dialog')).toBeNull();
});
it('FE-ADMIN-CONTRIB-010: open registration is named in the prompt', async () => {
serve({ ...UNDECIDED, registrationOpen: true });
render(<PlaceContribPanel />);
expect(
await within(await screen.findByRole('dialog')).findByText('admin.contribute.prompt.openRegistration')
).toBeInTheDocument();
});
it('FE-ADMIN-CONTRIB-011: asks again while the key is still being fetched, and the prompt follows', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true });
try {
let reads = 0;
server.use(
http.get('/api/admin/places-contribute', () => {
reads += 1;
return HttpResponse.json(
reads === 1 ? { ...UNDECIDED, eligible: false, ineligibleReason: 'no_key', showPrompt: false } : UNDECIDED
);
})
);
render(<PlaceContribPanel />);
expect(await screen.findByText('admin.contribute.ineligible.no_key')).toBeInTheDocument();
await vi.advanceTimersByTimeAsync(3_000);
expect(await screen.findByRole('dialog')).toBeInTheDocument();
expect(reads).toBe(2);
} finally {
vi.useRealTimers();
}
});
});
@@ -0,0 +1,200 @@
import type { PlaceContribField, PlaceContribState } from '@trek/shared';
import { ChevronRight, HeartHandshake, Undo2 } from 'lucide-react';
import { useState } from 'react';
import { useTranslation } from '../../i18n';
import type { TranslationFn } from '../../types';
import { getApiErrorMessage } from '../../utils/apiError';
import { SettingsCard, StatusPill } from '../Settings/settingsKit';
import ToggleSwitch from '../Settings/ToggleSwitch';
import ConfirmDialog from '../shared/ConfirmDialog';
import { fs } from '../shared/DialogShell';
import { useToast } from '../shared/Toast';
import { FigureBadge } from '../Tours/paddle/FigureBadge';
import PlaceContribLog from './PlaceContribLog';
import {
contribNote,
contribStatus,
fieldEntries,
fieldLabel,
refusalReason,
type ContribStatus,
} from './placeContribModel';
import PlaceContribPrompt from './PlaceContribPrompt';
import { usePlaceContrib } from './usePlaceContrib';
const PILL_TONE: Record<ContribStatus, 'success' | 'warning' | 'neutral'> = {
active: 'success',
paused: 'warning',
off: 'neutral',
unavailable: 'neutral',
};
function Figures({ state, t }: { state: PlaceContribState; t: TranslationFn }) {
const { locale } = useTranslation();
const number = new Intl.NumberFormat(locale);
const last = state.lastSuccessDay
? new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'short' }).format(
new Date(`${state.lastSuccessDay}T12:00:00`)
)
: t('admin.contribute.never');
return (
<div className="flex flex-wrap gap-1.5">
<FigureBadge
label={t('admin.contribute.figure.accepted')}
value={number.format(state.counts.accepted)}
info={t('admin.contribute.figure.acceptedInfo')}
/>
<FigureBadge
label={t('admin.contribute.figure.queue')}
value={number.format(state.queue.size)}
tone={state.queue.full ? 'warning' : 'neutral'}
info={state.queue.full ? t('admin.contribute.figure.queueFull') : undefined}
/>
<FigureBadge label={t('admin.contribute.figure.last')} value={last} />
</div>
);
}
/**
* Sharing place details with the TREK Places API, inside the TREK API card:
* one switch for the installation, one per field, the transmission log and the
* way to take everything back. Turning it on for the first time opens the same
* prompt an admin gets on the first visit, so an agreement always comes from it.
*/
export default function PlaceContribPanel() {
const { t } = useTranslation();
const toast = useToast();
const contrib = usePlaceContrib();
const { state } = contrib;
const [prompting, setPrompting] = useState<boolean | null>(null);
const [confirm, setConfirm] = useState<'off' | 'withdraw' | null>(null);
if (!state) return null;
const status = contribStatus(state);
const agreed = state.consent.decision === 'agreed' && state.consent.termsVersion === state.termsVersion;
// The prompt opens by itself once per visit while the server asks for it.
const showPrompt = prompting ?? state.showPrompt;
const fail = (err: unknown) => {
const reason = refusalReason(err);
toast.error(
reason === 'terms_outdated' || reason === 'no_field'
? t(`admin.contribute.refused.${reason}`)
: getApiErrorMessage(err, t('common.error'))
);
};
const toggleField = (field: PlaceContribField) => {
const fields = { ...state.consent.fields, [field]: !state.consent.fields[field] };
if (!Object.values(fields).some(Boolean)) {
setConfirm('off');
return;
}
contrib.decide({ action: 'fields', fields }).catch(fail);
};
const withdraw = () => {
setConfirm(null);
contrib.withdraw().then((r) => {
const total = Object.values(r.withdrawn).reduce((a, b) => a + b, 0);
toast.success(t('admin.contribute.withdrawn', { total }));
}, fail);
};
return (
<SettingsCard
flush
icon={HeartHandshake}
title={t('admin.contribute.title')}
badge={<StatusPill tone={PILL_TONE[status]}>{t(`admin.contribute.status.${status}`)}</StatusPill>}
hint={contribNote(t, state)}
action={
<ToggleSwitch
on={agreed && state.consent.enabled}
label={t('admin.contribute.title')}
disabled={!state.eligible || contrib.busy}
onToggle={() => (agreed && state.consent.enabled ? setConfirm('off') : setPrompting(true))}
/>
}
bodyClassName="flex flex-col gap-3 p-4"
>
{agreed && state.consent.enabled && (
<>
<Figures state={state} t={t} />
<ul className="m-0 grid list-none grid-cols-2 gap-1.5 p-0 max-sm:grid-cols-1">
{fieldEntries(state.consent.fields).map(([field, on]) => (
<li
key={field}
className="flex items-center justify-between gap-3 rounded-[12px] border border-edge-faint bg-surface-card px-3 py-1.5"
>
<span className={on ? 'text-content' : 'text-content-faint'} style={fs(12.5, 'body')}>
{fieldLabel(t, field)}
</span>
<ToggleSwitch
on={on}
label={fieldLabel(t, field)}
disabled={contrib.busy}
onToggle={() => toggleField(field)}
/>
</li>
))}
</ul>
</>
)}
{(agreed || state.consent.decision === 'off') && (
<details className="group overflow-hidden rounded-[12px] border border-edge-faint bg-surface-card">
{/* The admin page's fold head (pages/admin/FoldSummary), which a component cannot import. */}
<summary className="flex cursor-pointer list-none items-center gap-2.5 px-3.5 py-2.5 hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[color:var(--text-primary)] [&::-webkit-details-marker]:hidden">
<ChevronRight
size={15}
strokeWidth={2}
className="flex-none text-content-faint transition-transform group-open:rotate-90"
aria-hidden="true"
/>
<span className="font-medium text-content" style={fs(12.5, 'body')}>
{t('admin.contribute.log.title')}
</span>
</summary>
<div className="flex flex-col gap-3 border-t border-edge-faint p-3">
<PlaceContribLog />
<button
type="button"
disabled={contrib.busy}
onClick={() => setConfirm('withdraw')}
className="inline-flex items-center gap-1.5 self-start rounded-lg border border-edge-faint bg-surface-card px-3 py-1.5 font-medium text-danger hover:bg-danger-soft disabled:opacity-40"
style={fs(12.5, 'body')}
>
<Undo2 size={14} aria-hidden="true" />
{t('admin.contribute.withdraw')}
</button>
</div>
</details>
)}
{showPrompt && state.eligible && (
<PlaceContribPrompt state={state} contrib={contrib} onClose={() => setPrompting(false)} />
)}
<ConfirmDialog
isOpen={confirm === 'off'}
onClose={() => setConfirm(null)}
onConfirm={() => {
setConfirm(null);
contrib.decide({ action: 'off' }).catch(fail);
}}
title={t('admin.contribute.offTitle')}
message={t('admin.contribute.offMessage')}
confirmLabel={t('admin.contribute.offConfirm')}
/>
<ConfirmDialog
isOpen={confirm === 'withdraw'}
onClose={() => setConfirm(null)}
onConfirm={withdraw}
title={t('admin.contribute.withdrawTitle')}
message={t('admin.contribute.withdrawMessage')}
confirmLabel={t('admin.contribute.withdraw')}
danger
/>
</SettingsCard>
);
}
@@ -0,0 +1,198 @@
import type { PlaceContribFieldSwitches, PlaceContribState } from '@trek/shared';
import { Check, HeartHandshake, ShieldCheck, TriangleAlert, X } from 'lucide-react';
import { useState } from 'react';
import { useTranslation } from '../../i18n';
import { getApiErrorMessage } from '../../utils/apiError';
import ToggleSwitch from '../Settings/ToggleSwitch';
import {
DialogButton,
DialogFooter,
DialogHeader,
DialogShell,
DialogTile,
FooterSpacer,
fs,
NEUTRAL_TINT,
} from '../shared/DialogShell';
import { useToast } from '../shared/Toast';
import { ALL_FIELDS_ON, fieldEntries, fieldLabel, refusalReason } from './placeContribModel';
import type { usePlaceContrib } from './usePlaceContrib';
const NEVER = ['notes', 'files', 'trips', 'people', 'providers'] as const;
/**
* The question an admin gets once: share what this installation's users type
* about places with every other TREK. Asked warmly and with every field already
* on, because saying yes is the point of asking; but nothing leaves before the
* admin presses Agree, and "not now" and "no" are as easy to reach.
*
* Closing the dialog decides nothing: it comes back on the next visit until one
* of the three buttons is pressed.
*/
export default function PlaceContribPrompt({
state,
contrib,
onClose,
}: {
state: PlaceContribState;
contrib: ReturnType<typeof usePlaceContrib>;
onClose: () => void;
}) {
const { t } = useTranslation();
const toast = useToast();
const [fields, setFields] = useState<PlaceContribFieldSwitches>(() =>
state.consent.decision === 'agreed' || state.consent.decision === 'off' ? state.consent.fields : ALL_FIELDS_ON
);
const none = !Object.values(fields).some(Boolean);
const run = async (body: Parameters<typeof contrib.decide>[0], done?: string) => {
try {
await contrib.decide(body);
if (done) toast.success(done);
onClose();
} catch (err) {
const reason = refusalReason(err);
toast.error(
reason === 'terms_outdated' || reason === 'no_field'
? t(`admin.contribute.refused.${reason}`)
: getApiErrorMessage(err, t('common.error'))
);
}
};
return (
<DialogShell
onClose={onClose}
labelledBy="place-contrib-prompt-title"
width="detail"
blocked={contrib.busy}
header={
<DialogHeader
tile={
<DialogTile>
<HeartHandshake size={22} className="text-content" aria-hidden="true" />
</DialogTile>
}
tint={NEUTRAL_TINT}
labelId="place-contrib-prompt-title"
eyebrow="TREK Places API"
title={t('admin.contribute.prompt.title')}
onClose={onClose}
/>
}
footer={
<DialogFooter>
<DialogButton
disabled={contrib.busy}
onClick={() => void run({ action: 'decline', termsVersion: state.termsVersion })}
>
{t('admin.contribute.prompt.decline')}
</DialogButton>
<FooterSpacer />
<DialogButton disabled={contrib.busy} onClick={() => void run({ action: 'snooze' })}>
{t('admin.contribute.prompt.snooze')}
</DialogButton>
<DialogButton
variant="primary"
autoFocus
disabled={contrib.busy || none}
icon={<HeartHandshake size={15} aria-hidden="true" />}
onClick={() =>
void run(
{ action: 'agree', termsVersion: state.termsVersion, fields },
t('admin.contribute.prompt.thanks')
)
}
>
{t('admin.contribute.prompt.agree')}
</DialogButton>
</DialogFooter>
}
>
<div className="flex flex-col gap-2">
<p className="m-0 leading-relaxed text-content" style={fs(14, 'body')}>
{t('admin.contribute.prompt.lead')}
</p>
<p className="m-0 leading-relaxed text-content-secondary" style={fs(13, 'body')}>
{t('admin.contribute.prompt.why')}
</p>
</div>
<section className="flex flex-col gap-2" aria-labelledby="place-contrib-prompt-fields">
<h3 id="place-contrib-prompt-fields" className="m-0 font-semibold text-content" style={fs(13, 'body')}>
{t('admin.contribute.prompt.whatLabel')}
</h3>
<ul className="m-0 grid list-none grid-cols-2 gap-1.5 p-0 max-sm:grid-cols-1">
{fieldEntries(fields).map(([field, on]) => (
<li
key={field}
className="flex items-center justify-between gap-3 rounded-[12px] border border-edge-faint bg-surface-secondary px-3 py-2"
>
<span className="flex min-w-0 items-center gap-2 text-content" style={fs(13, 'body')}>
<Check
size={14}
strokeWidth={2.4}
className={on ? 'text-success' : 'text-content-faint opacity-40'}
aria-hidden="true"
/>
<span className="truncate">{fieldLabel(t, field)}</span>
</span>
<ToggleSwitch
on={on}
label={fieldLabel(t, field)}
onToggle={() => setFields((f) => ({ ...f, [field]: !f[field] }))}
/>
</li>
))}
</ul>
<p className="m-0 leading-normal text-content-faint" style={fs(11.5)}>
{t('admin.contribute.prompt.imageNote')}
</p>
</section>
<section
className="flex flex-col gap-2 rounded-[14px] border border-edge-faint bg-surface-secondary p-3"
aria-labelledby="place-contrib-prompt-never"
>
<h3
id="place-contrib-prompt-never"
className="m-0 flex items-center gap-1.5 font-semibold text-content"
style={fs(13, 'body')}
>
<ShieldCheck size={15} className="text-success" aria-hidden="true" />
{t('admin.contribute.prompt.neverLabel')}
</h3>
<ul className="m-0 flex list-none flex-wrap gap-1.5 p-0">
{NEVER.map((item) => (
<li
key={item}
className="inline-flex items-center gap-1 rounded-full border border-edge-faint bg-surface-card px-2.5 py-[3px] font-medium text-content-secondary"
style={fs(11.5)}
>
<X size={12} strokeWidth={2.4} className="text-content-faint" aria-hidden="true" />
{t(`admin.contribute.never.${item}`)}
</li>
))}
</ul>
<p className="m-0 leading-normal text-content-muted" style={fs(12, 'body')}>
{t('admin.contribute.prompt.how')} {t('admin.contribute.prompt.past')}
</p>
</section>
{state.registrationOpen && (
<p
className="m-0 flex items-start gap-2 rounded-[12px] bg-warning-soft px-3 py-2 leading-normal text-warning"
style={fs(12, 'body')}
role="note"
>
<TriangleAlert size={15} className="mt-[1px] flex-none" aria-hidden="true" />
{t('admin.contribute.prompt.openRegistration')}
</p>
)}
<p className="m-0 text-content-faint" style={fs(11.5)}>
{t('admin.contribute.prompt.footnote')}
</p>
</DialogShell>
);
}
@@ -1,4 +1,5 @@
import { useId, useState } from 'react'
import type { ValhallaProvider } from '@trek/shared'
import { useTranslation } from '../../i18n/TranslationContext'
import { fs } from '../shared/DialogShell'
import { INPUT, LABEL } from '../shared/dialogParts'
@@ -6,6 +7,7 @@ import { INPUT, LABEL } from '../shared/dialogParts'
export interface RoutingDefaults {
routing_base_url?: string
valhalla_base_url?: string
routing_valhalla_provider?: ValhallaProvider
}
interface RoutingFieldsProps {
@@ -25,6 +27,14 @@ const ROUTERS = [
{ key: 'valhalla_base_url', label: 'settings.valhallaBase', hint: 'settings.valhallaBaseHint', placeholder: 'https://valhalla.example.org' },
] as const
// '' is no choice of the admin: the instance then decides as before the choice existed.
const PROVIDERS = [
{ value: '', labelKey: 'settings.valhallaProviderOption.auto' },
{ value: 'trek', labelKey: 'settings.valhallaProviderOption.trek' },
{ value: 'fossgis', labelKey: 'settings.valhallaProviderOption.fossgis' },
{ value: 'custom', labelKey: 'settings.valhallaProviderOption.custom' },
] as const
// The phone screen's look, unchanged: MAdminDefaultUserSettings passes its own hint class.
const PHONE = {
wrap: 'min-w-0 space-y-1.5',
@@ -43,6 +53,12 @@ const DESKTOP = {
input: INPUT,
}
function FieldHint({ id, text, hintClassName }: { id: string; text: string; hintClassName?: string }) {
return hintClassName !== undefined
? <p id={id} className={hintClassName}>{text}</p>
: <p id={id} className="m-0 mt-1 leading-normal text-content-faint" style={fs(11)}>{text}</p>
}
function RoutingUrlField({ router, defaults, onSave, onReset, hintClassName }: RoutingFieldsProps & { router: typeof ROUTERS[number] }) {
const { t } = useTranslation()
const id = useId()
@@ -81,14 +97,45 @@ function RoutingUrlField({ router, defaults, onSave, onReset, hintClassName }: R
aria-describedby={`${id}-hint`}
className={look.input}
/>
{phone
? <p id={`${id}-hint`} className={hintClassName}>{t(router.hint)}</p>
: <p id={`${id}-hint`} className="m-0 mt-1 leading-normal text-content-faint" style={fs(11)}>{t(router.hint)}</p>}
<FieldHint id={`${id}-hint`} text={t(router.hint)} hintClassName={hintClassName} />
</div>
)
}
/** Which Valhalla answers what OSRM cannot; picking "automatic" clears the choice. */
function RoutingProviderField({ defaults, onSave, onReset, hintClassName }: RoutingFieldsProps) {
const { t } = useTranslation()
const id = useId()
const [saving, setSaving] = useState(false)
const phone = hintClassName !== undefined
const look = phone ? PHONE : DESKTOP
const pick = async (value: string) => {
setSaving(true)
try {
if (value === '') await onReset('routing_valhalla_provider')
else await onSave({ routing_valhalla_provider: value as ValhallaProvider })
} finally { setSaving(false) }
}
return (
<div className={`${look.wrap} ${!phone && saving ? 'opacity-60' : ''}`} aria-busy={saving}>
<div className={look.head}>
<label htmlFor={id} className={look.label}>{t('settings.valhallaProvider')}</label>
</div>
<select id={id} value={defaults.routing_valhalla_provider ?? ''} disabled={saving}
onChange={e => void pick(e.target.value)} aria-describedby={`${id}-hint`} className={look.input}>
{PROVIDERS.map(option => <option key={option.value} value={option.value}>{t(option.labelKey)}</option>)}
</select>
<FieldHint id={`${id}-hint`} text={t('settings.valhallaProviderHint')} hintClassName={hintClassName} />
</div>
)
}
export default function RoutingInstanceFields(props: RoutingFieldsProps) {
const phone = props.hintClassName !== undefined
return <div className={phone ? 'flex flex-col gap-3' : 'flex flex-col gap-4'}>{ROUTERS.map(router => <RoutingUrlField key={router.key} router={router} {...props} />)}</div>
return (
<div className={phone ? 'flex flex-col gap-3' : 'flex flex-col gap-4'}>
<RoutingProviderField {...props} />
{ROUTERS.map(router => <RoutingUrlField key={router.key} router={router} {...props} />)}
</div>
)
}
@@ -0,0 +1,160 @@
// FE-ADMIN-SVCID-001 to FE-ADMIN-SVCID-010
import userEvent from '@testing-library/user-event';
import type { ServiceIdentityStatus } from '@trek/shared';
import { http, HttpResponse } from 'msw';
import { describe, expect, it, vi } from 'vitest';
import { server } from '../../../tests/helpers/msw/server';
import { render, screen, waitFor } from '../../../tests/helpers/render';
import ServiceIdentityPanel from './ServiceIdentityPanel';
// The keys themselves, so a test fails on a missing or renamed key rather than on wording.
vi.mock('../../i18n', async (importOriginal) => ({
...(await importOriginal<typeof import('../../i18n')>()),
useTranslation: () => ({ t: (key: string) => key, locale: 'en-US' }),
}));
const QUOTA = { limit: 10_000, used: 2_500, remaining: 7_500, resetAt: '2026-10-30T00:00:00.000Z' };
const CONNECTED: ServiceIdentityStatus = {
state: 'connected',
tier: 'std',
keySource: 'registered',
services: [
{ service: 'places', inUse: true, quota: QUOTA },
{ service: 'photon', inUse: false, quota: null },
{ service: 'valhalla', inUse: false, quota: null },
],
lastSeenAt: '2026-10-29T12:00:00.000Z',
};
function serve(status: ServiceIdentityStatus) {
server.use(http.get('/api/admin/service-identity', () => HttpResponse.json(status)));
}
describe('ServiceIdentityPanel', () => {
it('FE-ADMIN-SVCID-001: shows the state, the tier and today against the limit', async () => {
serve(CONNECTED);
render(<ServiceIdentityPanel />);
expect(await screen.findByText('admin.trekApi.quota.state.connected')).toBeInTheDocument();
expect(screen.getByText('admin.trekApi.quota.tier.std')).toBeInTheDocument();
const bar = screen.getByRole('progressbar', { name: 'admin.trekApi.quota.service.places' });
expect(bar).toHaveAttribute('aria-valuenow', '2500');
expect(bar).toHaveAttribute('aria-valuemax', '10000');
// What is left is the figure of the tile; used and the limit sit beside it as badges.
expect(screen.getByText('7,500')).toBeInTheDocument();
expect(screen.getByText('2,500')).toBeInTheDocument();
expect(screen.getByText('10,000')).toBeInTheDocument();
expect(screen.getByText('admin.trekApi.quota.limit')).toBeInTheDocument();
// The day starts again at the same time for every service, so it is said once, in the header.
expect(screen.getAllByText('admin.trekApi.quota.resets')).toHaveLength(1);
expect(screen.queryByText(/admin\.trekApi\.quota\.hint\./)).toBeNull();
});
it('FE-ADMIN-SVCID-002: an installation without a key says so and offers a new identity', async () => {
serve({ state: 'legacy', tier: 'legacy', keySource: null, services: [], lastSeenAt: null });
render(<ServiceIdentityPanel />);
expect(await screen.findByText('admin.trekApi.quota.hint.legacy')).toBeInTheDocument();
expect(screen.queryByRole('progressbar')).toBeNull();
expect(screen.getByRole('button', { name: 'admin.trekApi.quota.regenerate' })).toBeInTheDocument();
});
it('FE-ADMIN-SVCID-003: switched off, it shows why and offers nothing', async () => {
serve({ state: 'off', tier: null, keySource: null, services: [], lastSeenAt: null });
render(<ServiceIdentityPanel />);
expect(await screen.findByText('admin.trekApi.quota.hint.off')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'admin.trekApi.quota.regenerate' })).toBeNull();
});
it('FE-ADMIN-SVCID-004: a key from the environment is named, and only changed there', async () => {
serve({ ...CONNECTED, keySource: 'env', tier: 'own' });
render(<ServiceIdentityPanel />);
// A badge naming the variable; the sentence explaining it is its tooltip.
expect(await screen.findByText('TREK_SERVICES_KEY')).toBeInTheDocument();
expect(screen.getByText('admin.trekApi.quota.key')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'admin.trekApi.quota.regenerate' })).toBeNull();
});
it('FE-ADMIN-SVCID-005: a service in use without an allowance to show says it cannot be read', async () => {
serve({ ...CONNECTED, services: [{ service: 'places', inUse: true, quota: null }] });
render(<ServiceIdentityPanel />);
expect(await screen.findByText('admin.trekApi.quota.unavailable')).toBeInTheDocument();
expect(screen.queryByRole('progressbar')).toBeNull();
});
it('FE-ADMIN-SVCID-009: lists place search, address search and routing, each with its own allowance', async () => {
serve({
...CONNECTED,
services: [
{ service: 'places', inUse: true, quota: QUOTA },
{ service: 'photon', inUse: true, quota: { ...QUOTA, used: 40, remaining: 9_960 } },
{ service: 'valhalla', inUse: true, quota: { ...QUOTA, used: 9_500, remaining: 500 } },
],
});
render(<ServiceIdentityPanel />);
const list = await screen.findByRole('list', { name: 'admin.trekApi.quota.title' });
expect(list.querySelectorAll('li')).toHaveLength(3);
const value = (name: string) => screen.getByRole('progressbar', { name }).getAttribute('aria-valuenow');
expect(value('admin.trekApi.quota.service.places')).toBe('2500');
expect(value('admin.trekApi.quota.service.photon')).toBe('40');
expect(value('admin.trekApi.quota.service.valhalla')).toBe('9500');
expect(screen.queryByText('admin.trekApi.quota.notInUse')).toBeNull();
});
it('FE-ADMIN-SVCID-010: a service this instance does not ask is named as not in use, its allowance still shown', async () => {
serve({
...CONNECTED,
services: [
{ service: 'places', inUse: true, quota: QUOTA },
{ service: 'photon', inUse: false, quota: null },
{ service: 'valhalla', inUse: false, quota: QUOTA },
],
});
render(<ServiceIdentityPanel />);
expect(await screen.findAllByText('admin.trekApi.quota.notInUse')).toHaveLength(2);
expect(screen.getAllByRole('progressbar')).toHaveLength(2);
expect(screen.queryByText('admin.trekApi.quota.unavailable')).toBeNull();
});
it('FE-ADMIN-SVCID-006: a failed read says so instead of showing nothing', async () => {
server.use(http.get('/api/admin/service-identity', () => HttpResponse.json({ error: 'nope' }, { status: 500 })));
render(<ServiceIdentityPanel />);
expect(await screen.findByText('admin.trekApi.quota.unavailable')).toBeInTheDocument();
});
it('FE-ADMIN-SVCID-007: a revoked key asks before it starts over, then shows the new state', async () => {
let regenerated = 0;
serve({ state: 'revoked', tier: 'std', keySource: 'registered', services: [], lastSeenAt: null });
server.use(
http.post('/api/admin/service-identity/regenerate', () => {
regenerated += 1;
return HttpResponse.json({
state: 'registering',
tier: 'legacy',
keySource: null,
services: [],
lastSeenAt: null,
});
})
);
const user = userEvent.setup();
render(<ServiceIdentityPanel />);
expect(await screen.findByText('admin.trekApi.quota.hint.revoked')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'admin.trekApi.quota.regenerate' }));
expect(screen.getByText('admin.trekApi.quota.regenerateBody')).toBeInTheDocument();
expect(regenerated).toBe(0);
const regenerateButtons = screen.getAllByRole('button', { name: 'admin.trekApi.quota.regenerate' });
const confirm = regenerateButtons[regenerateButtons.length - 1];
if (!confirm) throw new Error('no confirm button');
await user.click(confirm);
await waitFor(() => expect(regenerated).toBe(1));
expect(await screen.findByText('admin.trekApi.quota.hint.registering')).toBeInTheDocument();
});
it('FE-ADMIN-SVCID-008: a managed install leaves the identity to its operator', async () => {
serve({ state: 'revoked', tier: 'std', keySource: 'registered', services: [], lastSeenAt: null });
render(<ServiceIdentityPanel managed />);
expect(await screen.findByText('admin.trekApi.quota.hint.revoked')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'admin.trekApi.quota.regenerate' })).toBeNull();
});
});
@@ -0,0 +1,216 @@
import type { ServiceAllowance, ServiceIdentityState, ServiceIdentityStatus, ServiceQuotaView } from '@trek/shared';
import { MapPin, RefreshCw, Route, Search, Signal, type LucideIcon } from 'lucide-react';
import { useRef, useState } from 'react';
import { useTranslation } from '../../i18n';
import { useSettingsStore } from '../../store/settingsStore';
import type { TranslationFn } from '../../types';
import { getApiErrorMessage } from '../../utils/apiError';
import { formatClockTime } from '../../utils/formatters';
import { SettingsCard } from '../Settings/settingsKit';
import ConfirmDialog from '../shared/ConfirmDialog';
import { useToast } from '../shared/Toast';
import { FigureBadge } from '../Tours/paddle/FigureBadge';
import { useServiceIdentity } from './useServiceIdentity';
const STATE_DOT: Record<ServiceIdentityState, string> = {
connected: 'bg-success',
registering: 'bg-warning motion-safe:animate-pulse',
legacy: 'bg-[var(--text-faint)]',
off: 'bg-[var(--text-faint)]',
revoked: 'bg-danger',
};
const SERVICE_ICON: Record<string, LucideIcon> = { places: MapPin, photon: Search, valhalla: Route };
/** Below a tenth of the day left the bar turns amber, at nothing left red. */
function barTone(quota: ServiceQuotaView): string {
if (quota.remaining === 0) return 'bg-danger';
return quota.remaining < quota.limit / 10 ? 'bg-warning' : 'bg-accent';
}
function figureTone(quota: ServiceQuotaView): string {
if (quota.remaining === 0) return 'text-danger';
return quota.remaining < quota.limit / 10 ? 'text-warning' : 'text-content';
}
/** The clock time the counts start again, in the user's format; one for all services, which share the day. */
function useResetTime(status: ServiceIdentityStatus | null): string | null {
const is12h = useSettingsStore((s) => s.settings.time_format === '12h');
const at = status?.services.find((s) => s.quota)?.quota?.resetAt;
if (!at) return null;
const reset = new Date(at);
return formatClockTime(
`${String(reset.getHours()).padStart(2, '0')}:${String(reset.getMinutes()).padStart(2, '0')}`,
is12h
);
}
function tileNote(t: TranslationFn, allowance: ServiceAllowance): string | null {
if (!allowance.inUse) return t('admin.trekApi.quota.notInUse');
return allowance.quota ? null : t('admin.trekApi.quota.unavailable');
}
/**
* One service under the key, as a tile: what is left today as the figure that
* matters, the day's use as a bar, used and limit as badges. A service not in
* use is dimmed rather than hidden, so the row reads the same on every install.
*/
function ServiceTile({ allowance }: { allowance: ServiceAllowance }) {
const { t, locale } = useTranslation();
const number = new Intl.NumberFormat(locale);
const name = t(`admin.trekApi.quota.service.${allowance.service}`);
const note = tileNote(t, allowance);
const quota = allowance.quota;
const Icon = SERVICE_ICON[allowance.service] ?? MapPin;
const share = quota && quota.limit > 0 ? Math.min(100, (quota.used / quota.limit) * 100) : 100;
return (
<li
className={`flex min-w-0 flex-col gap-2.5 rounded-xl border border-edge-faint bg-surface-card p-3 shadow-sm ${allowance.inUse ? '' : 'opacity-60'}`}
>
<div className="flex min-w-0 items-center gap-2">
<span className="grid h-7 w-7 flex-none place-items-center rounded-lg bg-surface-tertiary text-content-muted">
<Icon size={14} strokeWidth={2} aria-hidden="true" />
</span>
<p className="m-0 truncate text-caption font-medium text-content-secondary">{name}</p>
</div>
{quota && (
<>
<div className="min-w-0">
<p className={`m-0 truncate text-title font-semibold tabular-nums leading-tight ${figureTone(quota)}`}>
{number.format(quota.remaining)}
</p>
<p className="m-0 text-caption text-content-muted">{t('admin.trekApi.quota.remaining')}</p>
</div>
<div
role="progressbar"
aria-label={name}
aria-valuemin={0}
aria-valuemax={quota.limit}
aria-valuenow={quota.used}
className="h-1.5 overflow-hidden rounded-full bg-surface-tertiary"
>
<div
className={`h-full rounded-full transition-[width] duration-500 ${barTone(quota)}`}
style={{ width: `${share}%` }}
/>
</div>
<div className="flex flex-wrap gap-1.5">
<FigureBadge label={t('admin.trekApi.quota.used')} value={number.format(quota.used)} />
<FigureBadge label={t('admin.trekApi.quota.limit')} value={number.format(quota.limit)} />
</div>
</>
)}
{note && <p className="m-0 text-caption leading-snug text-content-muted">{note}</p>}
</li>
);
}
function stateHint(t: TranslationFn, status: ServiceIdentityStatus | null, failed: boolean): string | null {
if (!status) return failed ? t('admin.trekApi.quota.unavailable') : null;
return status.state === 'connected' ? null : t(`admin.trekApi.quota.hint.${status.state}`);
}
/**
* How this installation stands with the TREK services: whether it has its key,
* and for place search, address search and routing today's allowance against
* what is used, and when the count starts again.
* Read when the card is in view and refreshed every 30 seconds while it stays.
* A managed install leaves the identity to its operator, so it offers no new one.
*/
export default function ServiceIdentityPanel({ managed = false }: { managed?: boolean }) {
const { t } = useTranslation();
const toast = useToast();
const panel = useRef<HTMLDivElement>(null);
const { status, failed, regenerating, regenerate } = useServiceIdentity(panel);
const [confirming, setConfirming] = useState(false);
const resetAt = useResetTime(status);
const confirmRegenerate = async () => {
setConfirming(false);
try {
await regenerate();
toast.success(t('admin.trekApi.quota.regenerated'));
} catch (err) {
toast.error(getApiErrorMessage(err, t('common.error')));
}
};
const hint = stateHint(t, status, failed);
const canRegenerate = !managed && status !== null && status.keySource !== 'env' && status.state !== 'off';
return (
<div ref={panel}>
<SettingsCard
flush
icon={Signal}
title={t('admin.trekApi.quota.title')}
badge={
<span className="inline-flex items-center gap-1.5 rounded-full bg-surface-card px-2 py-[2px] text-caption font-semibold text-content shadow-sm">
<span
aria-hidden="true"
className={`h-2 w-2 flex-none rounded-full ${STATE_DOT[status?.state ?? 'off']}`}
/>
{status ? t(`admin.trekApi.quota.state.${status.state}`) : '…'}
</span>
}
action={
<>
{status?.tier && <FigureBadge value={t(`admin.trekApi.quota.tier.${status.tier}`)} />}
{status?.keySource === 'env' && (
<FigureBadge
label={t('admin.trekApi.quota.key')}
value="TREK_SERVICES_KEY"
info={t('admin.trekApi.quota.envKey')}
/>
)}
{resetAt && <FigureBadge label={t('admin.trekApi.quota.resets')} value={resetAt} />}
</>
}
>
{status && status.services.length > 0 && (
<ul
aria-label={t('admin.trekApi.quota.title')}
className="m-0 grid list-none grid-cols-1 gap-2 p-0 sm:grid-cols-3"
>
{status.services.map((allowance) => (
<ServiceTile key={allowance.service} allowance={allowance} />
))}
</ul>
)}
{hint && <p className="m-0 text-caption leading-snug text-content-muted">{hint}</p>}
{/* The one action, on a rule of its own below the figures. */}
{canRegenerate && (
<div className="-mx-4 -mb-4 flex items-center justify-end border-t border-edge-faint px-4 py-2.5">
<button
type="button"
onClick={() => setConfirming(true)}
disabled={regenerating}
className="inline-flex items-center gap-1.5 rounded-lg border border-edge-faint bg-surface-card px-2.5 py-1 text-caption font-medium text-content-secondary shadow-sm hover:bg-surface-hover hover:text-content disabled:opacity-50"
>
<RefreshCw
size={13}
strokeWidth={2}
className={regenerating ? 'motion-safe:animate-spin' : ''}
aria-hidden="true"
/>
{t('admin.trekApi.quota.regenerate')}
</button>
</div>
)}
</SettingsCard>
<ConfirmDialog
isOpen={confirming}
onClose={() => setConfirming(false)}
onConfirm={() => void confirmRegenerate()}
title={t('admin.trekApi.quota.regenerateTitle')}
message={t('admin.trekApi.quota.regenerateBody')}
confirmLabel={t('admin.trekApi.quota.regenerate')}
danger={false}
/>
</div>
);
}
@@ -0,0 +1,45 @@
import {
PLACE_CONTRIB_FIELDS,
type PlaceContribField,
type PlaceContribFieldSwitches,
type PlaceContribState,
} from '@trek/shared';
import type { TranslationFn } from '../../types';
/** Every switch on: what the prompt proposes, and what an installation that never decided reads as. */
export const ALL_FIELDS_ON: PlaceContribFieldSwitches = {
website: true,
phone: true,
email: true,
opening_hours: true,
description: true,
image: true,
};
export const fieldLabel = (t: TranslationFn, field: PlaceContribField): string => t(`admin.contribute.field.${field}`);
/** The switches as a list, in the order the contract names the fields. */
export const fieldEntries = (switches: PlaceContribFieldSwitches): [PlaceContribField, boolean][] =>
PLACE_CONTRIB_FIELDS.map((field) => [field, switches[field]]);
export type ContribStatus = 'active' | 'paused' | 'off' | 'unavailable';
/** Where sharing stands, as the pill beside the title says it. */
export function contribStatus(state: PlaceContribState): ContribStatus {
if (!state.eligible) return 'unavailable';
if (!state.active) return 'off';
return state.pauseReason ? 'paused' : 'active';
}
/** The sentence under the title: why it cannot run, why it waits, or what it does. */
export function contribNote(t: TranslationFn, state: PlaceContribState): string {
if (!state.eligible && state.ineligibleReason) return t(`admin.contribute.ineligible.${state.ineligibleReason}`);
if (state.active && state.pauseReason) return t(`admin.contribute.pause.${state.pauseReason}`);
return t(state.active ? 'admin.contribute.noteActive' : 'admin.contribute.noteOff');
}
/** The refusal a decision can meet, as the server names it in `reason`, or null for any other failure. */
export function refusalReason(err: unknown): string | null {
const reason = (err as { response?: { data?: { reason?: unknown } } } | null)?.response?.data?.reason;
return typeof reason === 'string' && reason ? reason : null;
}
@@ -1,6 +1,6 @@
import { http, HttpResponse } from 'msw';
import { beforeEach, describe, expect, it } from 'vitest';
import { MASKED_SETTING_VALUE, type StorageAdminState, type StorageCategory, type StorageConfig } from '@trek/shared';
import { MASKED_SETTING_VALUE, STORAGE_RECLAIM_CATEGORIES, type StorageAdminState, type StorageCategory, type StorageConfig, type StorageReclaimReport } from '@trek/shared';
import { server } from '../../../../tests/helpers/msw/server';
import { fireEvent, render, screen, waitFor, within } from '../../../../tests/helpers/render';
import { ToastContainer } from '../../shared/Toast';
@@ -11,6 +11,16 @@ const S3_MASKED = {
secretAccessKey: MASKED_SETTING_VALUE, region: 'us-east-1', keyPrefix: '', retries: 1, timeoutMs: 30000,
};
/** A last check with three covers a week old and two younger ones; every other category never reclaimed. */
function reclaimReport(): StorageReclaimReport {
const categories = Object.fromEntries(
STORAGE_RECLAIM_CATEGORIES.map((c) => [c, { objects: 0, unreferenced: { objects: 0, bytes: 0 }, eligible: { objects: 0, bytes: 0 }, deleted: { objects: 0, bytes: 0 }, confirmationRequired: false, skipped: 'not_reclaimed' as const }]),
) as StorageReclaimReport['categories'];
categories.covers = { objects: 40, unreferenced: { objects: 5, bytes: 5000 }, eligible: { objects: 3, bytes: 3000 }, deleted: { objects: 0, bytes: 0 }, confirmationRequired: false, skipped: null };
categories.places = { objects: 10, unreferenced: { objects: 3, bytes: 300 }, eligible: { objects: 0, bytes: 0 }, deleted: { objects: 0, bytes: 0 }, confirmationRequired: true, skipped: null };
return { startedAt: Date.now() - 60_000, finishedAt: Date.now() - 30_000, mode: 'report', stopped: null, categories };
}
function baseState(overrides: Partial<StorageAdminState> = {}): StorageAdminState {
return {
backends: [
@@ -35,6 +45,7 @@ function baseState(overrides: Partial<StorageAdminState> = {}): StorageAdminStat
},
health: { replicaFailures: [] },
seedFilePresent: false,
reclaim: null,
usage: null,
backfills: [],
migrations: [],
@@ -1217,4 +1228,55 @@ describe('AdminStoragePanel', () => {
expect(within(row).getByText(/Sync failed: disk full/)).toBeInTheDocument();
expect(within(row).getByRole('button', { name: 'Sync now' })).toBeInTheDocument();
});
it('FE-ADMIN-STOR-051: unreferenced files: the last check shows, the switch, the check and a confirmation go to the server', async () => {
const lastRun = reclaimReport();
let put: unknown = null;
let runs = 0;
let confirm: unknown = null;
server.use(
http.put('/api/admin/storage/reclaim', async ({ request }) => {
put = await request.json();
return HttpResponse.json({ deleteEnabled: true, running: false, lastRun, lastDeleteRun: null });
}),
http.post('/api/admin/storage/reclaim/run', () => {
runs += 1;
return HttpResponse.json({ started: true }, { status: 202 });
}),
http.post('/api/admin/storage/reclaim/confirm', async ({ request }) => {
confirm = await request.json();
return HttpResponse.json({ deleteEnabled: true, running: false, lastRun, lastDeleteRun: null });
}),
);
await renderPanel(baseState({ reclaim: { deleteEnabled: false, running: false, lastRun, lastDeleteRun: null } }));
// Once a check started, the state the panel polls says it runs.
server.use(
http.get('/api/admin/storage', () =>
HttpResponse.json(baseState({ reclaim: { deleteEnabled: true, running: runs > 0, lastRun, lastDeleteRun: null } })),
),
);
expect(screen.getByText('Unreferenced files')).toBeInTheDocument();
expect(within(screen.getByTestId('storage-reclaim-covers')).getByText(/Can be freed/)).toBeInTheDocument();
expect(within(screen.getByTestId('storage-reclaim-places')).getByText(/More than a fifth/)).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Delete unreferenced files' }));
await waitFor(() => expect(put).toEqual({ deleteEnabled: true }));
await waitFor(() => expect(screen.getByRole('button', { name: 'Delete unreferenced files' })).toHaveAttribute('aria-pressed', 'true'));
fireEvent.click(within(screen.getByTestId('storage-reclaim-places')).getByRole('button', { name: 'Confirm' }));
await waitFor(() => expect(confirm).toEqual({ category: 'places', unreferenced: 3 }));
fireEvent.click(screen.getByRole('button', { name: 'Check now' }));
await waitFor(() => expect(runs).toBe(1));
// The check runs in the background: the panel shows it running until the state says otherwise.
await waitFor(() => expect(screen.getByText('Checking…')).toBeInTheDocument());
});
it('FE-ADMIN-STOR-051b: a refused check names the reason in the operator\'s language', async () => {
server.use(
http.post('/api/admin/storage/reclaim/run', () =>
HttpResponse.json({ error: 'busy', code: 'reclaim_busy' }, { status: 409 }),
),
);
await renderPanel(baseState({ reclaim: { deleteEnabled: false, running: false, lastRun: null, lastDeleteRun: null } }));
fireEvent.click(screen.getByRole('button', { name: 'Check now' }));
await waitFor(() => expect(screen.getByText('Another storage task is running. Try again in a moment.')).toBeInTheDocument());
});
});
@@ -38,6 +38,7 @@ import {
StatusPill,
} from '../../Settings/settingsKit'
import BackendForm from './BackendForm'
import StorageReclaimSection from './StorageReclaimSection'
import { CACHE_CATEGORIES, primaryNameOf } from './storageModel'
import { categoryNames, migrationPromptLine, useStoragePanel } from './useStoragePanel'
@@ -96,6 +97,7 @@ export default function AdminStoragePanel(): React.ReactElement {
const {
admin, editing, setEditing, confirmRemove, setConfirmRemove, syncPrompt, setSyncPrompt, migratePrompt,
closeMigratePrompt, migrationQueue, handleCancelMigration, handleRefreshStats, handleStartBackfill, handleCancelBackfill, loaded,
reclaim, reclaimChecking, reclaimSaving, reclaimConfirming, handleReclaimCheck, handleReclaimDelete, handleReclaimConfirm,
} = useStoragePanel()
// Open/closed only: the render below and moveAndSave both recompute
// computeMigrationCandidates(draft, state) fresh rather than reading the
@@ -627,6 +629,18 @@ export default function AdminStoragePanel(): React.ReactElement {
</div>
)}
<div className="mt-5">
<StorageReclaimSection
reclaim={reclaim}
checking={reclaimChecking}
saving={reclaimSaving}
confirming={reclaimConfirming}
onConfirm={(request) => void handleReclaimConfirm(request)}
onCheck={() => void handleReclaimCheck()}
onDelete={(enabled) => void handleReclaimDelete(enabled)}
/>
</div>
{editing && (
<BackendForm
initial={editing.initial}
@@ -0,0 +1,167 @@
import { Eraser, Loader2, ScanSearch } from 'lucide-react';
import React from 'react';
import { useTranslation } from '../../../i18n';
import { formatBytes } from '../../../utils/formatBytes';
import { relativeTime } from '../../../utils/relativeTime';
import Section from '../../Settings/Section';
import ToggleSwitch from '../../Settings/ToggleSwitch';
import { SETTINGS_BUTTON, SettingRow, SettingRows, SettingsHint, StatusPill } from '../../Settings/settingsKit';
import { fs } from '../../shared/DialogShell';
import type { ReclaimCount, ReclaimView } from './reclaimModel';
interface Props {
reclaim: ReclaimView;
/** A check was asked for or is running. */
checking: boolean;
/** The switch is on its way to the server. */
saving: boolean;
onCheck: () => void;
onDelete: (enabled: boolean) => void;
/** The category whose confirmation is on its way. */
confirming: ReclaimView['lines'][number]['category'] | null;
onConfirm: (request: { category: ReclaimView['lines'][number]['category']; unreferenced: number }) => void;
}
/**
* Unreferenced files on the desktop storage panel: what the last check found,
* the switch that lets the nightly run delete them, a check on demand and the
* confirmation a category with an unusually large share of unused files waits
* for. The phone shows the same through MStorageReclaimCard, off the same view model.
*/
export default function StorageReclaimSection({
reclaim,
checking,
saving,
onCheck,
onDelete,
confirming,
onConfirm,
}: Props): React.ReactElement {
const { t, locale } = useTranslation();
const count = (c: ReclaimCount) => t('storage.usage.line', { count: c.objects, size: formatBytes(c.bytes) });
const checked = reclaim.checkedAt !== null;
return (
<Section
title={t('storage.reclaim.title')}
icon={Eraser}
hint={t('storage.reclaim.hint')}
action={
<button
type="button"
className={SETTINGS_BUTTON}
style={fs(12.5, 'body')}
onClick={onCheck}
disabled={checking}
>
{checking ? (
<Loader2 size={14} strokeWidth={2.2} className="animate-spin" />
) : (
<ScanSearch size={14} strokeWidth={2.2} />
)}
{checking ? t('storage.reclaim.running') : t('storage.reclaim.check')}
</button>
}
>
<SettingRows>
<SettingRow
label={t('storage.reclaim.delete')}
hint={t('storage.reclaim.deleteHint')}
dimmed={saving}
control={
<ToggleSwitch
on={reclaim.deleteEnabled}
onToggle={() => onDelete(!reclaim.deleteEnabled)}
label={t('storage.reclaim.delete')}
disabled={saving}
/>
}
/>
<div className="px-3.5 py-3" data-testid="storage-reclaim-summary">
<p className="m-0 text-content-faint" style={fs(11.5)}>
{reclaim.checkedAt !== null
? t('storage.reclaim.checked', { age: relativeTime(reclaim.checkedAt, locale) })
: t('storage.reclaim.never')}
</p>
{reclaim.stopped && (
<p role="note" className="m-0 mt-1.5 leading-snug text-warning" style={fs(11.5)}>
{t(reclaim.stopped === 'failed' ? 'storage.reclaim.stoppedFailed' : 'storage.reclaim.stopped')}
</p>
)}
{checked && (
<div className="mt-2.5 grid grid-cols-1 gap-2 sm:grid-cols-3">
<Figure label={t('storage.reclaim.freeable')} value={count(reclaim.freeable)} />
<Figure label={t('storage.reclaim.waiting')} value={count(reclaim.waiting)} />
<Figure label={t('storage.reclaim.deleted')} value={count(reclaim.freed)} />
</div>
)}
{checked && !reclaim.stopped && reclaim.lines.length === 0 && (
<SettingsHint className="mt-2.5">{t('storage.reclaim.nothing')}</SettingsHint>
)}
{reclaim.lines.length > 0 && (
<ul className="m-0 mt-3 flex list-none flex-col gap-2 p-0">
{reclaim.lines.map((line) => (
<li
key={line.category}
data-testid={`storage-reclaim-${line.category}`}
className="flex flex-col gap-1"
>
<div className="flex flex-wrap items-center gap-x-2.5 gap-y-1">
<span className="font-medium text-content-secondary" style={fs(12.5, 'body')}>
{t(`storage.category.${line.category}`)}
</span>
{line.freeable.objects > 0 && (
<span className="font-geist tabular-nums text-content-faint" style={fs(11.5)}>
{t('storage.reclaim.freeable')}: {count(line.freeable)}
</span>
)}
{line.waiting.objects > 0 && (
<span className="font-geist tabular-nums text-content-faint" style={fs(11.5)}>
{t('storage.reclaim.waiting')}: {count(line.waiting)}
</span>
)}
{line.skipped && (
<StatusPill tone="warning">{t(`storage.reclaim.skip.${line.skipped}`)}</StatusPill>
)}
</div>
{line.confirmationRequired && (
<div className="flex flex-wrap items-center gap-2.5 rounded-[10px] bg-warning-soft px-2.5 py-1.5">
<p className="m-0 min-w-0 flex-1 basis-56 leading-snug text-warning" style={fs(11.5)}>
{t('storage.reclaim.confirmNeeded')}
</p>
<button
type="button"
className={SETTINGS_BUTTON}
style={fs(12, 'body')}
onClick={() => onConfirm({ category: line.category, unreferenced: line.unreferenced })}
disabled={confirming === line.category}
>
{confirming === line.category && (
<Loader2 size={13} strokeWidth={2.2} className="animate-spin" />
)}
{t('storage.reclaim.confirm')}
</button>
</div>
)}
</li>
))}
</ul>
)}
</div>
</SettingRows>
</Section>
);
}
function Figure({ label, value }: { label: string; value: string }): React.ReactElement {
return (
<div className="min-w-0 rounded-[12px] bg-surface-secondary px-3 py-2">
<p className="m-0 text-content-faint" style={fs(11)}>
{label}
</p>
<p className="m-0 mt-0.5 font-geist font-semibold tabular-nums text-content" style={fs(12.5, 'body')}>
{value}
</p>
</div>
);
}
@@ -0,0 +1,140 @@
// FE-ADMIN-STOR-RECLAIM-001 to -007: the reclaim report as both storage panels show it.
import { STORAGE_RECLAIM_CATEGORIES, type StorageReclaimCategoryReport, type StorageReclaimReport } from '@trek/shared';
import { reclaimView } from './reclaimModel';
const none = { objects: 0, bytes: 0 };
function category(patch: Partial<StorageReclaimCategoryReport> = {}): StorageReclaimCategoryReport {
return {
objects: 0,
unreferenced: none,
eligible: none,
deleted: none,
confirmationRequired: false,
skipped: null,
...patch,
};
}
function report(
patch: Partial<Record<(typeof STORAGE_RECLAIM_CATEGORIES)[number], StorageReclaimCategoryReport>>,
mode: StorageReclaimReport['mode'] = 'report'
): StorageReclaimReport {
const categories = Object.fromEntries(
STORAGE_RECLAIM_CATEGORIES.map((c) => [c, category({ skipped: 'not_reclaimed' })])
) as StorageReclaimReport['categories'];
return { startedAt: 1_000, finishedAt: 2_000, mode, stopped: null, categories: { ...categories, ...patch } };
}
describe('reclaimView', () => {
it('FE-ADMIN-STOR-RECLAIM-001: no state reads as deletion off, not running and never checked', () => {
expect(reclaimView(null)).toEqual({
deleteEnabled: false,
running: false,
checkedAt: null,
stopped: null,
freeable: none,
waiting: none,
freed: none,
freedAt: null,
lines: [],
});
});
it('FE-ADMIN-STOR-RECLAIM-002: freeable is what is a week old, waiting what is younger, summed over categories', () => {
const view = reclaimView({
deleteEnabled: true,
running: false,
lastDeleteRun: null,
lastRun: report({
covers: category({
objects: 40,
unreferenced: { objects: 5, bytes: 500 },
eligible: { objects: 3, bytes: 300 },
}),
places: category({ objects: 10, unreferenced: { objects: 1, bytes: 100 } }),
}),
});
expect(view.deleteEnabled).toBe(true);
expect(view.checkedAt).toBe(2_000);
expect(view.freeable).toEqual({ objects: 3, bytes: 300 });
expect(view.waiting).toEqual({ objects: 3, bytes: 300 });
expect(view.lines.map((line) => line.category)).toEqual(['covers', 'places']);
});
it('FE-ADMIN-STOR-RECLAIM-003: freed comes from the last run with deletion on, which a check on demand does not replace', () => {
const deleting = report(
{
files: category({
unreferenced: { objects: 2, bytes: 20 },
eligible: { objects: 2, bytes: 20 },
deleted: { objects: 2, bytes: 20 },
}),
},
'delete'
);
const view = reclaimView({
deleteEnabled: true,
running: false,
lastDeleteRun: { ...deleting, finishedAt: 900 },
lastRun: report({}),
});
expect(view.freed).toEqual({ objects: 2, bytes: 20 });
expect(view.freedAt).toBe(900);
expect(view.freeable).toEqual(none);
expect(view.lines).toEqual([]);
});
it('FE-ADMIN-STOR-RECLAIM-004: a skipped category shows its reason and counts toward nothing, one never reclaimed shows nothing', () => {
const view = reclaimView({
deleteEnabled: false,
running: false,
lastDeleteRun: null,
lastRun: report({ avatars: category({ skipped: 'foreign_install', unreferenced: { objects: 9, bytes: 9 } }) }),
});
expect(view.lines).toEqual([
{
category: 'avatars',
freeable: none,
waiting: none,
confirmationRequired: false,
unreferenced: 9,
skipped: 'foreign_install',
},
]);
expect(view.waiting).toEqual(none);
expect(view.lines.some((line) => line.category === 'backups')).toBe(false);
});
it('FE-ADMIN-STOR-RECLAIM-005: a pass that stopped says why, and a category it stopped in keeps its partial figures', () => {
const view = reclaimView({
deleteEnabled: false,
running: false,
lastDeleteRun: null,
lastRun: {
...report({ covers: category({ skipped: 'interrupted', unreferenced: { objects: 4, bytes: 40 } }) }),
stopped: 'failed',
},
});
expect(view.stopped).toBe('failed');
expect(view.waiting).toEqual({ objects: 4, bytes: 40 });
expect(view.lines[0]).toMatchObject({ category: 'covers', skipped: 'interrupted' });
});
it('FE-ADMIN-STOR-RECLAIM-006: a category waiting for a confirmation shows even with nothing old enough yet', () => {
const view = reclaimView({
deleteEnabled: true,
running: false,
lastDeleteRun: null,
lastRun: report({ places: category({ objects: 10, confirmationRequired: true }) }),
});
expect(view.lines).toEqual([
{ category: 'places', freeable: none, waiting: none, confirmationRequired: true, unreferenced: 0, skipped: null },
]);
});
it('FE-ADMIN-STOR-RECLAIM-007: a running check reads as running', () => {
expect(reclaimView({ deleteEnabled: false, running: true, lastRun: null, lastDeleteRun: null }).running).toBe(true);
});
});
@@ -0,0 +1,123 @@
import {
STORAGE_RECLAIM_CATEGORIES,
type StorageReclaimCategoryReport,
type StorageReclaimReport,
type StorageReclaimState,
} from '@trek/shared';
/** A number of files and their size, as the report counts them. */
export interface ReclaimCount {
objects: number;
bytes: number;
}
/** What one category of the last check has to say, when it has anything to say. */
interface ReclaimCategoryLine {
category: (typeof STORAGE_RECLAIM_CATEGORIES)[number];
/** Unused for a week or more: what the nightly run deletes once deletion is on. */
freeable: ReclaimCount;
/** Unused for less than a week: these get their week first. */
waiting: ReclaimCount;
/**
* An unusually large share of the category looks unused: nothing in it is
* deleted until an admin confirms that this is expected (a cleaned-up
* backlog, say, rather than a second installation in the same bucket).
*/
confirmationRequired: boolean;
/** Everything the check found unused in the category, the count a confirmation is given for. */
unreferenced: number;
/** Why the category was left alone, or stopped part way; null when it was checked through. */
skipped: Exclude<StorageReclaimCategoryReport['skipped'], 'not_reclaimed'> | null;
}
/** The admin's view of the reclaim pass: the switch and what the last check found. */
export interface ReclaimView {
deleteEnabled: boolean;
/** A check, nightly or on demand, is running now. */
running: boolean;
/** When the last check finished, ms; null before the first one. */
checkedAt: number | null;
/** Why the last check stopped before the end; null when it ran through. */
stopped: StorageReclaimReport['stopped'];
freeable: ReclaimCount;
waiting: ReclaimCount;
/** What the last run with deletion on removed: a check on demand only reports, so it never resets this. */
freed: ReclaimCount;
/** When that run finished, ms; null when nothing ever ran with deletion on. */
freedAt: number | null;
/** Only the categories with something to free, something waiting, something to confirm, or a reason they were skipped. */
lines: ReclaimCategoryLine[];
}
const NONE: ReclaimCount = { objects: 0, bytes: 0 };
function add(a: ReclaimCount, b: ReclaimCount): ReclaimCount {
return { objects: a.objects + b.objects, bytes: a.bytes + b.bytes };
}
function minus(a: ReclaimCount, b: ReclaimCount): ReclaimCount {
return { objects: Math.max(0, a.objects - b.objects), bytes: Math.max(0, a.bytes - b.bytes) };
}
function freedBy(run: StorageReclaimReport | null): ReclaimCount {
if (!run) return NONE;
return STORAGE_RECLAIM_CATEGORIES.reduce(
(sum, category) => add(sum, run.categories[category]?.deleted ?? NONE),
NONE
);
}
/**
* The reclaim state as the storage panels show it, desktop and phone alike.
* `null` (a server from before the reclaim pass, or a state not loaded) reads
* as deletion off, not running and never checked.
*/
/**
* One category of the last check as a line, or null when it has nothing to
* say. A category the pass stopped in still counts what it found; one it
* never judged counts nothing.
*/
function lineOf(
category: ReclaimCategoryLine['category'],
report: StorageReclaimCategoryReport | undefined
): ReclaimCategoryLine | null {
if (!report || report.skipped === 'not_reclaimed') return null;
const judged = report.skipped === null || report.skipped === 'interrupted' || report.skipped === 'delete_failed';
// What was deleted on this run no longer waits to be freed.
const freeable = judged ? minus(report.eligible, report.deleted) : NONE;
const waiting = judged ? minus(report.unreferenced, report.eligible) : NONE;
const line = {
category,
freeable,
waiting,
confirmationRequired: report.confirmationRequired,
unreferenced: report.unreferenced.objects,
skipped: report.skipped,
};
const quiet = freeable.objects === 0 && waiting.objects === 0 && !line.confirmationRequired && line.skipped === null;
return quiet ? null : line;
}
/**
* The reclaim state as the storage panels show it, desktop and phone alike.
* `null` (a server from before the reclaim pass, or a state not loaded) reads
* as deletion off, not running and never checked.
*/
export function reclaimView(state: StorageReclaimState | null): ReclaimView {
const run = state?.lastRun ?? null;
const lines = STORAGE_RECLAIM_CATEGORIES.flatMap((category) => lineOf(category, run?.categories[category]) ?? []);
const freeable = lines.reduce((sum, line) => add(sum, line.freeable), NONE);
const waiting = lines.reduce((sum, line) => add(sum, line.waiting), NONE);
const deleteRun = state?.lastDeleteRun ?? null;
return {
deleteEnabled: state?.deleteEnabled ?? false,
running: state?.running ?? false,
checkedAt: run?.finishedAt ?? null,
stopped: run?.stopped ?? null,
freeable,
waiting,
freed: freedBy(deleteRun),
freedAt: deleteRun?.finishedAt ?? null,
lines,
};
}
@@ -53,6 +53,7 @@ const STATE: StorageAdminState = {
},
health: { replicaFailures: [] },
seedFilePresent: false,
reclaim: null,
usage: null,
backfills: [],
migrations: [],
@@ -14,6 +14,7 @@ function baseState(overrides: Partial<StorageAdminState> = {}): StorageAdminStat
categories: { files: { backend: 'uploads-local', source: 'default' } } as StorageAdminState['categories'],
health: { replicaFailures: [] },
seedFilePresent: false,
reclaim: null,
usage: null,
backfills: [],
migrations: [],
@@ -1,11 +1,29 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import type { StorageAdminState, StorageBackend, StorageConfig, StorageConfigPut, StorageTestResponse } from '@trek/shared'
import type {
StorageAdminState,
StorageBackend,
StorageConfig,
StorageConfigPut,
StorageReclaimConfirmRequest,
StorageTestResponse,
} from '@trek/shared'
import { adminApi } from '../../../api/client'
import { storageReclaimApi } from '../../../api/storageReclaim'
import { getApiErrorMessage, type ApiError } from '../../../types'
import { settingsDocumentOf } from './storageModel'
export type StorageTestResults = Record<string, StorageTestResponse | 'running'>
/** A refused reclaim call: the server's code when it sent one the panel can name, its message otherwise. */
export type ReclaimFailure = { code: string } | { message: string }
function reclaimFailureOf(err: unknown, fallback: string): ReclaimFailure {
const code = (err as ApiError | null)?.response?.data as { code?: unknown } | undefined
return typeof code?.code === 'string' && code.code.startsWith('reclaim_')
? { code: code.code }
: { message: getApiErrorMessage(err, fallback) }
}
/** 50ms under vitest so poll tests run on real timers (MSW + fake timers don't mix). */
export const BACKFILL_POLL_MS = import.meta.env.MODE === 'test' ? 50 : 5000
@@ -58,6 +76,12 @@ export interface StorageAdmin {
startMigration: (category: string, to: string) => Promise<string | null>
cancelMigration: (category: string) => Promise<string | null>
refreshStats: () => Promise<string | null>
/** Switches the nightly deletion of unreferenced files on or off; null on success. */
setReclaimDelete: (enabled: boolean) => Promise<ReclaimFailure | null>
/** Starts a check that only reports, in the background; the state polls until it is done. Null on success. */
checkReclaim: () => Promise<ReclaimFailure | null>
/** Lets the nightly run delete in a category where an unusually large share looks unused. Null on success. */
confirmReclaim: (request: StorageReclaimConfirmRequest) => Promise<ReclaimFailure | null>
/** Re-GETs admin state (poll-safe — see the implementation comment below). Exposed for the panel's failed-queue recovery path. */
refreshState: () => Promise<void>
/**
@@ -271,7 +295,8 @@ export function useStorageAdmin(genericError: string, conflictError: string): St
useEffect(() => {
if (
!state?.backfills.some((b) => b.status === 'running') &&
!state?.migrations.some((m) => m.status === 'running')
!state?.migrations.some((m) => m.status === 'running') &&
!state?.reclaim?.running
)
return
const iv = setInterval(() => {
@@ -356,6 +381,71 @@ export function useStorageAdmin(genericError: string, conflictError: string): St
}
}, [genericError])
/**
* Writes the reclaim part of the state. It counts as a deliberate state
* application, so a poll GET that was in flight before it is dropped instead
* of putting the switch back where it was.
*/
const setReclaim = useCallback((reclaim: NonNullable<StorageAdminState['reclaim']>) => {
const prev = stateRef.current
if (!prev) return
stateSeq.current += 1
const next = { ...prev, reclaim }
stateRef.current = next
setState(next)
}, [])
const setReclaimDelete = useCallback(
async (enabled: boolean): Promise<ReclaimFailure | null> => {
try {
setReclaim(await storageReclaimApi.setDelete(enabled))
return null
} catch (err: unknown) {
return reclaimFailureOf(err, genericError)
}
},
[genericError, setReclaim],
)
const checkReclaim = useCallback(async (): Promise<ReclaimFailure | null> => {
try {
await storageReclaimApi.check()
// Running from here on: the poll above picks the report up once the pass is done.
const current = stateRef.current?.reclaim
setReclaim({
deleteEnabled: current?.deleteEnabled ?? false,
running: true,
lastRun: current?.lastRun ?? null,
lastDeleteRun: current?.lastDeleteRun ?? null,
})
return null
} catch (err: unknown) {
return reclaimFailureOf(err, genericError)
}
}, [genericError, setReclaim])
const confirmReclaim = useCallback(
async (request: StorageReclaimConfirmRequest): Promise<ReclaimFailure | null> => {
try {
setReclaim(await storageReclaimApi.confirm(request))
return null
} catch (err: unknown) {
const failure = reclaimFailureOf(err, genericError)
// The count moved on since it was shown: show the current one before the admin confirms again.
if ('code' in failure && failure.code === 'reclaim_confirm_stale') {
try {
await refreshState()
} catch (reloadErr: unknown) {
// Without the new figure there is nothing to confirm against: say why instead.
return reclaimFailureOf(reloadErr, genericError)
}
}
return failure
}
},
[genericError, setReclaim, refreshState],
)
return {
state,
storageBusy,
@@ -376,6 +466,9 @@ export function useStorageAdmin(genericError: string, conflictError: string): St
startMigration,
cancelMigration,
refreshStats,
setReclaimDelete,
checkReclaim,
confirmReclaim,
refreshState,
discardDraft,
}
@@ -1,4 +1,4 @@
// FE-ADMIN-STOR-PANEL-001 to -017: the storage panel logic behind both admin shells.
// FE-ADMIN-STOR-PANEL-001 to -020: the storage panel logic behind both admin shells.
import { act, renderHook, waitFor } from '@testing-library/react';
import { STORAGE_CATEGORIES, type StorageAdminState, type StorageBackend, type StorageConfig } from '@trek/shared';
@@ -28,6 +28,7 @@ function baseState(): StorageAdminState {
) as StorageAdminState['categories'],
health: { replicaFailures: [] },
seedFilePresent: false,
reclaim: null,
usage: null,
backfills: [],
migrations: [],
@@ -57,6 +58,9 @@ function makeAdmin(state: StorageAdminState | null, draft?: StorageConfig): Stor
startMigration: vi.fn(async () => null),
cancelMigration: vi.fn(async () => null),
refreshStats: vi.fn(async () => null),
setReclaimDelete: vi.fn(async () => null),
checkReclaim: vi.fn(async () => null),
confirmReclaim: vi.fn(async () => null),
refreshState: vi.fn(async () => {}),
discardDraft: vi.fn(async () => {}),
};
@@ -282,3 +286,48 @@ describe('migrationPromptLine', () => {
).toBe('storage.migrate.promptLineUnknown {"category":"storage.category.covers","from":"a","to":"b"}');
});
});
describe('useStoragePanel: unreferenced files', () => {
it('FE-ADMIN-STOR-PANEL-018: the reclaim switch and the check go through the admin hook, a failure as a toast', async () => {
fake.admin = makeAdmin(baseState());
vi.mocked(fake.admin.checkReclaim).mockResolvedValueOnce({ code: 'reclaim_busy' });
vi.mocked(fake.admin.setReclaimDelete).mockResolvedValueOnce({ message: 'disk full' });
const { result } = renderHook(() => useStoragePanel());
await act(async () => {
await result.current.handleReclaimDelete(true);
});
expect(fake.admin.setReclaimDelete).toHaveBeenCalledWith(true);
// A failure without a code the panel knows shows the server's message.
expect(toast.error).toHaveBeenCalledWith('disk full');
expect(result.current.reclaimSaving).toBe(false);
await act(async () => {
await result.current.handleReclaimCheck();
});
expect(fake.admin.checkReclaim).toHaveBeenCalledTimes(1);
// A code the panel knows is shown in the operator's language.
expect(toast.error).toHaveBeenCalledWith('storage.reclaim.error.reclaim_busy');
expect(result.current.reclaimChecking).toBe(false);
});
it('FE-ADMIN-STOR-PANEL-020: confirming a category goes through the admin hook and says so; a running check keeps the button busy', async () => {
const state = baseState();
state.reclaim = { deleteEnabled: true, running: true, lastRun: null, lastDeleteRun: null };
fake.admin = makeAdmin(state);
const { result } = renderHook(() => useStoragePanel());
expect(result.current.reclaimChecking).toBe(true);
await act(async () => {
await result.current.handleReclaimConfirm({ category: 'places', unreferenced: 3 });
});
expect(fake.admin.confirmReclaim).toHaveBeenCalledWith({ category: 'places', unreferenced: 3 });
expect(result.current.reclaimConfirming).toBeNull();
expect(toast.success).toHaveBeenCalledWith('storage.reclaim.confirmed');
});
it('FE-ADMIN-STOR-PANEL-019: a server without the reclaim state reads as deletion off and never checked', () => {
fake.admin = makeAdmin(baseState());
const { result } = renderHook(() => useStoragePanel());
expect(result.current.reclaim.deleteEnabled).toBe(false);
expect(result.current.reclaim.checkedAt).toBeNull();
expect(result.current.reclaim.lines).toEqual([]);
});
});
@@ -7,11 +7,13 @@ import type {
StorageConfig,
StorageConfigPut,
StorageMigrationStatus,
StorageReclaimConfirmRequest,
} from '@trek/shared';
import { useTranslation } from '../../../i18n';
import { formatBytes } from '../../../utils/formatBytes';
import { useToast } from '../../shared/Toast';
import { reclaimView } from './reclaimModel';
import {
adoptedMirrorFor,
computeMigrationCandidates,
@@ -31,7 +33,7 @@ import {
type FoldedBackendRow,
type MigrationCandidate,
} from './storageModel';
import { useStorageAdmin } from './useStorageAdmin';
import { useStorageAdmin, type ReclaimFailure } from './useStorageAdmin';
/** Display-name mapper for joined category lists: the raw id renders only in the badge. */
export const categoryNames = (t: (key: string) => string, ids: readonly string[]): string =>
@@ -165,6 +167,35 @@ export function useStoragePanel() {
if (error) toast.error(error);
};
// The click itself, until the server answered; the pass that follows shows through `reclaim.running`.
const [reclaimStarting, setReclaimStarting] = useState(false);
const [reclaimSaving, setReclaimSaving] = useState(false);
const reclaimError = (failure: ReclaimFailure) =>
'code' in failure ? t(`storage.reclaim.error.${failure.code}`) : failure.message;
const handleReclaimCheck = async () => {
setReclaimStarting(true);
const failure = await admin.checkReclaim();
setReclaimStarting(false);
if (failure) toast.error(reclaimError(failure));
};
const handleReclaimDelete = async (enabled: boolean) => {
setReclaimSaving(true);
const failure = await admin.setReclaimDelete(enabled);
setReclaimSaving(false);
if (failure) toast.error(reclaimError(failure));
};
// The category whose confirmation is on its way, so its button waits for the answer.
const [reclaimConfirming, setReclaimConfirming] = useState<StorageReclaimConfirmRequest['category'] | null>(null);
const handleReclaimConfirm = async (request: StorageReclaimConfirmRequest) => {
setReclaimConfirming(request.category);
const failure = await admin.confirmReclaim(request);
setReclaimConfirming(null);
if (failure) toast.error(reclaimError(failure));
else toast.success(t('storage.reclaim.confirmed'));
};
const reclaim = reclaimView(admin.state?.reclaim ?? null);
const reclaimChecking = reclaimStarting || reclaim.running;
const handleStartBackfill = async (row: FoldedBackendRow) => {
if (!row.mirrorName) return;
setSyncPrompt((prev) => (prev === row.name ? null : prev));
@@ -371,6 +402,13 @@ export function useStoragePanel() {
migrationQueue,
handleCancelMigration,
handleRefreshStats,
reclaim,
reclaimChecking,
reclaimSaving,
reclaimConfirming,
handleReclaimCheck,
handleReclaimDelete,
handleReclaimConfirm,
handleStartBackfill,
handleCancelBackfill,
loaded,
@@ -1,8 +1,14 @@
import { describe, expect, it } from 'vitest';
import { TREK_API_SOURCES, trekApiFacts, trekApiFields } from './trekApiModel';
import {
TREK_API_SOURCES,
trekApiAddressFeatures,
trekApiFacts,
trekApiFields,
trekApiRoutingFeatures,
} from './trekApiModel';
// FE-TREKAPIMODEL-001 to FE-TREKAPIMODEL-003
// FE-TREKAPIMODEL-001 to FE-TREKAPIMODEL-004
const t = (key: string) => `<${key}>`;
@@ -22,10 +28,12 @@ describe('trekApiModel', () => {
]);
});
it('FE-TREKAPIMODEL-002: leads with four facts, each with a glyph', () => {
it('FE-TREKAPIMODEL-002: leads with the three services, then the terms, each with a glyph', () => {
const facts = trekApiFacts(t);
expect(facts.map((f) => f.text)).toEqual([
'<admin.trekApi.factPlaces>',
'<admin.trekApi.factAddresses>',
'<admin.trekApi.factRouting>',
'<admin.trekApi.factNoKey>',
'<admin.trekApi.factOffline>',
'<admin.trekApi.factPrivacy>',
@@ -34,6 +42,28 @@ describe('trekApiModel', () => {
});
it('FE-TREKAPIMODEL-003: names the data sources untranslated', () => {
expect(TREK_API_SOURCES).toEqual(['Overture Maps Foundation', 'OpenStreetMap', 'Wikivoyage', 'Wikimedia']);
expect(TREK_API_SOURCES).toEqual([
'Overture Maps Foundation',
'OpenStreetMap',
'Wikivoyage',
'Wikimedia',
'Mapzen Terrain Tiles',
]);
});
it('FE-TREKAPIMODEL-004: lists what the address search and the routing answer', () => {
expect(trekApiAddressFeatures(t)).toEqual([
'<admin.trekApi.addrStreets>',
'<admin.trekApi.addrTowns>',
'<admin.trekApi.addrReverse>',
'<admin.trekApi.addrLanguages>',
]);
expect(trekApiRoutingFeatures(t)).toEqual([
'<admin.trekApi.routeCar>',
'<admin.trekApi.routeBike>',
'<admin.trekApi.routeFoot>',
'<admin.trekApi.routeAvoid>',
'<admin.trekApi.routeElevation>',
]);
});
});
+33 -4
View File
@@ -1,13 +1,19 @@
import { Globe2, KeyRound, ShieldOff, WifiOff } from 'lucide-react';
import { Globe2, KeyRound, Route, Search, ShieldOff, WifiOff } from 'lucide-react';
import type { TranslationFn } from '../../types';
/**
* Proper nouns, so they are not translated. Naming them is also a licence obligation,
* not decoration: ODbL and CC BY-SA both require attribution wherever their content is
* shown.
* shown, and the terrain tiles the routes take their heights from ask to be named too.
*/
export const TREK_API_SOURCES = ['Overture Maps Foundation', 'OpenStreetMap', 'Wikivoyage', 'Wikimedia'];
export const TREK_API_SOURCES = [
'Overture Maps Foundation',
'OpenStreetMap',
'Wikivoyage',
'Wikimedia',
'Mapzen Terrain Tiles',
];
/**
* The fields a TREK Places API result carries, for the desktop card and the phone block
@@ -29,10 +35,33 @@ export function trekApiFields(t: TranslationFn): string[] {
];
}
/** The four facts the TREK Places API block leads with, each with its glyph. */
/** What the address search answers: an address typed, a town, the address of a point. */
export function trekApiAddressFeatures(t: TranslationFn): string[] {
return [
t('admin.trekApi.addrStreets'),
t('admin.trekApi.addrTowns'),
t('admin.trekApi.addrReverse'),
t('admin.trekApi.addrLanguages'),
];
}
/** What the routing does: the three ways of getting there, what a drive can avoid, the heights. */
export function trekApiRoutingFeatures(t: TranslationFn): string[] {
return [
t('admin.trekApi.routeCar'),
t('admin.trekApi.routeBike'),
t('admin.trekApi.routeFoot'),
t('admin.trekApi.routeAvoid'),
t('admin.trekApi.routeElevation'),
];
}
/** The facts the TREK API block leads with, each with its glyph: the three services first, then the terms. */
export function trekApiFacts(t: TranslationFn) {
return [
{ Icon: Globe2, text: t('admin.trekApi.factPlaces') },
{ Icon: Search, text: t('admin.trekApi.factAddresses') },
{ Icon: Route, text: t('admin.trekApi.factRouting') },
{ Icon: KeyRound, text: t('admin.trekApi.factNoKey') },
{ Icon: WifiOff, text: t('admin.trekApi.factOffline') },
{ Icon: ShieldOff, text: t('admin.trekApi.factPrivacy') },
@@ -0,0 +1,31 @@
// FE-ADMIN-CONTRIBHOOK-001
import { act, renderHook, waitFor } from '@testing-library/react';
import type { PlaceContribState } from '@trek/shared';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { placeContribRepo } from '../../repo/placeContribRepo';
import { usePlaceContrib } from './usePlaceContrib';
const STATE = { ineligibleReason: null, active: true } as unknown as PlaceContribState;
afterEach(() => {
vi.restoreAllMocks();
});
describe('usePlaceContrib', () => {
it('FE-ADMIN-CONTRIBHOOK-001: a withdrawal that went through is answered even when the state cannot be read again', async () => {
const state = vi.spyOn(placeContribRepo, 'state').mockResolvedValueOnce(STATE);
vi.spyOn(placeContribRepo, 'withdraw').mockResolvedValue({ withdrawn: { website: 2 }, cleared: 1 });
const { result } = renderHook(() => usePlaceContrib());
await waitFor(() => expect(result.current.state).toBe(STATE));
state.mockRejectedValueOnce(new Error('offline'));
let answer: unknown;
await act(async () => {
answer = await result.current.withdraw();
});
expect(answer).toEqual({ withdrawn: { website: 2 }, cleared: 1 });
expect(result.current.state).toBe(STATE);
expect(result.current.busy).toBe(false);
});
});
@@ -0,0 +1,65 @@
import type { PlaceContribDecisionRequest, PlaceContribState } from '@trek/shared';
import { useCallback, useEffect, useState } from 'react';
import { placeContribRepo } from '../../repo/placeContribRepo';
const KEY_RETRIES = 6;
const KEY_RETRY_MS = 3_000;
/**
* The admin's decision on sharing place details. Read once when the settings
* tab opens, so the prompt can come up without the card being scrolled to;
* every decision answers the new state, which replaces the old one.
*/
export function usePlaceContrib() {
const [state, setState] = useState<PlaceContribState | null>(null);
const [failed, setFailed] = useState(false);
const [busy, setBusy] = useState(false);
useEffect(() => {
const controller = new AbortController();
let timer: ReturnType<typeof setTimeout> | undefined;
// A fresh installation fetches its key on first use, so the first answer can
// be no_key; asking again a few times lets the prompt appear once it landed.
const read = (tries: number) => {
placeContribRepo.state(controller.signal).then(
(next) => {
setState(next);
if (next.ineligibleReason === 'no_key' && tries > 1) timer = setTimeout(() => read(tries - 1), KEY_RETRY_MS);
},
() => {
if (!controller.signal.aborted) setFailed(true);
}
);
};
read(KEY_RETRIES);
return () => {
controller.abort();
clearTimeout(timer);
};
}, []);
const decide = useCallback(async (body: PlaceContribDecisionRequest): Promise<PlaceContribState> => {
setBusy(true);
try {
const next = await placeContribRepo.decide(body);
setState(next);
return next;
} finally {
setBusy(false);
}
}, []);
const withdraw = useCallback(async () => {
setBusy(true);
try {
const result = await placeContribRepo.withdraw();
// The withdrawal went through; a failed re-read keeps the old state rather than reporting it failed.
await placeContribRepo.state().then(setState, () => undefined);
return result;
} finally {
setBusy(false);
}
}, []);
return { state, failed, busy, decide, withdraw };
}
@@ -0,0 +1,91 @@
// FE-ADMIN-SVCID-HOOK-001 to FE-ADMIN-SVCID-HOOK-004
import { act, renderHook } from '@testing-library/react';
import type { ServiceIdentityStatus } from '@trek/shared';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { useServiceIdentity } from './useServiceIdentity';
const { status, regenerate, visible } = vi.hoisted(() => ({
status: vi.fn(),
regenerate: vi.fn(),
visible: { current: true },
}));
vi.mock('../../repo/serviceIdentityRepo', () => ({ serviceIdentityRepo: { status, regenerate } }));
vi.mock('../../hooks/useElementVisible', () => ({ useElementVisible: () => visible.current }));
const LEGACY: ServiceIdentityStatus = {
state: 'legacy',
tier: 'legacy',
keySource: null,
services: [],
lastSeenAt: null,
};
const card = { current: null };
beforeEach(() => {
vi.useFakeTimers();
visible.current = true;
status.mockReset().mockResolvedValue(LEGACY);
regenerate.mockReset();
});
afterEach(() => vi.useRealTimers());
describe('useServiceIdentity', () => {
it('FE-ADMIN-SVCID-HOOK-001: reads once in view, then every 30 seconds', async () => {
const { result } = renderHook(() => useServiceIdentity(card));
await act(async () => {});
expect(result.current.status).toEqual(LEGACY);
expect(status).toHaveBeenCalledTimes(1);
await act(async () => {
await vi.advanceTimersByTimeAsync(30_000);
});
expect(status).toHaveBeenCalledTimes(2);
});
it('FE-ADMIN-SVCID-HOOK-002: reads nothing while the card is out of view, and stops when it leaves', async () => {
visible.current = false;
const { rerender } = renderHook(() => useServiceIdentity(card));
await act(async () => {
await vi.advanceTimersByTimeAsync(90_000);
});
expect(status).not.toHaveBeenCalled();
visible.current = true;
rerender();
await act(async () => {});
expect(status).toHaveBeenCalledTimes(1);
visible.current = false;
rerender();
await act(async () => {
await vi.advanceTimersByTimeAsync(90_000);
});
expect(status).toHaveBeenCalledTimes(1);
});
it('FE-ADMIN-SVCID-HOOK-003: marks a failed read, and clears the mark on the next good one', async () => {
status.mockRejectedValueOnce(new Error('offline'));
const { result } = renderHook(() => useServiceIdentity(card));
await act(async () => {});
expect(result.current.failed).toBe(true);
await act(async () => {
await vi.advanceTimersByTimeAsync(30_000);
});
expect(result.current.failed).toBe(false);
});
it('FE-ADMIN-SVCID-HOOK-004: a new identity replaces the status, and a refusal reaches the caller', async () => {
const registering = { ...LEGACY, state: 'registering' as const };
regenerate.mockResolvedValueOnce(registering).mockRejectedValueOnce(new Error('409'));
const { result } = renderHook(() => useServiceIdentity(card));
await act(async () => {
await result.current.regenerate();
});
expect(result.current.status).toEqual(registering);
await act(async () => {
await expect(result.current.regenerate()).rejects.toThrow('409');
});
expect(result.current.regenerating).toBe(false);
});
});
@@ -0,0 +1,51 @@
import type { ServiceIdentityStatus } from '@trek/shared';
import { useCallback, useEffect, useState, type RefObject } from 'react';
import { useElementVisible } from '../../hooks/useElementVisible';
import { serviceIdentityRepo } from '../../repo/serviceIdentityRepo';
const REFRESH_MS = 30_000;
/**
* The installation's standing with the TREK services for the admin card:
* read when the card comes into view, then every 30 seconds while it stays
* there. Admin configuration, online only like the rest of the settings tab.
*/
export function useServiceIdentity(card: RefObject<Element | null>) {
const visible = useElementVisible(card);
const [status, setStatus] = useState<ServiceIdentityStatus | null>(null);
const [failed, setFailed] = useState(false);
const [regenerating, setRegenerating] = useState(false);
useEffect(() => {
if (!visible) return;
const controller = new AbortController();
const refresh = () => {
serviceIdentityRepo.status(controller.signal).then(
(next) => {
setStatus(next);
setFailed(false);
},
() => {
if (!controller.signal.aborted) setFailed(true);
}
);
};
refresh();
const timer = setInterval(refresh, REFRESH_MS);
return () => {
controller.abort();
clearInterval(timer);
};
}, [visible]);
const regenerate = useCallback(async (): Promise<void> => {
setRegenerating(true);
try {
setStatus(await serviceIdentityRepo.regenerate());
} finally {
setRegenerating(false);
}
}, []);
return { status, failed, regenerating, regenerate };
}
@@ -20,7 +20,10 @@ const trip = (id: number, start: string | null, end: string | null) => ({
end_date: end,
});
afterEach(() => vi.restoreAllMocks());
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
});
describe('rankPickerTrips', () => {
it('FE-AI-PICK-001: the running trip leads, then the soonest to come, then the latest past one', () => {
@@ -59,6 +62,9 @@ describe('rankPickerTrips', () => {
describe('useAssistantTripPicker', () => {
it('FE-AI-PICK-004: loads the trips once and ranks them; a failed load offers none', async () => {
// The hook ranks against the real clock; pin it so trip 7 keeps running.
vi.useFakeTimers({ shouldAdvanceTime: true, toFake: ['Date'] });
vi.setSystemTime(new Date(`${TODAY}T12:00:00`));
const list = vi
.spyOn(tripRepo, 'list')
.mockResolvedValueOnce({ trips: [trip(7, '2026-10-01', '2026-10-30') as Trip], archivedTrips: [] });
+268 -10
View File
@@ -1,4 +1,4 @@
// FE-COMP-JOURNEYMAP-001 to FE-COMP-JOURNEYMAP-054
// FE-COMP-JOURNEYMAP-001 to FE-COMP-JOURNEYMAP-062
vi.mock('../../api/websocket', () => ({
connect: vi.fn(),
@@ -12,6 +12,35 @@ vi.mock('../../api/websocket', () => ({
// Leaflet does not work in jsdom — mock the entire library
vi.mock('leaflet', () => {
const domEvent = {
on: vi.fn((el: HTMLElement, types: string, fn: (e: Event) => void) => {
types.split(' ').forEach(type => el.addEventListener(type, fn));
}),
stopPropagation: vi.fn((e: Event) => e.stopPropagation()),
disableClickPropagation: vi.fn((el: HTMLElement) => {
for (const type of ['mousedown', 'touchstart', 'dblclick', 'contextmenu']) el.addEventListener(type, e => e.stopPropagation());
}),
};
// The openable card (#2885): one per map, put on and taken off by the map itself.
// Its element is built on the first add, inside a stand-in for the map container.
const cardState = { onMap: false, element: null as HTMLElement | null, onAdd: [] as (() => void)[] };
const mockCard = {
state: cardState,
once: vi.fn((_type: string, fn: () => void) => { cardState.onAdd.push(fn); }),
setLatLng: vi.fn().mockReturnThis(),
setContent: vi.fn().mockReturnThis(),
getElement: vi.fn(() => cardState.element),
addTo: vi.fn(() => {
if (!cardState.element) {
cardState.element = document.createElement('div');
cardState.element.innerHTML = '<div class="trek-journey-popup-title">card</div>';
document.createElement('div').appendChild(cardState.element);
}
cardState.onMap = true;
cardState.onAdd.splice(0).forEach(fn => fn());
}),
remove: vi.fn(() => { cardState.onMap = false; }),
};
const mockMarker = {
addTo: vi.fn().mockReturnThis(),
bindTooltip: vi.fn().mockReturnThis(),
@@ -38,31 +67,38 @@ vi.mock('leaflet', () => {
getCenter: vi.fn(() => ({ lat: 0, lng: 0 })),
zoomIn: vi.fn(),
zoomOut: vi.fn(),
// The photo layer subscribes to zoom/pan and clusters in screen space (#1614).
// The photo and mark layers subscribe to zoom/pan and cluster in world
// pixels at the current zoom (#1614, #2889).
on: vi.fn(),
off: vi.fn(),
project: vi.fn(() => ({ x: 0, y: 0 })),
latLngToContainerPoint: vi.fn(() => ({ x: 0, y: 0 })),
hasLayer: vi.fn((layer: unknown) => (layer === mockCard ? cardState.onMap : true)),
};
return {
default: {
map: vi.fn(() => mockMap),
tileLayer: vi.fn(() => ({ addTo: vi.fn(), setUrl: vi.fn() })),
marker: vi.fn(() => mockMarker),
polyline: vi.fn(() => { const line: any = { addTo: vi.fn(() => line), bindTooltip: vi.fn(() => line) }; return line }),
polyline: vi.fn(() => { const line: any = { addTo: vi.fn(() => line), bindTooltip: vi.fn(() => line), remove: vi.fn() }; return line }),
divIcon: vi.fn(() => ({})),
latLngBounds: vi.fn(() => ({})),
layerGroup: vi.fn(() => ({ addLayer: vi.fn(), addTo: vi.fn(), remove: vi.fn() })),
// The map builds its own attribution control so it can collapse to the credit
// alone (see the GL twin: the phone lays a carousel over the bottom edge).
control: { attribution: vi.fn(() => ({ addTo: vi.fn() })) },
tooltip: vi.fn(() => mockCard),
DomEvent: domEvent,
},
map: vi.fn(() => mockMap),
tileLayer: vi.fn(() => ({ addTo: vi.fn(), setUrl: vi.fn() })),
marker: vi.fn(() => mockMarker),
polyline: vi.fn(() => { const line: any = { addTo: vi.fn(() => line), bindTooltip: vi.fn(() => line) }; return line }),
polyline: vi.fn(() => { const line: any = { addTo: vi.fn(() => line), bindTooltip: vi.fn(() => line), remove: vi.fn() }; return line }),
divIcon: vi.fn(() => ({})),
latLngBounds: vi.fn(() => ({})),
control: { attribution: vi.fn(() => ({ addTo: vi.fn() })) },
tooltip: vi.fn(() => mockCard),
DomEvent: domEvent,
};
});
@@ -76,6 +112,9 @@ import type { Mock } from 'vitest';
import L from 'leaflet';
import JourneyMap from './JourneyMap';
import type { JourneyMapHandle } from './JourneyMap';
import type { JourneyMapLayerVisibility } from './journeyMapLayers';
import { mercatorWorldPx } from './journeyMapMarks';
import type { JourneyMapStay } from '@trek/shared';
// maplibre-gl-leaflet hangs the vector basemap into Leaflet's tile pane. The mock
// only has to be callable and hand back a layer with the three methods the callers
@@ -178,6 +217,115 @@ describe('JourneyMap', () => {
);
});
describe('the marker card as a way into the entry (#2885)', () => {
interface MockCard {
state: { onMap: boolean; element: HTMLElement | null; onAdd: (() => void)[] };
addTo: Mock;
remove: Mock;
setContent: Mock;
}
// The leaflet mock hands every map the same card, so each case starts it unbuilt and off the map.
function mockedCard(): MockCard {
const card = vi.mocked(L.tooltip)() as unknown as MockCard;
vi.mocked(L.tooltip).mockClear();
return card;
}
beforeEach(() => {
Object.assign(mockedCard().state, { onMap: false, element: null, onAdd: [] });
});
function renderOpenable(onMarkerCardClick = vi.fn(), visibility?: JourneyMapLayerVisibility) {
const ref = React.createRef<JourneyMapHandle>();
const view = render(
<JourneyMap ref={ref} checkins={[]} entries={entriesWithCoords} onMarkerCardClick={onMarkerCardClick} layerVisibility={visibility} />,
);
return { ...view, ref, onMarkerCardClick };
}
function cardElement(): HTMLElement {
const { element } = mockedCard().state;
if (!element) throw new Error('the card was never built');
return element;
}
function cardTitle(): HTMLElement {
return cardElement().firstElementChild as HTMLElement;
}
it('FE-COMP-JOURNEYMAP-059: a tap on the card over the active pin opens that entry and never reaches the map', () => {
const { ref, onMarkerCardClick } = renderOpenable();
act(() => ref.current?.highlightMarker('e2'));
expect(L.tooltip).toHaveBeenCalledWith(expect.objectContaining({ className: 'map-tooltip trek-journey-tooltip is-openable' }));
const container = cardElement().parentElement as HTMLElement;
const mapClick = vi.fn();
const mapPress = vi.fn();
container.addEventListener('click', mapClick);
container.addEventListener('mousedown', mapPress);
cardTitle().dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
cardTitle().click();
act(() => ref.current?.highlightMarker('e1'));
cardTitle().click();
expect(onMarkerCardClick.mock.calls).toEqual([['e2'], ['e1']]);
expect(mapClick).not.toHaveBeenCalled();
expect(mapPress).not.toHaveBeenCalled();
});
it('FE-COMP-JOURNEYMAP-060: the pins do not open or close the card, so leaving the pin for the card keeps it', () => {
const { ref } = renderOpenable();
act(() => ref.current?.highlightMarker('e1'));
// A bound tooltip is what Leaflet closes on the pin's mouseout and blur, which
// a tap on the card sends first. The pins bind none and listen for the tap alone.
expect(mockedMarker().bindTooltip).not.toHaveBeenCalled();
expect(vi.mocked(mockedMarker().on).mock.calls.map((call: unknown[]) => call[0])).toEqual(['click', 'click']);
expect(mockedCard().state.onMap).toBe(true);
expect(mockedCard().remove).not.toHaveBeenCalled();
});
it('FE-COMP-JOURNEYMAP-061: the card follows the active pin and leaves with it or with the pins', () => {
mockedMarkerWithRemove();
const card = mockedCard();
const shown = { plan: true, recorded: true, entries: true };
const onMarkerCardClick = vi.fn();
const { ref, rerender } = renderOpenable(onMarkerCardClick, shown);
const map = mockedMap();
act(() => ref.current?.highlightMarker('e1'));
expect(card.setContent).toHaveBeenLastCalledWith(expect.stringContaining('Paris'));
act(() => ref.current?.highlightMarker('e2'));
expect(card.setContent).toHaveBeenLastCalledWith(expect.stringContaining('Berlin'));
expect(card.addTo).toHaveBeenCalledTimes(1);
act(() => ref.current?.highlightMarker(null));
expect(card.state.onMap).toBe(false);
act(() => ref.current?.highlightMarker('e1'));
map.hasLayer.mockImplementation((layer: unknown) => layer === card && card.state.onMap);
try {
rerender(<JourneyMap ref={ref} checkins={[]} entries={entriesWithCoords} onMarkerCardClick={onMarkerCardClick} layerVisibility={{ ...shown, entries: false }} />);
expect(card.state.onMap).toBe(false);
} finally {
map.hasLayer.mockImplementation((layer: unknown) => (layer === card ? card.state.onMap : true));
}
});
it('FE-COMP-JOURNEYMAP-062: without a handler the card stays a hover label on each pin that the drags on the map pass through', () => {
const ref = React.createRef<JourneyMapHandle>();
render(<JourneyMap ref={ref} checkins={[]} entries={entriesWithCoords} />);
act(() => ref.current?.highlightMarker('e1'));
expect(mockedMarker().bindTooltip).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining({ className: 'map-tooltip trek-journey-tooltip' }),
);
expect(L.tooltip).not.toHaveBeenCalled();
});
});
it('FE-COMP-JOURNEYMAP-006: exposes imperative handle (focusMarker)', () => {
const ref = React.createRef<JourneyMapHandle>();
render(
@@ -201,6 +349,15 @@ describe('JourneyMap', () => {
expect(firstCall.html).toContain('>1<');
});
it('FE-COMP-JOURNEYMAP-058: a stop without a number (a draft) gets an unnumbered pin', () => {
render(
<JourneyMap checkins={[]} entries={[{ ...entriesWithCoords[0], dayLabel: null }]} />
);
const html = String(vi.mocked(L.divIcon).mock.calls[0][0]?.html);
expect(html).toContain('<svg');
expect(html).toMatch(/font-weight="700"><\/text>/);
});
it('FE-COMP-JOURNEYMAP-008: renders markers with mood-based entry labels', () => {
const entriesWithMood = [
{ id: 'e1', lat: 48.8566, lng: 2.3522, title: 'Happy Paris', mood: 'happy', entry_date: '2025-06-01' },
@@ -782,9 +939,8 @@ describe('JourneyMap', () => {
});
// #2254 — the map effect defers its opening fitBounds/setView to a rAF, so this
// effect can draw while the map still has no center or zoom. Clustering
// projects to container pixels, which throws in that window and took the whole
// public journey page down with it.
// effect can draw while the map still has no center or zoom. Projecting in that
// window throws and took the whole public journey page down with it.
it('FE-COMP-JOURNEYMAP-050: waits out a map that has no view yet, then draws on moveend', () => {
const noView = () => { throw new Error('Set map center and zoom first.'); };
let hasView = false;
@@ -794,12 +950,12 @@ describe('JourneyMap', () => {
// The mock hands out one shared map instance, so it can be reached — and
// stripped of its view — before the component ever builds one. Typed down to
// the three spies this needs: L.map's signature promises a real Leaflet map.
type MapProbe = { getCenter: Mock; latLngToContainerPoint: Mock; on: Mock };
type MapProbe = { getCenter: Mock; project: Mock; on: Mock };
L.map(document.createElement('div'));
const map = mockedMap() as MapProbe;
vi.mocked(L.map).mockClear();
map.getCenter.mockImplementation(() => (hasView ? { lat: 0, lng: 0 } : noView()));
map.latLngToContainerPoint.mockImplementation(() => (hasView ? { x: 0, y: 0 } : noView()));
map.project.mockImplementation(() => (hasView ? { x: 0, y: 0 } : noView()));
try {
// Rendering must survive the viewless window, and draw nothing in it.
@@ -820,7 +976,7 @@ describe('JourneyMap', () => {
expect(photoHtml()[0]).toContain('/uploads/late.jpg');
} finally {
map.getCenter.mockImplementation(() => ({ lat: 0, lng: 0 }));
map.latLngToContainerPoint.mockImplementation(() => ({ x: 0, y: 0 }));
map.project.mockImplementation(() => ({ x: 0, y: 0 }));
}
});
@@ -868,6 +1024,108 @@ describe('JourneyMap', () => {
expect(divIconHtml(0)).not.toContain('#16a34a');
expect(divIconHtml(1)).toContain('#16a34a');
});
// #2889: a pan used to shift the screen grid the layers cluster on, so photos
// near a cell edge changed groups, counts and thumbnails without any zoom.
it('FE-COMP-JOURNEYMAP-055: panning keeps the photo and mark groups, only a zoom regroups them', () => {
const photos = [
{ id: 'p1', lat: 45, lng: 5, thumbUrl: '/uploads/a.jpg' },
{ id: 'p2', lat: 45, lng: 5.05, thumbUrl: '/uploads/b.jpg' },
];
const marks = [
{ kind: 'stay' as const, key: 's1', lat: 45, lng: 5, color: '#14b8a6', stay: {} as JourneyMapStay },
{ kind: 'stay' as const, key: 's2', lat: 45, lng: 5.05, color: '#14b8a6', stay: {} as JourneyMapStay },
];
L.map(document.createElement('div'));
const map = mockedMap() as { project: Mock; latLngToContainerPoint: Mock; getZoom: Mock; on: Mock; off: Mock };
vi.mocked(L.map).mockClear();
let zoom = 3;
let pan = 0;
map.getZoom.mockImplementation(() => zoom);
map.project.mockImplementation(([lat, lng]: [number, number], z: number) => mercatorWorldPx(lat, lng, z, 256));
map.latLngToContainerPoint.mockImplementation(([lat, lng]: [number, number]) => {
const world = mercatorWorldPx(lat, lng, zoom, 256);
return { x: world.x - pan, y: world.y };
});
const drawnSince = (from: number) =>
vi.mocked(L.divIcon).mock.calls.slice(from).map(c => String(c[0]?.html)).filter(h => h.includes('/uploads/') || h.includes('#14b8a6'));
const moveEnd = () => act(() => {
const gone = new Set(map.off.mock.calls.map(c => c[1]));
for (const [event, handler] of map.on.mock.calls) if (event === 'moveend' && !gone.has(handler)) (handler as () => void)();
});
try {
render(<JourneyMap checkins={[]} entries={[]} photos={photos} marks={marks} />);
let from = vi.mocked(L.divIcon).mock.calls.length;
moveEnd();
const first = drawnSince(from);
expect(first.filter(h => h.includes('/uploads/'))).toEqual([expect.stringContaining('>2<')]);
expect(first.filter(h => h.includes('#14b8a6'))).toHaveLength(1);
expect(map.project).toHaveBeenCalledWith([45, 5.05], 3);
expect(map.latLngToContainerPoint).not.toHaveBeenCalled();
// A pan that puts a 64 px cell edge between the two photos on screen.
const mid = (mercatorWorldPx(45, 5, 3, 256).x + mercatorWorldPx(45, 5.05, 3, 256).x) / 2;
pan = mid - (Math.floor(mid / 64) + 0.5) * 64;
from = vi.mocked(L.divIcon).mock.calls.length;
moveEnd();
expect(drawnSince(from)).toEqual(first);
zoom = 12;
from = vi.mocked(L.divIcon).mock.calls.length;
moveEnd();
const zoomed = drawnSince(from);
expect(zoomed.filter(h => h.includes('/uploads/'))).toHaveLength(2);
expect(zoomed.filter(h => h.includes('#14b8a6'))).toHaveLength(2);
} finally {
map.getZoom.mockImplementation(() => 10);
map.project.mockImplementation(() => ({ x: 0, y: 0 }));
map.latLngToContainerPoint.mockImplementation(() => ({ x: 0, y: 0 }));
}
});
describe('the line between the entries on recorded days (#2888)', () => {
const days = [
{ id: 'a', lat: 48.1, lng: 11.5, title: 'A', mood: null, entry_date: '2026-10-29' },
{ id: 'b', lat: 48.2, lng: 11.6, title: 'B', mood: null, entry_date: '2026-10-29' },
{ id: 'c', lat: 48.3, lng: 11.7, title: 'C', mood: null, entry_date: '2026-10-30' },
];
const tracks = [
{ place_id: -1, trip_id: 0, name: '2026-10-29', color: '#7c3aed', points: [[48.1, 11.5], [48.2, 11.6]] as [number, number][], kind: 'dawarich_live' as const, date: '2026-10-29' },
];
const connectionLines = () => {
const polyline = vi.mocked(L.polyline).mock;
return polyline.calls
.map((call, i) => ({ coords: call[0], dashed: (call[1] as { dashArray?: string } | undefined)?.dashArray === '4 6', line: polyline.results[i].value as { addTo: Mock; remove: Mock } }))
.filter(call => call.dashed);
};
it('FE-COMP-JOURNEYMAP-056: leaves the recorded day to its track and keeps the jump to the next day', () => {
render(<JourneyMap checkins={[]} entries={days} tracks={tracks} />);
const lines = connectionLines();
expect(lines.map(l => l.coords)).toEqual([
[[48.2, 11.6], [48.3, 11.7]],
[[48.1, 11.5], [48.2, 11.6]],
]);
expect(lines[0].line.addTo).toHaveBeenCalled();
expect(lines[1].line.addTo).not.toHaveBeenCalled();
});
it('FE-COMP-JOURNEYMAP-057: hiding what was recorded puts the covered stretch back, hiding the entries takes it off again', () => {
mockedMarkerWithRemove();
const shown = { plan: true, recorded: true, entries: true };
const { rerender } = render(<JourneyMap checkins={[]} entries={days} tracks={tracks} layerVisibility={shown} />);
const covered = connectionLines()[1].line;
rerender(<JourneyMap checkins={[]} entries={days} tracks={tracks} layerVisibility={{ ...shown, recorded: false }} />);
expect(covered.addTo).toHaveBeenCalledTimes(1);
rerender(<JourneyMap checkins={[]} entries={days} tracks={tracks} layerVisibility={{ ...shown, recorded: false, entries: false }} />);
expect(covered.remove).toHaveBeenCalledTimes(1);
expect(L.map).toHaveBeenCalledTimes(1);
});
});
});
/** The shared marker spy with the `remove` a hidden layer is taken off by. */
+131 -55
View File
@@ -1,4 +1,4 @@
import { useEffect, useRef, useImperativeHandle, useCallback, type CSSProperties, type Ref } from 'react'
import { useEffect, useRef, useImperativeHandle, useCallback, type CSSProperties, type Ref, type RefObject } from 'react'
import { clusterPhotos, photoMarkerHtml, type MapPhoto } from './journeyPhotoLayer'
import L from 'leaflet'
import { useSettingsStore } from '../../store/settingsStore'
@@ -11,7 +11,8 @@ import { escapeHtml, type JourneyTrack } from '@trek/shared'
import { ensureJourneyPopupStyle, formatMarkerDate, journeyPopupHtml } from './journeyMapPopup'
import { PLANNED_BADGE_SVG, type JourneyMapMark } from './journeyMapMarks'
import { isPlannedTrack, type JourneyMapLayerVisibility } from './journeyMapLayers'
import { NOTHING_DRAWN, drawLeafletMarks, switchLeafletLayers, type DrawnLayers, type LeafletLayerKind } from './journeyLeafletLayers'
import { NOTHING_DRAWN, drawLeafletMarks, isLeafletLayerShown, leafletWorldPx, switchLeafletLayers, type DrawnLayers, type LeafletLayerKind } from './journeyLeafletLayers'
import { entryConnections } from './journeyMapConnections'
export interface MapMarkerItem {
id: string
@@ -22,7 +23,7 @@ export interface MapMarkerItem {
mood?: string | null
time: string
dayColor: string
dayLabel: number
dayLabel: number | null
photoUrls: string[]
}
@@ -44,7 +45,7 @@ interface MapEntry {
mood?: string | null
entry_date: string
dayColor?: string
dayLabel?: number
dayLabel?: number | null
/** Thumbnails for the marker card, already resolved by the caller (the share view signs its own). */
photoUrls?: string[]
}
@@ -65,15 +66,15 @@ interface Props {
onMarkerClick?: (id: string, type?: string) => void
fullScreen?: boolean
/**
* Leave the marker labels off.
* Open the entry a marker card names when the card itself is tapped.
*
* On the phone the map sits above a carousel whose active card already carries
* the entry's name, and a tooltip on touch is a tap-to-open box rather than a
* hover hint — so it says the same thing twice and covers the map to do it
* (discussion #2299). On desktop the label is the only name a marker has, so
* this stays off there.
* On a phone the card is what a tap on a pin brings up, so it has to lead
* somewhere (#2885). Wiring it is what makes the card take the pointer, and the
* card then stands over the active pin, as the GL popup does; without
* it the card stays a label the map's drags pass through, as on desktop, where
* it is a hover card the mouse cannot reach.
*/
hideMarkerTooltip?: boolean
onMarkerCardClick?: (entryId: string) => void
paddingBottom?: number
/** CARTO key from the share payload: the public journey has no settings store to read. */
cartoApiKey?: string
@@ -116,7 +117,7 @@ function buildMarkerItems(entries: MapEntry[]): MapMarkerItem[] {
mood: e.mood,
time: e.entry_date,
dayColor: e.dayColor || '#52525B',
dayLabel: e.dayLabel ?? 1,
dayLabel: e.dayLabel === undefined ? 1 : e.dayLabel,
photoUrls: e.photoUrls ?? [],
})
}
@@ -128,12 +129,12 @@ function buildMarkerItems(entries: MapEntry[]): MapMarkerItem[] {
const MARKER_W = 28
const MARKER_H = 36
function markerSvg(dayColor: string, dayLabel: number, highlighted: boolean, planned = false): string {
function markerSvg(dayColor: string, dayLabel: number | null, highlighted: boolean, planned = false): string {
const stroke = highlighted ? '#fff' : 'rgba(255,255,255,0.5)'
const shadow = highlighted
? 'filter:drop-shadow(0 0 10px rgba(0,0,0,0.4)) drop-shadow(0 2px 6px rgba(0,0,0,0.4))'
: 'filter:drop-shadow(0 2px 4px rgba(0,0,0,0.25))'
const label = String(dayLabel)
const label = dayLabel === null ? '' : String(dayLabel)
const scale = highlighted ? 1.2 : 1
return `<div style="transform:scale(${scale});transition:transform 0.2s ease;${shadow};transform-origin:bottom center">
@@ -184,6 +185,91 @@ function panToMarker(map: L.Map, marker: L.Marker): void {
})
}
/**
* The same card the GL renderer shows, from the same builder: which map engine a
* reader happens to have selected should not change what a marker tells them
* (discussion #2299). The builder escapes everything that came from a person,
* which matters most here, since this map is what the public journey page renders.
*/
function entryCardHtml(item: MapMarkerItem): string {
return journeyPopupHtml({
title: item.label || item.locationName || 'Entry',
place: item.label ? item.locationName : '',
date: formatMarkerDate(item.time),
photoUrls: item.photoUrls,
})
}
const ENTRY_CARD_OPTIONS: L.TooltipOptions = { direction: 'top', offset: [0, -MARKER_H] }
/**
* The card that opens its entry when tapped (#2885), one per map like the GL
* popup, shown above the active pin.
*
* It is deliberately not bound to the pins. A bound tooltip is opened and closed
* by Leaflet on the pin's hover and focus, and a tap on the card is, to a phone,
* the pointer leaving the pin: the pin's mouseout closed the card between the
* tap and its click. Driven by the active pin alone, nothing but a change of
* entry takes it away.
*/
function createEntryCard(open: () => void): L.Tooltip {
const card = L.tooltip({ ...ENTRY_CARD_OPTIONS, className: 'map-tooltip trek-journey-tooltip is-openable' })
// The element is built on the first open and kept for every later one.
card.once('add', () => {
const el = card.getElement()
if (!el) return
// A press on the card is not the start of a drag or a tap on the map.
L.DomEvent.disableClickPropagation(el)
L.DomEvent.on(el, 'click', (ev) => {
L.DomEvent.stopPropagation(ev)
open()
})
})
return card
}
interface PinRefs {
onCardClickRef: RefObject<((entryId: string) => void) | undefined>
mapRef: RefObject<L.Map | null>
markersRef: RefObject<Map<string, L.Marker>>
itemsRef: RefObject<MapMarkerItem[]>
highlightedRef: RefObject<string | null>
}
/**
* The openable card of a host that wires onMarkerCardClick. The returned sync puts
* it over the active pin while that pin is on the map and takes it off otherwise.
*/
function useEntryCardSync({ onCardClickRef, mapRef, markersRef, itemsRef, highlightedRef }: PinRefs): () => void {
const cardRef = useRef<L.Tooltip | null>(null)
const cardEntryIdRef = useRef<string | null>(null)
const sync = useCallback(() => {
const map = mapRef.current
const id = highlightedRef.current
const marker = id ? markersRef.current.get(id) : undefined
const item = id ? itemsRef.current.find(i => i.id === id) : undefined
if (!onCardClickRef.current || !map || !marker || !item || !map.hasLayer(marker)) {
cardRef.current?.remove()
cardEntryIdRef.current = null
return
}
ensureJourneyPopupStyle()
let card = cardRef.current
if (!card) {
card = createEntryCard(() => {
if (cardEntryIdRef.current) onCardClickRef.current?.(cardEntryIdRef.current)
})
cardRef.current = card
}
cardEntryIdRef.current = item.id
card.setLatLng(marker.getLatLng()).setContent(entryCardHtml(item))
if (!map.hasLayer(card)) card.addTo(map)
}, [onCardClickRef, mapRef, markersRef, itemsRef, highlightedRef])
return sync
}
const EMPTY_TRAIL: { lat: number; lng: number }[] = []
const EMPTY_TRACKS: JourneyTrack[] = []
/** Fallback when a track carries no colour of its own, matching the planner's default. */
@@ -200,12 +286,12 @@ function fitOptions(paddingBottom: number | undefined): L.FitBoundsOptions {
}
function JourneyMap(
{ entries, photos, onPhotoClick, trail, tracks, height = 220, dark, activeMarkerId, onMarkerClick, fullScreen, paddingBottom, cartoApiKey, hideMarkerTooltip, layerVisibility = EVERY_LAYER, marks, onMarksPick, plannedEntryIds = NO_PLANNED, ref }: Props,
{ entries, photos, onPhotoClick, trail, tracks, height = 220, dark, activeMarkerId, onMarkerClick, fullScreen, paddingBottom, cartoApiKey, onMarkerCardClick, layerVisibility = EVERY_LAYER, marks, onMarksPick, plannedEntryIds = NO_PLANNED, ref }: Props,
) {
// Read through a ref: the flag is fixed per surface, and putting it in the
// Read through a ref: the handler is fixed per surface, and putting it in the
// marker effect's deps would rebuild every marker for nothing.
const hideMarkerTooltipRef = useRef(hideMarkerTooltip)
hideMarkerTooltipRef.current = hideMarkerTooltip
const onMarkerCardClickRef = useRef(onMarkerCardClick)
onMarkerCardClickRef.current = onMarkerCardClick
const stableTrail = trail || EMPTY_TRAIL
const stableTracks = tracks || EMPTY_TRACKS
const mapTileUrl = useSettingsStore(s => s.settings.map_tile_url)
@@ -256,6 +342,8 @@ function JourneyMap(
plannedRef.current = plannedEntryIds
})
const syncEntryCard = useEntryCardSync({ onCardClickRef: onMarkerCardClickRef, mapRef, markersRef, itemsRef, highlightedRef })
const highlightMarker = useCallback((id: string | null) => {
const prev = highlightedRef.current
highlightedRef.current = id
@@ -264,7 +352,8 @@ function JourneyMap(
)
if (prev && prev !== id) paint(prev, false)
if (id) paint(id, true)
}, [])
syncEntryCard()
}, [syncEntryCard])
/**
* Bring an entry's marker under the reader without changing how far out they are.
@@ -347,7 +436,7 @@ function JourneyMap(
iconPlannedRef.current = plannedRef.current
const place = <T extends L.Layer>(kind: LeafletLayerKind, layer: T): T => {
drawn[kind].push(layer)
if (visibilityRef.current[kind]) layer.addTo(map)
if (isLeafletLayerShown(kind, visibilityRef.current)) layer.addTo(map)
return layer
}
@@ -403,17 +492,18 @@ function JourneyMap(
coords.forEach(c => trackCoords.push(c))
}
// route trail: dashed line connecting entries in time order, same as JourneyMapGL
if (items.length > 1) {
const routeCoords = items.map(i => [i.lat, i.lng] as L.LatLngTuple)
place('entries', L.polyline(routeCoords, {
color: dark ? '#71717A' : '#A1A1AA',
weight: 1.5,
opacity: 0.5,
dashArray: '4 6',
lineCap: 'round', lineJoin: 'round',
}))
// The faint line between the entries in their order, same as JourneyMapGL, left
// off the stretches a recorded day already draws as travelled (#2888).
const connections = entryConnections(items.map(i => ({ lat: i.lat, lng: i.lng, date: i.time })), stableTracks)
const connectionStyle: L.PolylineOptions = {
color: dark ? '#71717A' : '#A1A1AA',
weight: 1.5,
opacity: 0.5,
dashArray: '4 6',
lineCap: 'round', lineJoin: 'round',
}
for (const line of connections.open) place('entries', L.polyline(line, connectionStyle))
for (const line of connections.covered) place('coveredConnections', L.polyline(line, connectionStyle))
// place markers
items.forEach((item, i) => {
@@ -421,26 +511,11 @@ function JourneyMap(
allCoords.push(pos)
const marker = place('entries', L.marker(pos, { icon: entryIcon(item, false, plannedRef.current.has(item.id)) }))
// The same card the GL renderer shows, from the same builder: which map
// engine a reader happens to have selected should not change what a marker
// tells them (discussion #2299). The builder escapes everything that came
// from a person, which matters most here — this map is what the public
// journey page renders.
if (!hideMarkerTooltipRef.current) {
// A host that opens the entry from its card gets the one card that follows
// the active pin instead (see syncEntryCard).
if (!onMarkerCardClickRef.current) {
ensureJourneyPopupStyle()
marker.bindTooltip(
journeyPopupHtml({
title: item.label || item.locationName || 'Entry',
place: item.label ? item.locationName : '',
date: formatMarkerDate(item.time),
photoUrls: item.photoUrls,
}),
{
direction: 'top',
offset: [0, -MARKER_H],
className: 'map-tooltip trek-journey-tooltip',
},
)
marker.bindTooltip(entryCardHtml(item), { ...ENTRY_CARD_OPTIONS, className: 'map-tooltip trek-journey-tooltip' })
}
marker.on('click', () => {
@@ -487,7 +562,8 @@ function JourneyMap(
// A switch puts its layer back on the map or takes it off, exactly as drawn.
useEffect(() => {
shownRef.current = switchLeafletLayers(mapRef.current, drawnRef.current, shownRef.current, layerVisibility)
}, [layerVisibility])
syncEntryCard()
}, [layerVisibility, syncEntryCard])
// The plan's check on an entry pin follows the plan layer without redrawing the map.
useEffect(() => {
@@ -509,8 +585,8 @@ function JourneyMap(
}, [tileUrl])
// Photo layer (#1614). Its own effect on purpose: photos arriving must not tear
// down and rebuild the map the way the entry effect does. Redrawn on zoom and
// pan because the clustering is done in screen space.
// down and rebuild the map the way the entry effect does. Redrawn after every
// move, but the clusters sit on a world grid, so only a zoom regroups them.
useEffect(() => {
const map = mapRef.current
if (!map) return
@@ -522,7 +598,7 @@ function JourneyMap(
// The initial view (setView/fitBounds) is set on a deferred rAF in the
// map-build effect above, so this can run before the map has a center/zoom
// — latLngToContainerPoint throws in that window. Skip; the moveend/zoomend
// and nothing can be projected in that window. Skip; the moveend/zoomend
// listener below redraws once the deferred view lands.
try {
map.getCenter()
@@ -531,7 +607,7 @@ function JourneyMap(
}
const group = L.layerGroup()
for (const cluster of clusterPhotos(photos, (lat, lng) => map.latLngToContainerPoint([lat, lng]))) {
for (const cluster of clusterPhotos(photos, leafletWorldPx(map))) {
const marker = L.marker([cluster.lat, cluster.lng], {
icon: L.divIcon({
className: '',
@@ -563,7 +639,7 @@ function JourneyMap(
// The plan's places and the stays of day reports (JRN-04), in their own layer
// like the photos: below the entry pins and above the thumbnails, regrouped
// on every move because marks are only joined where they would overlap.
// on zoom because marks are only joined where they would overlap.
useEffect(() => {
const map = mapRef.current
if (!map) return
@@ -23,7 +23,8 @@ interface MapEntry {
mood?: string | null
entry_date: string
dayColor?: string
dayLabel?: number
/** Null leaves the pin unnumbered: a draft the share link does not count. */
dayLabel?: number | null
}
interface Props {
@@ -38,7 +39,8 @@ interface Props {
onMarkerClick?: (id: string, type?: string) => void
fullScreen?: boolean
paddingBottom?: number
hideMarkerTooltip?: boolean
/** Open the entry a marker card names when the card is tapped, both renderers. */
onMarkerCardClick?: (entryId: string) => void
/** Open an entry's photos from the marker card's thumbnail strip. GL renderer only. */
onMarkerPhotoClick?: (entryId: string, photoIndex: number) => void
/** Geotagged photos as thumbnails on the map, both renderers (#2453). */
@@ -1,4 +1,4 @@
// FE-COMP-JMAPGL-001 to FE-COMP-JMAPGL-040, FE-COMP-JMAPGL-2453
// FE-COMP-JMAPGL-001 to FE-COMP-JMAPGL-048, FE-COMP-JMAPGL-2453, FE-COMP-JMAPGL-2910
type Spy = ReturnType<typeof vi.fn>
@@ -35,8 +35,9 @@ const gl = vi.hoisted(() => {
off: vi.fn(),
once: vi.fn(),
loaded: vi.fn(() => true),
// Container pixels from lng/lat, ten per degree: enough to tell near from far.
project: vi.fn(([lng, lat]: [number, number]) => ({ x: lng * 10, y: lat * 10 })),
// Container pixels, ten per degree. The layers must not group by them: they
// shift with every pan (#2889).
project: vi.fn(),
remove: vi.fn(),
resize: vi.fn(),
flyTo: vi.fn(),
@@ -182,6 +183,7 @@ beforeEach(() => {
return gl.map
})
gl.map.getZoom.mockReturnValue(10)
gl.map.project.mockImplementation(([lng, lat]: [number, number]) => ({ x: lng * 10, y: lat * 10 }))
gl.map.getSource.mockReturnValue(null)
vi.mocked(isStandardFamily).mockReturnValue(false)
vi.mocked(supportsCustom3d).mockReturnValue(false)
@@ -236,6 +238,15 @@ describe('JourneyMapGL', () => {
expect(gl.markers[1].element.innerHTML).toContain('>1<')
})
it('FE-COMP-JMAPGL-043: a stop without a number (a draft) gets an unnumbered pin', () => {
withToken()
render(<JourneyMapGL checkins={[]} entries={[{ ...entries[0], dayLabel: null }]} />)
expect(gl.markers).toHaveLength(1)
expect(gl.markers[0].element.innerHTML).toContain('#ff0055')
expect(gl.markers[0].element.innerHTML).toMatch(/font-weight="700"><\/text>/)
})
it('FE-COMP-JMAPGL-006: entries without coordinates never reach the map', () => {
withToken()
render(
@@ -253,25 +264,14 @@ describe('JourneyMapGL', () => {
render(<JourneyMapGL checkins={[]} entries={entries} />)
expect(gl.map.addSource).toHaveBeenCalledWith('journey-route', expect.objectContaining({ type: 'geojson' }))
const source = vi.mocked(gl.map.addSource).mock.calls[0][1] as { data: { geometry: { coordinates: number[][] } } }
expect(source.data.geometry.coordinates).toEqual([[2.3522, 48.8566], [13.405, 52.52]])
const source = vi.mocked(gl.map.addSource).mock.calls[0][1] as { data: { geometry: { coordinates: number[][][] } } }
expect(source.data.geometry.coordinates).toEqual([[[2.3522, 48.8566], [13.405, 52.52]]])
expect(gl.map.addLayer).toHaveBeenCalledWith(expect.objectContaining({
id: 'journey-route-line',
source: 'journey-route',
}))
})
it('FE-COMP-JMAPGL-008: an existing route source is updated instead of re-added', () => {
withToken()
const setData = vi.fn()
gl.map.getSource.mockReturnValue({ setData })
render(<JourneyMapGL checkins={[]} entries={entries} />)
expect(gl.map.addSource).not.toHaveBeenCalled()
expect(setData).toHaveBeenCalledWith(expect.objectContaining({ type: 'Feature' }))
})
it('FE-COMP-JMAPGL-038: a planned GPX track goes on the dashed layer, a recorded route on the solid one (JRN-01)', () => {
withToken()
render(
@@ -507,6 +507,86 @@ describe('JourneyMapGL', () => {
expect(document.querySelectorAll('#trek-journey-popup-style')).toHaveLength(1)
})
describe('the marker card as a way into the entry (#2885)', () => {
const withPhotos = [
{ ...entries[0], photoUrls: ['/a.jpg', '/b.jpg'] },
entries[1],
]
// The stub's setHTML records the markup; the card's content is put in by hand.
function openCard(props: Record<string, unknown>, id = 'e1') {
withToken()
const ref = React.createRef<JourneyMapGLHandle>()
render(<JourneyMapGL ref={ref} checkins={[]} entries={withPhotos} {...props} />)
act(() => { ref.current?.highlightMarker(id) })
const popup = gl.popups[0]
popup.element.innerHTML = String(popup.setHTML.mock.lastCall?.[0])
const mapClick = vi.fn()
const host = document.createElement('div')
host.appendChild(popup.element)
host.addEventListener('click', mapClick)
return { ref, popup, mapClick }
}
function tap(popup: PopupStub, selector: string) {
const target = popup.element.querySelector(selector) as HTMLElement
target.click()
}
it('FE-COMP-JMAPGL-044: a tap anywhere on the card opens its entry and stays off the map', () => {
const onMarkerCardClick = vi.fn()
const { popup, mapClick } = openCard({ onMarkerCardClick })
expect(popup.options.className).toContain('is-openable')
tap(popup, '.trek-journey-popup-title')
expect(onMarkerCardClick).toHaveBeenCalledWith('e1')
expect(mapClick).not.toHaveBeenCalled()
})
it('FE-COMP-JMAPGL-045: with a photo handler a thumbnail opens the photo, not the entry', () => {
const onMarkerCardClick = vi.fn()
const onMarkerPhotoClick = vi.fn()
const { popup } = openCard({ onMarkerCardClick, onMarkerPhotoClick })
tap(popup, '[data-shot="1"]')
expect(onMarkerPhotoClick).toHaveBeenCalledWith('e1', 1)
expect(onMarkerCardClick).not.toHaveBeenCalled()
})
it('FE-COMP-JMAPGL-046: without a photo handler a thumbnail opens the entry like the rest of the card', () => {
const onMarkerCardClick = vi.fn()
const { popup } = openCard({ onMarkerCardClick })
tap(popup, '[data-shot]')
expect(onMarkerCardClick).toHaveBeenCalledWith('e1')
})
it('FE-COMP-JMAPGL-047: without a handler the card stays a label the tap passes through', () => {
const { popup, mapClick } = openCard({})
expect(popup.options.className).toBe('trek-journey-popup')
tap(popup, '.trek-journey-popup-title')
expect(mapClick).toHaveBeenCalled()
})
it('FE-COMP-JMAPGL-048: the reused card opens the entry it shows now', () => {
const onMarkerCardClick = vi.fn()
const { ref, popup } = openCard({ onMarkerCardClick })
act(() => { ref.current?.highlightMarker('e2') })
popup.element.innerHTML = String(popup.setHTML.mock.lastCall?.[0])
tap(popup, '.trek-journey-popup-title')
expect(popup.element.classList.contains('is-openable')).toBe(true)
expect(popup.element.classList.contains('is-interactive')).toBe(false)
expect(onMarkerCardClick).toHaveBeenCalledWith('e2')
})
})
it('FE-COMP-JMAPGL-023: focusMarker eases over with the 3D pitch and no zoom of its own', () => {
withToken()
const ref = React.createRef<JourneyMapGLHandle>()
@@ -553,9 +633,10 @@ describe('JourneyMapGL', () => {
{ id: 'b', lat: 45.1, lng: 5.1, thumbUrl: '/api/photos/2/thumbnail' },
{ id: 'c', lat: 48, lng: 11, thumbUrl: '/api/photos/3/thumbnail' },
]
gl.map.getZoom.mockReturnValue(4)
render(<JourneyMapGL checkins={[]} entries={entries} photos={photos} onPhotoClick={onPhotoClick} />)
const thumbs = gl.markers.filter(m => m.element.innerHTML.includes('/api/photos/'))
// a and b fall in one 64px bucket at ten pixels a degree, c in its own.
// At zoom 4 a and b lie three world pixels apart in one 64px cell, c far off.
expect(thumbs).toHaveLength(2)
expect(thumbs[0].element.innerHTML).toContain('>2<')
thumbs[0].element.click()
@@ -563,6 +644,54 @@ describe('JourneyMapGL', () => {
expect(gl.map.on).toHaveBeenCalledWith('moveend', expect.any(Function))
})
it('FE-COMP-JMAPGL-2910: no marker element sets its own position, so the engine keeps it absolute', () => {
withToken()
const photos = [{ id: 'a', lat: 45, lng: 5, thumbUrl: '/api/photos/1/thumbnail' }]
const marks = [{ kind: 'stay', key: 's1', lat: 46, lng: 6, color: '#14b8a6', stay: {} }]
render(<JourneyMapGL checkins={[]} entries={entries} photos={photos} marks={marks} />)
expect(gl.markers.some(m => m.element.innerHTML.includes('/api/photos/'))).toBe(true)
for (const marker of gl.markers) expect(marker.element.style.position).toBe('')
})
it('FE-COMP-JMAPGL-2889: panning keeps the photo and mark groups, only a zoom regroups them', () => {
withToken()
const photos = [
{ id: 'a', lat: 45, lng: 5, thumbUrl: '/api/photos/1/thumbnail' },
{ id: 'b', lat: 45, lng: 5.1, thumbUrl: '/api/photos/2/thumbnail' },
]
const marks = [
{ kind: 'stay', key: 's1', lat: 45, lng: 5, color: '#14b8a6', stay: {} },
{ kind: 'stay', key: 's2', lat: 45, lng: 5.1, color: '#14b8a6', stay: {} },
]
gl.map.getZoom.mockReturnValue(4)
render(<JourneyMapGL checkins={[]} entries={entries} photos={photos} marks={marks} />)
const drawn = () => {
const shown = gl.markers.filter(m => !m.remove.mock.calls.length)
return {
photos: shown.filter(m => m.element.innerHTML.includes('/api/photos/')).map(m => [m.lngLat, m.element.innerHTML]),
marks: shown.filter(m => m.element.innerHTML.includes('#14b8a6')).map(m => [m.lngLat, m.element.innerHTML]),
}
}
const moveEnd = () => act(() => {
const gone = new Set(gl.map.off.mock.calls.map(c => c[1]))
for (const [event, handler] of gl.map.on.mock.calls) if (event === 'moveend' && !gone.has(handler)) (handler as () => void)()
})
const before = drawn()
expect(before.photos).toHaveLength(1)
expect(before.photos[0][1]).toContain('>2<')
expect(before.marks).toHaveLength(1)
// A pan moves every container point; at this offset b crosses a cell edge on screen.
gl.map.project.mockImplementation(([lng, lat]: [number, number]) => ({ x: lng * 10 - 19, y: lat * 10 }))
moveEnd()
expect(drawn()).toEqual(before)
gl.map.getZoom.mockReturnValue(12)
moveEnd()
expect(drawn().photos).toHaveLength(2)
expect(drawn().marks).toHaveLength(2)
})
it('FE-COMP-JMAPGL-026: focusMarker on an unknown id is a no-op', () => {
withToken()
const ref = React.createRef<JourneyMapGLHandle>()
@@ -722,4 +851,45 @@ describe('JourneyMapGL', () => {
expect(gl.markers[0].element.innerHTML).toContain('#16a34a')
expect(mapboxgl.Map).toHaveBeenCalledTimes(1)
})
it('FE-COMP-JMAPGL-041: a recorded day takes the line between its entries off the map, the rest stays (#2888)', () => {
withToken()
const days = [
{ id: 'a', lat: 48.1, lng: 11.5, entry_date: '2026-10-29' },
{ id: 'b', lat: 48.2, lng: 11.6, entry_date: '2026-10-29' },
{ id: 'c', lat: 48.3, lng: 11.7, entry_date: '2026-10-30' },
{ id: 'd', lat: 48.4, lng: 11.8, entry_date: '2026-10-30' },
]
render(
<JourneyMapGL
checkins={[]}
entries={days}
tracks={[{ place_id: -1, trip_id: 0, name: '2026-10-29', color: '#7c3aed', points: [[48.1, 11.5], [48.2, 11.6]], kind: 'dawarich_live', date: '2026-10-29' }]}
/>,
)
const data = (id: string) => (vi.mocked(gl.map.addSource).mock.calls.find(c => c[0] === id)?.[1] as { data: { geometry: { coordinates: number[][][] } } }).data.geometry.coordinates
expect(data('journey-route')).toEqual([[[11.6, 48.2], [11.7, 48.3], [11.8, 48.4]]])
expect(data('journey-route-covered')).toEqual([[[11.5, 48.1], [11.6, 48.2]]])
const covered = vi.mocked(gl.map.addLayer).mock.calls.map(c => c[0] as { id: string; layout: Record<string, unknown> }).find(l => l.id === 'journey-route-covered-line')
expect(covered?.layout.visibility).toBe('none')
})
it('FE-COMP-JMAPGL-042: hiding what was recorded brings the covered stretches back while the entries show', () => {
withToken()
const shown = { plan: true, recorded: true, entries: true }
const days = [
{ id: 'a', lat: 48.1, lng: 11.5, entry_date: '2026-10-29' },
{ id: 'b', lat: 48.2, lng: 11.6, entry_date: '2026-10-29' },
]
const tracks = [{ place_id: -1, trip_id: 0, name: 'Day', color: null, points: [[48.1, 11.5], [48.2, 11.6]] as [number, number][], kind: 'day_recording' as const, date: '2026-10-29' }]
const { rerender } = render(<JourneyMapGL checkins={[]} entries={days} tracks={tracks} layerVisibility={shown} />)
expect(gl.map.addSource).not.toHaveBeenCalledWith('journey-route', expect.anything())
rerender(<JourneyMapGL checkins={[]} entries={days} tracks={tracks} layerVisibility={{ ...shown, recorded: false }} />)
expect(gl.map.setLayoutProperty).toHaveBeenCalledWith('journey-route-covered-line', 'visibility', 'visible')
rerender(<JourneyMapGL checkins={[]} entries={days} tracks={tracks} layerVisibility={{ ...shown, recorded: false, entries: false }} />)
expect(gl.map.setLayoutProperty).toHaveBeenLastCalledWith('journey-route-covered-line', 'visibility', 'none')
})
})
+75 -52
View File
@@ -7,8 +7,9 @@ import { buildGlMap } from '../Map/glSupport'
import type { JourneyTrack } from '@trek/shared'
import { SHOT_INDEX_ATTR, ensureJourneyPopupStyle, formatMarkerDate, journeyPopupHtml } from './journeyMapPopup'
import { clusterPhotos, photoMarkerHtml, type MapPhoto } from './journeyPhotoLayer'
import { MARK_CLUSTER_PX, PLANNED_BADGE_SVG, clusterPoints, markHitSvg, type JourneyMapMark } from './journeyMapMarks'
import { MARK_CLUSTER_PX, PLANNED_BADGE_SVG, clusterPoints, glWorldPx, markHitSvg, type JourneyMapMark } from './journeyMapMarks'
import { isPlannedTrack, type JourneyMapLayerVisibility } from './journeyMapLayers'
import { coveredConnectionsShown, entryConnections } from './journeyMapConnections'
export interface JourneyMapGLHandle {
highlightMarker: (id: string | null) => void
@@ -25,7 +26,7 @@ interface MapEntry {
mood?: string | null
entry_date: string
dayColor?: string
dayLabel?: number
dayLabel?: number | null
/** Thumbnails for the marker card, already resolved by the caller (the share view signs its own). */
photoUrls?: string[]
}
@@ -42,8 +43,8 @@ interface Props {
activeMarkerId?: string | null
onMarkerClick?: (id: string, type?: string) => void
fullScreen?: boolean
/** See the Leaflet twin: no marker labels where a carousel already names the entry. */
hideMarkerTooltip?: boolean
/** See the Leaflet twin: a tap on the card opens the entry it names (#2885). */
onMarkerCardClick?: (entryId: string) => void
/**
* Open the entry's photos from the card's thumbnail strip.
*
@@ -78,7 +79,7 @@ interface Item {
locationName: string
time: string
dayColor: string
dayLabel: number
dayLabel: number | null
photoUrls: string[]
}
@@ -97,7 +98,7 @@ function buildItems(entries: MapEntry[]): Item[] {
locationName: e.location_name || '',
time: e.entry_date,
dayColor: e.dayColor || '#52525B',
dayLabel: e.dayLabel ?? 1,
dayLabel: e.dayLabel === undefined ? 1 : e.dayLabel,
photoUrls: e.photoUrls ?? [],
})
}
@@ -114,8 +115,35 @@ const LAYER_IDS: Record<keyof JourneyMapLayerVisibility, string[]> = {
}
const EVERY_LAYER: JourneyMapLayerVisibility = { plan: true, recorded: true, entries: true }
const NO_PLANNED: ReadonlySet<string> = new Set()
/** The stretches between entries a recorded day already draws; shown only while that recording is hidden. */
const COVERED_CONNECTION_LAYER = 'journey-route-covered-line'
function markerHtml(dayColor: string, dayLabel: number, highlighted: boolean, planned = false): HTMLDivElement {
/** One of the faint lines between the entries, as a dashed layer over its own source. */
function addConnectionLayer(map: mapboxgl.Map, id: string, lines: [number, number][][], dark: boolean, visible: boolean) {
if (lines.length === 0) return
map.addSource(id, {
type: 'geojson',
data: {
type: 'Feature',
properties: {},
geometry: { type: 'MultiLineString', coordinates: lines.map(line => line.map(([lat, lng]) => [lng, lat])) },
},
})
map.addLayer({
id: `${id}-line`,
type: 'line',
source: id,
paint: {
'line-color': dark ? '#71717A' : '#A1A1AA',
'line-width': 1.5,
'line-opacity': 0.5,
'line-dasharray': [2, 3],
},
layout: { 'line-cap': 'round', 'line-join': 'round', visibility: visible ? 'visible' : 'none' },
})
}
function markerHtml(dayColor: string, dayLabel: number | null, highlighted: boolean, planned = false): HTMLDivElement {
const fill = dayColor
const textColor = '#fff'
const stroke = highlighted ? '#fff' : 'rgba(255,255,255,0.5)'
@@ -123,7 +151,7 @@ function markerHtml(dayColor: string, dayLabel: number, highlighted: boolean, pl
? 'drop-shadow(0 0 10px rgba(0,0,0,0.4)) drop-shadow(0 2px 6px rgba(0,0,0,0.4))'
: 'drop-shadow(0 2px 4px rgba(0,0,0,0.25))'
const scale = highlighted ? 1.2 : 1
const label = String(dayLabel)
const label = dayLabel === null ? '' : String(dayLabel)
// Outer wrap holds the element mapbox positions via `transform: translate(...)`.
// Anything animated (scale, filter) has to live on an inner child — otherwise
@@ -166,13 +194,13 @@ function fitOptions(paddingBottom: number | undefined, tilted: boolean | undefin
}
function JourneyMapGL(
{ entries, trail, tracks, height = 220, dark, activeMarkerId, onMarkerClick, fullScreen, paddingBottom, glProvider = 'mapbox-gl', gl, hideMarkerTooltip, onMarkerPhotoClick, photos, onPhotoClick, layerVisibility = EVERY_LAYER, marks, onMarksPick, plannedEntryIds = NO_PLANNED, ref }: Props,
{ entries, trail, tracks, height = 220, dark, activeMarkerId, onMarkerClick, fullScreen, paddingBottom, glProvider = 'mapbox-gl', gl, onMarkerCardClick, onMarkerPhotoClick, photos, onPhotoClick, layerVisibility = EVERY_LAYER, marks, onMarksPick, plannedEntryIds = NO_PLANNED, ref }: Props,
) {
const hideMarkerTooltipRef = useRef(hideMarkerTooltip)
hideMarkerTooltipRef.current = hideMarkerTooltip
const onMarkerCardClickRef = useRef(onMarkerCardClick)
onMarkerCardClickRef.current = onMarkerCardClick
const onMarkerPhotoClickRef = useRef(onMarkerPhotoClick)
onMarkerPhotoClickRef.current = onMarkerPhotoClick
/** Which entry the card is currently describing, for the delegated photo click. */
/** Which entry the card is currently describing, for the delegated card and photo clicks. */
const popupItemIdRef = useRef<string | null>(null)
const stableTrail = trail || EMPTY_TRAIL
const stableTracks = tracks || EMPTY_TRACKS
@@ -224,9 +252,6 @@ function JourneyMapGL(
mapLangRef.current = mapLang
const showPopup = useCallback((id: string) => {
// See `hideMarkerTooltip` on the Leaflet twin: below the carousel the card
// already says this, and the popup only covers the map to repeat it.
if (hideMarkerTooltipRef.current) return
const item = itemsRef.current.find(i => i.id === id)
if (!item || !mapRef.current) return
ensureJourneyPopupStyle()
@@ -244,6 +269,7 @@ function JourneyMapGL(
const offset: [number, number] = [0, -46]
popupItemIdRef.current = item.id
const interactive = !!onMarkerPhotoClickRef.current && item.photoUrls.length > 0
const openable = !!onMarkerCardClickRef.current
if (popupRef.current) {
popupRef.current.setLngLat([item.lng, item.lat])
popupRef.current.setHTML(html)
@@ -252,6 +278,7 @@ function JourneyMapGL(
if (el) {
el.classList.toggle('trek-dark', !!darkRef.current)
el.classList.toggle('is-interactive', interactive)
el.classList.toggle('is-openable', openable)
}
} else {
popupRef.current = new gl.Popup({
@@ -260,7 +287,7 @@ function JourneyMapGL(
closeOnMove: false,
anchor: 'bottom',
offset,
className: `trek-journey-popup${darkRef.current ? ' trek-dark' : ''}${interactive ? ' is-interactive' : ''}`,
className: `trek-journey-popup${darkRef.current ? ' trek-dark' : ''}${interactive ? ' is-interactive' : ''}${openable ? ' is-openable' : ''}`,
maxWidth: '280px',
})
.setLngLat([item.lng, item.lat])
@@ -270,11 +297,18 @@ function JourneyMapGL(
// strip on every entry, so a listener on the thumbnails themselves would have
// to be rebound each time and would leak the ones it forgot.
popupRef.current.getElement()?.addEventListener('click', (ev: Event) => {
const shot = (ev.target as HTMLElement | null)?.closest(`[${SHOT_INDEX_ATTR}]`)
const entryId = popupItemIdRef.current
if (!shot || !entryId) return
ev.stopPropagation()
onMarkerPhotoClickRef.current?.(entryId, Number(shot.getAttribute(SHOT_INDEX_ATTR)))
if (!entryId) return
const shot = (ev.target as HTMLElement | null)?.closest(`[${SHOT_INDEX_ATTR}]`)
const onPhoto = onMarkerPhotoClickRef.current
const onCard = onMarkerCardClickRef.current
if (shot && onPhoto) {
ev.stopPropagation()
onPhoto(entryId, Number(shot.getAttribute(SHOT_INDEX_ATTR)))
} else if (onCard) {
ev.stopPropagation()
onCard(entryId)
}
})
}
}, [gl])
@@ -397,31 +431,12 @@ function JourneyMapGL(
try { map.setConfigProperty('basemap', 'language', basemapLanguage(mapLangRef.current)) } catch { /* style/SDK may not support it */ }
}
// route trail — dashed line connecting entries in time order
if (items.length > 1) {
const coords = items.map(i => [i.lng, i.lat])
if (map.getSource('journey-route')) (map.getSource('journey-route') as mapboxgl.GeoJSONSource).setData({
type: 'Feature', properties: {}, geometry: { type: 'LineString', coordinates: coords } as GeoJSON.LineString,
})
else {
map.addSource('journey-route', {
type: 'geojson',
data: { type: 'Feature', properties: {}, geometry: { type: 'LineString', coordinates: coords } as GeoJSON.LineString },
})
map.addLayer({
id: 'journey-route-line',
type: 'line',
source: 'journey-route',
paint: {
'line-color': darkRef.current ? '#71717A' : '#A1A1AA',
'line-width': 1.5,
'line-opacity': 0.5,
'line-dasharray': [2, 3],
},
layout: layout('entries', { 'line-cap': 'round', 'line-join': 'round' }),
})
}
}
// The faint line between the entries in their order, left off the stretches
// a recorded day already draws as travelled (#2888). Those go on a layer of
// their own that stands in while the reader hides the recording.
const connections = entryConnections(items.map(i => ({ lat: i.lat, lng: i.lng, date: i.time })), stableTracks)
addConnectionLayer(map, 'journey-route', connections.open, !!darkRef.current, visibilityRef.current.entries)
addConnectionLayer(map, 'journey-route-covered', connections.covered, !!darkRef.current, coveredConnectionsShown(visibilityRef.current))
// Tracks, one source for all of them, coloured per feature so a journey
// with several routes keeps them apart. Casing underneath, same as the
@@ -526,9 +541,10 @@ function JourneyMapGL(
}, [entries, stableTrail, stableTracks, glProvider, glStyle, mapboxToken, enableMapbox3d, mapboxQuality, fullScreen, paddingBottom])
// Photo layer (#2453), the GL twin of the Leaflet one: its own effect so photos
// arriving do not rebuild the map, redrawn on every move because the clustering
// is done in screen space. Same dependencies as the build effect above, so it
// attaches to the map that effect just made.
// arriving do not rebuild the map. Redrawn after every move, but the clusters
// sit on a world grid, so only a zoom regroups them; a pan, a turn or a tilt
// leaves them as they were. Same dependencies as the build effect above, so
// it attaches to the map that effect just made.
useEffect(() => {
const map = mapRef.current
if (!map) return
@@ -539,9 +555,12 @@ function JourneyMapGL(
const draw = () => {
clear()
if (!photos?.length) return
for (const cluster of clusterPhotos(photos, (lat, lng) => map.project([lng, lat]))) {
for (const cluster of clusterPhotos(photos, glWorldPx(map))) {
const el = document.createElement('div')
el.style.cssText = 'position:relative;width:48px;height:48px;cursor:pointer'
// No inline `position` (#2910): the engine's marker class positions the element
// absolutely, and `position:relative` would drop it into the normal flow, where
// every thumbnail sits below the ones drawn before it.
el.style.cssText = 'width:48px;height:48px;cursor:pointer'
el.innerHTML = photoMarkerHtml(cluster.members[0].thumbUrl, cluster.members.length)
el.addEventListener('click', (ev) => {
ev.stopPropagation()
@@ -575,6 +594,10 @@ function JourneyMapGL(
markersRef.current.forEach(m => { m.getElement().style.display = layerVisibility.entries ? '' : 'none' })
}
}
const coveredShown = coveredConnectionsShown(layerVisibility)
if (coveredConnectionsShown(shownRef.current) !== coveredShown) {
try { map.setLayoutProperty(COVERED_CONNECTION_LAYER, 'visibility', coveredShown ? 'visible' : 'none') } catch { /* not drawn on this map */ }
}
shownRef.current = layerVisibility
}, [layerVisibility])
@@ -589,7 +612,7 @@ function JourneyMapGL(
}, [plannedEntryIds, setMarkerStyle])
// The plan's places and the stays (JRN-04), the GL twin of the Leaflet layer:
// regrouped on every move, between the photos and the entry pins.
// regrouped on zoom, between the photos and the entry pins.
useEffect(() => {
const map = mapRef.current
if (!map) return
@@ -608,7 +631,7 @@ function JourneyMapGL(
} catch { /* empty bounds */ }
}
}
for (const hit of clusterPoints(marks, (lat, lng) => map.project([lng, lat]), MARK_CLUSTER_PX)) {
for (const hit of clusterPoints(marks, glWorldPx(map), MARK_CLUSTER_PX)) {
const look = markHitSvg(hit.members)
const el = document.createElement('div')
el.style.cssText = `width:${look.width}px;height:${look.height}px;cursor:pointer`
@@ -1,4 +1,4 @@
// FE-COMP-JENTRYVIEW-001 to FE-COMP-JENTRYVIEW-020
// FE-COMP-JENTRYVIEW-001 to FE-COMP-JENTRYVIEW-022
import { render, screen, fireEvent } from '../../../tests/helpers/render'
import { resetAllStores, seedStore } from '../../../tests/helpers/store'
@@ -136,6 +136,18 @@ describe('MobileEntryView', () => {
expect(container.querySelector('svg.lucide-camera')).toBeNull()
})
it('FE-COMP-JENTRYVIEW-021: the hero holds the proportions of the photo and shows its thumbnail before the original arrives (#2907)', () => {
const { container } = renderView(buildEntry({ photos: [{ ...buildPhoto(4), width: 3000, height: 2000 }] }))
const hero = container.querySelector('img') as HTMLImageElement
expect(hero.style.aspectRatio).toBe('3000 / 2000')
expect(hero.style.backgroundImage).toContain('/api/photos/4/thumbnail')
})
it('FE-COMP-JENTRYVIEW-022: a photo without recorded dimensions still reserves a 4:3 hero', () => {
const { container } = renderView(buildEntry({ photos: [buildPhoto(4)] }))
expect((container.querySelector('img') as HTMLImageElement).style.aspectRatio).toBe('4 / 3')
})
it('FE-COMP-JENTRYVIEW-008: several photos add a counter and a thumbnail strip', () => {
const { container } = renderView(buildEntry({ photos: [buildPhoto(4), buildPhoto(5), buildPhoto(6)] }))
expect(screen.getByText('3 photos')).toBeInTheDocument()
@@ -4,6 +4,7 @@ import {
Sun, CloudSun, Cloud, CloudRain, CloudLightning, Snowflake,
ThumbsUp, ThumbsDown,
} from 'lucide-react'
import type { CSSProperties } from 'react'
import JournalBody from './JournalBody'
import { useTranslation } from '../../i18n'
import { formatLocationName } from '../../utils/formatters'
@@ -39,6 +40,22 @@ function photoUrl(
return `/api/photos/${p.photo_id}/${size}`
}
/**
* The hero's box before its picture arrives (#2907): the photo's own proportions
* when the upload recorded them, else 4:3, so the story below does not jump down
* once the original has loaded. The thumbnail, usually cached by the strip or the
* feed already, fills that box meanwhile.
*/
function heroPlaceholderStyle(photo: JourneyPhoto, thumbUrl: string): CSSProperties {
const ratio = photo.width && photo.height ? `${photo.width} / ${photo.height}` : '4 / 3'
return {
aspectRatio: ratio,
backgroundImage: `url("${encodeURI(thumbUrl)}")`,
backgroundSize: 'cover',
backgroundPosition: 'center',
}
}
interface Props {
entry: JourneyEntry
readOnly?: boolean
@@ -114,8 +131,10 @@ export default function MobileEntryView({ entry, readOnly, publicPhotoUrl, onClo
<img
src={photoUrl(photos[0], photos[0].media_type === 'video' ? 'thumbnail' : 'original', publicPhotoUrl)}
alt=""
className={`w-full max-h-[50vh] ${photos[0].media_type === 'video' ? 'object-contain' : 'object-cover'
decoding="async"
className={`block w-full max-h-[50vh] bg-surface-secondary ${photos[0].media_type === 'video' ? 'object-contain' : 'object-cover'
}`}
style={heroPlaceholderStyle(photos[0], photoUrl(photos[0], 'thumbnail', publicPhotoUrl))}
/>
)}
@@ -143,7 +162,7 @@ export default function MobileEntryView({ entry, readOnly, publicPhotoUrl, onClo
key={p.id || i}
type="button"
aria-label={p.caption || t('journey.photos')}
className={`relative h-16 w-16 flex-shrink-0 cursor-pointer overflow-hidden rounded-lg border-0 p-0 hover:ring-2 ring-zinc-900/30 dark:ring-white/30 transition-all ${p.media_type === 'video' ? 'bg-black' : 'bg-transparent'
className={`relative h-16 w-16 flex-shrink-0 cursor-pointer overflow-hidden rounded-lg border-0 p-0 hover:ring-2 ring-zinc-900/30 dark:ring-white/30 transition-all ${p.media_type === 'video' ? 'bg-black' : 'bg-surface-secondary'
}`}
onClick={() => onPhotoClick(photos, i)}
>
@@ -1,4 +1,4 @@
// FE-COMP-JMAPTL-001 to FE-COMP-JMAPTL-016
// FE-COMP-JMAPTL-001 to FE-COMP-JMAPTL-018
const mapHandle = vi.hoisted(() => ({
highlightMarker: vi.fn(),
@@ -190,6 +190,16 @@ describe('MobileMapTimeline', () => {
expect(Element.prototype.scrollIntoView).toHaveBeenCalled()
})
it('FE-COMP-JMAPTL-018: a tap on a marker card opens that entry straight away (#2885)', () => {
const onEntryClick = vi.fn()
renderTimeline({ onEntryClick })
const onMarkerCardClick = lastMapProps.current.onMarkerCardClick as (id: string) => void
act(() => { onMarkerCardClick('2') })
expect(onEntryClick).toHaveBeenCalledWith(entries[1])
})
it('FE-COMP-JMAPTL-007: a marker click for an unknown entry is ignored', () => {
renderTimeline()
const onMarkerClick = lastMapProps.current.onMarkerClick as (id: string) => void
@@ -70,7 +70,7 @@ export default function MobileMapTimeline({
}: Props) {
const {
mapRef, carouselRef, cardRefs, activeIndex, setActiveIndex, scrubberDays,
syncMapToCard: syncMapToCarousel, handleMarkerClick, handleCardTap, jumpToDay,
syncMapToCard: syncMapToCarousel, handleMarkerClick, handleCardTap, openEntryById, jumpToDay,
} = useJourneyCarouselSync({ entries, mapEntries, onOpenEntry: onEntryClick })
// The delayed initial focus reads both through refs so it always works off
// the current map entries, not the ones from the render that armed the timer.
@@ -169,6 +169,7 @@ export default function MobileMapTimeline({
dark={dark}
activeMarkerId={activeEntryId}
onMarkerClick={handleMarkerClick}
onMarkerCardClick={openEntryById}
fullScreen
paddingBottom={250}
cartoApiKey={cartoApiKey}
@@ -1,4 +1,4 @@
// FE-COMP-LIGHTBOX-001 to FE-COMP-LIGHTBOX-027
// FE-COMP-LIGHTBOX-001 to FE-COMP-LIGHTBOX-029
// Plyr needs a real media pipeline, so the player is stubbed here.
vi.mock('./VideoPlayer', () => ({
@@ -326,4 +326,28 @@ describe('PhotoLightbox', () => {
expect(screen.getByText('Google', { selector: 'p' })).toBeInTheDocument();
expect(screen.queryByRole('link')).not.toBeInTheDocument();
});
it('FE-COMP-LIGHTBOX-028: the thumbnail and a spinner stand in until the original has loaded (#2907)', () => {
const { container } = render(
<PhotoLightbox photos={[{ id: 'a', src: '/a/original', thumbSrc: '/a/thumbnail' }]} onClose={vi.fn()} />,
);
const placeholder = screen.getByTestId('lightbox-loading');
expect(placeholder.querySelector('img')).toHaveAttribute('src', '/a/thumbnail');
expect(placeholder.querySelector('svg.animate-spin')).toBeInTheDocument();
fireEvent.load(container.ownerDocument.querySelector('img[src="/a/original"]') as HTMLImageElement);
expect(screen.queryByTestId('lightbox-loading')).not.toBeInTheDocument();
});
it('FE-COMP-LIGHTBOX-029: the next photo waits for its own original, and a failed one drops the spinner too', () => {
render(
<PhotoLightbox photos={[{ id: 'a', src: '/a.jpg' }, { id: 'b', src: '/b.jpg' }]} onClose={vi.fn()} />,
);
fireEvent.load(document.querySelector('img[src="/a.jpg"]') as HTMLImageElement);
expect(screen.queryByTestId('lightbox-loading')).not.toBeInTheDocument();
fireEvent.keyDown(window, { key: 'ArrowRight' });
expect(screen.getByTestId('lightbox-loading')).toBeInTheDocument();
fireEvent.error(document.querySelector('img[src="/b.jpg"]') as HTMLImageElement);
expect(screen.queryByTestId('lightbox-loading')).not.toBeInTheDocument();
});
});
@@ -1,5 +1,5 @@
import { useState, useEffect, useCallback, useRef } from 'react'
import { ChevronLeft, ChevronRight, X, ZoomIn, ZoomOut } from 'lucide-react'
import { ChevronLeft, ChevronRight, Loader2, X, ZoomIn, ZoomOut } from 'lucide-react'
import VideoPlayer from './VideoPlayerLazy'
import { usePhotoZoom } from './usePhotoZoom'
import { Tooltip } from '../shared/Tooltip'
@@ -8,6 +8,12 @@ import { isRtlLanguage, useTranslation } from '../../i18n'
interface LightboxPhoto {
id: string
src: string
/**
* A small rendition of the same photo, usually cached already by the grid that
* opened the lightbox. It stands in while the original loads, which on a slow
* server or connection can take seconds (#2907).
*/
thumbSrc?: string
caption?: string | null
/** Where the caption's credit points to (a photo's source page), opened in a new tab. */
captionHref?: string | null
@@ -52,6 +58,9 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
// Zoom starts over on every photo (#1484).
const zoom = usePhotoZoom(photo?.id)
const isImage = !!photo && photo.mediaType !== 'video'
// The id whose original has finished (or failed) loading; any other photo is still on its way.
const [loadedId, setLoadedId] = useState<string | null>(null)
const loading = isImage && loadedId !== photo.id
const hasPrev = idx > 0
const hasNext = idx < photos.length - 1
@@ -187,6 +196,8 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
src={photo.src}
alt={photo.caption || ''}
draggable={false}
onLoad={() => setLoadedId(photo.id)}
onError={() => setLoadedId(photo.id)}
{...zoom.mouse}
style={{
maxWidth: '92vw', maxHeight: '92vh',
@@ -198,6 +209,17 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
/>
)}
{loading && (
<div data-testid="lightbox-loading" aria-hidden="true" style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', pointerEvents: 'none' }}>
{photo.thumbSrc && (
<img src={photo.thumbSrc} alt="" draggable={false} style={{ width: '92vw', height: '92vh', objectFit: 'contain', borderRadius: 4 }} />
)}
<span style={{ ...ROUND_BTN, position: 'absolute', cursor: 'default' }}>
<Loader2 size={18} className="animate-spin" />
</span>
</div>
)}
{/* Next button */}
{hasNext && (
<button type="button" onClick={next} aria-label={t('journey.lightbox.next')} className="flex sm:opacity-0 sm:group-hover/lightbox:opacity-100 focus-visible:opacity-100 transition-opacity" style={{
@@ -1,12 +1,21 @@
import L from 'leaflet';
import { coveredConnectionsShown } from './journeyMapConnections';
import type { JourneyMapLayerVisibility } from './journeyMapLayers';
import { MARK_CLUSTER_PX, clusterPoints, markHitSvg, type JourneyMapMark } from './journeyMapMarks';
import { MARK_CLUSTER_PX, clusterPoints, markHitSvg, type JourneyMapMark, type WorldPx } from './journeyMapMarks';
/** The layers of the Leaflet journey map a switch takes off and puts back (JRN-04). */
export type LeafletLayerKind = keyof JourneyMapLayerVisibility;
/**
* The layers of the Leaflet journey map a switch takes off and puts back (JRN-04),
* plus the stretches between entries a recording already shows, which follow two.
*/
export type LeafletLayerKind = keyof JourneyMapLayerVisibility | 'coveredConnections';
export type DrawnLayers = Record<LeafletLayerKind, L.Layer[]>;
export const NOTHING_DRAWN = (): DrawnLayers => ({ plan: [], recorded: [], entries: [] });
export const NOTHING_DRAWN = (): DrawnLayers => ({ plan: [], recorded: [], entries: [], coveredConnections: [] });
/** Whether a layer of this kind is on the map with these switches. */
export function isLeafletLayerShown(kind: LeafletLayerKind, visibility: JourneyMapLayerVisibility): boolean {
return kind === 'coveredConnections' ? coveredConnectionsShown(visibility) : visibility[kind];
}
/**
* Puts each layer whose switch changed back on the map or takes it off,
@@ -20,15 +29,25 @@ export function switchLeafletLayers(
): JourneyMapLayerVisibility {
if (!map) return shown;
for (const kind of Object.keys(drawn) as LeafletLayerKind[]) {
if (shown[kind] === next[kind]) continue;
const visible = isLeafletLayerShown(kind, next);
if (isLeafletLayerShown(kind, shown) === visible) continue;
for (const layer of drawn[kind]) {
if (next[kind]) layer.addTo(map);
if (visible) layer.addTo(map);
else layer.remove();
}
}
return next;
}
/**
* World pixels at the map's current zoom, through the map's own CRS so a
* GCJ-02 basemap groups where it draws. Only meaningful once the map has a view.
*/
export function leafletWorldPx(map: L.Map): WorldPx {
const zoom = map.getZoom();
return (lat, lng) => map.project([lat, lng], zoom);
}
/**
* The plan's places and the stays as one layer: below the entry pins, above
* the photo thumbnails, joined only where they would overlap on screen.
@@ -47,7 +66,7 @@ export function drawLeafletMarks(
return null;
}
const group = L.layerGroup();
for (const hit of clusterPoints(marks, (lat, lng) => map.latLngToContainerPoint([lat, lng]), MARK_CLUSTER_PX)) {
for (const hit of clusterPoints(marks, leafletWorldPx(map), MARK_CLUSTER_PX)) {
const look = markHitSvg(hit.members);
const marker = L.marker([hit.lat, hit.lng], {
icon: L.divIcon({
@@ -0,0 +1,117 @@
// FE-JRN-CONN-001 to FE-JRN-CONN-008
import type { JourneyTrack } from '@trek/shared';
import { describe, expect, it } from 'vitest';
import { coveredConnectionsShown, entryConnections } from './journeyMapConnections';
const stop = (lat: number, date: string) => ({ lat, lng: lat, date });
function recorded(
date: string,
kind: JourneyTrack['kind'] = 'day_recording',
points: [number, number][] = [
[1, 1],
[2, 2],
]
): JourneyTrack {
return { place_id: -1, trip_id: 0, name: date, color: null, points, kind, date };
}
describe('entryConnections (#2888)', () => {
it('FE-JRN-CONN-001: without a recording the whole line stays open, one polyline through every stop', () => {
const result = entryConnections([stop(1, '2026-10-29'), stop(2, '2026-10-29'), stop(3, '2026-10-30')], []);
expect(result.open).toEqual([
[
[1, 1],
[2, 2],
[3, 3],
],
]);
expect(result.covered).toEqual([]);
});
it('FE-JRN-CONN-002: a recorded day covers the stretches between its entries, the jump into a day without one stays open', () => {
const result = entryConnections(
[stop(1, '2026-10-29'), stop(2, '2026-10-29'), stop(3, '2026-10-30'), stop(4, '2026-10-30')],
[recorded('2026-10-29', 'dawarich_live')]
);
expect(result.covered).toEqual([
[
[1, 1],
[2, 2],
],
]);
expect(result.open).toEqual([
[
[2, 2],
[3, 3],
[4, 4],
],
]);
});
it('FE-JRN-CONN-003: the night between two recorded days is covered, a day in between without one is not', () => {
const tracks = [recorded('2026-10-29'), recorded('2026-10-30'), recorded('2026-11-01')];
expect(entryConnections([stop(1, '2026-10-29'), stop(2, '2026-10-30')], tracks).open).toEqual([]);
expect(entryConnections([stop(1, '2026-10-30'), stop(2, '2026-11-01')], tracks).covered).toEqual([]);
});
it('FE-JRN-CONN-004: a trip GPX, a line without a day and a recording without points cover nothing', () => {
const stops = [stop(1, '2026-10-29'), stop(2, '2026-10-29')];
const gpx: JourneyTrack = { ...recorded('2026-10-29'), kind: 'trip_gpx' };
const undated: JourneyTrack = { ...recorded('2026-10-29'), date: undefined };
const empty = recorded('2026-10-29', 'day_recording', [[1, 1]]);
expect(entryConnections(stops, [gpx, undated, empty]).covered).toEqual([]);
});
it('FE-JRN-CONN-005: open and covered stretches alternate in the order of the stops', () => {
const result = entryConnections(
[
stop(1, '2026-10-28'),
stop(2, '2026-10-29'),
stop(3, '2026-10-29'),
stop(4, '2026-10-31'),
stop(5, '2026-10-31'),
],
[recorded('2026-10-29'), recorded('2026-10-31')]
);
expect(result.open).toEqual([
[
[1, 1],
[2, 2],
],
[
[3, 3],
[4, 4],
],
]);
expect(result.covered).toEqual([
[
[2, 2],
[3, 3],
],
[
[4, 4],
[5, 5],
],
]);
});
it('FE-JRN-CONN-006: a timestamp is read by its day, and an unreadable date never counts as recorded', () => {
expect(
entryConnections([stop(1, '2026-10-29T08:00:00Z'), stop(2, '2026-10-29')], [recorded('2026-10-29')]).open
).toEqual([]);
expect(entryConnections([stop(1, 'someday'), stop(2, '2026-10-29')], [recorded('2026-10-29')]).covered).toEqual([]);
});
it('FE-JRN-CONN-007: fewer than two stops make no line', () => {
expect(entryConnections([stop(1, '2026-10-29')], [])).toEqual({ open: [], covered: [] });
});
});
describe('coveredConnectionsShown', () => {
it('FE-JRN-CONN-008: stands in only while the entries show and the recording is hidden', () => {
expect(coveredConnectionsShown({ plan: true, recorded: true, entries: true })).toBe(false);
expect(coveredConnectionsShown({ plan: true, recorded: false, entries: true })).toBe(true);
expect(coveredConnectionsShown({ plan: true, recorded: false, entries: false })).toBe(false);
});
});
@@ -0,0 +1,93 @@
import type { JourneyTrack } from '@trek/shared';
import { isPlannedTrack, type JourneyMapLayerVisibility } from './journeyMapLayers';
/** A point of the line between entries, `[lat, lng]`. */
type LatLng = [number, number];
/** An entry pin as the connection sees it: where it stands and on which day. */
interface ConnectionStop {
lat: number;
lng: number;
/** `YYYY-MM-DD`; a longer ISO string is read by its date. */
date: string;
}
/**
* The faint line between the entries, cut where the map already shows how the
* traveller got from one to the next.
*
* `open` is every stretch nothing else on the map accounts for, so the
* straight line is the best guess there is. `covered` is every stretch whose
* days were all recorded: the recorded line is the real way, and a straight
* one across it only gets in its way (#2888). It is still handed back, so a
* reader who hides what was recorded gets the guess back for those stretches.
*/
interface EntryConnections {
open: LatLng[][];
covered: LatLng[][];
}
const DAY_MS = 86_400_000;
function dayNumber(date: string): number | null {
const time = Date.parse(`${date.slice(0, 10)}T00:00:00Z`);
return Number.isNaN(time) ? null : Math.round(time / DAY_MS);
}
/** The days a recorded line with points stands for; a trip's GPX is the plan and stands for none. */
function recordedDays(tracks: readonly JourneyTrack[]): Set<number> {
const days = new Set<number>();
for (const track of tracks) {
if (isPlannedTrack(track) || !track.date || track.points.length < 2) continue;
const day = dayNumber(track.date);
if (day !== null) days.add(day);
}
return days;
}
/**
* Whether the way between two stops is on the map already: every day from the
* first stop's to the second's was recorded, the night between two recorded
* days included. One day in between without a recording leaves it open.
*/
function travelled(from: string, to: string, recorded: ReadonlySet<number>): boolean {
const a = dayNumber(from);
const b = dayNumber(to);
if (a === null || b === null) return false;
const first = Math.min(a, b);
const last = Math.max(a, b);
if (last - first + 1 > recorded.size) return false;
for (let day = first; day <= last; day++) {
if (!recorded.has(day)) return false;
}
return true;
}
/**
* Splits the line through the stops, taken in the order given (the pins'
* order on the map), into the stretches still open and those a recording
* covers. Neighbouring stretches of the same kind stay one line.
*/
export function entryConnections(stops: readonly ConnectionStop[], tracks: readonly JourneyTrack[]): EntryConnections {
const result: EntryConnections = { open: [], covered: [] };
const recorded = recordedDays(tracks);
let line: LatLng[] | null = null;
let lineCovered = false;
for (let i = 1; i < stops.length; i++) {
const from = stops[i - 1];
const to = stops[i];
const covered = travelled(from.date, to.date, recorded);
if (!line || covered !== lineCovered) {
line = [[from.lat, from.lng]];
(covered ? result.covered : result.open).push(line);
lineCovered = covered;
}
line.push([to.lat, to.lng]);
}
return result;
}
/** The covered stretches stand in for the recording only while the pins are shown and the recording is not. */
export function coveredConnectionsShown(visibility: JourneyMapLayerVisibility): boolean {
return visibility.entries && !visibility.recorded;
}
@@ -1,4 +1,4 @@
// FE-JOURNEY-MAPMARKS-001 to FE-JOURNEY-MAPMARKS-003
// FE-JOURNEY-MAPMARKS-001 to FE-JOURNEY-MAPMARKS-005
//
// JRN-04: the plan and stay marks both renderers draw, and how they join.
import type { JourneyMapPlace, JourneyMapStay } from '@trek/shared';
@@ -6,7 +6,9 @@ import { describe, expect, it } from 'vitest';
import {
MARK_CLUSTER_PX,
clusterPoints,
glWorldPx,
markHitSvg,
mercatorWorldPx,
planPinSvg,
safeColor,
type JourneyMapMark,
@@ -54,4 +56,39 @@ describe('journey map marks', () => {
expect(safeColor(null)).toBe('#64748b');
expect(planPinSvg('red" onload="x')).not.toContain('onload');
});
it('FE-JOURNEY-MAPMARKS-004: world pixels are Web Mercator at the zoom, doubling per step and clamped at the poles', () => {
expect(mercatorWorldPx(0, 0, 0, 512)).toEqual({ x: 256, y: 256 });
expect(mercatorWorldPx(0, -180, 0, 512).x).toBe(0);
const z5 = mercatorWorldPx(35.01, 135.68, 5, 512);
const z6 = mercatorWorldPx(35.01, 135.68, 6, 512);
expect(z6.x).toBeCloseTo(z5.x * 2, 6);
expect(z6.y).toBeCloseTo(z5.y * 2, 6);
expect(mercatorWorldPx(90, 0, 0, 512).y).toBeCloseTo(0, 3);
expect(mercatorWorldPx(-90, 0, 0, 512).y).toBeCloseTo(512, 3);
});
it('FE-JOURNEY-MAPMARKS-005: groups on the GL world grid hold however the view is panned, and split on zoom (#2889)', () => {
const marks = [planMark('a', 35.0), planMark('b', 35.0005), planMark('c', 35.001)];
const keys = (hits: { members: JourneyMapMark[] }[]) => hits.map((h) => h.members.map((m) => m.key));
// What a container point does: the same world position, less the pan.
const onScreen = (pan: number) =>
keys(
clusterPoints(
marks,
(lat, lng) => {
const world = mercatorWorldPx(lat, lng, 13, 512);
return { x: world.x, y: world.y - pan };
},
MARK_CLUSTER_PX
)
);
const screenGroupings = new Set(Array.from({ length: MARK_CLUSTER_PX }, (_, pan) => JSON.stringify(onScreen(pan))));
expect(screenGroupings.size).toBeGreaterThan(1);
const atZoom = (zoom: number) => keys(clusterPoints(marks, glWorldPx({ getZoom: () => zoom }), MARK_CLUSTER_PX));
expect(atZoom(13)).toEqual([['a', 'b', 'c']]);
expect(atZoom(18)).toEqual([['a'], ['b'], ['c']]);
});
});
@@ -15,7 +15,7 @@ export type JourneyMapMark =
export const PLAN_FALLBACK_COLOR = '#64748b';
/**
* Marks closer than this on screen are one hit: the reader could not pick one
* Marks in one cell of this size are one hit: the reader could not pick one
* of them anyway. Tighter than the photo grid, since a mark is a pin and not a
* thumbnail, so marks a street apart stay apart.
*/
@@ -27,19 +27,49 @@ const STAY_DOT = 14;
const MARK_CLUSTER_SIZE = 28;
/**
* Grid clustering in screen space, shared by both renderers: points whose
* projected position falls in the same `px` cell become one, anchored on the
* first so the pin points where that member is. `project` is the engine's own
* lat/lng to container-pixel conversion.
* A position in world pixels: the whole map laid out at the current zoom, with
* the origin at its north-west corner. Unlike a container point it does not
* move when the map is panned, rotated or tilted.
*/
export type WorldPx = (lat: number, lng: number) => { x: number; y: number };
const MAX_MERCATOR_LAT = 85.0511287798;
/**
* Web Mercator world pixels at `zoom` for a tile of `tileSize` pixels. Both GL
* engines lay out their world on 512 px tiles; Leaflet projects through its
* own CRS instead, so a GCJ-02 basemap keeps its offset.
*/
export function mercatorWorldPx(lat: number, lng: number, zoom: number, tileSize: number): { x: number; y: number } {
const size = tileSize * 2 ** zoom;
const phi = (Math.max(-MAX_MERCATOR_LAT, Math.min(MAX_MERCATOR_LAT, lat)) * Math.PI) / 180;
return {
x: ((lng + 180) / 360) * size,
y: ((1 - Math.log(Math.tan(phi) + 1 / Math.cos(phi)) / Math.PI) / 2) * size,
};
}
/** World pixels at a GL map's current zoom, free of its centre, bearing and pitch. */
export function glWorldPx(map: { getZoom(): number }): WorldPx {
const zoom = map.getZoom();
return (lat, lng) => mercatorWorldPx(lat, lng, zoom, 512);
}
/**
* Grid clustering shared by both renderers: points whose world position falls
* in the same `px` cell become one, anchored on the first so the pin points
* where that member is. The grid is laid over the world and not over the
* viewport, so panning keeps every group as it is and only a zoom regroups
* (#2889).
*/
export function clusterPoints<T extends { lat: number; lng: number }>(
points: readonly T[],
project: (lat: number, lng: number) => { x: number; y: number },
toWorldPx: WorldPx,
px: number
): { lat: number; lng: number; members: T[] }[] {
const buckets = new Map<string, T[]>();
for (const point of points) {
const pt = project(point.lat, point.lng);
const pt = toWorldPx(point.lat, point.lng);
const key = `${Math.round(pt.x / px)}:${Math.round(pt.y / px)}`;
const list = buckets.get(key);
if (list) list.push(point);
@@ -93,11 +93,24 @@ export function ensureJourneyPopupStyle(): void {
s.textContent = `
.mapboxgl-popup.trek-journey-popup,
.maplibregl-popup.trek-journey-popup { pointer-events: none; animation: trek-journey-popup-in 180ms ease-out; }
/* The card as a whole never takes the pointer — it sits over the map and would
swallow drags. The photo strip is the one exception, and only where the host
wired a handler for it. */
/* The card sits over the map and takes the pointer only where the host gave it
an action: the whole card where it opens its entry (the phone, where a tap on
a pin is what brings it up), the photo strip where it opens the pictures.
Anywhere else it stays a label the map's drags pass through. */
.mapboxgl-popup.trek-journey-popup.is-openable .mapboxgl-popup-content,
.maplibregl-popup.trek-journey-popup.is-openable .maplibregl-popup-content { pointer-events: auto; cursor: pointer; }
.trek-journey-popup.is-interactive .trek-journey-popup-shots { pointer-events: auto; cursor: zoom-in; }
.trek-journey-popup.is-interactive .trek-journey-popup-shot:hover { filter: brightness(1.06); }
/* The shared map-tooltip style turns the pointer off on every Leaflet tooltip. */
.leaflet-tooltip.map-tooltip.trek-journey-tooltip.is-openable { pointer-events: auto; cursor: pointer; }
/* The press shows on what the card holds: Leaflet positions the tooltip with its
own transform and sets its opacity inline, so the shell itself is off limits. */
.mapboxgl-popup.trek-journey-popup.is-openable .mapboxgl-popup-content > *,
.maplibregl-popup.trek-journey-popup.is-openable .maplibregl-popup-content > *,
.leaflet-tooltip.trek-journey-tooltip.is-openable > * { transition: opacity 120ms ease-out; }
.mapboxgl-popup.trek-journey-popup.is-openable .mapboxgl-popup-content:active > *,
.maplibregl-popup.trek-journey-popup.is-openable .maplibregl-popup-content:active > *,
.leaflet-tooltip.trek-journey-tooltip.is-openable:active > * { opacity: 0.6; }
.mapboxgl-popup.trek-journey-popup .mapboxgl-popup-content,
.maplibregl-popup.trek-journey-popup .maplibregl-popup-content,
.leaflet-tooltip.trek-journey-tooltip {
@@ -0,0 +1,98 @@
// FE-JRN-STOPS-001 to FE-JRN-STOPS-007
import { describe, expect, it } from 'vitest';
import { compareJourneyEntries, isJourneyMapEntry, journeyMapStops, type JourneyStopEntry } from './journeyMapStops';
function entry(over: Partial<JourneyStopEntry> & { id: number }): JourneyStopEntry {
return {
entry_date: '2026-10-24',
sort_order: 0,
type: 'entry',
title: 'Stop',
location_lat: 35,
location_lng: 135.7,
...over,
};
}
function numbers(entries: JourneyStopEntry[]): Record<string, number | null> {
return Object.fromEntries(journeyMapStops(entries).map(({ entry: e, stop }) => [String(e.id), stop]));
}
describe('journeyMapStops', () => {
it('FE-JRN-STOPS-001: counts through the whole journey instead of restarting each day', () => {
const entries = [
entry({ id: 1, entry_date: '2026-10-23' }),
entry({ id: 2, entry_date: '2026-10-23', sort_order: 1 }),
entry({ id: 3, entry_date: '2026-10-23', sort_order: 2 }),
entry({ id: 4, entry_date: '2026-10-24' }),
entry({ id: 5, entry_date: '2026-10-24', sort_order: 1 }),
];
expect(numbers(entries)).toEqual({ 1: 1, 2: 2, 3: 3, 4: 4, 5: 5 });
});
it('FE-JRN-STOPS-002: numbers in reading order whatever order the entries arrive in', () => {
const entries = [
entry({ id: 9, entry_date: '2026-10-24', sort_order: 1 }),
entry({ id: 7, entry_date: '2026-10-23' }),
entry({ id: 8, entry_date: '2026-10-24', sort_order: 0 }),
];
expect(journeyMapStops(entries).map((s) => s.entry.id)).toEqual([7, 8, 9]);
expect(numbers(entries)).toEqual({ 7: 1, 8: 2, 9: 3 });
});
it('FE-JRN-STOPS-003: a sort_order tie is broken by id, as the server orders them', () => {
const entries = [entry({ id: 12 }), entry({ id: 10 }), entry({ id: 11 })];
expect(journeyMapStops(entries).map((s) => s.entry.id)).toEqual([10, 11, 12]);
expect(compareJourneyEntries(entry({ id: 10 }), entry({ id: 11 }))).toBeLessThan(0);
});
it('FE-JRN-STOPS-004: a draft keeps its pin without a number and does not move the stops after it', () => {
const entries = [
entry({ id: 1, entry_date: '2026-10-23' }),
entry({ id: 2, entry_date: '2026-10-23', sort_order: 1, is_draft: true }),
entry({ id: 3, entry_date: '2026-10-24' }),
];
expect(numbers(entries)).toEqual({ 1: 1, 2: null, 3: 2 });
expect(numbers(entries.filter((e) => !e.is_draft))).toEqual({ 1: 1, 3: 2 });
});
it('FE-JRN-STOPS-005: skeletons, gallery placeholders and entries without coordinates stay off the map', () => {
const entries = [
entry({ id: 1, type: 'skeleton' }),
entry({ id: 2, title: 'Gallery' }),
entry({ id: 3, title: '[Trip Photos]' }),
entry({ id: 4, location_lat: null, location_lng: null }),
entry({ id: 5, sort_order: 1 }),
];
expect(numbers(entries)).toEqual({ 5: 1 });
expect(entries.map(isJourneyMapEntry)).toEqual([false, false, false, false, true]);
});
it('FE-JRN-STOPS-006: the owner journal and the share link give every published stop the same number', () => {
const owner = [
entry({ id: 21, entry_date: '2026-10-23' }),
entry({ id: 22, entry_date: '2026-10-23', sort_order: 1, is_draft: true }),
entry({ id: 23, entry_date: '2026-10-23', sort_order: 2 }),
entry({ id: 24, entry_date: '2026-10-24', type: 'skeleton' }),
entry({ id: 25, entry_date: '2026-10-24', sort_order: 1 }),
];
const shared = owner.filter((e) => !e.is_draft && e.type !== 'skeleton');
const ownerNumbers = numbers(owner);
delete ownerNumbers[22];
expect(ownerNumbers).toEqual(numbers(shared));
});
it('FE-JRN-STOPS-007: leaves the caller its list untouched', () => {
const entries = [entry({ id: 2, sort_order: 1 }), entry({ id: 1 })];
journeyMapStops(entries);
expect(entries.map((e) => e.id)).toEqual([2, 1]);
});
});
@@ -0,0 +1,59 @@
/**
* Which journal entries stand on a journey's map and the number each one carries.
*
* The owner's journal and the public share link both draw the same pins, and they
* used to number them by two different rules: the share link counted through the
* whole journey (#1962) while the owner's map restarted at 1 every day, so the
* same stop read 66 on one and 6 on the other (#2886). Both views now take their
* numbers from here.
*/
export interface JourneyStopEntry {
id: number | string;
entry_date: string;
sort_order?: number | null;
title?: string | null;
type?: string | null;
is_draft?: boolean | number | null;
location_lat?: number | null;
location_lng?: number | null;
}
interface JourneyMapStop<E> {
entry: E;
/** The stop's place in the whole journey, or null for a draft the share link does not show. */
stop: number | null;
}
/** Placeholder entries the old gallery model kept in the journal; a migration removes them, older caches may still hold them. */
const GALLERY_PLACEHOLDER_TITLES = new Set(['Gallery', '[Trip Photos]']);
export function isGalleryPlaceholder(entry: Pick<JourneyStopEntry, 'title'>): boolean {
return GALLERY_PLACEHOLDER_TITLES.has(entry.title ?? '');
}
/** A skeleton is a suggestion taken from the trip, not a place anyone wrote about. */
export function isJourneyMapEntry(entry: JourneyStopEntry): boolean {
return !!entry.location_lat && !!entry.location_lng && entry.type !== 'skeleton' && !isGalleryPlaceholder(entry);
}
/** The journal's reading order, the same one the server reads the entries in. */
export function compareJourneyEntries(a: JourneyStopEntry, b: JourneyStopEntry): number {
if (a.entry_date !== b.entry_date) return a.entry_date < b.entry_date ? -1 : 1;
const bySortOrder = (a.sort_order ?? 0) - (b.sort_order ?? 0);
if (bySortOrder !== 0) return bySortOrder;
return Number(a.id) - Number(b.id);
}
/**
* The located entries in reading order, each with its stop number. A draft keeps
* its pin for the people writing the journal but takes no number, so every stop
* after it reads the same as on the share link, which leaves drafts out.
*/
export function journeyMapStops<E extends JourneyStopEntry>(entries: readonly E[]): JourneyMapStop<E>[] {
let stop = 0;
return entries
.filter(isJourneyMapEntry)
.sort(compareJourneyEntries)
.map((entry) => ({ entry, stop: entry.is_draft ? null : ++stop }));
}
@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest'
import { clusterPhotos, photoMarkerHtml } from './journeyPhotoLayer'
describe('journey photo layer (#2453)', () => {
it('FE-JOURNEY-PHOTOLAYER-001: buckets by screen position, anchors on the first photo, badges a count', () => {
it('FE-JOURNEY-PHOTOLAYER-001: buckets by world position, anchors on the first photo, badges a count', () => {
const photos = [
{ id: '1', lat: 1, lng: 1, thumbUrl: '/a.jpg' },
{ id: '2', lat: 1.2, lng: 1.2, thumbUrl: '/b.jpg' },
@@ -1,4 +1,4 @@
import { clusterPoints } from './journeyMapMarks'
import { clusterPoints, type WorldPx } from './journeyMapMarks'
/** A photo that knows where it was taken (#1614). */
export interface MapPhoto {
@@ -9,24 +9,23 @@ export interface MapPhoto {
}
/**
* Grid clustering in screen space, shared by the Leaflet and the GL journey map.
* Grid clustering of the photos, shared by the Leaflet and the GL journey map.
*
* The Journey maps have never had clustering, and the library the planner uses
* hangs off react-leaflet while these maps drive their engines directly.
* Bucketing by rounded pixel position is a few lines, is deterministic, and is
* enough for the job: photos of one place collapse into one thumbnail with a
* count, and pulling the map apart separates them again. `project` is the
* engine's own lat/lng to container-pixel conversion.
* Bucketing by rounded world-pixel position is a few lines, is deterministic,
* and is enough for the job: photos of one place collapse into one thumbnail
* with a count, zooming in separates them again, and panning leaves them be.
*/
export const PHOTO_CLUSTER_PX = 64
export function clusterPhotos(
photos: MapPhoto[],
project: (lat: number, lng: number) => { x: number; y: number },
toWorldPx: WorldPx,
): { lat: number; lng: number; members: MapPhoto[] }[] {
// Anchored on the first member rather than the centroid: the thumbnail shown
// is that photo's, so the pin should point where that picture was taken.
return clusterPoints(photos, project, PHOTO_CLUSTER_PX)
return clusterPoints(photos, toWorldPx, PHOTO_CLUSTER_PX)
}
export function photoMarkerHtml(thumbUrl: string, count: number): string {
@@ -1,4 +1,4 @@
// FE-JRN-CAROUSEL-001 to FE-JRN-CAROUSEL-007: the card carousel over the journey map,
// FE-JRN-CAROUSEL-001 to FE-JRN-CAROUSEL-008: the card carousel over the journey map,
// behind both the phone journey screen and the narrow desktop and public timeline.
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -136,4 +136,13 @@ describe('useJourneyCarouselSync', () => {
expect(hook.result.current.activeIndex).toBe(1);
expect(map.highlightMarker).toHaveBeenCalledWith(null);
});
it('FE-JRN-CAROUSEL-008: a marker card opens its entry by id, wherever the carousel stands (#2885)', () => {
const { result, props } = setup();
act(() => result.current.openEntryById('3'));
expect(props.onOpenEntry).toHaveBeenCalledWith(ENTRIES[2]);
expect(result.current.activeIndex).toBe(0);
act(() => result.current.openEntryById('99'));
expect(props.onOpenEntry).toHaveBeenCalledTimes(1);
});
});
@@ -123,6 +123,16 @@ export function useJourneyCarouselSync<E extends CarouselEntry>({
[activeIndex, onOpenEntry, scrollCardIntoCenter, syncMapOnTap, syncMapToCard]
);
// The marker card on the map names one entry, so a tap on it opens that entry
// straight away, the same way a tap on the active carousel card does (#2885).
const openEntryById = useCallback(
(id: string) => {
const entry = entries.find((e) => String(e.id) === id);
if (entry) onOpenEntry(entry);
},
[entries, onOpenEntry]
);
// The day bar lands on the first entry of that day, which is where a reader who
// asked for "day nine" means.
const jumpToDay = useCallback(
@@ -146,6 +156,7 @@ export function useJourneyCarouselSync<E extends CarouselEntry>({
syncMapToCard,
handleMarkerClick,
handleCardTap,
openEntryById,
jumpToDay,
};
}
@@ -115,6 +115,8 @@ describe('useJourneyDayImport', () => {
it('FE-JRN-DAYIMPORT-004: the route goes along only when switched on, kept as previewed', async () => {
const { result, onKept, onClose } = setup();
await waitFor(() => expect(result.current.route.offer).toBe('keep'));
expect(result.current.mapTracks.length).toBeGreaterThan(0);
expect(result.current.mapTracks.every((track) => track.date === '2026-05-14')).toBe(true);
repo.save.mockResolvedValue({ day: buildRecordedDay(), outcome: 'created' });
act(() => result.current.route.toggle());
@@ -155,8 +155,9 @@ function useDayMap(
color: dayColor,
points: segment.points,
kind: 'day_recording',
date,
})),
[route, dayColor, t]
[route, dayColor, date, t]
);
return { entries, tracks };
}
@@ -202,6 +202,8 @@ describe('useJourneyMapLayers', () => {
expect(result.current.tracks.every((track) => track.kind === 'day_recording' && track.color === '#14b8a6')).toBe(
true
);
// The day travels as a date of its own, so the map can tell which stretches it covers (#2888).
expect(result.current.tracks.map((track) => track.date)).toEqual(['2026-05-14', '2026-05-14']);
expect(result.current.controls.map((c) => c.layer)).toEqual(['recorded', 'entries', 'photos']);
expect(result.current.controls[0]).toEqual({ layer: 'recorded', count: 1, state: 'ready' });
});
@@ -163,6 +163,7 @@ export function useJourneyMapLayers({
color,
points,
kind: 'day_recording',
date: day.date,
}));
}),
[sources.recordings, colorOfDay, t, locale]
@@ -187,7 +188,7 @@ export function useJourneyMapLayers({
[places, stays, visibility, entryIdsOnMap, stayColor]
);
const recordedDays = useMemo(() => new Set(recorded.map((track) => track.name)).size, [recorded]);
const recordedDays = useMemo(() => new Set(recorded.map((track) => track.date ?? track.name)).size, [recorded]);
const controls = useMemo(
() =>
buildControls({
@@ -47,6 +47,7 @@ describe('useJourneyRecordings', () => {
expect(result.current.byDate.get('2026-05-15')?.id).toBe(4);
expect(result.current.tracks).toHaveLength(3);
expect(result.current.tracks.every((track) => track.kind === 'day_recording')).toBe(true);
expect(result.current.tracks.map((track) => track.date)).toEqual(['2026-05-14', '2026-05-14', '2026-05-15']);
// One line per piece: a gap between two pieces is never drawn over.
expect(result.current.tracks.slice(0, 2).map((track) => track.points)).toEqual([
WALK_SEGMENT.points,
@@ -105,6 +105,7 @@ export function useJourneyRecordings(
color,
points: segment.points,
kind: 'day_recording',
date: day.date,
}));
}),
[days, colorOf, t, locale]
@@ -1,4 +1,4 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'
import { http, HttpResponse } from 'msw'
import { server } from '../../../tests/helpers/msw/server'
import { pluginsApi, type PluginRouteResult } from '../../api/client'
@@ -15,8 +15,8 @@ import {
calculateAlternatives,
avoidedClasses,
routeEngineFor,
osrmLegSegment,
} from './RouteCalculator'
import { legSegment } from './routeText'
// Every route now goes to the FOSSGIS per-profile hosts. The car-only project-osrm.org
// demo ignored the profile in the URL, so walking routes followed the road network.
@@ -387,6 +387,12 @@ function pluginRouteResult(over: Partial<PluginRouteResult> = {}): PluginRouteRe
}
}
// FOSSGIS: OSRM routes the days and Valhalla only what OSRM cannot. Where Valhalla routes
// every day is valhallaDayRoute.test.ts.
beforeEach(() => {
useSettingsStore.setState(st => ({ settings: { ...st.settings, routing_valhalla_provider: 'fossgis' } }))
})
afterEach(() => {
vi.restoreAllMocks()
useSettingsStore.setState({ settings: { ...useSettingsStore.getState().settings, distance_unit: 'metric' } })
@@ -913,7 +919,8 @@ describe('calculateAlternatives', () => {
it('FE-COMP-ROUTECALCULATOR-053: an instance with its own OSRM is never sent to the public Valhalla', async () => {
let valhallaCalls = 0
useSettingsStore.setState(st => ({ settings: { ...st.settings, routing_base_url: 'https://osrm.example.org' } }))
// No routing service chosen: the own OSRM alone decides.
useSettingsStore.setState(st => ({ settings: { ...st.settings, routing_base_url: 'https://osrm.example.org', routing_valhalla_provider: '' } }))
server.use(
http.get('https://osrm.example.org/route/v1/driving/:coords', ({ request }) => {
const exclude = new URL(request.url).searchParams.get('exclude')
@@ -1232,11 +1239,11 @@ describe('a trip that avoids something', () => {
})
})
describe('osrmLegSegment', () => {
describe('legSegment', () => {
const waypoints = [{ lat: 48, lng: 2 }, { lat: 50, lng: 4 }, { lat: 52, lng: 6 }]
it('spans waypoint i to i + 1 with the label at the midpoint', () => {
const seg = osrmLegSegment({ distance: 1500, duration: 600 }, 1, waypoints)
const seg = legSegment({ distance: 1500, duration: 600 }, 1, waypoints)
expect(seg.from).toEqual([50, 4])
expect(seg.to).toEqual([52, 6])
expect(seg.mid).toEqual([51, 5])
@@ -1245,7 +1252,7 @@ describe('osrmLegSegment', () => {
})
it('formats driving as measured and walking at 5 km/h', () => {
const seg = osrmLegSegment({ distance: 5000, duration: 600 }, 0, waypoints)
const seg = legSegment({ distance: 5000, duration: 600 }, 0, waypoints)
expect(seg.drivingText).toBe('10 min')
expect(seg.walkingText).toBe('1 h 0 min')
expect(seg.durationText).toBeUndefined()
@@ -1253,6 +1260,6 @@ describe('osrmLegSegment', () => {
it('writes short metric distances in metres', () => {
useSettingsStore.setState({ settings: { ...useSettingsStore.getState().settings, distance_unit: 'metric' } })
expect(osrmLegSegment({ distance: 420.4, duration: 60 }, 0, waypoints).distanceText).toBe('420 m')
expect(legSegment({ distance: 420.4, duration: 60 }, 0, waypoints).distanceText).toBe('420 m')
})
})
+135 -290
View File
@@ -1,11 +1,13 @@
import { useSettingsStore } from '../../store/settingsStore'
import { pluginsApi } from '../../api/client'
import type { DistanceUnit, RouteResult, RouteSegment, RouteWithLegs, SnappedWaypoint, Waypoint, RouteAnchors } from '../../types'
import type { RouteEngine, RouteResult, RouteSegment, RouteWithLegs, SnappedWaypoint, Waypoint, RouteAnchors } from '../../types'
import { haversineKm } from '../../utils/geo'
import { formatDistance } from '../../utils/units'
import { countRoute } from './routeUsageCounter'
import { cacheRoute, rememberRoute, routeInMemory, storedRoute } from './routeStore'
import { valhallaRouteAvoiding, valhallaRun, valhallaAvailable, valhallaAlternates, valhallaSpacing, legAvoids, type AvoidClass, type ValhallaLeg } from './valhallaRoute'
import { formatDuration, formatRouteDistance, getDistanceUnit, legSegment } from './routeText'
import type { RouteAlternative } from './routeTypes'
import { valhallaAvailable, valhallaPlansDays, valhallaRoutesDays, type AvoidClass } from './valhallaRoute'
import { EXCLUDABLE_CLASSES, valhallaDayAlternatives, valhallaDayRoute, valhallaExcluding } from './valhallaDayRoute'
import { furthestFrom, sameRoad, type RouteUsageSurface } from '@trek/shared'
// FOSSGIS hosts OSRM with real per-profile routing (car/foot/bike) — the
@@ -213,12 +215,15 @@ export function parsePluginProfile(profile: string): { pluginId: string; profile
return { pluginId: rest.slice(0, slash), profileId: rest.slice(slash + 1) }
}
/**
* Which engine priced a route: OSRM, the second engine that weighs road classes away, or
* a route provider plugin. Their figures are three different speed models, so a figure
* from one read against a figure from another measures the models, not the roads.
*/
export type RouteEngine = 'osrm' | 'valhalla' | 'plugin'
/** One of the three profiles both engines know, or null for a plugin's own. */
function builtInProfile(profile: RouteProfileKey): 'driving' | 'walking' | 'cycling' | null {
switch (profile) {
case 'driving': return 'driving'
case 'walking': return 'walking'
case 'cycling': return 'cycling'
default: return null
}
}
/**
* The classes a request really weighs away, in a stable order, and none when it cannot.
@@ -234,10 +239,75 @@ export function avoidedClasses(profile: RouteProfileKey, avoid: readonly AvoidCl
: []
}
/** The engine `calculateRouteWithLegs` hands a request with this profile and avoidance to. */
/**
* The engine a request with this profile and avoidance is planned with: Valhalla for every
* day where it routes the days, and for a day that avoids something wherever it can; OSRM
* for the rest. Planned, not promised: a day Valhalla cannot answer, or one asked while
* the relay rests, is drawn by OSRM, and the answer says so in its `engine`.
*/
export function routeEngineFor(profile: RouteProfileKey, avoid: readonly AvoidClass[]): RouteEngine {
if (parsePluginProfile(profile)) return 'plugin'
return avoidedClasses(profile, avoid).length ? 'valhalla' : 'osrm'
if (avoidedClasses(profile, avoid).length) return 'valhalla'
return builtInProfile(profile) && valhallaPlansDays() ? 'valhalla' : 'osrm'
}
/** The profile Valhalla routes a request under, or null where `routeEngineFor` gives it to another engine. */
function valhallaProfile(profile: RouteProfileKey, avoid: readonly AvoidClass[]): 'driving' | 'walking' | 'cycling' | null {
return routeEngineFor(profile, avoid) === 'valhalla' ? builtInProfile(profile) : null
}
/**
* Where a Valhalla answer is kept: beside the OSRM key, which keeps the shape it always
* had. A day that weighs classes away keeps the key it has had since only Valhalla could
* answer one, so the days a device already holds stay found; a day that avoids nothing
* names the engine instead.
*/
function valhallaKey(plainKey: string, avoiding: readonly AvoidClass[]): string {
return avoiding.length ? `${plainKey}:avoid=${avoiding.join(',')}` : `${plainKey}:valhalla`
}
/**
* OSRM's answer for a day Valhalla could not route. A day that avoided nothing is then
* routed as it always was, without a word. One that avoided something says that nothing
* was avoided, with the reason, so the rail flags the day instead of implying the setting
* held on a road nobody weighed.
*/
function withFallbackNoted(plain: RouteWithLegs, avoiding: AvoidClass[]): RouteWithLegs {
const drawn = withEngine(plain, 'osrm')
return avoiding.length ? { ...drawn, avoidance: { asked: avoiding, achieved: [], fellBack: true } } : drawn
}
/**
* A kept route with the engine that drew it. A key holds one engine's answers only, so an
* entry kept before answers named their engine is that key's.
*/
function withEngine(route: RouteWithLegs, engine: RouteEngine): RouteWithLegs {
return route.engine ? route : { ...route, engine }
}
/**
* A day planned with Valhalla: its answer, kept under the Valhalla key, or where it gives
* none OSRM's for the whole day, kept under the plain key. One engine per day, never one
* leg from each. While the relay rests, a day that avoids nothing is not put to it at all.
*/
async function valhallaOrOsrmDay(
waypoints: Waypoint[],
{ profile, avoiding, keys, signal }: {
profile: 'driving' | 'walking' | 'cycling'
avoiding: AvoidClass[]
keys: { valhalla: string; plain: string; coords: string }
signal?: AbortSignal
},
): Promise<RouteWithLegs> {
const asking = avoiding.length > 0 || valhallaRoutesDays()
const routed = asking ? await valhallaDayRoute(waypoints, profile, avoiding, signal) : null
if (routed) {
cacheRoute(keys.valhalla, routed)
return routed
}
const plain = (await storedRoute(keys.plain)) ?? await osrmWithLegs(waypoints, keys.coords, profile, signal)
cacheRoute(keys.plain, plain)
return withFallbackNoted(plain, avoiding)
}
/** Fetches a full route via OSRM and returns coordinates, distance, and duration estimates for driving/walking. */
@@ -467,31 +537,11 @@ export async function calculateSegments(
if (data.code !== 'Ok' || !data.routes?.[0]) throw new Error('No route found')
const legs = data.routes[0].legs
return legs.map((leg: OsrmLeg, i: number): RouteSegment => osrmLegSegment(leg, i, waypoints))
return legs.map((leg: OsrmLeg, i: number): RouteSegment => legSegment(leg, i, waypoints))
}
interface OsrmLeg { distance: number; duration: number }
/**
* The connector data for OSRM leg i, which runs from waypoint i to waypoint i + 1:
* both ends, the midpoint the label sits on, and the walking time at 5 km/h next to
* the driving time OSRM measured.
*/
export function osrmLegSegment(leg: OsrmLeg, i: number, waypoints: Waypoint[]): RouteSegment {
const from: [number, number] = [waypoints[i].lat, waypoints[i].lng]
const to: [number, number] = [waypoints[i + 1].lat, waypoints[i + 1].lng]
const mid: [number, number] = [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2]
const walkingDuration = leg.distance / (5000 / 3600)
return {
mid, from, to,
distance: leg.distance,
duration: leg.duration,
walkingText: formatDuration(walkingDuration),
drivingText: formatDuration(leg.duration),
distanceText: formatRouteDistance(leg.distance),
}
}
/**
* One OSRM call per waypoint-run that returns BOTH the real road geometry (for the
* map) and per-leg distance/duration (for the sidebar connectors). Results are cached
@@ -513,6 +563,7 @@ export async function calculateRouteWithLegs(
return { coordinates: [], distance: 0, duration: 0, legs: [] }
}
const valhallaDay = valhallaProfile(profile, avoid)
const avoiding = avoidedClasses(profile, avoid)
const coords = waypoints.map((p) => `${p.lng},${p.lat}`).join(';')
@@ -520,41 +571,37 @@ export async function calculateRouteWithLegs(
// part of the key — otherwise switching km↔mi would return stale text (#1300).
// A plugin route is trip-/day-specific (it may return different charging stops for
// the same coordinates on a different day), so its key includes tripId/dayId;
// the built-in OSRM profiles are context-free and leave those out.
// the built-in profiles are context-free and leave those out.
//
// The engine belongs in the key because the two price roads differently: a day OSRM
// drew handed out as Valhalla's after the admin switched engines would keep the old
// times on every device that held it, and the other way round. An OSRM answer keeps
// the key it always had, so the routes already kept on a device stay good.
//
// The avoidance belongs in the key for two reasons pointing opposite ways. Without it
// turning the switch on returns the tolled route out of cache in under a millisecond,
// so nothing on screen changes and it reads as a broken toggle. And the leak the other
// way is worse: this Map is shared with the ordinary day planner, the studio and the
// booking geometry, none of which ask for avoidance, so an avoid-routed answer stored
// under the plain key would hand them a road nobody drives and a second engine's
// times. So the avoiding key only ever holds a Valhalla answer: when Valhalla cannot
// answer and OSRM drives the request after all, that answer is filed under the plain
// key, where it is exactly what an ordinary caller would have got. Filed under the
// avoiding key it stood in for the avoided road until the next reload, however soon
// Valhalla came back.
// under the plain key would hand them a road nobody drives. So the Valhalla keys only
// ever hold a Valhalla answer: when Valhalla cannot answer and OSRM drives the request
// after all, that answer is filed under the OSRM key, where it is exactly what an
// ordinary caller would have got. Filed under the Valhalla key it stood in for the
// weighed road until the next reload, however soon Valhalla came back.
const pluginScope = profile.startsWith('plugin:') ? `:${tripId ?? ''}:${dayId ?? ''}` : ''
const avoidScope = avoiding.length ? `:avoid=${avoiding.join(',')}` : ''
const plainKey = `${profile}:${getDistanceUnit()}:${coords}${pluginScope}`
const cacheKey = `${plainKey}${avoidScope}`
// Which engine the day is planned with does not follow the relay's rest, so a day kept
// from Valhalla is still found while the relay rests, offline above all.
const cacheKey = valhallaDay ? valhallaKey(plainKey, avoiding) : plainKey
// A plugin route stays in memory: its answer depends on the trip and the day,
// and may carry live data such as charging stops. The rest is kept on the device
// too, so a trip that shows its whole route opens drawn (#2794).
const cached = pluginScope ? routeInMemory(cacheKey) : await storedRoute(cacheKey)
if (cached) return cached
if (cached) return withEngine(cached, routeEngineFor(profile, avoid))
if (avoiding.length) {
const routed = await routeAvoidingWithLegs(waypoints, avoiding, signal)
if (routed) {
cacheRoute(cacheKey, routed)
return routed
}
// Null is a Valhalla that could not answer at all. OSRM keeps the day drawn rather
// than blank, and the answer says that nothing was avoided, with the reason, so the
// rail flags the day instead of implying the setting held on a road nobody weighed.
const plain = (await storedRoute(plainKey)) ?? await osrmWithLegs(waypoints, coords, profile, signal)
cacheRoute(plainKey, plain)
return { ...plain, avoidance: { asked: avoiding, achieved: [], fellBack: true } }
if (valhallaDay) {
const keys = { valhalla: cacheKey, plain: plainKey, coords }
return valhallaOrOsrmDay(waypoints, { profile: valhallaDay, avoiding, keys, signal })
}
// Plugin profile (`plugin:<id>/<profile>`): the server invokes that routeProvider
@@ -569,27 +616,18 @@ export async function calculateRouteWithLegs(
waypoints: waypoints.map((p) => ({ lat: p.lat, lng: p.lng })),
}, { signal })
if (!route) throw new Error('No route found')
const legs: RouteSegment[] = route.legs.map((leg, i): RouteSegment => {
const from: [number, number] = [waypoints[i].lat, waypoints[i].lng]
const to: [number, number] = [waypoints[i + 1].lat, waypoints[i + 1].lng]
const mid: [number, number] = [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2]
return {
mid, from, to,
distance: leg.distance,
duration: leg.duration,
walkingText: formatDuration(leg.distance / (5000 / 3600)),
drivingText: formatDuration(leg.duration),
distanceText: formatRouteDistance(leg.distance),
durationText: formatDuration(leg.duration),
...(leg.note ? { noteText: leg.note } : {}),
}
})
const legs = route.legs.map((leg, i): RouteSegment => ({
...legSegment(leg, i, waypoints),
durationText: formatDuration(leg.duration),
...(leg.note ? { noteText: leg.note } : {}),
}))
const result: RouteWithLegs = {
coordinates: route.coordinates,
distance: route.distance,
duration: route.duration,
legs,
...(route.viaPoints.length ? { vias: route.viaPoints } : {}),
engine: 'plugin',
}
rememberRoute(cacheKey, result)
return result
@@ -625,70 +663,13 @@ async function osrmWithLegs(
// The day plan's connectors also show the leg's own duration line.
const legs: RouteSegment[] = (route.legs || []).map(
(leg: OsrmLeg, i: number): RouteSegment => ({
...osrmLegSegment(leg, i, waypoints),
...legSegment(leg, i, waypoints),
durationText: formatDuration(leg.duration),
})
)
const snapped = readSnapped(data, waypoints)
return { coordinates, distance: route.distance, duration: route.duration, legs, ...(snapped ? { snapped } : {}) }
}
/**
* A whole chain from the second engine, weighted away from some road classes.
*
* Shaped exactly like the OSRM answer above so the callers never branch on which engine
* spoke — same leg list, same formatted text, same snap positions. What it adds is
* `avoidance`: what was asked for against what the road actually turned out to be, which
* is the only honest way to label a weighting that can fail.
*
* Null rather than a throw when it cannot answer, so the caller falls through to OSRM
* and the day stays drawn.
*/
async function routeAvoidingWithLegs(
waypoints: Waypoint[],
avoid: AvoidClass[],
signal?: AbortSignal,
): Promise<RouteWithLegs | null> {
const sample = {
profile: 'driving' as const,
surface: 'legs' as const,
selfHosted: !!useSettingsStore.getState().settings.routing_base_url?.trim(),
waypoints: waypoints.length,
km: waypoints.slice(1).reduce((sum, point, i) => sum + haversineKm(waypoints[i], point), 0),
}
const run = await valhallaRun(waypoints, 'driving', avoid, signal)
// Counted by hand because the adapter speaks to a different engine with a different
// verb, and the counter exists to answer "how much routing does this instance do" —
// an engine it cannot see is exactly the traffic that would go missing from it.
if (!signal?.aborted) countRoute({ ...sample, failed: !run })
if (!run) return null
const legs: RouteSegment[] = run.legs.map((leg, i): RouteSegment => {
const from: [number, number] = [waypoints[i].lat, waypoints[i].lng]
const to: [number, number] = [waypoints[i + 1].lat, waypoints[i + 1].lng]
return {
mid: [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2],
from,
to,
distance: leg.distance,
duration: leg.duration,
walkingText: formatDuration(leg.distance / (5000 / 3600)),
drivingText: formatDuration(leg.duration),
distanceText: formatRouteDistance(leg.distance),
durationText: formatDuration(leg.duration),
}
})
return {
coordinates: run.total.coordinates,
distance: run.total.distance,
duration: run.total.duration,
legs,
snapped: run.snapped,
avoidance: { asked: avoid, achieved: avoid.filter(cls => legAvoids(run.total, cls)) },
hasFerry: run.total.hasFerry,
}
return { coordinates, distance: route.distance, duration: route.duration, legs, ...(snapped ? { snapped } : {}), engine: 'osrm' }
}
/**
@@ -722,75 +703,6 @@ function readSnapped(data: unknown, waypoints: Waypoint[]): SnappedWaypoint[] |
return out
}
function getDistanceUnit(): DistanceUnit {
return useSettingsStore.getState().settings.distance_unit === 'imperial' ? 'imperial' : 'metric'
}
function formatRouteDistance(meters: number): string {
const unit = getDistanceUnit()
if (unit === 'metric' && meters < 1000) {
return `${Math.round(meters)} m`
}
return formatDistance(meters / 1000, unit)
}
function formatDuration(seconds: number): string {
const h = Math.floor(seconds / 3600)
const m = Math.floor((seconds % 3600) / 60)
if (h > 0) {
return `${h} h ${m} min`
}
return `${m} min`
}
/** One way of driving a leg, as a router offers it. */
export interface RouteAlternative {
coordinates: [number, number][]
distance: number
duration: number
/** Where this route differs most from the first one — the point that would pin it. */
divergence: { lat: number; lng: number } | null
/** Set when this way exists because a road class was left out of it. */
avoids?: AvoidClass
/**
* Which engine priced this route. Absent means OSRM, which is what answers every route
* of a trip that avoids nothing, except the avoidance offer on a default install.
*
* It exists because the engines do not agree on speed: measured over twelve European
* legs the per-leg drive times run from 14.7 % under OSRM's to 13.2 % over, and the
* sign depends on the region: Valhalla is faster on Spanish autovía and slower through
* a city. So a figure from one of them subtracted from a figure from the other is not a
* difference in driving time, it is the gap between two speed models, and the reader
* has no way of telling the two apart.
*/
engine?: RouteEngine
/** Whether the way crosses by ferry, where the engine that drew it says so. */
hasFerry?: boolean
}
/** What two routes are compared by: their line, and their figures where there is none. */
export type RoadLine = Pick<RouteAlternative, 'coordinates' | 'distance' | 'duration'>
/**
* Road classes worth asking the router to leave out, in the order they are tried.
*
* OSRM's own alternative search is conservative: it only offers a second road when the
* detour is short enough and shares little enough with the first, so on a long motorway
* run it usually answers with exactly one route — while a perfectly good, slower way over
* the B-roads exists and is what somebody opening "other ways" is looking for. Excluding
* a class asks a different question and reliably produces that road.
*
* Only for driving: the foot and bike profiles have no excludable classes, and asking
* anyway earns an `InvalidOptions` for nothing.
*
* Ferry is on the list for Valhalla's sake and skipped on the OSRM path below. OSRM
* does carry a ferry class, but on a leg where a ferry is the only crossing it answers
* NoRoute rather than the long way round, which is not an alternative anybody can use.
* Valhalla weights it instead and drives around, which is the whole point.
*/
const EXCLUDABLE_CLASSES = ['motorway', 'toll', 'ferry'] as const
/**
* Hosts that have already answered "I do not do exclude", by base URL.
*
@@ -838,49 +750,6 @@ async function routeExcluding(
return osrmExcluding(from, to, profile, exclude, signal)
}
/**
* The same leg from Valhalla, weighted away from one class, or null.
*
* The check that makes this honest is `legAvoids`: `use_tolls: 0` is a preference, so
* between two points with no untolled connection the answer is still a tolled road.
* Offering that as "No tolls" would put a lie on the map, so it is dropped and the
* OSRM attempt gets its turn.
*/
async function valhallaExcluding(
from: Waypoint,
to: Waypoint,
profile: 'driving' | 'walking' | 'cycling',
exclude: AvoidClass,
signal?: AbortSignal,
): Promise<RouteAlternative | null> {
if (!valhallaAvailable()) return null
const sample = {
profile,
surface: 'alternatives' as const,
selfHosted: !!useSettingsStore.getState().settings.routing_base_url?.trim(),
waypoints: 2,
km: haversineKm(from, to),
}
const leg = await valhallaRouteAvoiding(from, to, profile, exclude, signal)
// Counted here rather than in the adapter, so the adapter stays a format translator
// and every routing request an instance makes still lands in the one counter.
if (!signal?.aborted) countRoute({ ...sample, failed: !leg })
if (!leg || !legAvoids(leg, exclude)) return null
return valhallaOffer(leg)
}
/** A Valhalla leg as an offer, carrying the engine that priced it and what it crosses. */
function valhallaOffer(leg: ValhallaLeg): RouteAlternative {
return {
coordinates: leg.coordinates,
distance: leg.distance,
duration: leg.duration,
divergence: null,
engine: 'valhalla',
hasFerry: leg.hasFerry,
}
}
/** The same leg from OSRM with the class excluded outright, or null. */
async function osrmExcluding(
from: Waypoint,
@@ -928,20 +797,25 @@ async function osrmExcluding(
* onto this road on every future request, without storing a polyline that would go stale
* with the next OSM update.
*
* `avoid` is the classes the trip weighs away. A driving leg of such a trip is routed by
* Valhalla, so its offers come from Valhalla too, weighed the same way, and never from
* OSRM: a list holding both engines is what offered a road the rail was not on as the
* quicker one, and clicking it changed nothing.
* `avoid` is the classes the trip weighs away. A leg Valhalla routes, because it routes
* the days or because the trip avoids something, gets its offers from Valhalla too,
* weighed the same way, and never from OSRM: a list holding both engines is what offered
* a road the rail was not on as the quicker one, and clicking it changed nothing.
*/
export async function calculateAlternatives(
from: Waypoint,
to: Waypoint,
profile: 'driving' | 'walking' | 'cycling' = 'driving',
{ signal, limit = 3, avoid = [] }: { signal?: AbortSignal; limit?: number; avoid?: readonly AvoidClass[] } = {},
{ signal, limit = 3, avoid = [], engine = routeEngineFor(profile, avoid) }: {
signal?: AbortSignal
limit?: number
avoid?: readonly AvoidClass[]
/** The engine that drew the leg, where it is known; the planned one otherwise. */
engine?: RouteEngine
} = {},
): Promise<RouteAlternative[]> {
const avoiding = avoidedClasses(profile, avoid)
const routes = avoiding.length
? await alternativesAvoiding(from, to, avoiding, limit, signal)
const routes = engine === 'valhalla'
? await alternativesFromValhalla(from, to, profile, avoidedClasses(profile, avoid), { limit, signal })
: await alternativesFromOsrm(from, to, profile, limit, signal)
if (!routes.length) return routes
@@ -953,54 +827,25 @@ export async function calculateAlternatives(
}
/**
* The offers for a leg of a trip that weighs classes away, every one of them Valhalla's.
* The offers for a leg of a day Valhalla routes, every one of them Valhalla's.
*
* Throws when Valhalla has nothing to say, so the picker reports a router that is not
* answering. Quietly offering OSRM's roads instead is the very mix this path exists to end.
*
* One way back gets the question the OSRM path asks too: the same drive with one more
* class left out, only of those the trip does not already avoid, and only where the road
* that comes back really is without it. Paced like the pieces of a split day, because the
* public instance allows one request a second.
* A day that weighs classes away has no other engine to ask: this throws when Valhalla has
* nothing to say, so the picker reports a router that is not answering. Quietly offering
* OSRM's roads instead is the very mix this path exists to end. A day that avoids nothing
* went to OSRM whole when Valhalla did not answer it, so its offers do the same.
*/
async function alternativesAvoiding(
async function alternativesFromValhalla(
from: Waypoint,
to: Waypoint,
profile: 'driving' | 'walking' | 'cycling',
avoiding: AvoidClass[],
limit: number,
signal?: AbortSignal,
{ limit, signal }: { limit: number; signal?: AbortSignal },
): Promise<RouteAlternative[]> {
const sample = {
profile: 'driving' as const,
surface: 'alternatives' as const,
selfHosted: !!useSettingsStore.getState().settings.routing_base_url?.trim(),
waypoints: 2,
km: haversineKm(from, to),
}
const answered = await valhallaAlternates(from, to, 'driving', avoiding, Math.max(0, limit - 1), signal)
if (!signal?.aborted) countRoute({ ...sample, failed: !answered })
if (!answered?.length) throw new Error('No route found')
const routes: RouteAlternative[] = []
for (const leg of answered) {
const offer = valhallaOffer(leg)
if (!routes.some(r => sameRoad(r, offer))) routes.push(offer)
}
if (routes.length >= 2) return routes
for (const cls of EXCLUDABLE_CLASSES) {
if (avoiding.includes(cls)) continue
await valhallaSpacing(signal)
if (signal?.aborted) break
const run = await valhallaRun([from, to], 'driving', [...avoiding, cls], signal)
if (!signal?.aborted) countRoute({ ...sample, failed: !run })
if (!run || !legAvoids(run.total, cls)) continue
const detour = valhallaOffer(run.total)
if (routes.some(r => sameRoad(r, detour))) continue
routes.push({ ...detour, avoids: cls })
break
}
return routes
const asking = avoiding.length > 0 || valhallaRoutesDays()
const offered = asking ? await valhallaDayAlternatives(from, to, profile, avoiding, { limit, signal }) : null
if (offered) return offered
if (avoiding.length) throw new Error('No route found')
return alternativesFromOsrm(from, to, profile, limit, signal)
}
/** The offers for a leg of a trip that avoids nothing: OSRM's, and one avoidance offer. */
@@ -100,6 +100,9 @@ describe('TripRouteOverviewPanel', () => {
expect(screen.getByTestId('trip-overview-unrouted')).toHaveTextContent('map.overview.unrouted')
expect(screen.getAllByRole('img', { name: 'map.overview.dayUnrouted' })).toHaveLength(1)
// The short figures read as floors, the trip's and the day's, not as measurements (#2876).
expect(screen.getAllByText('map.overview.distanceAtLeast')).toHaveLength(2)
expect(screen.getByText('140.5 km')).toBeInTheDocument()
})
it('FE-MAP-TROU-010: does not call a leg unrouted while the round is still running', () => {
@@ -2,7 +2,7 @@ import { AlertTriangle, Route } from 'lucide-react'
import { useTranslation } from '../../i18n'
import { MapTogglePill } from './MapTogglePill'
import { routeModeIcon } from '../Planner/routeModes'
import { formatDistance } from '../../utils/units'
import { routeDistanceLabel } from './tripRouteLabels'
import type { TripRouteOverview as Overview } from './useTripRouteOverview'
import type { DistanceUnit } from '../../types'
@@ -65,7 +65,7 @@ export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelect
{/* Same tier as the label beside it: the two read as one line rather than as a
heading with a number stuck under it. */}
<span className="text-content" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 600 }}>
{formatDistance(overview.totalDistance / 1000, unit)}
{routeDistanceLabel(overview.totalDistance, unrouted, unit, t)}
{/* Still routing: the number is a partial sum, and saying so beats a total
that silently grows while you read it. */}
{overview.loading && <span className="text-content-muted" style={{ fontWeight: 400 }}>{' '}…</span>}
@@ -112,7 +112,7 @@ export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelect
/>
)}
<span className="text-content-muted" style={{ flexShrink: 0, fontVariantNumeric: 'tabular-nums' }}>
{formatDistance(day.distance / 1000, unit)}
{routeDistanceLabel(day.distance, dayUnrouted, unit, t)}
</span>
</>
)
@@ -97,6 +97,8 @@ describe('attachLocationMarker', () => {
expect(root.children).toHaveLength(3)
// The cone starts hidden — there is no heading until the first fix.
expect((root.children[1] as HTMLElement).style.display).toBe('none')
// The GL marker class owns `position`; an inline one would drop it into the flow.
expect(root.style.position).toBe('')
})
it('FE-COMP-LOCMARKERGL-003: adds the accuracy source and fill layer when the map is already loaded', () => {
@@ -13,7 +13,9 @@ type MarkerConstructor = new (options?: { element?: HTMLElement; anchor?: string
// and mapbox doesn't get confused about which element to position.
function buildLocationEl(): { root: HTMLDivElement; cone: HTMLDivElement } {
const root = document.createElement('div')
root.style.cssText = 'width:28px;height:28px;position:relative;pointer-events:none;'
// No inline `position`: the GL marker class keeps the root absolute, which the
// children's insets resolve against (see the note on markers in MapViewGL).
root.style.cssText = 'width:28px;height:28px;pointer-events:none;'
// Accuracy pulse behind the dot
const pulse = document.createElement('div')
pulse.style.cssText = `
+52
View File
@@ -0,0 +1,52 @@
import { useSettingsStore } from '../../store/settingsStore';
import type { DistanceUnit, RouteSegment, Waypoint } from '../../types';
import { formatDistance } from '../../utils/units';
/** The unit a route's texts are written in, which is why it is part of the route cache key. */
export function getDistanceUnit(): DistanceUnit {
return useSettingsStore.getState().settings.distance_unit === 'imperial' ? 'imperial' : 'metric';
}
/** A routed distance as the connectors show it: metres below a kilometre, else the user's unit. */
export function formatRouteDistance(meters: number): string {
const unit = getDistanceUnit();
if (unit === 'metric' && meters < 1000) {
return `${Math.round(meters)} m`;
}
return formatDistance(meters / 1000, unit);
}
/** A routed time in hours and minutes, the minutes rounded down. */
export function formatDuration(seconds: number): string {
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
if (h > 0) {
return `${h} h ${m} min`;
}
return `${m} min`;
}
/**
* The connector data for leg i of a routed chain, which runs from waypoint i to waypoint
* i + 1: both ends, the midpoint the label sits on, and the walking time at 5 km/h next to
* the time the engine measured. The same for every engine, so a day reads alike whichever
* of them drew it.
*/
export function legSegment(
leg: { distance: number; duration: number },
i: number,
waypoints: Waypoint[]
): RouteSegment {
const from: [number, number] = [waypoints[i].lat, waypoints[i].lng];
const to: [number, number] = [waypoints[i + 1].lat, waypoints[i + 1].lng];
return {
mid: [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2],
from,
to,
distance: leg.distance,
duration: leg.duration,
walkingText: formatDuration(leg.distance / (5000 / 3600)),
drivingText: formatDuration(leg.duration),
distanceText: formatRouteDistance(leg.distance),
};
}
+30
View File
@@ -0,0 +1,30 @@
import type { RouteAvoidClass, RouteEngine } from '../../types';
/** One way of driving a leg, as a router offers it. */
export interface RouteAlternative {
coordinates: [number, number][];
distance: number;
duration: number;
/** Where this route differs most from the first one — the point that would pin it. */
divergence: { lat: number; lng: number } | null;
/** Set when this way exists because a road class was left out of it. */
avoids?: RouteAvoidClass;
/**
* Which engine priced this route. Absent means OSRM, which answers every route of a
* trip that avoids nothing where Valhalla does not route the days, except the
* avoidance offer.
*
* It exists because the engines do not agree on speed: measured over twelve European
* legs the per-leg drive times run from 14.7 % under OSRM's to 13.2 % over, and the
* sign depends on the region: Valhalla is faster on Spanish autovía and slower through
* a city. So a figure from one of them subtracted from a figure from the other is not a
* difference in driving time, it is the gap between two speed models, and the reader
* has no way of telling the two apart.
*/
engine?: RouteEngine;
/** Whether the way crosses by ferry, where the engine that drew it says so. */
hasFerry?: boolean;
}
/** What two routes are compared by: their line, and their figures where there is none. */
export type RoadLine = Pick<RouteAlternative, 'coordinates' | 'distance' | 'duration'>;
@@ -78,31 +78,61 @@ describe('tripRouteGeometry', () => {
expect(calculateRouteWithLegs).not.toHaveBeenCalled()
})
it('FE-MAP-TRG-005: the deadline gives back what answered and leaves the rest as straight lines', async () => {
neverAnswers()
// The PDF used to route under an 8 s deadline: with a second between two requests that
// is about seven legs, so a month-long trip printed most of its days as straight lines
// and a total that looked final, and every export routed a few more days (#2876).
it('FE-MAP-TRG-005: a long trip is routed to its last leg, and says how far it has got', async () => {
const days = Array.from({ length: 12 }, (_, i) => buildDay({ id: i + 1, day_number: i + 1 }))
const assignments: AssignmentsMap = Object.fromEntries(days.map(day => [
String(day.id),
[at(48 + day.id / 10, 2.35, 0, day.id), at(48 + day.id / 10, 2.45, 1, day.id)],
]))
vi.useFakeTimers()
try {
const pending = routeTrip(input, { profile: 'driving', tripId: 7, timeoutMs: 8000 })
await vi.advanceTimersByTimeAsync(8100)
vi.mocked(calculateRouteWithLegs).mockImplementation(() => new Promise(resolve => {
setTimeout(() => resolve({ coordinates: [[48.86, 2.35], [48.90, 2.42]], distance: 10000, duration: 600, legs: [leg(10000)] }), 100)
}))
const onProgress = vi.fn<(done: number, total: number) => void>()
const pending = routeTrip({ ...input, days, assignments }, { profile: 'driving', tripId: 7, onProgress })
await vi.advanceTimersByTimeAsync(12 * 1200)
const summary = await pending
// The shape of the trip survives...
expect(summary.lines).toHaveLength(2)
expect(summary.lines[0]).toEqual([[48.86, 2.35], [48.90, 2.42]])
// ...and nothing that never answered is counted.
expect(summary.totalDistance).toBe(0)
expect(calculateRouteWithLegs).toHaveBeenCalledTimes(12)
expect(summary.unroutedLegs).toBe(0)
expect(summary.totalDistance).toBe(120000)
expect(onProgress.mock.calls[0]).toEqual([0, 12])
expect(onProgress.mock.calls.map(([done]) => done)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
expect(onProgress.mock.calls.every(([, total]) => total === 12)).toBe(true)
} finally {
vi.useRealTimers()
}
})
it('FE-MAP-TRG-006: a caller\'s own abort cuts the routing short too', async () => {
it("FE-MAP-TRG-006: a caller's own abort cuts the routing short, and what never answered is counted", async () => {
neverAnswers()
const controller = new AbortController()
const pending = routeTrip(input, { profile: 'driving', tripId: 7, timeoutMs: 60_000, signal: controller.signal })
const pending = routeTrip(input, { profile: 'driving', tripId: 7, signal: controller.signal })
controller.abort()
await expect(pending).resolves.toMatchObject({ totalDistance: 0 })
await expect(pending).resolves.toMatchObject({ totalDistance: 0, unroutedLegs: 2 })
})
it('FE-MAP-TRG-014: a host that never answers costs one leg its road, not the whole round', async () => {
neverAnswers()
vi.useFakeTimers()
try {
const pending = routeTrip(input, { profile: 'driving', tripId: 7 })
await vi.advanceTimersByTimeAsync(30_000)
expect(calculateRouteWithLegs).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(1100 + 30_000)
const summary = await pending
expect(calculateRouteWithLegs).toHaveBeenCalledTimes(2)
expect(summary.lines).toHaveLength(2)
expect(summary.unroutedLegs).toBe(2)
} finally {
vi.useRealTimers()
}
})
// The public OSRM hosts allow about one request a second. Every leg of every day at

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