Compare commits

...

128 Commits

Author SHA1 Message Date
dependabot[bot] daf3c765b0 chore(deps): bump bcryptjs and @types/bcryptjs
Bumps [bcryptjs](https://github.com/dcodeIO/bcrypt.js) and [@types/bcryptjs](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/bcryptjs). These dependencies needed to be updated together.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Pin the last release that handles the built-ins first, keep Dependabot off
3.33 and later, and add a test that reads the shipped serializer and fails
on a version with the registry read first.
2026-11-24 00:04:19 +01:00
github-actions[bot] 8809654a43 chore: bump version to 5.2.0 [skip ci] 2026-11-23 21:40:14 +00:00
553 changed files with 15366 additions and 3805 deletions
+33
View File
@@ -26,15 +26,48 @@ updates:
prefix: chore(deps)
prefix-development: chore(deps-dev)
groups:
# Packages that release in lockstep move together, so a PR never pins
# half of them on one version and half on the next.
# better-sqlite3 and kysely are pinned exactly by @mikro-orm/sqlite and
# share its connection, so they move with MikroORM.
mikro-orm:
patterns: ['@mikro-orm/*', better-sqlite3, kysely]
update-types: [minor, patch]
nestjs:
patterns: ['@nestjs/*']
update-types: [minor, patch]
npm-minor-and-patch:
update-types: [minor, patch]
ignore:
# nestjs-zod, which validates every request body, does not support
# NestJS 12 yet. The framework moves by hand once it does.
- dependency-name: '@nestjs/*'
update-types: [version-update:semver-major]
# TypeScript 7 is the native compiler and has no JavaScript API yet:
# typescript-eslint, the coverage instrumenter and the Postgres probe all
# call into it (readConfigFile, ScriptTarget). It moves by hand once the
# tooling supports it.
- dependency-name: typescript
update-types: [version-update:semver-major]
# mapbox-gl 3.33 and later read the worker registry key before handling
# Set and Error, and maplibre-gl, bundled beside it, stamps that key on
# both built-ins: every vector tile then fails with "reading 'omit'".
# glWorkerRegistry.test.ts fails on a version with that order; it moves
# by hand once mapbox-gl checks the built-ins first again.
- dependency-name: mapbox-gl
versions: ['>=3.33.0']
# The packages below move by hand, each for its reason. A security
# advisory for one of them still shows up in the Security tab, where it
# is handled together with that reason.
#
# Pinned exactly by @nestjs/schedule; a newer cron of our own would be a
# second copy whose CronJob the scheduler does not accept.
- dependency-name: cron
update-types: [version-update:semver-major, version-update:semver-minor, version-update:semver-patch]
# Root pins that must name the rollup version the lockfile installs (the
# Alpine image needs the musl binaries).
- dependency-name: '@rollup/rollup-linux-*-musl'
update-types: [version-update:semver-major, version-update:semver-minor, version-update:semver-patch]
# plugin-sdk is standalone with a lockfile of its own and ships to npm.
- package-ecosystem: npm
+55 -1
View File
@@ -105,9 +105,63 @@ jobs:
track: ${{ inputs.track || 'internal' }}
status: draft
# The same build for installs outside Google Play: the universal APK Google
# Play makes of this bundle, signed with the Play app signing key, published
# to liketrek/trek-android for Obtainium (wiki/Native-Apps.md). Only for a
# release tag, and held back while the app needs a server version that is
# not released yet.
- name: Whether the latest server release serves this build
id: released
env:
GH_TOKEN: ${{ github.token }}
run: |
tag=$(gh api "repos/$GITHUB_REPOSITORY/releases/latest" --jq .tag_name)
git fetch --depth=1 origin "refs/tags/$tag:refs/tags/$tag"
git show "$tag:server/src/nest/health/features.controller.ts" > "$RUNNER_TEMP/released-features.ts"
node scripts/ci/android-apk-release.mjs guard "$RUNNER_TEMP/released-features.ts" >> "$GITHUB_OUTPUT"
- name: Universal APK from Google Play
if: steps.released.outputs.publish == 'true'
env:
PLAY_APK_SERVICE_ACCOUNT_JSON: ${{ secrets.PLAY_APK_SERVICE_ACCOUNT_JSON }}
APK: trek-${{ steps.version.outputs.version }}.apk
run: |
printf '%s' "$PLAY_APK_SERVICE_ACCOUNT_JSON" > "$RUNNER_TEMP/play-apk.json"
node scripts/ci/android-apk-release.mjs download "$RUNNER_TEMP/play-apk.json" com.liketrek.trek \
"${{ steps.version.outputs.build }}" "$RUNNER_TEMP/$APK"
rm -f "$RUNNER_TEMP/play-apk.json"
cd "$RUNNER_TEMP" && sha256sum "$APK" > "$APK.sha256"
- uses: actions/create-github-app-token@v3
if: steps.released.outputs.publish == 'true'
id: apk-token
with:
app-id: ${{ secrets.RELEASE_APP_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
owner: liketrek
repositories: trek-android
# One release per app version: a newer build of the same version replaces
# its APK, so the release always holds what Google Play holds for it.
- name: Publish to liketrek/trek-android
if: steps.released.outputs.publish == 'true'
env:
GH_TOKEN: ${{ steps.apk-token.outputs.token }}
VERSION: ${{ steps.version.outputs.version }}
BUILD: ${{ steps.version.outputs.build }}
run: |
apk="$RUNNER_TEMP/trek-$VERSION.apk"
notes="TREK $VERSION for Android (build $BUILD): the build Google Play distributes, with the same signature. Connect it to your own TREK server; push and TREK Cloud need Google Play services. Changes: https://github.com/liketrek/TREK/releases"
if gh release view "v$VERSION" -R liketrek/trek-android > /dev/null 2>&1; then
gh release upload "v$VERSION" -R liketrek/trek-android --clobber "$apk" "$apk.sha256"
gh release edit "v$VERSION" -R liketrek/trek-android --notes "$notes"
else
gh release create "v$VERSION" -R liketrek/trek-android --title "TREK $VERSION" --notes "$notes" "$apk" "$apk.sha256"
fi
- name: Remove the upload key
if: always()
run: rm -f "$RUNNER_TEMP/upload.jks"
run: rm -f "$RUNNER_TEMP/upload.jks" "$RUNNER_TEMP/play-apk.json"
ios:
if: github.repository == 'liketrek/TREK'
+8
View File
@@ -1224,6 +1224,14 @@ jobs:
--set service.port=8080 \
--set-json 'httpRoute={"enabled":true,"parentRefs":[{"name":"gateway","namespace":"gateway-system","sectionName":"https"}],"hostnames":["trek.example.com"],"paths":["/","/api"],"annotations":{"example.com/note":"custom route"},"timeouts":{"request":"0s","backendRequest":"0s"}}' \
> "$out/http-route-variants.yaml"
helm template trek charts/trek \
--set-json 'extraObjects=[{"apiVersion":"batch/v1","kind":"CronJob","metadata":{"name":"{{ include \"trek.fullname\" . }}-backup-copy"},"spec":{"schedule":"0 3 * * *","jobTemplate":{"spec":{"template":{"spec":{"restartPolicy":"OnFailure","containers":[{"name":"copy","image":"busybox:1.36","command":["ls","/data/backups"],"volumeMounts":[{"name":"data","mountPath":"/data","readOnly":true}]}],"volumes":[{"name":"data","persistentVolumeClaim":{"claimName":"{{ include \"trek.fullname\" . }}-data","readOnly":true}}]}}}}}},"apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: {{ .Release.Name }}-notes\ndata:\n release: {{ .Release.Name | quote }}\n"]' \
> "$out/extra-objects.yaml"
# kubeconform accepts a name that still reads {{ ... }}, so check that both forms went through tpl.
if grep -n '{{' "$out/extra-objects.yaml"; then
echo "::error::extraObjects left a template unrendered"
exit 1
fi
- name: Check the manifests against the Kubernetes schemas
# The pinned Gateway API schema adds HTTPRoute validation without skipping unknown resources.
+2
View File
@@ -101,6 +101,8 @@ COPY --from=gosu-build /out/gosu /usr/local/bin/gosu
ENV XDG_CACHE_HOME=/tmp/kf6-cache
# Prevent Qt from probing for a display in headless containers.
ENV QT_QPA_PLATFORM=offscreen
# A UTF-8 locale, so Qt does not warn about the C locale on every extractor run.
ENV LANG=C.UTF-8
# Fixed path for both amd64 (static binary) and arm64 (symlink to apt binary).
# Override with KITINERARY_EXTRACTOR_PATH if you install it elsewhere.
ENV KITINERARY_EXTRACTOR_PATH=/usr/local/bin/kitinerary-extractor
+14 -59
View File
@@ -12,14 +12,14 @@ TREK has grown from a travel planner into a whole ecosystem for trips: plan toge
<br />
<a href="https://apps.apple.com/app/id6831237775"><picture><source media="(prefers-color-scheme: dark)" srcset="docs/app/app-store-dark.svg" /><source media="(prefers-color-scheme: light)" srcset="docs/app/app-store-light.svg" /><img src="docs/app/app-store-light.svg" alt="Download TREK on the App Store, with a QR code" width="320" /></picture></a>
&nbsp;
<a href="https://play.google.com/store/apps/details?id=com.liketrek.trek"><picture><source media="(prefers-color-scheme: dark)" srcset="docs/app/google-play-dark.svg" /><source media="(prefers-color-scheme: light)" srcset="docs/app/google-play-light.svg" /><img src="docs/app/google-play-light.svg" alt="Get TREK on Google Play, with a QR code" width="320" /></picture></a>
<br />
<a href="https://demo.liketrek.com"><img alt="Demo" src="https://img.shields.io/badge/Demo-try-111827?style=for-the-badge" /></a>
&nbsp;
<a href="https://hub.docker.com/r/mauriceboe/trek"><img alt="Docker" src="https://img.shields.io/badge/Docker-ready-2496ED?style=for-the-badge" /></a>
&nbsp;
<a href="https://sonarcloud.io/project/overview?id=liketrek_TREK"><img alt="Sonar Quality Gate" src="https://img.shields.io/sonar/quality_gate/liketrek_TREK?server=https%3A%2F%2Fsonarcloud.io&style=for-the-badge" /></a>
&nbsp;
<img alt="GitHub Actions Workflow Status" src="https://img.shields.io/github/actions/workflow/status/liketrek/TREK/test.yml?branch=main&style=for-the-badge">
&nbsp;
<a href="https://discord.gg/NhZBDSd4qW"><img alt="Discord" src="https://img.shields.io/badge/Discord-join-5865F2?style=for-the-badge" /></a>
&nbsp;
<a href="https://kanban.pakulat.org/shared/I4wxF6inOOMB0C6hH6kQm3efyNxFjwyI"><img alt="Roadmap" src="https://img.shields.io/badge/Roadmap-view-0EA5E9?style=for-the-badge" /></a>
@@ -38,7 +38,6 @@ TREK has grown from a travel planner into a whole ecosystem for trips: plan toge
&nbsp;
<a href="https://github.com/liketrek/TREK"><img alt="Stars" src="https://img.shields.io/github/stars/liketrek/trek?style=for-the-badge&label=Stars&color=6B7280" /></a>
<sub>PUBLIC SERVICES PROUDLY SPONSORED BY</sub><br /><a href="https://cloud.dataforest.net/en?mtm_campaign=trek"><picture><source media="(prefers-color-scheme: dark)" srcset="docs/sponsors/dataforest-light.svg" /><source media="(prefers-color-scheme: light)" srcset="docs/sponsors/dataforest-dark.svg" /><img src="docs/sponsors/dataforest-dark.svg" alt="dataforest cloud" height="30" /></picture></a>
</div>
---
@@ -53,14 +52,8 @@ TREK has grown from a travel planner into a whole ecosystem for trips: plan toge
## What you get
<picture>
<source media="(max-width: 700px)" srcset="docs/tiles/grid-mobile.svg" />
<source media="(prefers-color-scheme: dark)" srcset="docs/tiles/grid-desktop-dark.svg" />
<img src="docs/tiles/grid-desktop.svg" alt="Plan, track, share" width="100%" />
</picture>
<details>
<summary><b>See all features</b></summary>
<summary><h3>See all features</h3></summary>
<br />
@@ -220,34 +213,12 @@ Most of what follows is an addon an admin switches on or off. Lists, Costs, Docu
<br />
## Powered by [dataforest cloud](https://cloud.dataforest.net/en?mtm_campaign=trek)
<div align="center">
<br />
<sub>POWERED BY</sub><br />
<a href="https://cloud.dataforest.net/en?mtm_campaign=trek"><picture><source media="(prefers-color-scheme: dark)" srcset="docs/sponsors/dataforest-light.svg" /><source media="(prefers-color-scheme: light)" srcset="docs/sponsors/dataforest-dark.svg" /><img src="docs/sponsors/dataforest-dark.svg" alt="dataforest cloud" height="40" /></picture></a>
<a href="https://cloud.dataforest.net/en?mtm_campaign=trek">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/sponsors/dataforest-light.svg" />
<source media="(prefers-color-scheme: light)" srcset="docs/sponsors/dataforest-dark.svg" />
<img src="docs/sponsors/dataforest-dark.svg" alt="dataforest cloud" height="60" />
</picture>
</a>
<br />
<br />
**Every TREK installation in the world searches through servers that [dataforest cloud](https://cloud.dataforest.net/en?mtm_campaign=trek) sponsors.**
The place index with over 88 million places, the address search in every TREK language and the planet-wide routing all run on [dataforest cloud](https://cloud.dataforest.net/en?mtm_campaign=trek) in Frankfurt, Germany, free of charge for everyone who self-hosts TREK. Without this sponsorship, these services would not exist in this form.
Thank you, [dataforest](https://cloud.dataforest.net/en?mtm_campaign=trek), for backing open source this generously. 💚
<br />
<a href="https://cloud.dataforest.net/en?mtm_campaign=trek"><img alt="Visit dataforest cloud" src="https://img.shields.io/badge/Visit-dataforest_cloud-02C382?style=for-the-badge" /></a>
Looking for a server for your own TREK? [dataforest cloud](https://cloud.dataforest.net/en?mtm_campaign=trek) is where TREK's own services live.
The place index with 88 million places, the address search and the planet-wide routing run on <a href="https://cloud.dataforest.net/en?mtm_campaign=trek">dataforest cloud</a> in Frankfurt, free for every self-hosted TREK. Thank you! 💚
</div>
@@ -255,13 +226,7 @@ Looking for a server for your own TREK? [dataforest cloud](https://cloud.datafor
## AI usage
We use LLM-assisted coding tools across parts of this codebase. Nothing ships that a
maintainer has not read and understood: every change goes through a pull request, is
reviewed and tested, and has a human who can answer for it. "The AI wrote that" is not
an answer any of us would accept from ourselves.
See [**How we use AI in TREK**](https://github.com/liketrek/TREK/discussions/1851) for
the details.
We use LLM-assisted coding tools, and nothing ships that a maintainer has not read, reviewed, tested and can answer for. More in [How we use AI in TREK](https://github.com/liketrek/TREK/discussions/1851).
<br />
@@ -285,7 +250,7 @@ Open `http://localhost:3000`, or `http://<server-ip>:3000` from another machine.
<div align="center">
<a href="#docker-compose-production">Docker Compose</a>&nbsp;&nbsp;·&nbsp;&nbsp;<a href="#helm-kubernetes">Helm / Kubernetes</a>&nbsp;&nbsp;·&nbsp;&nbsp;<a href="#install-as-app-pwa">Install as PWA</a>&nbsp;&nbsp;·&nbsp;&nbsp;<a href="#reverse-proxy">Reverse Proxy</a>
<a href="#docker-compose-production">Docker Compose</a>&nbsp;&nbsp;·&nbsp;&nbsp;<a href="#helm-kubernetes">Helm / Kubernetes</a>&nbsp;&nbsp;·&nbsp;&nbsp;<a href="#reverse-proxy">Reverse Proxy</a>
</div>
@@ -342,18 +307,6 @@ See [`charts/README.md`](https://github.com/liketrek/TREK/blob/main/charts/READM
<br />
<h2 id="install-as-app-pwa">Install as App (PWA)</h2>
TREK works as a Progressive Web App, and the TREK Travel Planner app for iPhone, iPad and Android connects to the same server ([Native Apps](https://github.com/liketrek/TREK/wiki/Native-Apps)). To install the web app instead:
1. Open TREK in the browser (HTTPS required)
2. **iOS**: Share ▸ *Add to Home Screen*
3. **Android**: Menu ▸ *Install app* (or *Add to Home Screen*)
TREK then launches fullscreen with its own icon, just like a native app.
<br />
## Updating
See [Updating](https://github.com/liketrek/TREK/wiki/Updating) — Docker Compose,
@@ -442,6 +395,8 @@ Caddy handles TLS and WebSockets automatically.
Every variable, its default and what it does: see
[Environment Variables](https://github.com/liketrek/TREK/wiki/Environment-Variables).
<br />
## Data sources
The Atlas map's country and sub-national (province/county) boundaries come from
+1
View File
@@ -60,3 +60,4 @@ See `values.yaml` for more options.
- Set `env.OIDC_DISCOVERY_URL` to override the auto-constructed OIDC discovery endpoint. Required for providers (e.g. Authentik) that expose it at a non-standard path.
- `podSecurityContext` defaults to `fsGroup: 1000` with `fsGroupChangePolicy: OnRootMismatch`, and `securityContext` (the container's) is empty. The container then starts as root, hands `/app/data` and `/app/uploads` to `node` (uid 1000) if the directory or anything directly inside it is not owned by `node` yet, and drops to `node`. Deeper files are not checked. Only the owning user is changed (plus a `root` group), so a different `fsGroup` stays in place. A volume that refuses `chown` (NFS with `root_squash`) logs a warning instead; set `runAsUser: 1000` then. To run as `node` from the start, for example under the `restricted` Pod Security Standard, set `podSecurityContext.runAsUser: 1000` and `runAsGroup: 1000`; the image then skips that step and the privilege drop. See the example in `values.yaml`.
- Use `extraVolumes` and `extraVolumeMounts` to add your own volumes to the pod. To give the booking import more KItinerary extractors, mount a ConfigMap at `/usr/local/share/kitinerary/extractors`, with one `.json` and one `.js` key for each extractor; see the example in `values.yaml`.
- Use `extraObjects` to render further Kubernetes objects next to the chart's own, for example a backup `CronJob`. Each item is a map or a string of YAML, and `{{ }}` in it is evaluated, so `{{ .Release.Name }}` works. A backup job should copy TREK's own backups from `backups/` on the data volume and mount it read only, since that volume also holds the encryption key. The archives carry `.encryption_key` too unless `ENCRYPTION_KEY` is set, so protect the copy's destination like the data volume.
+2 -2
View File
@@ -1,5 +1,5 @@
apiVersion: v2
name: trek
version: 5.1.4
version: 5.2.1
description: Minimal Helm chart for TREK app
appVersion: "5.1.4"
appVersion: "5.2.1"
+8
View File
@@ -0,0 +1,8 @@
{{- range .Values.extraObjects }}
---
{{- if kindIs "string" . }}
{{ tpl . $ }}
{{- else }}
{{ tpl (toYaml .) $ }}
{{- end }}
{{- end }}
+23
View File
@@ -338,6 +338,29 @@ extraVolumes: []
# readOnly: true
extraVolumeMounts: []
# Further Kubernetes objects the chart renders next to its own, for example a Job, a
# CronJob or a ConfigMap. Each item is rendered as written, either as a map or as a
# string of YAML, and {{ }} in it is evaluated, so {{ include "trek.fullname" . }} or
# {{ .Release.Name }} work, in both forms. Write literal braces as {{ "{{" }}.
# A backup job must only read the data volume: it also holds the encryption key and the
# server's secrets, and a second writer corrupts travel.db. Rather than copying the live
# travel.db, copy TREK's own backups (Admin, Backup, automatic backups) from backups/ in
# that volume. Those archives carry .encryption_key too (unless ENCRYPTION_KEY is set),
# so protect the job's destination like the data volume itself.
# extraObjects:
# - apiVersion: v1
# kind: ConfigMap
# metadata:
# name: '{{ include "trek.fullname" . }}-extra'
# data:
# note: hello
# - |
# apiVersion: v1
# kind: ConfigMap
# metadata:
# name: {{ .Release.Name }}-notes
extraObjects: []
resources:
requests:
cpu: 100m
@@ -1,6 +1,9 @@
package com.liketrek.trek;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.util.TypedValue;
@@ -11,11 +14,13 @@ import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.getcapacitor.BridgeActivity;
import com.getcapacitor.WebViewListener;
import com.liketrek.trek.screen.TrekKeyCommands;
import com.liketrek.trek.tiles.TrekTileStore;
import com.liketrek.trek.widget.TrekWidgetUpdater;
@@ -26,6 +31,9 @@ public class MainActivity extends BridgeActivity {
/** The share sheet (share/ShareActivity.kt) left an item for the import. */
public static final String ACTION_SHARE_HANDOFF = "com.liketrek.trek.SHARE_HANDOFF";
/** The page colour of the address screen (native-shell/shell.css --page). */
private static final int SHELL_PAGE = 0xFFFFFAF5;
@Override
protected void onCreate(Bundle savedInstanceState) {
registerPlugin(TrekShellPlugin.class);
@@ -57,6 +65,33 @@ public class MainActivity extends BridgeActivity {
// and Chrome honours that, but the WebView draws the stretch on its root
// scroller natively. It scales the whole view, top bar and bottom dock included.
bridge.getWebView().setOverScrollMode(View.OVER_SCROLL_NEVER);
// The address screen, and the step from it to the server just picked:
// the warm ground of the first screens behind everything, so the
// restart and the page's first frames do not flash white. The window's
// colour is also what an older WebView shows under the status bar,
// where it lays the page out between the bars (native/appBoot.ts).
if (!onServer || restarting) {
Drawable windowBackground = getWindow().getDecorView().getBackground();
// A new drawable: setBackgroundColor would recolour the theme's own one,
// and the restore below would hand the window the warm ground back.
getWindow().getDecorView().setBackground(new ColorDrawable(SHELL_PAGE));
bridge.getWebView().setBackgroundColor(SHELL_PAGE);
// Once the server's page is up, the window is the one a normal launch
// has, so the status bar of an older WebView follows the system again.
if (onServer) {
bridge.addWebViewListener(new WebViewListener() {
private boolean restored;
@Override
public void onPageLoaded(WebView webView) {
if (restored) return;
restored = true;
getWindow().getDecorView().setBackground(windowBackground);
webView.setBackgroundColor(Color.WHITE);
}
});
}
}
// Set before any WebView callback can run: they are posted to this thread.
if (onServer) {
bridge.setWebViewClient(
+234
View File
@@ -0,0 +1,234 @@
import { devices, expect, test, type Locator, type Page } from '@playwright/test';
import { encodePolyline6 } from '@trek/shared';
async function createTourTrip(page: Page): Promise<number> {
const trip = await page.request.post('/api/trips', {
data: { title: 'Tour type picker', start_date: '2099-06-01', end_date: '2099-06-05' },
});
await expect(trip).toBeOK();
const {
trip: { id },
} = await trip.json();
await expect(await page.request.put(`/api/trips/${id}/addons/tours`, { data: { enabled: true } })).toBeOK();
return id;
}
async function expectInside(element: Locator, boundary: Locator) {
await expect
.poll(async () => {
const target = await element.boundingBox();
const rail = await boundary.boundingBox();
return (
!!target &&
!!rail &&
target.x >= rail.x - 1 &&
target.y >= rail.y - 1 &&
target.x + target.width <= rail.x + rail.width + 1 &&
target.y + target.height <= rail.y + rail.height + 1
);
})
.toBe(true);
}
function editorFields(page: Page) {
const trigger = page.getByTestId('tour-type-select');
const scrollArea = page.getByTestId('tour-planner-editor-scroll');
return { trigger, scrollArea, menu: page.getByRole('group', { name: 'Tour type', exact: true }) };
}
test('Tour type follows and fits inside the narrow editor rail', async ({ page }) => {
await page.setViewportSize({ width: 1024, height: 480 });
const tripId = await createTourTrip(page);
await page.goto(`/trips/${tripId}?tab=tour-planner`);
await page.getByRole('button', { name: 'Plan new tour' }).click();
await expect(page.getByTestId('tour-planner-empty-state')).toBeAttached();
const grip = page.locator('[data-resize="left"]');
for (let step = 0; step < 8; step++) await grip.press('ArrowLeft');
const { trigger, scrollArea, menu } = editorFields(page);
await trigger.scrollIntoViewIfNeeded();
await expectInside(trigger, scrollArea);
await trigger.click();
await expectInside(menu, scrollArea);
await expect.poll(() => menu.evaluate((el) => el.scrollHeight > el.clientHeight)).toBe(true);
async function anchorGap() {
return menu.evaluate((el) => {
const anchor = document.querySelector('[data-testid="tour-type-select"]')!.getBoundingClientRect();
const panel = el.getBoundingClientRect();
return Math.round(Math.max(panel.top - anchor.bottom, anchor.top - panel.bottom));
});
}
await expect.poll(anchorGap).toBe(4);
const start = await scrollArea.evaluate((el) => el.scrollTop);
await scrollArea.evaluate((el) => el.scrollBy(0, 20));
await expect.poll(() => scrollArea.evaluate((el) => el.scrollTop)).toBeGreaterThan(start);
await expect.poll(anchorGap).toBe(4);
await expectInside(menu, scrollArea);
await scrollArea.evaluate((el, top) => {
el.scrollTop = top;
}, start);
await expect.poll(anchorGap).toBe(4);
await page.keyboard.press('Escape');
await expect(trigger).toBeFocused();
await expect(menu).toHaveCount(0);
await trigger.click();
await scrollArea.evaluate((el) => el.scrollBy(0, 180));
await expect(trigger).toHaveAttribute('aria-expanded', 'false');
await expect(menu).toHaveCount(0);
await scrollArea.evaluate((el) => {
el.scrollTop = 0;
});
await expect(menu).toHaveCount(0);
await trigger.click();
const ski = menu.getByTestId('tour-type-option-ski');
await page.keyboard.press('End');
await expect(ski).toBeInViewport();
await expect(ski).toBeFocused();
await page.keyboard.press('Enter');
await expect(trigger).toContainText('Ski & winter');
await expect(menu).toHaveCount(0);
await page.getByRole('button', { name: 'Alpine', exact: true }).click();
const hardest = page.getByRole('button', { name: 'Hardest runs', exact: true });
const hardestMenu = page.getByRole('group', { name: 'Hardest runs', exact: true });
await hardest.click();
await expectInside(hardestMenu, scrollArea);
await hardestMenu.getByRole('button', { name: 'Easy', exact: true }).click();
await expect(hardest).toContainText('Easy');
await expect(hardestMenu).toHaveCount(0);
});
test('the saved hike difficulty dropdown fits above the field and keeps alpine confirmation', async ({ page }) => {
await page.setViewportSize({ width: 1024, height: 520 });
const tripId = await createTourTrip(page);
const saved = await page.request.post(`/api/trips/${tripId}/tours`, {
data: {
name: 'Saved ridge walk',
tour_type: 'hike',
max_hiking_difficulty: 2,
route_geometry: [
[48.1, 11.1, 500],
[48.11, 11.11, 550],
],
waypoints: [
{ lat: 48.1, lng: 11.1, role: 'start', sequence: 0 },
{ lat: 48.11, lng: 11.11, role: 'end', sequence: 1 },
],
},
});
await expect(saved).toBeOK();
const {
tour: { place_id },
} = await saved.json();
const detailUrl = `**/api/trips/${tripId}/tours/${place_id}`;
const detailGate = Promise.withResolvers<void>();
await page.route(
detailUrl,
async (route) => {
await detailGate.promise;
await route.continue();
},
{ times: 1 }
);
const shape = encodePolyline6([
{ lat: 48.1, lon: 11.1 },
{ lat: 48.11, lon: 11.11 },
]);
await page.route('**/api/routing/valhalla/route', (route) =>
route.fulfill({
json: { trip: { legs: [{ shape, summary: { length: 1.4, time: 1200 } }] } },
})
);
await page.goto(`/trips/${tripId}?tab=tour-planner`);
const detailRequested = page.waitForRequest(detailUrl);
await page.getByRole('option', { name: /Saved ridge walk/ }).click();
await detailRequested;
const { trigger, menu, scrollArea } = editorFields(page);
try {
await expect(trigger).toHaveCount(0);
await expect(menu).toHaveCount(0);
} finally {
detailGate.resolve();
}
await expect(page.getByLabel('Tour name')).toHaveValue('Saved ridge walk');
await trigger.click();
await expectInside(menu, scrollArea);
await page.keyboard.press('Escape');
const difficulty = page.getByRole('button', { name: 'Maximum trail difficulty', exact: true });
const difficultyMenu = page.getByRole('group', { name: 'Maximum trail difficulty', exact: true });
await difficulty.scrollIntoViewIfNeeded();
await difficulty.click();
await expectInside(difficultyMenu, scrollArea);
await expect(difficultyMenu).toHaveCSS('transform-origin', /px [1-9][0-9.]*px$/);
await page.keyboard.press('Escape');
await expect(difficulty).toBeFocused();
await expect(difficultyMenu).toHaveCount(0);
await difficulty.click();
await scrollArea.evaluate((el) => {
el.scrollTop = 0;
});
await expect(difficulty).toHaveAttribute('aria-expanded', 'false');
await expect(difficultyMenu).toHaveCount(0);
await difficulty.click();
await difficultyMenu.getByRole('button', { name: 'T3: Demanding mountain hiking' }).click();
await expect(difficulty).toContainText('T3:');
await difficulty.click();
await difficultyMenu.getByRole('button', { name: 'T4: Alpine hiking' }).click();
await expect(page.getByRole('heading', { name: 'Enable alpine routing?' })).toBeVisible();
await page.getByRole('button', { name: 'Cancel' }).click();
await expect(difficulty).toContainText('T3:');
const categories = page.getByTestId('tour-poi-categories');
await categories.click();
await expectInside(page.getByRole('group', { name: 'What to look for', exact: true }), scrollArea);
});
test('the tour editor dropdowns fit in the native tablet layout', async ({ playwright, baseURL, storageState }) => {
const browser = await playwright.webkit.launch();
try {
const page = await browser.newPage({
...devices['iPad Pro 11'],
viewport: { width: 680, height: 620 },
baseURL,
storageState,
});
page.setDefaultTimeout(10_000);
// The browser supplies the WebKit viewport and touch input. This flag selects the app shell.
await page.addInitScript(() => Object.assign(window, { CapacitorCustomPlatform: { name: 'ios' } }));
const tripId = await createTourTrip(page);
await page.goto(`/trips/${tripId}?tab=tour-planner`);
await page.getByRole('tab', { name: 'Plan a tour', exact: true }).tap();
await page.getByRole('button', { name: 'Plan new tour' }).tap();
const { trigger, menu, scrollArea } = editorFields(page);
await trigger.tap();
await expectInside(menu, scrollArea);
await scrollArea.evaluate((el) => el.scrollBy(0, 160));
await expect(trigger).toHaveAttribute('aria-expanded', 'false');
const difficulty = page.getByRole('button', { name: 'Maximum trail difficulty', exact: true });
const difficultyMenu = page.getByRole('group', { name: 'Maximum trail difficulty', exact: true });
await difficulty.tap();
await expectInside(difficultyMenu, scrollArea);
await difficultyMenu.getByRole('button', { name: 'T1: Hiking' }).tap();
await expect(difficulty).toContainText('T1:');
await expect(difficultyMenu).toHaveCount(0);
await trigger.tap();
await menu.getByTestId('tour-type-option-ski').tap();
await page.getByRole('button', { name: 'Alpine', exact: true }).tap();
const hardest = page.getByRole('button', { name: 'Hardest runs', exact: true });
const hardestMenu = page.getByRole('group', { name: 'Hardest runs', exact: true });
await hardest.tap();
await expectInside(hardestMenu, scrollArea);
await hardestMenu.getByRole('button', { name: 'Easy', exact: true }).tap();
await expect(hardest).toContainText('Easy');
} finally {
await browser.close();
}
});
+4 -1
View File
@@ -5,6 +5,7 @@ import { SplashScreen } from '@capacitor/splash-screen';
import { StatusBar, Style } from '@capacitor/status-bar';
import { PASSWORD_MIN_LENGTH, passwordProblem, passwordRuleStates } from '../../shared/src/auth/password-policy';
import logoWhite from '../public/logo-light.svg'; // #fff wordmark, for the landscape
import { pageUnderStatusBar } from '../src/native/appBoot';
import { AUTH_GATE_NAMES, canSignInInApp, type AuthGate } from '../src/native/authGate';
import { opensSoon, refundedBeforeOpening } from '../src/native/cloudOrders';
import { fakeIapClient, getIapClient, productIdFor, type Purchase } from '../src/native/iap';
@@ -1705,7 +1706,9 @@ function showUnreachable(server: string, cert?: ClientCertDemand, failure?: stri
*/
async function paintStatusBar(): Promise<void> {
try {
await StatusBar.setStyle({ style: Style.Dark });
// Below the bar on an older Android WebView the page stops, and the bar
// stands on the window's light colour instead: dark icons there.
await StatusBar.setStyle({ style: pageUnderStatusBar() ? Style.Dark : Style.Light });
if (wideLayout.matches) await StatusBar.hide();
else await StatusBar.show();
} catch {
+26 -5
View File
@@ -204,11 +204,32 @@
--sea: #cfe3ef;
--text-face: 'Plus Jakarta Sans', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
--display-face: 'Poppins', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
/* The insets of the device, from the web view or, on iOS, from the native side. */
--safe-top: max(env(safe-area-inset-top, 0px), var(--trek-native-safe-top, 0px));
--safe-bottom: max(env(safe-area-inset-bottom, 0px), var(--trek-native-safe-bottom, 0px));
--safe-start: max(env(safe-area-inset-left, 0px), var(--trek-native-safe-left, 0px));
--safe-end: max(env(safe-area-inset-right, 0px), var(--trek-native-safe-right, 0px));
/* The insets of the device, from the web view or from the native side. On
* Android a web view can report env() as 0 while the page reaches under the
* status and navigation bars; Capacitor's SystemBars writes the real insets
* to --safe-area-inset-* instead (0 where it lays the web view out between
* the bars). iOS measures its own (TrekBridgeViewController publishSafeArea).
* In a browser the variables are unset: env() alone. */
--safe-top: max(
env(safe-area-inset-top, 0px),
var(--safe-area-inset-top, 0px),
var(--trek-native-safe-top, 0px)
);
--safe-bottom: max(
env(safe-area-inset-bottom, 0px),
var(--safe-area-inset-bottom, 0px),
var(--trek-native-safe-bottom, 0px)
);
--safe-start: max(
env(safe-area-inset-left, 0px),
var(--safe-area-inset-left, 0px),
var(--trek-native-safe-left, 0px)
);
--safe-end: max(
env(safe-area-inset-right, 0px),
var(--safe-area-inset-right, 0px),
var(--trek-native-safe-right, 0px)
);
color-scheme: light;
-webkit-text-size-adjust: 100%;
}
+7 -7
View File
@@ -1,6 +1,6 @@
{
"name": "@trek/client",
"version": "5.1.4",
"version": "5.2.1",
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
},
@@ -103,7 +103,7 @@
"@fontsource/yellowtail": "^5.3.0",
"@maplibre/maplibre-gl-leaflet": "0.1.4",
"@noble/hashes": "^1.8.0",
"@simplewebauthn/browser": "^13.3.0",
"@simplewebauthn/browser": "^14.0.0",
"@trek/shared": "*",
"axios": "^1.21.0",
"dexie": "^4.4.7",
@@ -112,13 +112,13 @@
"iso-3166-2": "^1.0.0",
"leaflet": "^1.9.4",
"lucide-react": "^0.577.0",
"mapbox-gl": "^3.35.2",
"mapbox-gl": "3.32.0",
"maplibre-gl": "6.19.0",
"modern-screenshot": "4.7.0",
"plyr": "^3.8.5",
"react": "^19.3.1",
"react-dom": "^19.3.1",
"react-dropzone": "^14.4.1",
"react-dropzone": "^20.2.1",
"react-leaflet": "^5.0.0",
"react-leaflet-cluster": "^4.1.3",
"react-markdown": "^10.1.0",
@@ -141,7 +141,7 @@
"@testing-library/user-event": "^14.6.13",
"@trivago/prettier-plugin-sort-imports": "^6.0.2",
"@types/leaflet": "^1.9.22",
"@types/node": "^25.9.8",
"@types/node": "^26.6.11",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@vitejs/plugin-react": "^6.2.1",
@@ -154,7 +154,7 @@
"eslint-plugin-react-refresh": "^0.5.8",
"fake-indexeddb": "^6.2.7",
"jsdom": "^29.1.1",
"msw": "^2.15.0",
"msw": "^3.0.8",
"postcss": "^8.5.33",
"prettier": "^3.10.1",
"prettier-plugin-organize-imports": "^4.3.0",
@@ -163,7 +163,7 @@
"sharp": "^0.35.5",
"tailwindcss": "^3.4.19",
"typescript": "^6.0.3",
"typescript-eslint": "^8.72.1",
"typescript-eslint": "^8.73.0",
"vite": "8.3.8",
"vite-plugin-pwa": "^2.0.0",
"vitest": "^4.1.12"
+10
View File
@@ -12,6 +12,16 @@
(function () {
try {
var raw = localStorage.getItem('trek_appearance');
// Inside the iOS and Android app, before anyone signed in on this server
// from here: the page carries on the address screen's colour until the
// sign-in screen is up (native/appBoot.ts), instead of flashing white.
// The app's bridge is in place before this script runs.
var w = window;
var inApp = !!(w.androidBridge || (w.webkit && w.webkit.messageHandlers && w.webkit.messageHandlers.bridge));
if (inApp && !raw) {
document.documentElement.setAttribute('data-app-boot', '');
document.documentElement.style.backgroundColor = '#fffaf5';
}
if (!raw) return;
var s = JSON.parse(raw);
if (!s || s.v !== 1) return;
+3 -3
View File
@@ -1,6 +1,6 @@
{
"src": {
"@typescript-eslint/no-non-null-assertion": 367,
"@typescript-eslint/no-non-null-assertion": 354,
"@typescript-eslint/no-misused-promises": 820,
"no-console": 88,
"complexity": 216,
@@ -8,14 +8,14 @@
"trek/no-swallowed-catch": 126,
"max-params": 31,
"trek/store-without-selector": 66,
"react-hooks/refs": 534,
"react-hooks/refs": 533,
"react-hooks/set-state-in-effect": 189,
"@typescript-eslint/no-floating-promises": 162,
"react-hooks/exhaustive-deps": 113,
"@typescript-eslint/no-unused-vars": 117,
"react-hooks/immutability": 28,
"max-lines-per-function": 127,
"react-hooks/static-components": 50,
"react-hooks/static-components": 38,
"react-hooks/preserve-manual-memoization": 12,
"no-useless-assignment": 7,
"no-empty": 19,
-1
View File
@@ -2121,7 +2121,6 @@
"tests/unit/sync/tripSyncManager.test.ts",
"tests/unit/tripStore.test.ts",
"tests/unit/utils/cleanAmount.test.ts",
"tests/unit/utils/fileDownload.test.ts",
"tests/unit/utils/formatters.test.ts",
"tests/unit/utils/placeFiles.test.ts",
"tests/unit/utils/shellGuard.test.ts",
+5 -5
View File
@@ -8,18 +8,18 @@
"src/components/Map/MapView.tsx": 1200,
"src/components/Map/MapViewGL.test.tsx": 2919,
"src/components/Map/MapViewGL.tsx": 2116,
"src/components/Planner/DayDetailPanel.test.tsx": 2333,
"src/components/Planner/DayDetailPanel.test.tsx": 2332,
"src/components/Planner/DayPlanSidebar.test.tsx": 5349,
"src/components/Planner/DayPlanSidebar.tsx": 2910,
"src/components/Planner/DayPlanSidebar.tsx": 2908,
"src/components/Planner/PlaceFormModal.test.tsx": 2836,
"src/components/Planner/PlaceInspector.tsx": 1128,
"src/components/Studio/TravelElements.tsx": 1559,
"src/components/Studio/countryShapes.ts": 2595,
"src/index.css": 1636,
"src/mobile/screens/admin/MAdminPluginsPanel.tsx": 1503,
"src/pages/JourneyDetailPage.test.tsx": 4028,
"src/pages/LoginPage.tsx": 1294,
"src/pages/TripPlannerPage.tsx": 1128,
"src/pages/JourneyDetailPage.test.tsx": 3886,
"src/pages/LoginPage.tsx": 1273,
"src/pages/TripPlannerPage.tsx": 1127,
"src/pages/atlas/useAtlas.ts": 1207,
"src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx": 3518,
"src/pages/tripPlanner/useTripPlanner.test.tsx": 3267,
+2 -2
View File
@@ -45,7 +45,7 @@
"components/Journey/JourneyMapGL.tsx": 5,
"components/Journey/MobileEntryView.tsx": 94,
"components/Journey/MobileMapTimeline.tsx": 8,
"components/Journey/PhotoLightbox.tsx": 13,
"components/Journey/PhotoLightbox.tsx": 11,
"components/Journey/VideoPlayer.tsx": 2,
"components/Journey/VideoPlayerLazy.tsx": 1,
"components/Journey/journeyMapPopup.ts": 17,
@@ -262,7 +262,7 @@
"mobile/screens/trip/tabs/MCollabTab.tsx": 1,
"mobile/screens/trip/tabs/MCostsTab.tsx": 70,
"mobile/screens/trip/tabs/MDocSyncSheet.tsx": 43,
"mobile/screens/trip/tabs/MFileLightbox.tsx": 12,
"mobile/screens/trip/tabs/MFileLightbox.tsx": 11,
"mobile/screens/trip/tabs/MFileLinkSheet.tsx": 2,
"mobile/screens/trip/tabs/MFileMenuSheet.tsx": 1,
"mobile/screens/trip/tabs/MFileTrashSheet.tsx": 4,
+28 -4
View File
@@ -1,13 +1,14 @@
import React from 'react'
import { render, screen, waitFor, act } from '@testing-library/react'
import { MemoryRouter, useLocation } from 'react-router'
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { describe, it, expect, beforeEach, onTestFinished, vi } from 'vitest'
import { http, HttpResponse } from 'msw'
import { server } from '../tests/helpers/msw/server'
import { useAuthStore } from './store/authStore'
import { useSettingsStore } from './store/settingsStore'
import { resetAllStores } from '../tests/helpers/store'
import { buildUser, buildSettings, buildTrip } from '../tests/helpers/factories'
import { locationAt } from '../tests/helpers/location'
import { offlineDb } from './db/offlineDb'
import { SETTINGS_WAIT_MS } from './utils/startDestination'
import App from './App'
@@ -185,9 +186,29 @@ describe('RootRedirect — startup destination', () => {
seedAuth({ isAuthenticated: true, user: buildUser() })
useSettingsStore.setState({ isLoaded: false })
stubActiveTrip({ id: 42, title: 'Japan' })
// App asks for the settings on its own as soon as the user is signed in.
// Held until the redirect is decided, or whichever answer lands first wins
// and the test proves nothing about the mirror; released here, so it cannot
// land in the next test either.
let releaseSettings = () => {}
const settingsHeld = new Promise<void>((resolve) => { releaseSettings = resolve })
onTestFinished(() => releaseSettings())
server.use(
http.get('/api/settings', async () => {
await settingsHeld
return HttpResponse.json({
settings: buildSettings({ start_page: 'active_trip', start_trip_tab: 'finanzplan' }),
})
}),
)
renderApp('/')
await waitFor(() => expect(screen.getByText('TripPlanner')).toBeInTheDocument())
expect(currentPath()).toBe('/trips/42?tab=finanzplan')
expect(useSettingsStore.getState().isLoaded).toBe(false)
releaseSettings()
await waitFor(() => expect(useSettingsStore.getState().isLoaded).toBe(true))
})
})
@@ -532,7 +553,7 @@ describe('Version cache-busting', () => {
const reload = vi.fn()
Object.defineProperty(window, 'location', {
writable: true,
value: { ...window.location, reload },
value: locationAt('/', { reload }),
})
server.use(
@@ -587,7 +608,7 @@ describe('Version cache-busting', () => {
// and try to update.
localStorage.setItem('trek_app_version', '2.9.9')
const reload = vi.fn()
Object.defineProperty(window, 'location', { writable: true, value: { ...window.location, reload } })
Object.defineProperty(window, 'location', { writable: true, value: locationAt('/', { reload }) })
server.use(
http.get('/api/auth/app-config', () =>
@@ -609,7 +630,7 @@ describe('Version cache-busting', () => {
// failure neither deletes anything nor reloads into the old worker's shell.
localStorage.setItem('trek_app_version', '2.9.9')
const reload = vi.fn()
Object.defineProperty(window, 'location', { writable: true, value: { ...window.location, reload } })
Object.defineProperty(window, 'location', { writable: true, value: locationAt('/', { reload }) })
const cachesDelete = vi.fn().mockResolvedValue(true)
const unregister = vi.fn().mockResolvedValue(true)
vi.stubGlobal('caches', { keys: vi.fn().mockResolvedValue(['workbox-precache-v2', 'map-tiles']), delete: cachesDelete })
@@ -685,6 +706,9 @@ describe('RootRedirect — preference not mirrored on this device', () => {
vi.useFakeTimers({ shouldAdvanceTime: true })
seedAuth({ isAuthenticated: true, user: buildUser() })
useSettingsStore.setState({ isLoaded: false })
// No backend: the settings never arrive, so only the timeout can decide.
// Answered, they would open the dashboard on their own and hide the wait.
server.use(http.get('/api/settings', () => HttpResponse.error()))
renderApp('/')
expect(screen.queryByText('Dashboard')).not.toBeInTheDocument()
+12 -1
View File
@@ -1,4 +1,4 @@
import React, { useEffect, useState, useRef, ReactNode, Suspense } from 'react'
import React, { useEffect, useLayoutEffect, useState, useRef, ReactNode, Suspense } from 'react'
import { Routes, Route, Navigate, useLocation, useNavigationType } from 'react-router'
import { useAuthStore } from './store/authStore'
import { useSettingsStore } from './store/settingsStore'
@@ -17,6 +17,8 @@ import BackgroundTasksWidget from './components/BackgroundTasks/BackgroundTasksW
import MobileShell from './mobile/MobileShell'
import MRouteFallback from './mobile/components/MRouteFallback'
import ErrorBoundary from './components/shared/ErrorBoundary'
import AppBootScreen from './components/shared/AppBootScreen'
import { endAppBoot, isAppBoot } from './native/appBoot'
import { lazyWithRetry } from './utils/lazyWithRetry'
import { reconcileAppVersion } from './utils/versionHandover'
import { useServerVersionStore } from './store/serverVersionStore'
@@ -113,6 +115,7 @@ function ProtectedRoute({ children, adminRequired = false, addonId }: ProtectedR
const isPhone = useIsPhone()
if (isLoading) {
if (isAppBoot()) return <AppBootScreen />
return (
<div className="min-h-screen flex items-center justify-center bg-slate-50">
<div className="flex flex-col items-center gap-3">
@@ -286,6 +289,7 @@ function RootRedirect() {
}, [isLoading, isAuthenticated, settingsLoaded, settingsGaveUp, settings, target])
if (isLoading || (isAuthenticated && !target)) {
if (isAppBoot()) return <AppBootScreen />
return (
<div className="min-h-screen flex items-center justify-center bg-slate-50">
<div className="w-10 h-10 border-4 border-slate-200 border-t-slate-900 rounded-full animate-spin"></div>
@@ -306,6 +310,7 @@ function RouteFallback() {
// on a phone the desktop spinner on bg-surface would be a foreign white sheet
// in front of the mobile screen.
const isPhone = useIsPhone()
if (isAppBoot()) return <AppBootScreen />
if (isPhone) return <MRouteFallback />
return (
<div className="min-h-screen flex items-center justify-center bg-surface">
@@ -398,6 +403,12 @@ export default function App() {
const location = useLocation()
const isSharedPage = location.pathname.startsWith('/shared/')
// Inside the app: the handover from its address screen ends once a signed-in
// screen is up, before it paints, so it can rise in (native/appBoot.ts).
useLayoutEffect(() => {
if (isAuthenticated && location.pathname !== '/' && location.pathname !== '/login') endAppBoot()
}, [isAuthenticated, location.pathname])
useEffect(() => {
const run = () =>
applyAppearance({
@@ -1,7 +1,7 @@
// FE-ADMIN-DUS-001 to FE-ADMIN-DUS-031
import { render, screen, waitFor, within, fireEvent } from '../../../tests/helpers/render';
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { delay, http, HttpResponse } from 'msw';
import { server } from '../../../tests/helpers/msw/server';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { buildAdmin } from '../../../tests/helpers/factories';
@@ -341,12 +341,43 @@ describe('DefaultUserSettingsTab', () => {
expect(input).toHaveValue('pk.old');
await user.clear(input);
await user.type(input, 'pk.new');
fireEvent.blur(input);
// Leave the field for real: fireEvent.blur keeps the focus on it, so the reset click
// would blur it a second time and race that save against the reset request
await user.tab();
expect(input).not.toHaveFocus();
await waitFor(() => expect(puts).toEqual([{ mapbox_access_token: 'pk.new' }]));
// Clicking the reset link also blurs the field again, so only the last PUT is checked
await user.click(resetLink('Shared Mapbox token'));
await waitFor(() => expect(puts[puts.length - 1]).toEqual({ mapbox_access_token: null }));
await waitFor(() => expect(puts).toEqual([{ mapbox_access_token: 'pk.new' }, { mapbox_access_token: null }]));
await waitFor(() => expect(screen.getByPlaceholderText('pk.eyJ…')).toHaveValue(''));
});
it('FE-ADMIN-DUS-032: a reset clicked while the save of the field is still out is the one that stays', async () => {
const user = userEvent.setup();
const { state } = stubDefaults({ map_provider: 'mapbox-gl', mapbox_access_token: 'pk.old' });
// The save is the slower request: sent at once, the reset would overtake it.
const done: string[] = [];
server.use(
http.put('/api/admin/default-user-settings', async ({ request }) => {
const body = await request.json() as Record<string, unknown>;
if (body.mapbox_access_token !== null) await delay(100);
if (body.mapbox_access_token === null) delete state.mapbox_access_token;
else state.mapbox_access_token = body.mapbox_access_token;
done.push(body.mapbox_access_token === null ? 'reset' : 'save');
return HttpResponse.json({ ...state });
}),
);
render(<DefaultUserSettingsTab />);
await screen.findByText('Shared Mapbox token');
const input = screen.getByPlaceholderText('pk.eyJ…');
await user.clear(input);
await user.type(input, 'pk.new');
// The click leaves the field, which saves it, and resets it right after.
await user.click(resetLink('Shared Mapbox token'));
await waitFor(() => expect(done).toEqual(['save', 'reset']));
expect(state.mapbox_access_token).toBeUndefined();
await waitFor(() => expect(screen.getByPlaceholderText('pk.eyJ…')).toHaveValue(''));
});
@@ -449,12 +480,14 @@ describe('DefaultUserSettingsTab', () => {
expect(input).toHaveValue('ck.old');
await user.clear(input);
await user.type(input, 'ck.new');
fireEvent.blur(input);
// Leave the field for real: fireEvent.blur keeps the focus on it, so the reset click
// would blur it a second time and race that save against the reset request
await user.tab();
expect(input).not.toHaveFocus();
await waitFor(() => expect(puts).toEqual([{ carto_api_key: 'ck.new' }]));
// Clicking the reset link also blurs the field again, so only the last PUT is checked
await user.click(resetLink('Shared CARTO key'));
await waitFor(() => expect(puts[puts.length - 1]).toEqual({ carto_api_key: null }));
await waitFor(() => expect(puts).toEqual([{ carto_api_key: 'ck.new' }, { carto_api_key: null }]));
await waitFor(() => expect(cartoInput()).toHaveValue(''));
});
@@ -11,6 +11,39 @@ import DevNotificationsPanel from './DevNotificationsPanel';
const ADMIN_USER = buildUser({ id: 1, username: 'testadmin', role: 'admin' });
/**
* Renders the panel and waits until both lookups (trips and users) have landed, so a test
* acts on the settled panel and no lookup answers after it has ended.
*/
async function renderSettled() {
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Trip-Scoped Events');
await screen.findByText('User-Scoped Events');
}
const LOOKUPS = ['/api/admin/users', '/api/trips'];
/**
* Records the GET requests to `paths` that have been answered, for the tests whose lookups
* come back empty or failed and so change nothing on screen to wait for. Call before render;
* the returned function waits until exactly `paths` (a path once per expected request) ended.
*/
function trackRequests(paths: string[] = LOOKUPS) {
const answered: string[] = [];
const onEnd = ({ request }: { request: Request }) => {
const { pathname } = new URL(request.url);
if (request.method === 'GET' && paths.includes(pathname)) answered.push(pathname);
};
server.events.on('request:end', onEnd);
return async () => {
try {
await waitFor(() => expect([...answered].sort()).toEqual([...paths].sort()));
} finally {
server.events.removeListener('request:end', onEnd);
}
};
}
beforeEach(() => {
resetAllStores();
seedStore(useAuthStore, { user: ADMIN_USER, isAuthenticated: true });
@@ -21,9 +54,12 @@ afterEach(() => {
});
describe('DevNotificationsPanel', () => {
it('FE-ADMIN-DEVNOTIF-001: "DEV ONLY" badge is always visible', () => {
it('FE-ADMIN-DEVNOTIF-001: "DEV ONLY" badge is always visible', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>);
expect(screen.getByText('DEV ONLY')).toBeInTheDocument();
// Let the lookups the panel started land here, not in the next test
await screen.findByText('Trip-Scoped Events');
await screen.findByText('User-Scoped Events');
});
it('FE-ADMIN-DEVNOTIF-002: four section titles render after data loads', async () => {
@@ -36,8 +72,7 @@ describe('DevNotificationsPanel', () => {
});
it('FE-ADMIN-DEVNOTIF-003: trip selector populated from API', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Trip-Scoped Events');
await renderSettled();
const [tripSelect] = screen.getAllByRole('combobox');
const options = Array.from(tripSelect.querySelectorAll('option'));
const labels = options.map(o => o.textContent);
@@ -46,8 +81,7 @@ describe('DevNotificationsPanel', () => {
});
it('FE-ADMIN-DEVNOTIF-004: user selector populated from API', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('User-Scoped Events');
await renderSettled();
const selects = screen.getAllByRole('combobox');
// Second combobox is the user selector (first is trip selector)
const userSelect = selects[1];
@@ -66,8 +100,7 @@ describe('DevNotificationsPanel', () => {
}),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
await user.click(screen.getByText('Simple → Me').closest('button')!);
await waitFor(() => expect(capturedBody).toBeDefined());
expect(capturedBody).toMatchObject({
@@ -75,6 +108,8 @@ describe('DevNotificationsPanel', () => {
scope: 'user',
targetId: ADMIN_USER.id,
});
// The send settles inside this test, so its toast cannot land in the next one
await screen.findByText('Sent: simple-me');
});
it('FE-ADMIN-DEVNOTIF-006: success toast shown after fire', async () => {
@@ -84,30 +119,34 @@ describe('DevNotificationsPanel', () => {
),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
await user.click(screen.getByText('Simple → Me').closest('button')!);
expect(await screen.findByText('Sent: simple-me')).toBeInTheDocument();
});
it('FE-ADMIN-DEVNOTIF-007: all buttons disabled while a send is in-flight', async () => {
// The send is held open until the assertion ran, then released, so it settles in this test
let release!: () => void;
const gate = new Promise<void>(resolve => { release = resolve; });
server.use(
http.post('/api/admin/dev/test-notification', async () => {
await new Promise(() => {}); // never resolves — simulates in-flight
await gate;
return HttpResponse.json({ ok: true });
}),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
// The request handler never resolves, so sending stays true after the click settles
// The request handler is held, so sending stays true after the click settles
await user.click(screen.getByText('Simple → Me').closest('button')!);
await waitFor(() => {
const buttons = screen.getAllByRole('button');
buttons.forEach(btn => expect(btn).toBeDisabled());
});
release();
await screen.findByText('Sent: simple-me');
});
it('FE-ADMIN-DEVNOTIF-008: the server error field is what the toast shows', async () => {
@@ -117,8 +156,7 @@ describe('DevNotificationsPanel', () => {
),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
await user.click(screen.getByText('Simple → Me').closest('button')!);
expect(await screen.findByText('No channel configured')).toBeInTheDocument();
});
@@ -130,8 +168,7 @@ describe('DevNotificationsPanel', () => {
),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
await user.click(screen.getByText('Simple → Me').closest('button')!);
expect(await screen.findByText('Failed')).toBeInTheDocument();
});
@@ -145,8 +182,7 @@ describe('DevNotificationsPanel', () => {
}),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Trip-Scoped Events');
await renderSettled();
const [tripSelect] = screen.getAllByRole('combobox');
const tokyoOption = Array.from(tripSelect.querySelectorAll('option')).find(
@@ -159,15 +195,19 @@ describe('DevNotificationsPanel', () => {
await waitFor(() => expect(capturedBody).toBeDefined());
expect(capturedBody!.targetId).toBe(tokyoId);
// The send settles inside this test, so its toast cannot land in the next one
await screen.findByText('Sent: booking_change');
});
it('FE-ADMIN-DEVNOTIF-010: Trip-Scoped section absent when no trips', async () => {
server.use(
http.get('/api/trips', () => HttpResponse.json({ trips: [] })),
);
const lookupsAnswered = trackRequests();
render(<><ToastContainer /><DevNotificationsPanel /></>);
// Wait for user data to confirm async effects have settled
await screen.findByText('User-Scoped Events');
await lookupsAnswered();
expect(screen.queryByText('Trip-Scoped Events')).not.toBeInTheDocument();
});
@@ -180,8 +220,7 @@ describe('DevNotificationsPanel', () => {
}),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
await user.click(screen.getByText('Boolean → Me').closest('button')!);
await screen.findByText('Sent: boolean-me');
@@ -216,8 +255,7 @@ describe('DevNotificationsPanel', () => {
}),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Trip-Scoped Events');
await renderSettled();
const [tripSelect] = screen.getAllByRole('combobox');
const tripId = Number((tripSelect as HTMLSelectElement).value);
@@ -247,8 +285,7 @@ describe('DevNotificationsPanel', () => {
}),
);
const user = userEvent.setup();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('User-Scoped Events');
await renderSettled();
const userSelect = screen.getAllByRole('combobox')[1] as HTMLSelectElement;
const aliceOption = Array.from(userSelect.querySelectorAll('option')).find(
@@ -278,9 +315,11 @@ describe('DevNotificationsPanel', () => {
it('FE-ADMIN-DEVNOTIF-014: the User-Scoped section is hidden when no users come back', async () => {
server.use(http.get('/api/admin/users', () => HttpResponse.json({ users: [] })));
const lookupsAnswered = trackRequests();
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Trip-Scoped Events');
await lookupsAnswered();
expect(screen.queryByText('User-Scoped Events')).not.toBeInTheDocument();
});
@@ -288,22 +327,38 @@ describe('DevNotificationsPanel', () => {
server.use(
http.get('/api/trips', () => HttpResponse.error()),
http.get('/api/admin/users', () => HttpResponse.error()),
// A network error makes the API client probe /api/health before it rejects; the server
// is down here, so the probe fails too instead of going out to the real network
http.get('/api/health', () => HttpResponse.error()),
);
const lookupsAnswered = trackRequests([...LOOKUPS, '/api/health', '/api/health']);
render(<><ToastContainer /><DevNotificationsPanel /></>);
expect(await screen.findByText('Type Testing')).toBeInTheDocument();
await lookupsAnswered();
await waitFor(() => expect(screen.queryByText('Trip-Scoped Events')).not.toBeInTheDocument());
expect(screen.queryByText('User-Scoped Events')).not.toBeInTheDocument();
expect(screen.getByText('Admin-Scoped Events')).toBeInTheDocument();
});
it('FE-ADMIN-DEVNOTIF-016: a trigger takes its hover background from CSS, not inline styles', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>);
await screen.findByText('Type Testing');
await renderSettled();
const btn = screen.getByText('Simple → Me').closest('button')!;
fireEvent.mouseEnter(btn);
expect(btn.style.background).toBe('');
expect(btn.className).toContain('hover:bg-surface-secondary');
});
it('FE-ADMIN-DEVNOTIF-017: a send button stays the same element while the panel updates around it', async () => {
render(<><ToastContainer /><DevNotificationsPanel /></>);
const btn = screen.getByRole('button', { name: /Simple → Me/ });
// The lookups answer and re-render the panel.
await screen.findByText('Trip-Scoped Events');
await screen.findByText('User-Scoped Events');
expect(btn.isConnected).toBe(true);
expect(screen.getByRole('button', { name: /Simple → Me/ })).toBe(btn);
});
});
@@ -25,20 +25,17 @@ function ButtonGrid({ children }: { children: React.ReactNode }): React.ReactEle
return <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">{children}</div>
}
export default function DevNotificationsPanel(): React.ReactElement {
const ids = useId()
const {
sending, trips, selectedTripId, setSelectedTripId, users, selectedUserId, setSelectedUserId,
tripInviteId, vacayInviteId, send,
} = useDevNotifications()
// ── Helpers ──────────────────────────────────────────────────────────────
const Btn = ({
id, label, sub, icon: Icon, onClick,
}: {
id: string; label: string; sub: string; icon: React.ElementType; onClick: () => void
}) => (
/**
* One send button. Declared here, not inside the panel: a component made during
* render is a new type on every render, so React would remount every button on
* each state change and a click could land on one that is already gone.
*/
function Btn({
id, label, sub, icon: Icon, onClick, sending,
}: {
id: string; label: string; sub: string; icon: React.ElementType; onClick: () => void; sending: string | null
}): React.ReactElement {
return (
<button type="button"
onClick={onClick}
disabled={sending !== null}
@@ -54,6 +51,14 @@ export default function DevNotificationsPanel(): React.ReactElement {
{sending === id && <Loader2 size={15} className="flex-none animate-spin text-content-faint" />}
</button>
)
}
export default function DevNotificationsPanel(): React.ReactElement {
const ids = useId()
const {
sending, trips, selectedTripId, setSelectedTripId, users, selectedUserId, setSelectedUserId,
tripInviteId, vacayInviteId, send,
} = useDevNotifications()
return (
<div>
@@ -66,16 +71,16 @@ export default function DevNotificationsPanel(): React.ReactElement {
badge={<StatusPill tone="warning">DEV ONLY</StatusPill>}
>
<ButtonGrid>
<Btn id="simple-me" label="Simple → Me" sub="test_simple · user" icon={Bell}
<Btn sending={sending} id="simple-me" label="Simple → Me" sub="test_simple · user" icon={Bell}
onClick={send.simpleMe}
/>
<Btn id="boolean-me" label="Boolean → Me" sub="test_boolean · user" icon={CheckCircle}
<Btn sending={sending} id="boolean-me" label="Boolean → Me" sub="test_boolean · user" icon={CheckCircle}
onClick={send.booleanMe}
/>
<Btn id="navigate-me" label="Navigate → Me" sub="test_navigate · user" icon={Navigation}
<Btn sending={sending} id="navigate-me" label="Navigate → Me" sub="test_navigate · user" icon={Navigation}
onClick={send.navigateMe}
/>
<Btn id="simple-admins" label="Simple → All Admins" sub="test_simple · admin" icon={Zap}
<Btn sending={sending} id="simple-admins" label="Simple → All Admins" sub="test_simple · admin" icon={Zap}
onClick={send.simpleAdmins}
/>
</ButtonGrid>
@@ -94,19 +99,19 @@ export default function DevNotificationsPanel(): React.ReactElement {
</SelectBox>
</EditorField>
<ButtonGrid>
<Btn id="booking_change" label="booking_change" sub="navigate · trip" icon={Calendar}
<Btn sending={sending} id="booking_change" label="booking_change" sub="navigate · trip" icon={Calendar}
onClick={send.bookingChange}
/>
<Btn id="trip_reminder" label="trip_reminder" sub="navigate · trip" icon={Clock}
<Btn sending={sending} id="trip_reminder" label="trip_reminder" sub="navigate · trip" icon={Clock}
onClick={send.tripReminder}
/>
<Btn id="photos_shared" label="photos_shared" sub="navigate · trip" icon={Image}
<Btn sending={sending} id="photos_shared" label="photos_shared" sub="navigate · trip" icon={Image}
onClick={send.photosShared}
/>
<Btn id="collab_message" label="collab_message" sub="navigate · trip" icon={MessageSquare}
<Btn sending={sending} id="collab_message" label="collab_message" sub="navigate · trip" icon={MessageSquare}
onClick={send.collabMessage}
/>
<Btn id="packing_tagged" label="packing_tagged" sub="navigate · trip" icon={Tag}
<Btn sending={sending} id="packing_tagged" label="packing_tagged" sub="navigate · trip" icon={Tag}
onClick={send.packingTagged}
/>
</ButtonGrid>
@@ -127,6 +132,7 @@ export default function DevNotificationsPanel(): React.ReactElement {
</EditorField>
<ButtonGrid>
<Btn
sending={sending}
id={tripInviteId}
label="trip_invite"
sub="navigate · user"
@@ -134,6 +140,7 @@ export default function DevNotificationsPanel(): React.ReactElement {
onClick={send.tripInvite}
/>
<Btn
sending={sending}
id={vacayInviteId}
label="vacay_invite"
sub="navigate · user"
@@ -147,7 +154,7 @@ export default function DevNotificationsPanel(): React.ReactElement {
{/* ── Admin-Scoped Events ──────────────────────────────────────────── */}
<SettingsCard icon={ShieldCheck} title="Admin-Scoped Events" hint="Fires to all admin users.">
<ButtonGrid>
<Btn id="version_available" label="version_available" sub="navigate · admin" icon={Download}
<Btn sending={sending} id="version_available" label="version_available" sub="navigate · admin" icon={Download}
onClick={send.versionAvailable}
/>
</ButtonGrid>
@@ -137,19 +137,25 @@ describe('useDefaultUserSettings', () => {
act(() => result.current.pickTilePreset(''));
act(() => result.current.pickStylePreset(''));
// Writes go out in order, a microtask later: let any that was queued start first.
await act(async () => {});
expect(update).not.toHaveBeenCalled();
act(() => result.current.pickTilePreset('https://tile.openstreetmap.de/{z}/{x}/{y}.png'));
expect(result.current.mapTileUrl).toBe('https://tile.openstreetmap.de/{z}/{x}/{y}.png');
expect(update).toHaveBeenLastCalledWith({ map_tile_url: 'https://tile.openstreetmap.de/{z}/{x}/{y}.png' });
await waitFor(() =>
expect(update).toHaveBeenLastCalledWith({ map_tile_url: 'https://tile.openstreetmap.de/{z}/{x}/{y}.png' })
);
act(() => result.current.pickStylePreset('https://tiles.openfreemap.org/styles/positron'));
expect(update).toHaveBeenLastCalledWith({ maplibre_style: 'https://tiles.openfreemap.org/styles/positron' });
await waitFor(() =>
expect(update).toHaveBeenLastCalledWith({ maplibre_style: 'https://tiles.openfreemap.org/styles/positron' })
);
act(() => result.current.setMapboxStyle('mapbox://styles/not-for-maplibre'));
act(() => result.current.commitStyle());
expect(result.current.mapboxStyle).toBe(OPENFREEMAP_DEFAULT_STYLE);
expect(update).toHaveBeenLastCalledWith({ maplibre_style: OPENFREEMAP_DEFAULT_STYLE });
await waitFor(() => expect(update).toHaveBeenLastCalledWith({ maplibre_style: OPENFREEMAP_DEFAULT_STYLE }));
await waitFor(() => expect(toast.success).toHaveBeenCalledTimes(3));
});
});
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react';
import { adminApi } from '../../api/client';
import { useWritesInOrder } from '../../hooks/useWritesInOrder';
import { useTranslation } from '../../i18n';
import { useAuthStore } from '../../store/authStore';
import { useSettingsStore } from '../../store/settingsStore';
@@ -87,32 +88,38 @@ export function useDefaultUserSettings({ errorMessage, previewCreatedAt }: Defau
.catch(() => setLoaded(true));
}, []);
const save = async (patch: Partial<Defaults>) => {
try {
const updated = await adminApi.updateDefaultUserSettings(patch as Record<string, unknown>);
setDefaults(updated);
toast.success(t('admin.defaultSettings.saved'));
} catch (err: unknown) {
toast.error(errorMessage(err, t('common.error')));
}
};
// A field's save on blur and the reset clicked right after it reach the server in
// that order, or the save landing last would store the old value again.
const inOrder = useWritesInOrder();
const reset = async (key: keyof Defaults) => {
try {
const updated = await adminApi.updateDefaultUserSettings({ [key]: null });
setDefaults(updated);
if (key === 'map_tile_url') setMapTileUrl('');
if (key === 'mapbox_access_token') setMapboxToken('');
if (key === 'carto_api_key') setCartoKey('');
if (key === 'mapbox_style' || key === 'maplibre_style') {
const provider = normalizeProvider(defaults.map_provider);
setMapboxStyle(provider === 'leaflet' ? '' : defaultStyleForProvider(provider));
const save = (patch: Partial<Defaults>) =>
inOrder(async () => {
try {
const updated = await adminApi.updateDefaultUserSettings(patch as Record<string, unknown>);
setDefaults(updated);
toast.success(t('admin.defaultSettings.saved'));
} catch (err: unknown) {
toast.error(errorMessage(err, t('common.error')));
}
toast.success(t('admin.defaultSettings.reset'));
} catch (err: unknown) {
toast.error(errorMessage(err, t('common.error')));
}
};
});
const reset = (key: keyof Defaults) =>
inOrder(async () => {
try {
const updated = await adminApi.updateDefaultUserSettings({ [key]: null });
setDefaults(updated);
if (key === 'map_tile_url') setMapTileUrl('');
if (key === 'mapbox_access_token') setMapboxToken('');
if (key === 'carto_api_key') setCartoKey('');
if (key === 'mapbox_style' || key === 'maplibre_style') {
const provider = normalizeProvider(defaults.map_provider);
setMapboxStyle(provider === 'leaflet' ? '' : defaultStyleForProvider(provider));
}
toast.success(t('admin.defaultSettings.reset'));
} catch (err: unknown) {
toast.error(errorMessage(err, t('common.error')));
}
});
const isSet = (key: keyof Defaults) => defaults[key] !== undefined;
@@ -111,11 +111,23 @@ export const CHATGPT_USAGE_URL = 'https://chatgpt.com/settings/usage';
* error page and the user pastes its address back; only the port may differ.
*/
export function isChatgptCallback(text: string): boolean {
return chatgptCallbackUrl(text) !== null;
}
/**
* The pasted callback as the server reads it, or null when it is something
* else. The address bar and the hint under the field show it without `http://`,
* so an address pasted that way gets the scheme put back.
*/
export function chatgptCallbackUrl(text: string): string | null {
const trimmed = text.trim();
const address = /^[a-z][a-z\d+.-]*:\/\//i.test(trimmed) ? trimmed : `http://${trimmed}`;
let url: URL;
try {
url = new URL(text.trim());
url = new URL(address);
} catch {
return false;
return null;
}
return url.protocol === 'http:' && url.hostname === '127.0.0.1' && url.pathname === '/auth/callback';
const ok = url.protocol === 'http:' && url.hostname === '127.0.0.1' && url.pathname === '/auth/callback';
return ok ? address : null;
}
@@ -40,7 +40,7 @@ beforeEach(() => {
describe('BackgroundTasksWidget', () => {
it('shows the warnings when a finished job produced no items', () => {
const warning = 'voucher.pdf: AI parsing failed — LLM request failed (400): response_format unsupported'
const warning = 'voucher.pdf: AI parsing failed: LLM request failed (400): response_format unsupported'
useBackgroundTasksStore.setState({ tasks: [task({ warnings: [warning] })] })
render(<BackgroundTasksWidget />)
expect(screen.getByText('No reservations could be extracted from the uploaded files.')).toBeInTheDocument()
@@ -141,7 +141,7 @@ describe('BackgroundTasksWidget', () => {
* disappeared on save.
*/
it('shows the warnings on a job that did produce items', () => {
const warning = 'voucher.pdf: could not locate "Curbside Pickup Counter 7" — set it manually before saving'
const warning = 'voucher.pdf: could not locate "Curbside Pickup Counter 7", set it manually before saving'
useBackgroundTasksStore.setState({
tasks: [task({ items: [{ id: 1 } as never], warnings: [warning] })],
})
@@ -339,6 +339,8 @@ describe('CollectionPlaceDetail', () => {
address: 'Somewhere',
lat: 52.5,
lng: 13.4,
// No notes on this place, and none written (#3168).
notes: null,
});
// Back in read mode.
expect(await screen.findByRole('button', { name: 'Edit' })).toBeInTheDocument();
@@ -32,7 +32,7 @@ interface CollectionPlaceDetailProps {
anchorRect?: { left: number; width: number } | null
onClose: () => void
onSetStatus: (status: CollectionStatus) => void
onSave: (patch: { name?: string; description?: string | null; links?: CollectionLink[]; category_id?: number | null; label_ids?: number[]; image_url?: string | null; lat?: number | null; lng?: number | null; address?: string | null }) => Promise<void>
onSave: (patch: { name?: string; description?: string | null; notes?: string | null; links?: CollectionLink[]; category_id?: number | null; label_ids?: number[]; image_url?: string | null; lat?: number | null; lng?: number | null; address?: string | null }) => Promise<void>
/** Upload a custom cover image (#1136); enables the cover change/remove controls. */
onUploadImage?: (file: File) => Promise<void>
onCopyToTrip: () => void
@@ -74,7 +74,7 @@ export default function CollectionPlaceDetail({
const navigationTargets = getNavigationTargets(place)
const descRef = useRef<HTMLTextAreaElement>(null)
const {
editing, setEditing, name, setName, categoryId, setCategoryId, description, setDescription, links, setLinks, setLink,
editing, setEditing, name, setName, categoryId, setCategoryId, description, setDescription, notes, setNotes, links, setLinks, setLink,
labelIds, toggleLabel, address, setAddress, lat, setLat, lng, setLng, saving, imgBusy, cover: banner, assignedLabels,
handleImagePick: handleCoverPick, handleImageRemove, cancelEdit: resetForm, save,
} = useCollectionPlaceForm({ place, labels, onSave, onUploadImage, t, normalizeLinkUrl, withCoordinates: true })
@@ -226,6 +226,11 @@ export default function CollectionPlaceDetail({
<MarkdownToolbar textareaRef={descRef} onUpdate={setDescription} />
<textarea ref={descRef} value={description} onChange={e => setDescription(e.target.value)} rows={4} placeholder={t('collections.descriptionPlaceholder')} className="col-detail-textarea" />
</div>
{/* Notes: the traveller's own, apart from the description (#3168) */}
<div className="col-detail-field">
<div className="col-detail-label">{t('collections.notes')}</div>
<textarea value={notes} onChange={e => setNotes(e.target.value)} rows={3} placeholder={t('collections.notesPlaceholder')} className="col-detail-textarea" />
</div>
{/* Links */}
<div className="col-detail-field">
<div className="col-detail-label">{t('collections.links')}</div>
@@ -248,6 +253,12 @@ export default function CollectionPlaceDetail({
<Markdown remarkPlugins={[remarkGfm, remarkBreaks]} components={markdownLinkComponents}>{place.description}</Markdown>
</div>
)}
{place.notes?.trim() && (
<div className="col-detail-field">
<div className="col-detail-label">{t('collections.notes')}</div>
<p className="m-0 whitespace-pre-wrap text-body text-content-muted [overflow-wrap:anywhere]">{place.notes}</p>
</div>
)}
{place.links && place.links.length > 0 && (
<div className="col-detail-links">
{place.links.map((l, i) => (
@@ -176,6 +176,7 @@ describe('useCollectionPlaceForm', () => {
expect(detail.props.onSave).toHaveBeenCalledWith({
name: 'Louvre',
description: 'Museum',
notes: null,
links: [{ label: 'Map', url: 'https://maps.example' }],
category_id: 3,
label_ids: [11],
@@ -192,6 +193,7 @@ describe('useCollectionPlaceForm', () => {
expect(sheet.props.onSave).toHaveBeenCalledWith({
name: 'Louvre',
description: 'Museum',
notes: null,
links: [{ label: 'Site', url: 'https://louvre.example' }],
category_id: 3,
label_ids: [10],
@@ -199,6 +201,25 @@ describe('useCollectionPlaceForm', () => {
});
});
it('FE-COMP-COLPLACEHOOK-014: seeds, edits and saves the own notes on a saved place (#3168)', async () => {
const sheet = setup({ place: place({ notes: 'Book a week ahead' }) });
expect(sheet.result.current.notes).toBe('Book a week ahead');
act(() => {
sheet.result.current.setEditing(true);
sheet.result.current.setNotes(' Closed on Tuesdays ');
});
await act(async () => {
await sheet.result.current.save();
});
expect(sheet.props.onSave).toHaveBeenCalledWith(expect.objectContaining({ notes: 'Closed on Tuesdays' }));
act(() => sheet.result.current.setNotes(' '));
await act(async () => {
await sheet.result.current.save();
});
expect(sheet.props.onSave).toHaveBeenLastCalledWith(expect.objectContaining({ notes: null }));
});
it('FE-COMP-COLPLACEHOOK-010: a failed save stays in edit mode and toasts', async () => {
const onSave = vi.fn().mockRejectedValue({ response: { data: { error: 'Locked' } } });
const { result } = setup({ onSave });
@@ -12,6 +12,7 @@ import { cleanListLinks } from './useListEditor';
export interface CollectionPlacePatch {
name?: string;
description?: string | null;
notes?: string | null;
links?: CollectionLink[];
category_id?: number | null;
label_ids?: number[];
@@ -84,6 +85,8 @@ export function useCollectionPlaceForm({
const [name, setName] = useState(shown?.name ?? '');
const [categoryId, setCategoryId] = useState<number | null>(shown?.category_id ?? null);
const [description, setDescription] = useState(shown?.description ?? '');
// The traveller's own notes on the place (#3168), apart from its description.
const [notes, setNotes] = useState(shown?.notes ?? '');
const [links, setLinks] = useState<CollectionLink[]>(shown?.links ?? []);
const [labelIds, setLabelIds] = useState<number[]>(shown?.label_ids ?? []);
const [address, setAddress] = useState(shown?.address ?? '');
@@ -101,6 +104,7 @@ export function useCollectionPlaceForm({
setName(p.name);
setCategoryId(p.category_id ?? null);
setDescription(p.description ?? '');
setNotes(p.notes ?? '');
setLinks(p.links ?? []);
setLabelIds(p.label_ids ?? []);
setAddress(p.address ?? '');
@@ -189,6 +193,7 @@ export function useCollectionPlaceForm({
const base = {
name: name.trim() || shown.name,
description: description.trim() || null,
notes: notes.trim() || null,
links: cleanListLinks(links, normalizeLinkUrl),
category_id: categoryId,
label_ids: labelIds,
@@ -215,6 +220,8 @@ export function useCollectionPlaceForm({
setCategoryId,
description,
setDescription,
notes,
setNotes,
links,
setLinks,
setLink,
@@ -526,6 +526,24 @@ describe('FileManager', () => {
});
});
it('FE-COMP-FILEMANAGER-039: a file pasted while the drop zone has focus is uploaded once', async () => {
const onUpload = vi.fn().mockResolvedValue({ file: { id: 56 } });
render(<FileManager {...defaultProps} onUpload={onUpload} />);
const zone = document.querySelector('[role="presentation"]') as HTMLElement;
const file = new File(['data'], 'pasted.png', { type: 'image/png' });
const pasteEvent = new Event('paste', { bubbles: true, cancelable: true });
Object.defineProperty(pasteEvent, 'clipboardData', {
value: { types: ['Files'], files: [file], items: [{ kind: 'file', type: 'image/png', getAsFile: () => file }] },
});
await fireEvent(zone, pasteEvent);
await waitFor(() => expect(onUpload).toHaveBeenCalled());
await new Promise((resolve) => setTimeout(resolve, 50));
expect(onUpload).toHaveBeenCalledTimes(1);
});
it('FE-COMP-FILEMANAGER-028: upload with places open assign modal after upload', async () => {
const { buildPlace } = await import('../../../tests/helpers/factories');
const place = buildPlace({ id: 10, name: 'Sagrada Familia' });
@@ -124,7 +124,9 @@ export function useFileManager({ files = [], onUpload, onDelete, onUpdate, place
toast.error(t('files.uploadErrorSize', { max: maxUploadMb }))
}
},
noClick: false,
// Pasting is handled once for the whole panel (handlePaste), with the upload
// permission check; the zone's own paste upload would send each file twice.
noPaste: true,
})
const handlePaste = useCallback((e: React.ClipboardEvent) => {
@@ -1,4 +1,4 @@
// FE-COMP-LIGHTBOX-001 to FE-COMP-LIGHTBOX-029
// FE-COMP-LIGHTBOX-001 to FE-COMP-LIGHTBOX-030
// Plyr needs a real media pipeline, so the player is stubbed here.
vi.mock('./VideoPlayer', () => ({
@@ -87,9 +87,9 @@ describe('PhotoLightbox', () => {
it('FE-COMP-LIGHTBOX-007: does not render when photos array is empty', () => {
const onClose = vi.fn();
const { container } = render(<PhotoLightbox photos={[]} onClose={onClose} />);
render(<PhotoLightbox photos={[]} onClose={onClose} />);
// Component returns null when photo is undefined (empty array, index 0 is undefined)
expect(container.querySelector('img')).not.toBeInTheDocument();
expect(document.querySelector('img')).not.toBeInTheDocument();
});
it('FE-COMP-LIGHTBOX-008: calls onClose when close button clicked', () => {
@@ -100,10 +100,10 @@ describe('PhotoLightbox', () => {
});
it('FE-COMP-LIGHTBOX-009: opens at the requested start index', () => {
const { container } = render(<PhotoLightbox photos={samplePhotos} startIndex={2} onClose={vi.fn()} />);
render(<PhotoLightbox photos={samplePhotos} startIndex={2} onClose={vi.fn()} />);
expect(screen.getByText('3 / 3')).toBeInTheDocument();
// The third photo has no caption, so its img is presentational.
expect(container.querySelector('img')).toHaveAttribute('src', '/photos/3.jpg');
expect(document.querySelector('img')).toHaveAttribute('src', '/photos/3.jpg');
});
it('FE-COMP-LIGHTBOX-010: only offers the arrows that lead somewhere', () => {
@@ -162,8 +162,8 @@ describe('PhotoLightbox', () => {
});
it('FE-COMP-LIGHTBOX-015: swipes horizontally to move between photos', () => {
const { container } = render(<PhotoLightbox photos={samplePhotos} startIndex={1} onClose={vi.fn()} />);
const surface = container.firstElementChild as HTMLElement;
render(<PhotoLightbox photos={samplePhotos} startIndex={1} onClose={vi.fn()} />);
const surface = screen.getByRole('dialog');
fireEvent.touchStart(surface, { touches: [{ clientX: 200, clientY: 200 }] });
fireEvent.touchEnd(surface, { changedTouches: [{ clientX: 100, clientY: 210 }] });
@@ -176,8 +176,8 @@ describe('PhotoLightbox', () => {
it('FE-COMP-LIGHTBOX-016: swipes down to close', () => {
const onClose = vi.fn();
const { container } = render(<PhotoLightbox photos={samplePhotos} onClose={onClose} />);
const surface = container.firstElementChild as HTMLElement;
render(<PhotoLightbox photos={samplePhotos} onClose={onClose} />);
const surface = screen.getByRole('dialog');
fireEvent.touchStart(surface, { touches: [{ clientX: 200, clientY: 100 }] });
fireEvent.touchEnd(surface, { changedTouches: [{ clientX: 210, clientY: 300 }] });
@@ -187,8 +187,8 @@ describe('PhotoLightbox', () => {
it('FE-COMP-LIGHTBOX-017: ignores a touch end without a matching touch start', () => {
const onClose = vi.fn();
const { container } = render(<PhotoLightbox photos={samplePhotos} onClose={onClose} />);
const surface = container.firstElementChild as HTMLElement;
render(<PhotoLightbox photos={samplePhotos} onClose={onClose} />);
const surface = screen.getByRole('dialog');
fireEvent.touchEnd(surface, { changedTouches: [{ clientX: 210, clientY: 300 }] });
@@ -294,8 +294,8 @@ describe('PhotoLightbox', () => {
});
it('FE-COMP-LIGHTBOX-026: a swipe to the right turns to the next photo', () => {
const { container } = render(<PhotoLightbox photos={samplePhotos} startIndex={1} onClose={vi.fn()} />);
const surface = container.firstElementChild as HTMLElement;
render(<PhotoLightbox photos={samplePhotos} startIndex={1} onClose={vi.fn()} />);
const surface = screen.getByRole('dialog');
fireEvent.touchStart(surface, { touches: [{ clientX: 100, clientY: 200 }] });
fireEvent.touchEnd(surface, { changedTouches: [{ clientX: 200, clientY: 210 }] });
@@ -305,6 +305,13 @@ describe('PhotoLightbox', () => {
fireEvent.touchEnd(surface, { changedTouches: [{ clientX: 100, clientY: 210 }] });
expect(screen.getByText('2 / 3')).toBeInTheDocument();
});
it('FE-COMP-LIGHTBOX-030: the left inset of the screen stays on the left, where the close button now sits', () => {
render(<PhotoLightbox photos={samplePhotos} onClose={vi.fn()} />);
const style = screen.getByRole('dialog').style;
expect(style.paddingInlineEnd).toContain('safe-area-inset-left');
expect(style.paddingInlineStart).toContain('safe-area-inset-right');
});
});
it('FE-COMP-LIGHTBOX-027: a caption with a source page links to it in a new tab, one without stays text', () => {
+51 -27
View File
@@ -1,9 +1,11 @@
import { useState, useEffect, useCallback, useRef } from 'react'
import { createPortal } from 'react-dom'
import { ChevronLeft, ChevronRight, Loader2, X, ZoomIn, ZoomOut } from 'lucide-react'
import VideoPlayer from './VideoPlayerLazy'
import { usePhotoZoom } from './usePhotoZoom'
import { Tooltip } from '../shared/Tooltip'
import { isRtlLanguage, useTranslation } from '../../i18n'
import { lockBodyScroll } from '../../utils/bodyScrollLock'
interface LightboxPhoto {
id: string
@@ -34,10 +36,22 @@ interface Props {
/** The round glass buttons of the top bar. */
const ROUND_BTN: React.CSSProperties = {
background: 'rgba(255,255,255,0.1)', border: 'none', borderRadius: '50%',
width: 36, height: 36, display: 'flex', alignItems: 'center', justifyContent: 'center',
color: '#fff', cursor: 'pointer',
width: 40, height: 40, display: 'flex', alignItems: 'center', justifyContent: 'center',
color: '#fff', cursor: 'pointer', flex: 'none',
}
/** Close is the one every visitor needs: a little stronger than the rest. */
const CLOSE_BTN: React.CSSProperties = { ...ROUND_BTN, background: 'rgba(255,255,255,0.18)' }
/**
* The device's insets, from whichever source reports them: env() in a browser,
* the values Capacitor's SystemBars writes on Android, the ones the iOS app
* measures itself. The viewer is portalled to <body>, outside the phone shell
* that defines its own --m-safe-* tokens, so it reads the sources directly.
*/
const SAFE = (side: 'top' | 'bottom' | 'left' | 'right') =>
`max(env(safe-area-inset-${side}, 0px), var(--safe-area-inset-${side}, 0px), var(--trek-native-safe-${side}, 0px))`
export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }: Props) {
const [idx, setIdx] = useState(startIndex)
const touchStart = useRef<{ x: number; y: number } | null>(null)
@@ -51,7 +65,11 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
useEffect(() => {
const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null
dialogRef.current?.focus()
return () => opener?.focus()
const unlock = lockBodyScroll()
return () => {
unlock()
opener?.focus()
}
}, [])
const photo = photos[idx]
@@ -111,7 +129,9 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
if (!photo) return null
return (
// Portalled to <body>: inside a transformed sheet or pane, `fixed` would be
// relative to that box and the viewer would open as a small window in it.
return createPortal(
<div
ref={dialogRef}
role="dialog"
@@ -120,26 +140,28 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
tabIndex={-1}
style={{
outline: 'none',
position: 'fixed', inset: 0, zIndex: 10000,
position: 'fixed', inset: 0, zIndex: 'var(--z-modal)',
background: 'rgba(0,0,0,0.92)', backdropFilter: 'blur(20px)',
display: 'flex', flexDirection: 'column',
paddingBottom: 'var(--bottom-nav-h)',
paddingBottom: SAFE('bottom'),
// The insets belong to the screen's sides, which right to left swaps.
paddingInlineStart: SAFE(rtl ? 'right' : 'left'),
paddingInlineEnd: SAFE(rtl ? 'left' : 'right'),
}}
onTouchStart={onTouchStart}
onTouchMove={onTouchMove}
onTouchEnd={onTouchEnd}
>
{/* Photo area — centered with nav overlays */}
<div
className="group/lightbox"
style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative', overflow: 'hidden' }}
>
{/* Top bar */}
<div style={{ position: 'absolute', top: 0, insetInline: 0, zIndex: 10, display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 20px' }}>
<span style={{ color: 'rgba(255,255,255,0.5)', fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 500 }}>
{idx + 1} / {photos.length}
</span>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
{/* Top bar: its own row below the status bar and a notch, so the close
button is always there to tap and never sits over the photo. */}
<div style={{
flex: 'none', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12,
paddingBlock: `calc(${SAFE('top')} + 10px) 10px`, paddingInline: 16,
}}>
<span style={{ color: 'rgba(255,255,255,0.5)', fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 500, fontVariantNumeric: 'tabular-nums' }}>
{idx + 1} / {photos.length}
</span>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
{isImage && (
<>
<Tooltip label={t('journey.lightbox.zoomOut')}>
@@ -162,16 +184,17 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
</Tooltip>
</>
)}
<button type="button" onClick={onClose} aria-label={t('common.close')} style={{
background: 'rgba(255,255,255,0.1)', border: 'none', borderRadius: '50%',
width: 36, height: 36, display: 'flex', alignItems: 'center', justifyContent: 'center',
color: '#fff', cursor: 'pointer',
}}>
<X size={18} />
<button type="button" onClick={onClose} aria-label={t('common.close')} style={CLOSE_BTN}>
<X size={20} />
</button>
</div>
</div>
</div>
{/* Photo area: what is left below the bar, with the page arrows over it. */}
<div
className="group/lightbox"
style={{ flex: 1, minHeight: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative', overflow: 'hidden', padding: '0 8px 8px' }}
>
{/* Prev button — visible on hover (desktop), always visible (mobile) */}
{hasPrev && (
<button type="button" onClick={prev} aria-label={t('journey.lightbox.previous')} className="flex sm:opacity-0 sm:group-hover/lightbox:opacity-100 focus-visible:opacity-100 transition-opacity" style={{
@@ -200,7 +223,7 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
onError={() => setLoadedId(photo.id)}
{...zoom.mouse}
style={{
maxWidth: '92vw', maxHeight: '92vh',
maxWidth: '100%', maxHeight: '100%',
objectFit: 'contain', borderRadius: 4,
animation: 'fadeIn 0.15s ease',
userSelect: 'none',
@@ -212,7 +235,7 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
{loading && (
<div data-testid="lightbox-loading" aria-hidden="true" style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', pointerEvents: 'none' }}>
{photo.thumbSrc && (
<img src={photo.thumbSrc} alt="" draggable={false} style={{ width: '92vw', height: '92vh', objectFit: 'contain', borderRadius: 4 }} />
<img src={photo.thumbSrc} alt="" draggable={false} style={{ width: '100%', height: '100%', objectFit: 'contain', borderRadius: 4 }} />
)}
<span style={{ ...ROUND_BTN, position: 'absolute', cursor: 'default' }}>
<Loader2 size={18} className="animate-spin" />
@@ -252,6 +275,7 @@ export default function PhotoLightbox({ photos, startIndex = 0, onClose, label }
</div>
)}
</div>
</div>
</div>,
document.body,
)
}
+2 -2
View File
@@ -544,9 +544,9 @@ describe('Navbar styling and menu details', () => {
const discord = screen.getByTitle('Discord');
fireEvent.mouseEnter(discord);
expect(discord.style.background).toBe('rgba(88, 101, 242, 0.125)');
expect(discord.style.background).toBe('rgba(88, 101, 242, 0.15)');
fireEvent.mouseLeave(discord);
expect(discord.style.background).toBe('var(--bg-tertiary)');
expect(discord.style.background).toBe('');
expect(document.querySelector('img[src="/text-light.svg"]')).not.toBeNull();
});
+3 -18
View File
@@ -17,6 +17,7 @@ import { useCollapseOnOverflow } from '../../hooks/useCollapseOnOverflow'
import { openMailInbox } from '../MailIngest/mailInboxOpener'
import { useMailInboxShell } from '../MailIngest/useMailInboxShell'
import MailInboxDialog from '../MailIngest/MailInboxDialog'
import UserMenuFooter from './UserMenuFooter'
const ADDON_ICONS: Record<string, LucideIcon> = { CalendarDays, Briefcase, Globe, Compass, Bookmark }
@@ -311,7 +312,7 @@ export default function Navbar({ tripTitle, tripId, onBack, showBack, onSettings
{userMenuOpen && createPortal(
<>
<div style={{ position: 'fixed', inset: 0, zIndex: 9998 }} role="presentation" onClick={() => setUserMenuOpen(false)} />
<div className="trek-menu-enter w-52 rounded-xl shadow-xl border overflow-hidden bg-surface-card border-edge" style={{ position: 'fixed', top: 'var(--nav-h)', insetInlineEnd: 8, zIndex: 9999 }}>
<div className="trek-menu-enter w-60 rounded-xl shadow-xl border overflow-hidden bg-surface-card border-edge" style={{ position: 'fixed', top: 'var(--nav-h)', insetInlineEnd: 8, zIndex: 9999 }}>
<div className="px-4 py-3 border-b border-edge-secondary">
<p className="text-sm font-medium text-content">{user.username}</p>
<p className="text-xs truncate text-content-muted">{user.email}</p>
@@ -368,23 +369,7 @@ export default function Navbar({ tripTitle, tripId, onBack, showBack, onSettings
<LogOut className="w-4 h-4" />
{t('nav.logout')}
</button>
{appVersion && (
<div className="px-4 pt-2 pb-2.5 text-center border-t border-edge-secondary" style={{ marginTop: 4 }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
<div style={{ display: 'inline-flex', alignItems: 'center', gap: 5, background: 'var(--bg-tertiary)', borderRadius: 99, padding: '4px 12px' }}>
<img src={dark ? '/text-light.svg' : '/text-dark.svg'} alt="TREK" style={{ height: 10, opacity: 0.5 }} />
<span style={{ fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, color: 'var(--text-faint)' }}>v{appVersion}</span>
</div>
<a href="https://discord.gg/NhZBDSd4qW" target="_blank" rel="noopener noreferrer"
style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 24, height: 24, borderRadius: 99, background: 'var(--bg-tertiary)', transition: 'background 0.15s' }}
onMouseEnter={e => e.currentTarget.style.background = '#5865F220'}
onMouseLeave={e => e.currentTarget.style.background = 'var(--bg-tertiary)'}
title="Discord">
<svg width="12" height="12" viewBox="0 0 24 24" fill="var(--text-faint)"><path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z"/></svg>
</a>
</div>
</div>
)}
{appVersion && <UserMenuFooter appVersion={appVersion} dark={dark} managed={!!managed} />}
</div>
</div>
</>,
@@ -0,0 +1,44 @@
// FE-MENUFOOT-001 to FE-MENUFOOT-004
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '../../../tests/helpers/render';
import { isNativeApp } from '../../native/platform';
import UserMenuFooter from './UserMenuFooter';
vi.mock('../../native/platform', () => ({ isNativeApp: vi.fn(() => false) }));
function titles(): string[] {
return [...document.querySelectorAll('a[title]')].map((a) => a.getAttribute('title') ?? '');
}
describe('UserMenuFooter', () => {
it('FE-MENUFOOT-001: shows the version and the three support links beside Discord', () => {
render(<UserMenuFooter appVersion="5.2.1" dark={false} managed={false} />);
expect(screen.getByText('v5.2.1')).toBeInTheDocument();
expect(document.querySelector('img[src="/text-dark.svg"]')).not.toBeNull();
expect(titles()).toEqual(['Patreon', 'Ko-fi', 'Buy Me a Coffee', 'Discord']);
expect(screen.getByTitle('Ko-fi')).toHaveAttribute('href', 'https://ko-fi.com/mauriceboe');
expect(screen.getByTitle('Buy Me a Coffee')).toHaveAttribute('href', 'https://buymeacoffee.com/mauriceboe');
expect(screen.getByTitle('Patreon')).toHaveAttribute('href', 'https://www.patreon.com/cw/mauriceboe');
});
it('FE-MENUFOOT-002: a managed install keeps only Discord', () => {
render(<UserMenuFooter appVersion="5.2.1" dark managed />);
expect(titles()).toEqual(['Discord']);
expect(document.querySelector('img[src="/text-light.svg"]')).not.toBeNull();
});
it('FE-MENUFOOT-003: the native app shows no donation link', () => {
vi.mocked(isNativeApp).mockReturnValueOnce(true);
render(<UserMenuFooter appVersion="5.2.1" dark={false} managed={false} />);
expect(titles()).toEqual(['Discord']);
});
it('FE-MENUFOOT-004: hovering a link washes it in its brand colour and leaving clears it', () => {
render(<UserMenuFooter appVersion="5.2.1" dark={false} managed={false} />);
const kofi = screen.getByTitle('Ko-fi');
fireEvent.mouseEnter(kofi);
expect(kofi.style.background).toBe('rgba(255, 94, 91, 0.15)');
fireEvent.mouseLeave(kofi);
expect(kofi.style.background).toBe('');
});
});
@@ -0,0 +1,100 @@
import { Coffee, Heart } from 'lucide-react';
import React from 'react';
import { donationsShown } from '../../utils/donations';
import { PATREON_PATH, PATREON_URL } from '../shared/PatreonIcon';
const DISCORD_PATH =
'M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z';
interface FooterLink {
title: string;
href: string;
/** The brand's colour, as a faint wash behind the icon on hover. */
tint: string;
icon: React.ReactNode;
}
function brandSvg(path: string): React.ReactNode {
return (
<svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d={path} />
</svg>
);
}
const DISCORD: FooterLink = {
title: 'Discord',
href: 'https://discord.gg/NhZBDSd4qW',
tint: '#5865F2', // Discord's brand colour
icon: brandSvg(DISCORD_PATH),
};
const SUPPORT: FooterLink[] = [
{
title: 'Patreon',
href: PATREON_URL,
tint: '#ff424d', // Patreon's brand colour
icon: brandSvg(PATREON_PATH),
},
{
title: 'Ko-fi',
href: 'https://ko-fi.com/mauriceboe',
tint: '#ff5e5b', // Ko-fi's brand colour
icon: <Heart size={12} strokeWidth={2.4} aria-hidden="true" />,
},
{
title: 'Buy Me a Coffee',
href: 'https://buymeacoffee.com/mauriceboe',
tint: '#ffdd00', // Buy Me a Coffee's brand colour
icon: <Coffee size={12} strokeWidth={2.4} aria-hidden="true" />,
},
];
interface Props {
appVersion: string;
dark: boolean;
/** A centrally administered install: its users are not the ones to ask for support. */
managed: boolean;
}
/**
* The foot of the user menu: the running version, then the round links to the
* community and, where donations may be shown, the three ways to support TREK.
*/
export default function UserMenuFooter({ appVersion, dark, managed }: Props): React.ReactElement {
const links = !managed && donationsShown() ? [...SUPPORT, DISCORD] : [DISCORD];
return (
<div className="mt-1 flex items-center justify-center gap-1.5 border-t border-edge-secondary px-3 pb-2.5 pt-2">
<div className="inline-flex items-center gap-[5px] rounded-full bg-surface-tertiary px-2.5 py-1">
<img src={dark ? '/text-light.svg' : '/text-dark.svg'} alt="TREK" className="h-2.5 opacity-50" />
<span
className="font-semibold text-content-faint"
style={{ fontSize: 'calc(10px * var(--fs-scale-caption, 1))' }}
>
v{appVersion}
</span>
</div>
{links.map((link) => (
<a
key={link.title}
href={link.href}
target="_blank"
rel="noopener noreferrer"
title={link.title}
aria-label={link.title}
className="grid h-6 w-6 flex-none place-items-center rounded-full bg-surface-tertiary text-content-faint transition-colors"
onMouseEnter={(e) => {
e.currentTarget.style.background = `${link.tint}26`;
e.currentTarget.style.color = 'var(--text-primary)';
}}
onMouseLeave={(e) => {
e.currentTarget.style.background = '';
e.currentTarget.style.color = '';
}}
>
{link.icon}
</a>
))}
</div>
);
}
@@ -14,8 +14,9 @@ export type InboxAction = 'add' | 'choose' | 'file' | 'manual' | 'discard';
const INFO_ONLY: ReadonlySet<MailIngestReason> = new Set(['forwarding_confirmation', 'newsletter', 'auto_reply']);
/**
* A passing AI failure is read again by the server on its own; an allowance
* used up leaves the form and the document, so there is no "read again" here.
* The server reads a mail again after a passing AI failure and keeps it here
* only once its last try failed too; an allowance used up leaves the form and
* the document, so there is no "read again" here.
*/
export function actionsOf(entry: MailIngestInboxEntry): InboxAction[] {
const reason = entry.reason ?? entry.message.reason;
+14 -2
View File
@@ -3,7 +3,7 @@ import { pluginsApi } from '../../api/client'
import type { RouteEngine, RouteResult, RouteSegment, RouteWithLegs, SnappedWaypoint, Waypoint, RouteAnchors } from '../../types'
import { haversineKm } from '../../utils/geo'
import { countRoute } from './routeUsageCounter'
import { cacheRoute, rememberRoute, routeInMemory, storedRoute } from './routeStore'
import { cacheRoute, keepStandIn, rememberRoute, routeInMemory, standIn, storedRoute } from './routeStore'
import { formatDuration, formatRouteDistance, getDistanceUnit, legSegment } from './routeText'
import type { RouteAlternative } from './routeTypes'
import { valhallaAvailable, valhallaPlansDays, valhallaRoutesDays, type AvoidClass } from './valhallaRoute'
@@ -289,6 +289,12 @@ function withEngine(route: RouteWithLegs, engine: RouteEngine): RouteWithLegs {
* A day planned with Valhalla: its answer, kept under the Valhalla key, or where it gives
* none OSRM's for the whole day, kept under the plain key. One engine per day, never one
* leg from each. While the relay rests, a day that avoids nothing is not put to it at all.
*
* A day that avoids nothing and that Valhalla could not route is not put to it again for a
* while: OSRM's answer, the same road an OSRM instance draws, stands in for it under a key
* of its own, so every visit does not wait out the relay first (#3228). Never under the
* Valhalla key, which holds only what Valhalla answered. A day that avoids something is
* asked again, since the stand-in drives the very road it means to leave out.
*/
async function valhallaOrOsrmDay(
waypoints: Waypoint[],
@@ -299,6 +305,9 @@ async function valhallaOrOsrmDay(
signal?: AbortSignal
},
): Promise<RouteWithLegs> {
const standInKey = avoiding.length ? null : `${keys.valhalla}:standin`
const stoodIn = standInKey ? await standIn(standInKey) : null
if (stoodIn) return stoodIn
const asking = avoiding.length > 0 || valhallaRoutesDays()
const routed = asking ? await valhallaDayRoute(waypoints, profile, avoiding, signal) : null
if (routed) {
@@ -307,7 +316,10 @@ async function valhallaOrOsrmDay(
}
const plain = (await storedRoute(keys.plain)) ?? await osrmWithLegs(waypoints, keys.coords, profile, signal)
cacheRoute(keys.plain, plain)
return withFallbackNoted(plain, avoiding)
const drawn = withFallbackNoted(plain, avoiding)
// A day left before Valhalla answered, or never put to it, was not refused by it.
if (standInKey && asking && !signal?.aborted) keepStandIn(standInKey, drawn)
return drawn
}
/** Fetches a full route via OSRM and returns coordinates, distance, and duration estimates for driving/walking. */
@@ -1,3 +1,4 @@
import type { Ref } from 'react'
import { AlertTriangle, Route } from 'lucide-react'
import { useTranslation } from '../../i18n'
import { MapTogglePill } from './MapTogglePill'
@@ -6,6 +7,9 @@ import { routeDistanceLabel } from './tripRouteLabels'
import type { TripRouteOverview as Overview } from './useTripRouteOverview'
import type { DistanceUnit } from '../../types'
export const TRIP_OVERVIEW_MAX_WIDTH = 320
export const TRIP_OVERVIEW_INSET = 14
/**
* Toggle for the whole-trip route overview (#1736). Same frosted shell as the other
* map controls, so it lines up with the compass and the layer switcher.
@@ -29,13 +33,14 @@ export function TripRouteOverviewPill({ active, onToggle }: { active: boolean; o
* One component for both shells: the phone and the desktop place it differently but the
* rows are the same rows, and a second copy of them is a second thing to keep in step.
*/
export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelectDay, maxWidth = 320 }: {
export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelectDay, maxWidth = TRIP_OVERVIEW_MAX_WIDTH, cardRef }: {
overview: Overview
unit: DistanceUnit
selectedDayId?: number | null
onSelectDay?: (dayId: number) => void
/** How wide the card may grow before day names start to ellipsize. */
maxWidth?: number
cardRef?: Ref<HTMLDivElement>
}) {
const { t } = useTranslation()
if (!overview.days.length) return null
@@ -45,6 +50,7 @@ export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelect
return (
<div
ref={cardRef}
data-testid="trip-overview-panel"
style={{
pointerEvents: 'auto', borderRadius: 14, overflow: 'hidden',
@@ -35,4 +35,12 @@ describe('centredMapCard', () => {
expect(resolve(box.width, 1920)).toBe(800);
expect(resolve(box.centre, 1920)).toBe(960);
});
it('keeps the whole-trip toggle reachable beside the day card', () => {
const box = centredMapCard(350, 310, { clearPill: true, rightGap: 74 });
const width = resolve(box.width, 1280);
const centre = resolve(box.centre, 1280);
expect(centre - width / 2).toBeGreaterThanOrEqual(350 + 62);
expect(centre + width / 2).toBeLessThanOrEqual(1280 - 310 - 74);
});
});
+13 -4
View File
@@ -18,6 +18,7 @@ const PILL_CLEARANCE = MAP_LAYER_SWITCHER_INSET + MAP_ROUND_CONTROL_SIZE + 8;
* it and gives up the few pixels it needs, a wide map keeps it exactly centred.
* The phone shows these cards as sheets with no pill beside them, so it leaves
* `clearPill` off.
* `rightGap` reserves room for a map control on the other edge.
*
* `extent` is what the card is placed in: '100%' of the map, or '100vw' for the
* fixed day panel.
@@ -29,13 +30,21 @@ const PILL_CLEARANCE = MAP_LAYER_SWITCHER_INSET + MAP_ROUND_CONTROL_SIZE + 8;
export function centredMapCard(
leftWidth: number,
rightWidth: number,
{ extent = '100%', clearPill = false }: { extent?: string; clearPill?: boolean } = {}
{
extent = '100%',
clearPill = false,
rightGap = EDGE_GAP,
}: { extent?: string; clearPill?: boolean; rightGap?: number } = {}
): { centre: string; width: string } {
const free = `(${extent} - ${leftWidth}px - ${rightWidth}px)`;
const centre = `calc(${leftWidth}px + ${free} / 2)`;
if (!clearPill) return { centre, width: `min(800px, calc(${free} - ${2 * EDGE_GAP}px))` };
const width = `min(800px, calc(${free} - ${PILL_CLEARANCE + EDGE_GAP}px))`;
return { width, centre: `max(${centre}, calc(${leftWidth}px + ${PILL_CLEARANCE}px + ${width} / 2))` };
const leftGap = clearPill ? PILL_CLEARANCE : EDGE_GAP;
const width = `min(800px, calc(${free} - ${leftGap + rightGap}px))`;
const centreClearingLeft = `max(${centre}, calc(${leftWidth}px + ${leftGap}px + ${width} / 2))`;
if (rightGap === EDGE_GAP) return { width, centre: clearPill ? centreClearingLeft : centre };
const maxCentre = `calc(${extent} - ${rightWidth + rightGap}px - ${width} / 2)`;
return { width, centre: `min(${centreClearingLeft}, ${maxCentre})` };
}
/** How a card that floats over the map is placed there, read by `centredMapCard`. */
@@ -0,0 +1,45 @@
import { readFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import { dirname, join } from 'node:path';
import { describe, expect, it } from 'vitest';
// mapbox-gl and maplibre-gl ship in the same bundle, and both pass messages to
// their workers through a class registry that stamps `_classRegistryKey` on
// constructors. maplibre stamps the built-ins Set and Error globally. mapbox-gl
// 3.33 and later read that key before their own Set and Error handling, find no
// entry for "Set" in their registry and throw "Cannot read properties of
// undefined (reading 'omit')" for every vector tile, so the Mapbox basemap stays
// blank while raster layers still load. These read the shipped files because the
// clash only exists between the two real libraries.
const requireFromClient = createRequire(import.meta.url);
function distFile(pkg: string, file: string): string {
const root = dirname(requireFromClient.resolve(`${pkg}/package.json`));
return readFileSync(join(root, 'dist', file), 'utf8');
}
function functionBody(source: string, signature: string): string {
const start = source.indexOf(signature);
expect(start, `${signature} not found`).toBeGreaterThan(-1);
return source.slice(start, source.indexOf('\n}\n', start));
}
describe('GL worker class registry', () => {
it('FE-COMP-GLWORKERREGISTRY-001: maplibre-gl stamps the global Set and Error', () => {
const maplibre = distFile('maplibre-gl', 'maplibre-gl-dev.mjs');
expect(maplibre).toMatch(/register\("Set", Set\)/);
expect(maplibre).toMatch(/register\("Error", Error\)/);
});
it('FE-COMP-GLWORKERREGISTRY-002: mapbox-gl handles Set and Error before it reads the registry key', () => {
const serialize = functionBody(
distFile('mapbox-gl', 'mapbox-gl-dev.js'),
'function serialize(input, transferables)'
);
const registryRead = serialize.indexOf('._classRegistryKey');
expect(registryRead).toBeGreaterThan(-1);
expect(serialize.indexOf('instanceof Set')).toBeGreaterThan(-1);
expect(serialize.indexOf('instanceof Set')).toBeLessThan(registryRead);
expect(serialize.indexOf('instanceof Error')).toBeLessThan(registryRead);
});
});
+18
View File
@@ -39,3 +39,21 @@ export async function storedRoute(key: string): Promise<RouteWithLegs | null> {
if (kept) rememberRoute(key, kept);
return kept;
}
/**
* How long OSRM's answer stands in for a day Valhalla could not route. Long enough that
* reopening the trip draws that day at once instead of waiting out the relay again on
* every visit (#3228), short enough that a Valhalla back from an outage gets the day again
* the same day.
*/
const STAND_IN_MS = 60 * 60 * 1000;
/** Keeps OSRM's answer for a day Valhalla could not route, on the device only, for `STAND_IN_MS`. */
export function keepStandIn(key: string, route: RouteWithLegs): void {
void routeCacheRepo.put(key, route);
}
/** The answer that stood in for a day Valhalla could not route, while it is recent enough. */
export function standIn(key: string): Promise<RouteWithLegs | null> {
return routeCacheRepo.get<RouteWithLegs>(key, STAND_IN_MS);
}
@@ -17,6 +17,9 @@ export interface TripRouteOverview extends TripRouteSummary {
loading: boolean
}
/** The overview as the planner reads it: also whether the trip has any stop to route at all. */
type PlannedTripRouteOverview = TripRouteOverview & { hasPlannedRoute: boolean }
const EMPTY: TripRouteOverview = { ...summariseTripRoute([]), loading: false }
const EMPTY_PLACES: Place[] = []
@@ -49,7 +52,7 @@ export function useTripRouteOverview(
vias?: TripRouteVias,
/** MDT-02: where the stages of the trip's multi-day tours run, so a day holding one draws that stage. */
tourStageStops?: TourStageStops,
): TripRouteOverview {
): PlannedTripRouteOverview {
const optimizeFromAccommodation = useSettingsStore(s => s.settings.optimize_from_accommodation)
const toursEnabled = useTripAddonEnabled(tripId, 'tours')
// Leg text is formatted at compute time, so a km↔mi switch has to re-run (#1300).
@@ -131,5 +134,6 @@ export function useTripRouteOverview(
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [planKey, tripId, distanceUnit])
return result
const hasPlannedRoute = plan.length > 0
return useMemo(() => ({ ...result, hasPlannedRoute }), [result, hasPlannedRoute])
}
@@ -59,6 +59,8 @@ interface Traffic {
osrm: string[];
}
const HOUR = 60 * 60 * 1000;
const answered = (body: RouteBody) => HttpResponse.json({ trip: valhallaTrip(body.locations) });
/** Every routing host answering, the relay as `relay` says; what each was asked is recorded. */
@@ -274,12 +276,59 @@ describe('the route cache keeps the engine apart', () => {
up = true;
resetValhallaTurns();
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).distance).toBe(2000);
expect(traffic.relay).toHaveLength(1);
const now = Date.now();
vi.spyOn(Date, 'now').mockReturnValue(now + HOUR + 1);
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).distance).toBe(4000);
expect([traffic.relay.length, traffic.osrm.length]).toEqual([2, 1]);
});
it('VDAY-CACHE-005: a day the relay could not route opens drawn after a reload, without waiting for the relay again (#3228)', async () => {
const points = freshDay(3);
let slow = true;
const traffic = listen((body) =>
slow ? HttpResponse.json({ error: 'The TREK routing service took too long' }, { status: 504 }) : answered(body)
);
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).engine).toBe('osrm');
const { offlineDb } = await import('../../db/offlineDb');
const stoodIn = (key: string) => key.includes(`${points[0].lng},${points[0].lat}`) && key.endsWith(':standin');
await vi.waitFor(async () => expect(await offlineDb.routeCache.filter((row) => stoodIn(row.key)).count()).toBe(1));
// A reload: the modules, and with them the routes in memory and the relay's rest, start over.
vi.resetModules();
const reloaded = await import('./RouteCalculator');
const again = await reloaded.calculateRouteWithLegs(points, { profile: 'driving' });
expect([again.distance, again.engine]).toEqual([2000, 'osrm']);
expect([traffic.relay.length, traffic.osrm.length]).toEqual([1, 1]);
// An hour on, the relay gets the day again and its answer is kept as the day's.
slow = false;
const now = Date.now();
vi.spyOn(Date, 'now').mockReturnValue(now + HOUR + 1);
const routed = await reloaded.calculateRouteWithLegs(points, { profile: 'driving' });
expect([routed.distance, routed.engine]).toEqual([4000, 'valhalla']);
expect([traffic.relay.length, traffic.osrm.length]).toEqual([2, 1]);
});
});
describe('the route cache while the relay rests', () => {
it('VDAY-CACHE-006: a day drawn by OSRM while the relay rested is asked again as soon as it is back', async () => {
let up = false;
const traffic = listen((body) => (up ? answered(body) : HttpResponse.json({ error: 'down' }, { status: 503 })));
await calculateRouteWithLegs(freshDay(2), { profile: 'driving' });
const points = freshDay(3);
expect((await calculateRouteWithLegs(points, { profile: 'driving' })).engine).toBe('osrm');
expect(traffic.relay).toHaveLength(1);
up = true;
resetValhallaTurns();
const routed = await calculateRouteWithLegs(points, { profile: 'driving' });
expect([routed.distance, routed.engine]).toEqual([4000, 'valhalla']);
expect(traffic.relay).toHaveLength(2);
});
it('VDAY-CACHE-003: a day kept from Valhalla is still found while the relay rests, as it is offline', async () => {
const points = freshDay(3);
let up = true;
+33 -2
View File
@@ -463,6 +463,36 @@ describe('downloadTripPDF', () => {
expect(html).not.toContain('<script>alert(1)</script>')
})
// #3236: day notes, transport notes and the day intro are markdown in the planner too.
it('FE-COMP-TRIPPDF-016m: renders markdown in day notes, transport notes and the day intro, sanitized', async () => {
const md = {
...richArgs,
days: [{ ...dayWithPlaces, notes: '**Intro** day\n\n- museum\n- lunch' }],
dayNotes: [{ ...dayNote, time: '*Bring* water\n___\n<script>alert(1)</script>' }],
reservations: [{ ...transportReservation, notes: 'Seat **14A**\n1. check in\n2. board' }],
}
await downloadTripPDF(md)
const html = getIframe()?.srcdoc ?? ''
const doc = new DOMParser().parseFromString(html, 'text/html')
const card = (selector: string) => {
const found = doc.querySelector(selector)
if (!found) throw new Error(`${selector} is not in the export`)
return found
}
const intro = card('.day-intro')
expect(intro.querySelector('strong')?.textContent).toBe('Intro')
expect([...intro.querySelectorAll('li')].map(li => li.textContent)).toEqual(['museum', 'lunch'])
const noteLine = card('.tl-note .note-time')
expect(noteLine.querySelector('em')?.textContent).toBe('Bring')
expect(noteLine.querySelector('hr')).not.toBeNull()
expect(noteLine.querySelector('script')).toBeNull()
expect(noteLine.textContent).toContain('<script>alert(1)</script>')
const transportNote = card('.transport-note')
expect(transportNote.querySelector('strong')?.textContent).toBe('14A')
expect([...transportNote.querySelectorAll('ol li')].map(li => li.textContent)).toEqual(['check in', 'board'])
expect(html).not.toContain('**')
})
it('FE-COMP-TRIPPDF-016b: formats price chip and totals in the trip currency, not EUR', async () => {
const usdArgs = {
...richArgs,
@@ -1464,7 +1494,8 @@ describe('downloadTripPDF — transport notes', () => {
await downloadTripPDF({ ...richArgs, reservations: [{ ...withNote, notes: 'Gate <b>B12</b>' }] })
const html = getIframe()!.srcdoc
expect(html).toContain('<div class="note-time transport-note">Gate &lt;b&gt;B12&lt;/b&gt;</div>')
// Markdown like the planner (#3236), raw HTML still printed as text.
expect(html).toContain('<div class="note-time transport-note md"><p><bdi>Gate &lt;b&gt;B12&lt;/b&gt;</bdi></p></div>')
expect(html).not.toContain('pdf-no-transport-notes"')
expect(notesToggle()!.getAttribute('aria-checked')).toBe('true')
})
@@ -1472,7 +1503,7 @@ describe('downloadTripPDF — transport notes', () => {
it('FE-PDF-TNOTES-002: without any transport note there is nothing to switch', async () => {
await downloadTripPDF(richArgs)
expect(getIframe()!.srcdoc).not.toContain('class="note-time transport-note"')
expect(getIframe()!.srcdoc).not.toContain('class="note-time transport-note')
expect(notesToggle()).toBeNull()
// The page break switch is still there on its own.
expect(document.querySelector('#pdf-daybreak-toggle')).not.toBeNull()
+3 -2
View File
@@ -245,6 +245,7 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor
return url ? thumbs.get(url) ?? url : null
},
markdown: text => markdown.row(text),
markdownHtml: text => markdown.html(text),
}
/*
@@ -303,7 +304,7 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor
? `<div class="empty-day">${escHtml(tr('dayplan.emptyDay'))}</div>`
: `<ol class="timeline">${merged.map(item => {
if (item.type === 'transport') return bookingItem(item.data as PdfBooking, day, ctx, flags)
if (item.type === 'note') return noteItem(item.data as DayNote)
if (item.type === 'note') return noteItem(item.data as DayNote, ctx)
const a = item.data as Assignment
if (!a.place) return ''
number++
@@ -316,7 +317,7 @@ export async function downloadTripPDF({ trip, days, places, assignments: allStor
cost: dayCost(day.id) || null,
}, ctx)
const strip = photoStrip((stripPhotos.get(day.id) || []).map(p => ({ ...p, url: stripCopies.get(p.url) ?? p.url })))
const intro = day.notes && day.notes.trim() ? `<div class="day-intro">${escHtml(day.notes.trim())}</div>` : ''
const intro = day.notes && day.notes.trim() ? `<div class="day-intro md">${markdown.html(day.notes.trim())}</div>` : ''
const stays = staysBlock(staysForDay(day, days, accommodationList), day, ctx)
// A real <table> so the browser repeats the <thead> day header at the top of
+12 -4
View File
@@ -1,15 +1,22 @@
import { createMarkdownHtml } from '../shared/markdownHtml';
/**
* A place's description and notes are markdown in the app, so the export
* renders them the same way instead of printing the raw syntax (#2692): one
* info row per text, the HTML from the app's own sanitized pipeline.
* Place descriptions and notes, day notes, booking notes and the day intro are
* markdown in the app, so the export renders them the same way instead of
* printing the raw syntax (#2692, #3236), the HTML from the app's own sanitized
* pipeline. `row` lays a place's text out as an info row, `html` is the bare
* markup for a card that brings its own box.
*/
export function createPdfMarkdown(): { row: (text: string) => string; dispose: () => void } {
export function createPdfMarkdown(): {
row: (text: string) => string;
html: (text: string) => string;
dispose: () => void;
} {
const markdown = createMarkdownHtml();
return {
row: (text) =>
`<div class="info-row"><span class="info-spacer"></span><div class="info-text muted md">${markdown.html(text)}</div></div>`,
html: markdown.html,
dispose: markdown.dispose,
};
}
@@ -17,6 +24,7 @@ export function createPdfMarkdown(): { row: (text: string) => string; dispose: (
/** The markdown's own spacing, lists, tables and links at the export's small size. */
export const PDF_MARKDOWN_CSS = `
.info-text.md { min-width: 0; overflow-wrap: anywhere; }
.note-time.md, .day-intro.md { white-space: normal; }
.md > :first-child { margin-top: 0; }
.md > :last-child { margin-bottom: 0; }
.md p, .md ul, .md ol, .md table, .md blockquote, .md pre { margin: 0 0 4px; }
+3 -2
View File
@@ -50,6 +50,7 @@ function context(over: Partial<PdfDayContext> = {}): PdfDayContext {
placesById: new Map([[fullPlace.id, fullPlace]]),
photoOf: () => null,
markdown: (text) => `<p>${text}</p>`,
markdownHtml: (text) => `<p>${text}</p>`,
...over,
};
}
@@ -169,7 +170,7 @@ describe('noteItem', () => {
icon: 'Ticket',
color: '#2563eb',
} as DayNote;
const tinted = parse(noteItem(note));
const tinted = parse(noteItem(note, context()));
expect(tinted.querySelector('.note-card')?.className).toBe('note-card note-tinted');
expect(tinted.querySelector('.note-card')?.getAttribute('style')).toBe('--note:#2563eb');
expect(texts(tinted, '.note-text')).toEqual(['Buy <tickets>']);
@@ -177,7 +178,7 @@ describe('noteItem', () => {
expect(texts(tinted, '.note-time')).toEqual(['08:00']);
expect(tinted.querySelector('.tl-start')).toBeNull();
const plain = parse(noteItem({ ...note, color: 'not-a-colour', time: null } as DayNote));
const plain = parse(noteItem({ ...note, color: 'not-a-colour', time: null } as DayNote, context()));
expect(plain.querySelector('.note-card')?.className).toBe('note-card');
expect(plain.querySelector('.note-time')).toBeNull();
});
+8 -5
View File
@@ -30,8 +30,10 @@ export interface PdfDayContext {
placesById: ReadonlyMap<number, Place>;
/** The picture to print for a place, already shrunk where it could be; null for none. */
photoOf: (place: Assignment['place']) => string | null;
/** A place's description or notes as sanitized markdown. */
/** A place's description or notes as sanitized markdown, laid out as an info row. */
markdown: (text: string) => string;
/** A note's markdown as sanitized HTML, for a card that brings its own box. */
markdownHtml: (text: string) => string;
}
const NEUTRAL = '#6b6b75';
@@ -214,7 +216,7 @@ export function bookingItem(r: PdfBooking, day: Day, ctx: PdfDayContext, flags:
${bookingLines(r, tr).map(bookingLineHtml).join('')}
${location ? `<div class="note-time">${escHtml(location)}</div>` : ''}
${extras.length ? `<div class="note-extra">${extras.join('')}</div>` : ''}
${note ? `<div class="note-time transport-note">${escHtml(note)}</div>` : ''}
${note ? `<div class="note-time transport-note md">${ctx.markdownHtml(note)}</div>` : ''}
</div>
</div>`;
return item('booking', timeColumn(start, end), bookingIcon(r.type, 11), card, `--kind:${tint}`);
@@ -226,15 +228,16 @@ export function bookingItem(r: PdfBooking, day: Day, ctx: PdfDayContext, flags:
* A day note. A coloured note carries its colour as the rule along its edge and its
* icon (#1629), not as a fill: a tint costs ink and reads as grey on a mono printer.
*/
export function noteItem(note: DayNote): string {
export function noteItem(note: DayNote, ctx: PdfDayContext): string {
const colour = note.color ? hexColour(note.color, '') : '';
// A note's `time` is the free line the day plan prints under its text, not a clock,
// so it stays in the card and the time column stays empty.
// so it stays in the card and the time column stays empty. The planner renders it as
// markdown, so the card does too (#3236).
const subtitle = typeof note.time === 'string' ? note.time.trim() : '';
const card = `<div class="note-card${colour ? ' note-tinted' : ''}"${colour ? ` style="--note:${colour}"` : ''}>
<span class="note-icon">${noteIcon(note.icon)}</span>
<div class="note-body"><div class="note-text">${escHtml(note.text)}</div>${
subtitle ? `<div class="note-time">${escHtml(subtitle)}</div>` : ''
subtitle ? `<div class="note-time md">${ctx.markdownHtml(subtitle)}</div>` : ''
}</div>
</div>`;
return item('note', timeColumn('', ''), '', card);
@@ -204,6 +204,9 @@ describe('BookingCostsSection', () => {
expect(screen.getByText('Transport')).toBeInTheDocument();
expect(screen.getByText(money(99, 'CHF'))).toBeInTheDocument();
expect(screen.queryByRole('button', { name: /Create expense/ })).not.toBeInTheDocument();
// The save adds the cost itself and opens no editor, so the preview says that (#3237).
expect(screen.getByText('Added to Costs when you save the booking.')).toBeInTheDocument();
expect(screen.queryByText('Saves the booking, then opens the Costs editor.')).not.toBeInTheDocument();
});
it('FE-PLANNER-COSTSEC-016: an amount without a currency is in the trip currency, whatever the display currency (#2525)', () => {
@@ -29,7 +29,7 @@ export function BookingCostsSection({ reservationId, placeId = null, hintKey = '
reservationId: number | null
/** Set instead of reservationId when the block sits in the place form (#1298). */
placeId?: number | null
/** What gets saved before the editor opens — "the booking" or "the place". */
/** The create button's hint: what gets saved before the editor opens, "the booking" or "the place". */
hintKey?: string
/** A cost parsed from an import that will be linked on save — previewed before the booking exists. */
pendingExpense?: { total_price: number; currency?: string | null; category: string } | null
@@ -76,6 +76,8 @@ export function BookingCostsSection({ reservationId, placeId = null, hintKey = '
}
// Import review (booking not saved yet): preview the parsed cost that will be linked on save.
// The save adds it itself and opens no editor, so the line under it says so, not the
// create button's hint (#3237).
if (linked.length === 0 && pendingExpense && pendingExpense.total_price > 0) {
const meta = catMeta(pendingExpense.category)
const Icon = meta.Icon
@@ -86,7 +88,7 @@ export function BookingCostsSection({ reservationId, placeId = null, hintKey = '
<span style={{ width: 26, height: 26, borderRadius: 7, display: 'grid', placeItems: 'center', background: meta.color + '22', color: meta.color, flexShrink: 0 }}><Icon size={14} /></span>
<div style={{ flex: 1, minWidth: 0 }}>
<div className="text-content" style={{ ...fs(14, 'body'), fontWeight: 600 }}>{t(meta.labelKey)}</div>
<div className="text-content-faint" style={fs(12, 'body')}>{t(hintKey)}</div>
<div className="text-content-faint" style={fs(12, 'body')}>{t('reservations.importedExpenseHint')}</div>
</div>
<span className="text-content" style={{ ...fs(14, 'body'), fontWeight: 700, flexShrink: 0 }}>{formatMoney(pendingExpense.total_price, ownCurrency(pendingExpense.currency), locale)}</span>
</div>
@@ -1,32 +1,12 @@
// FE-PLANNER-DAYDETAIL-DF-001 to FE-PLANNER-DAYDETAIL-DF-002
// The day panel's heading with "date first in day headings" on (#2921).
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { buildAdmin, buildDay, buildTrip } from '../../../tests/helpers/factories';
import { server } from '../../../tests/helpers/msw/server';
import { dayDetailProps as props, resetDayDetailPanel } from '../../../tests/helpers/dayDetailPanel';
import { render, screen } from '../../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { useAuthStore } from '../../store/authStore';
import { seedStore } from '../../../tests/helpers/store';
import { useSettingsStore } from '../../store/settingsStore';
import { useTripStore } from '../../store/tripStore';
import DayDetailPanel from './DayDetailPanel';
const day = buildDay({ id: 1, trip_id: 1, date: '2025-06-15', title: 'Day in Paris' });
const props = {
day,
days: [day],
places: [],
categories: [],
tripId: 1,
assignments: {},
reservations: [],
lat: null,
lng: null,
onClose: vi.fn(),
onAccommodationChange: vi.fn(),
};
function settings(dayDateFirst: boolean) {
seedStore(useSettingsStore, {
settings: { time_format: '24h', temperature_unit: 'celsius', day_date_first: dayDateFirst },
@@ -34,14 +14,7 @@ function settings(dayDateFirst: boolean) {
}
beforeEach(() => {
resetAllStores();
vi.clearAllMocks();
server.use(
http.get('/api/weather/detailed', () => HttpResponse.json({ error: true })),
http.get('/api/trips/1/accommodations', () => HttpResponse.json({ accommodations: [] }))
);
seedStore(useAuthStore, { user: buildAdmin(), isAuthenticated: true });
seedStore(useTripStore, { trip: buildTrip({ id: 1 }) });
resetDayDetailPanel();
});
describe('DayDetailPanel with the date first', () => {
@@ -5,43 +5,17 @@ import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { server } from '../../../tests/helpers/msw/server';
import { useAuthStore } from '../../store/authStore';
import { useTripStore } from '../../store/tripStore';
import { useSettingsStore } from '../../store/settingsStore';
import { usePermissionsStore } from '../../store/permissionsStore';
import { usePluginStore } from '../../store/pluginStore';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { buildUser, buildAdmin, buildTrip, buildDay, buildPlace, buildReservation } from '../../../tests/helpers/factories';
import { seedStore } from '../../../tests/helpers/store';
import { buildUser, buildAdmin, buildDay, buildPlace, buildReservation } from '../../../tests/helpers/factories';
import { dayDetailDay as day, dayDetailProps as defaultProps, resetDayDetailPanel } from '../../../tests/helpers/dayDetailPanel';
import DayDetailPanel from './DayDetailPanel';
import { isBlurred } from '../../../tests/helpers/bookingCodeBlur';
const day = buildDay({ id: 1, trip_id: 1, date: '2025-06-15', title: 'Day in Paris' });
const defaultProps = {
day,
days: [day],
places: [],
categories: [],
tripId: 1,
assignments: {},
reservations: [],
lat: null,
lng: null,
onClose: vi.fn(),
onAccommodationChange: vi.fn(),
};
beforeEach(() => {
resetAllStores();
vi.clearAllMocks();
server.use(
http.get('/api/weather/detailed', () => HttpResponse.json({ error: true })),
http.get('/api/trips/1/accommodations', () => HttpResponse.json({ accommodations: [] })),
);
seedStore(useAuthStore, { user: buildAdmin(), isAuthenticated: true });
seedStore(useTripStore, { trip: buildTrip({ id: 1 }) });
seedStore(useSettingsStore, {
settings: { time_format: '24h', temperature_unit: 'celsius', blur_booking_codes: false },
});
resetDayDetailPanel({ time_format: '24h', temperature_unit: 'celsius', blur_booking_codes: false });
});
/** The stay picker filters by category through a pill that opens its list; this picks one entry of it. */
@@ -147,13 +121,23 @@ describe('DayDetailPanel', () => {
});
it('FE-PLANNER-DAYDETAIL-009: weather loading state shown briefly', async () => {
// The forecast is held until the spinner was seen, then released, so the request
// does not stay open past this test.
let release!: () => void;
const gate = new Promise<void>((resolve) => { release = resolve; });
server.use(
http.get('/api/weather/detailed', () => new Promise(() => {})), // never resolves
http.get('/api/weather/detailed', async () => {
await gate;
return HttpResponse.json({ error: true });
}),
);
render(<DayDetailPanel {...defaultProps} lat={48.8566} lng={2.3522} />);
// The spinner announces itself as a loading status
const spinner = await screen.findByRole('status', { name: 'Loading...' });
expect(spinner.querySelector('.animate-spin')).not.toBeNull();
release();
expect(await screen.findByText(/No weather/i)).toBeInTheDocument();
});
it('FE-PLANNER-DAYDETAIL-101: a late forecast for the previous day never replaces the one for the current day', async () => {
@@ -1606,14 +1590,14 @@ describe('DayDetailPanel remaining branches', () => {
const user = userEvent.setup();
const onAccommodationChange = vi.fn();
let updateBody: Record<string, unknown> | null = null;
let listCalls = 0;
// The reload after the save reads the new name; keyed on the save, not on a
// count of reads, so a stray read before it cannot rename the stay early.
server.use(
http.get('/api/trips/1/accommodations', () => {
listCalls += 1;
return HttpResponse.json({
accommodations: [hotel(listCalls > 1 ? { place_name: 'Reloaded Hotel' } : {})],
});
}),
http.get('/api/trips/1/accommodations', () =>
HttpResponse.json({
accommodations: [hotel(updateBody ? { place_name: 'Reloaded Hotel' } : {})],
}),
),
http.put('/api/trips/1/accommodations/1', async ({ request }) => {
updateBody = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({ accommodation: hotel() });
@@ -1874,25 +1858,40 @@ describe('DayDetailPanel remaining branches, part two', () => {
expect(await screen.findByText('15h 20m')).toBeInTheDocument();
});
it('FE-W5DDP-021: a collapsed untitled day falls back to its position, or to ? when it has none', () => {
it('FE-W5DDP-021: a collapsed untitled day falls back to its position, or to ? when it has none', async () => {
// Each mount reads the stays; wait for that read to be answered, so it cannot
// reach the handler of the test that runs next.
let staysRead = 0;
server.use(
http.get('/api/trips/1/accommodations', () => {
staysRead += 1;
return HttpResponse.json({ accommodations: [] });
}),
);
const bare = buildDay({ id: 2, trip_id: 1, date: null, title: null });
const { unmount } = render(<DayDetailPanel {...defaultProps} day={bare} days={[defaultProps.day, bare]} collapsed />);
expect(screen.getByText('Day 2')).toBeInTheDocument();
await waitFor(() => expect(staysRead).toBe(1));
unmount();
render(<DayDetailPanel {...defaultProps} day={bare} days={[]} collapsed />);
expect(screen.getByText('Day ?')).toBeInTheDocument();
await waitFor(() => expect(staysRead).toBe(2));
});
it('FE-W5DDP-020: an empty reload after the edit-save clears the accommodation', async () => {
const user = userEvent.setup();
let listCalls = 0;
// The list empties once the edit is saved, not on a count of reads, so a stray
// read before the save cannot empty it early.
let saved = false;
server.use(
http.get('/api/trips/1/accommodations', () => {
listCalls += 1;
return listCalls === 1 ? HttpResponse.json({ accommodations: [hotel()] }) : HttpResponse.json({});
http.get('/api/trips/1/accommodations', () =>
saved ? HttpResponse.json({}) : HttpResponse.json({ accommodations: [hotel()] }),
),
http.put('/api/trips/1/accommodations/1', () => {
saved = true;
return HttpResponse.json({ accommodation: hotel() });
}),
http.put('/api/trips/1/accommodations/1', () => HttpResponse.json({ accommodation: hotel() })),
);
render(<DayDetailPanel {...defaultProps} places={[buildPlace({ id: 5, name: 'Grand Hotel' })]} />);
@@ -1,4 +1,4 @@
import React, { useEffect, useRef, useId, type ReactNode } from 'react'
import React, { useEffect, useRef, useId, type ReactNode, type Ref } from 'react'
import { X, CloudRain, Wind, Droplets, Sunrise, Sunset, Hotel, Calendar, MapPin, LogIn, LogOut, Pencil, ChevronsDown, ChevronsUp, ArrowRight, Check, Moon, type LucideIcon } from 'lucide-react'
import type { WeatherResult } from '@trek/shared'
import { usePluginViewContributions, PluginCardFooter } from '../Plugins/PluginContributions'
@@ -53,6 +53,8 @@ interface DayDetailPanelProps {
onAccommodationChange: () => void
leftWidth?: number
rightWidth?: number
rightGap?: number
panelRef?: Ref<HTMLDivElement>
collapsed?: boolean
onToggleCollapse?: () => void
mobile?: boolean
@@ -73,7 +75,7 @@ interface DayDetailPanelProps {
* head band that folds the card away, then the weather, the bookings of the
* day and where the night is spent, each under its own label.
*/
export default function DayDetailPanel({ day, days, places, categories = [], tripId, assignments, reservations = [], lat, lng, onClose, onAccommodationChange, leftWidth = 0, rightWidth = 0, collapsed: collapsedProp = false, onToggleCollapse, mobile = false, onUpdateDayTitle, weatherPlaceName = null, openStayPicker = false, onStayPickerOpened, onOpenBooking }: DayDetailPanelProps) {
export default function DayDetailPanel({ day, days, places, categories = [], tripId, assignments, reservations = [], lat, lng, onClose, onAccommodationChange, leftWidth = 0, rightWidth = 0, rightGap, panelRef, collapsed: collapsedProp = false, onToggleCollapse, mobile = false, onUpdateDayTitle, weatherPlaceName = null, openStayPicker = false, onStayPickerOpened, onOpenBooking }: DayDetailPanelProps) {
const { t, language } = useTranslation()
const can = useCanDo()
const toast = useToast()
@@ -184,10 +186,10 @@ export default function DayDetailPanel({ day, days, places, categories = [], tri
setShowHotelPicker('edit')
}
const removeAccommodation = (acc: Accommodation) => { handleRemoveAccommodation(acc).catch(showError) }
const mapCard = centredMapCard(leftWidth, rightWidth, { extent: '100vw', clearPill: !mobile })
const mapCard = centredMapCard(leftWidth, rightWidth, { extent: '100vw', clearPill: !mobile, rightGap })
return (
<div className="fixed z-50" style={{ bottom: 'calc(var(--bottom-nav-h) + 20px)', left: mapCard.centre, transform: 'translateX(-50%)', width: mapCard.width, ...(mobile ? { zIndex: 10000 } : null), fontFamily: 'var(--font-system)' }}>
<div ref={panelRef} className="fixed z-50" style={{ bottom: 'calc(var(--bottom-nav-h) + 20px)', left: mapCard.centre, transform: 'translateX(-50%)', width: mapCard.width, ...(mobile ? { zIndex: 10000 } : null), fontFamily: 'var(--font-system)' }}>
<div ref={cardRef}
className="flex flex-col overflow-hidden rounded-[20px] border border-edge-faint bg-surface-elevated shadow-popover backdrop-blur-[40px] backdrop-saturate-[1.8]"
style={{ maxHeight: collapsed ? 'none' : '60vh' }}>
@@ -158,6 +158,18 @@ function dayHeader(title: string) {
}
describe('DayPlanSidebar day header', () => {
it('opens the selected day details while the whole-trip overview is active', async () => {
const user = userEvent.setup();
const day = buildDay({ id: 10, date: '2025-06-01', title: 'My Day' });
const props = makeDefaultProps({ days: [day], selectedDayId: day.id });
render(<DayPlanSidebar {...props} openSelectedDayDetail />);
await user.click(screen.getByText('My Day'));
expect(props.onSelectDay).toHaveBeenCalledWith(day.id);
expect(props.onDayDetail).toHaveBeenCalledWith(day);
});
it('FE-PLANNER-DAYPLAN-176: a transfer day lists the check-out hotel before the check-in one', async () => {
const user = userEvent.setup();
const days = [
@@ -585,3 +585,87 @@ describe('DayPlanSidebar, public transit between two city walks (CW-08)', () =>
expect(screen.getByTestId('tour-day-overrun')).toHaveTextContent('Ends at 14:00, after Harbour starts at 13:00');
});
});
// The walk from a train's arrival to the night's hotel: no stop is at either end, so
// there is no mode to change, and the desktop left it inert. The transit search is
// what can be planned for it, as for every other leg.
describe('DayPlanSidebar, public transit from a booking arrival to the hotel', () => {
it('FE-PLANNER-DAYPLAN-171f: the walk from a train arrival to the hotel, which no stop owns, offers public transport', async () => {
const user = userEvent.setup();
const onPlanTransitLeg = vi.fn();
const days = [
buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }),
buildDay({ id: 11, date: '2025-06-02', title: 'Day 2' }),
buildDay({ id: 12, date: '2025-06-03', title: 'Day 3' }),
];
const accommodations = [
{
id: 1,
trip_id: 1,
start_day_id: 10,
end_day_id: 12,
place_lat: 47.5,
place_lng: 19.05,
place_name: 'Basilica apARTment',
},
];
const train = buildReservation({
id: 430,
type: 'train',
title: 'Wien => Budapest',
day_id: 11,
end_day_id: 11,
day_plan_position: 5,
reservation_time: '2025-06-02T16:42:00',
reservation_end_time: '2025-06-02T19:29:00',
endpoints: [
{
role: 'from',
sequence: 0,
name: 'Wien Hbf',
code: null,
lat: 48.18,
lng: 16.37,
timezone: null,
local_date: null,
local_time: null,
},
{
role: 'to',
sequence: 1,
name: 'Budapest Keleti',
code: null,
lat: 47.5,
lng: 19.08,
timezone: null,
local_date: null,
local_time: null,
},
],
});
const albertina = buildPlace({ id: 1, name: 'Albertina', place_time: '12:00', lat: 48.2, lng: 16.37 });
render(
<DayPlanSidebar
{...makeDefaultProps({
days,
assignments: { '11': [buildAssignment({ id: 11, day_id: 11, order_index: 0, place: albertina })] },
accommodations,
reservations: [train],
selectedDayId: 11,
routeShown: true,
onPlanTransitLeg,
})}
/>
);
await user.click(await screen.findByLabelText('Public transit'));
expect(contextMenu().queryByRole('button', { name: 'Driving' })).not.toBeInTheDocument();
await user.click(contextMenu().getByRole('button', { name: 'Public transit' }));
expect(onPlanTransitLeg).toHaveBeenCalledWith(
expect.objectContaining({
dayId: 11,
from: expect.objectContaining({ lat: 47.5, lng: 19.08 }),
to: { name: 'Basilica apARTment', lat: 47.5, lng: 19.05 },
})
);
});
});
@@ -69,7 +69,7 @@ import { findTodayDayId } from './today'
import { markdownLinkComponents } from '../shared/markdownLink'
import { RouteConnector, HotelRouteConnector } from './DayPlanSidebarRouteConnector'
import { resolveLegMode } from './legMode'
import { useLegModeActions } from './useLegModeActions'
import { transitOnlyMenuItems, useLegModeActions } from './useLegModeActions'
import { dayExportStops, fillAroundLocked } from './dayRoute'
import { projectDayItinerary, projectedById, type TourStageStops } from '../Map/dayTourProjection'
import type { DayRoutePoint } from '../Map/dayRoutePlan'
@@ -104,6 +104,7 @@ export interface DayPlanSidebarProps {
categories: Category[]
assignments: AssignmentsMap
selectedDayId: number | null
openSelectedDayDetail?: boolean
selectedPlaceId: number | null
selectedAssignmentId: number | null
onSelectDay: (dayId: number | null, skipFit?: boolean) => void
@@ -1413,6 +1414,27 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
} as unknown as React.MouseEvent)
}
// A hotel bookend leg opens the mode menu of the stop that owns it, the first stop's
// incoming mode at the top and the last stop's outgoing mode at the bottom. One no
// stop owns, a booking's arrival to the hotel, can only have transit planned.
const hotelLegRow = (dayId: number, leg: { seg: RouteSegment; name: string; targetId?: number }, placement: 'top' | 'bottom') => {
const connector = <HotelRouteConnector seg={leg.seg} name={leg.name} profile={routeProfile} placement={placement} />
const targetId = leg.targetId
const planTransit = targetId == null ? transitLegPlanner(dayId, leg.seg) : undefined
const open = targetId != null
? (e: React.MouseEvent) => (placement === 'top' ? openIncomingLegModeMenu : openLegModeMenu)(e, targetId, dayId, leg.seg)
: planTransit && ((e: React.MouseEvent) => ctxMenu.open(e, transitOnlyMenuItems(planTransit, t)))
if (!canEditDays || !open) return connector
const label = targetId != null ? t('dayplan.transportMode.change') : t('transit.title')
return (
<Tooltip label={label} placement="top">
<div role="button" tabIndex={0} onClick={open} onKeyDown={e => openLegMenuByKey(e, open)} style={{ cursor: 'pointer' }} aria-label={label}>
{connector}
</div>
</Tooltip>
)
}
return (
// Sized as a flex child as well as by height: the desktop panel puts the Days / Road
// trip switch above this, and at height 100% alone the list ran the switch's height
@@ -1459,12 +1481,11 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
<div className={`scroll-container flex flex-col gap-2 p-2${hasDragged ? '' : ' trek-stagger'}`} style={{ flex: 1, overflowY: 'auto', minHeight: 0 }} ref={scrollContainerRef} onScroll={(e) => onScrollTopChange?.((e.currentTarget as HTMLElement).scrollTop)}>
{days.map((day, index) => {
const isSelected = selectedDayId === day.id
// Shared by the click and the key handler so the two can never drift
// apart — pressing Enter on the row has to toggle, not just select.
// Named for the selection, not the expand/collapse `toggleDay` above.
// An already-selected day can reopen its details from the overview.
const toggleDaySelection = () => {
if (isSelected) { onSelectDay(null); if (onDayDetail) onDayDetail(null) }
else { onSelectDay(day.id); if (onDayDetail) onDayDetail(day) }
const dayToOpen = isSelected && !props.openSelectedDayDetail ? null : day
onSelectDay(dayToOpen?.id ?? null)
onDayDetail?.(dayToOpen)
}
const isExpanded = expandedDays.has(day.id)
const da = getDayAssignments(day.id)
@@ -1734,17 +1755,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
dropAfterLastItem(day.id, { assignmentId, noteId })
}}
>
{hotelLegs[day.id]?.top && (() => {
const targetId = hotelLegs[day.id]?.top?.targetId
const connector = <HotelRouteConnector seg={hotelLegs[day.id]!.top!.seg} name={hotelLegs[day.id]!.top!.name} profile={routeProfile} placement="top" />
return canEditDays && targetId != null ? (
<Tooltip label={t('dayplan.transportMode.change')} placement="top">
<div role="button" tabIndex={0} onClick={e => openIncomingLegModeMenu(e, targetId, day.id, hotelLegs[day.id]!.top!.seg)} onKeyDown={e => openLegMenuByKey(e, m => openIncomingLegModeMenu(m, targetId, day.id, hotelLegs[day.id]!.top!.seg))} style={{ cursor: 'pointer' }} aria-label={t('dayplan.transportMode.change')}>
{connector}
</div>
</Tooltip>
) : connector
})()}
{hotelLegs[day.id]?.top && hotelLegRow(day.id, hotelLegs[day.id]!.top!, 'top')}
{daySchedule.byPosition[day.id]?.start.map(si => <PluginDayScheduleRow key={`${si.pluginId}:${si.id}`} item={si} />)}
{visibleCount === 0 && !dayNoteUi ? (
<div
@@ -2477,17 +2488,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
})
)}
{daySchedule.byPosition[day.id]?.end.map(si => <PluginDayScheduleRow key={`${si.pluginId}:${si.id}`} item={si} />)}
{hotelLegs[day.id]?.bottom && (() => {
const targetId = hotelLegs[day.id]?.bottom?.targetId
const connector = <HotelRouteConnector seg={hotelLegs[day.id]!.bottom!.seg} name={hotelLegs[day.id]!.bottom!.name} profile={routeProfile} placement="bottom" />
return canEditDays && targetId != null ? (
<Tooltip label={t('dayplan.transportMode.change')} placement="top">
<div role="button" tabIndex={0} onClick={e => openLegModeMenu(e, targetId, day.id, hotelLegs[day.id]!.bottom!.seg)} onKeyDown={e => openLegMenuByKey(e, m => openLegModeMenu(m, targetId, day.id, hotelLegs[day.id]!.bottom!.seg))} style={{ cursor: 'pointer' }} aria-label={t('dayplan.transportMode.change')}>
{connector}
</div>
</Tooltip>
) : connector
})()}
{hotelLegs[day.id]?.bottom && hotelLegRow(day.id, hotelLegs[day.id]!.bottom!, 'bottom')}
<AssistantDayPreview tripId={tripId} dayId={day.id} />{/* The assistant's waiting changes, then the drop zone at the list end */}
<div
style={{ minHeight: 12, padding: '2px 8px' }}
@@ -15,6 +15,7 @@ import {
displayTitle,
groupReservations,
groupTransports,
hasPassed,
onTravelers,
parseMeta,
phaseOf,
@@ -394,4 +395,48 @@ describe('onTravelers and the shared type colours', () => {
expect(groups.transit.map(r => r.id)).toEqual([1]);
expect(sortReservations([later, transit, open, sooner], days, 'date', 'asc', label).map(r => r.id)).toEqual([1, 3, 2, 4]);
});
it('FE-PLANNER-BKMODEL-044: hasPassed reads the end, else the start, in local wall-clock time', () => {
const now = new Date(2025, 5, 2, 12, 0);
expect(hasPassed(buildReservation({ reservation_time: '2025-06-02T11:00' }), now)).toBe(true);
expect(hasPassed(buildReservation({ reservation_time: '2025-06-02T13:00' }), now)).toBe(false);
// The end counts: a flight that left in the morning and lands this afternoon is not over.
expect(hasPassed(buildReservation({ reservation_time: '2025-06-02T08:00', reservation_end_time: '2025-06-02T15:00' }), now)).toBe(false);
// An end time without a date is on the start's day.
expect(hasPassed(buildReservation({ reservation_time: '2025-06-02T08:00', reservation_end_time: '11:30' }), now)).toBe(true);
// A date without a time lasts until the day is over.
expect(hasPassed(buildReservation({ reservation_time: '2025-06-02' }), now)).toBe(false);
expect(hasPassed(buildReservation({ reservation_time: '2025-06-01' }), now)).toBe(true);
// Without any date nothing says it is over.
expect(hasPassed(buildReservation({ reservation_time: null, day_id: null }), now)).toBe(false);
});
it('FE-PLANNER-BKMODEL-045: groupTransports moves what is over into past, latest first, only when given the time', () => {
const early = buildReservation({ id: 1, type: 'train', status: 'confirmed', reservation_time: '2025-06-01T09:00' });
const lastNight = buildReservation({ id: 2, type: 'transit', status: 'pending', reservation_time: '2025-06-01T21:00' });
const ahead = buildReservation({ id: 3, type: 'bus', status: 'confirmed', reservation_time: '2025-06-03T09:00' });
const now = new Date(2025, 5, 2, 12, 0);
const groups = groupTransports([ahead, early, lastNight], days, now);
expect(groups.confirmed.map(r => r.id)).toEqual([3]);
expect(groups.transit).toEqual([]);
expect(groups.past.map(r => r.id)).toEqual([2, 1]);
expect(groupTransports([ahead, early, lastNight], days).past).toEqual([]);
});
it('FE-PLANNER-BKMODEL-046: hasPassed takes the linked days when a booking carries no date of its own', () => {
const now = new Date(2025, 5, 3, 12, 0);
const hotel = buildReservation({ id: 1, type: 'hotel', status: 'confirmed', reservation_time: null, reservation_end_time: null, accommodation_start_day_id: 501, accommodation_end_day_id: 502 });
const stillThere = buildReservation({ id: 2, type: 'hotel', status: 'confirmed', reservation_time: null, reservation_end_time: null, accommodation_start_day_id: 502, accommodation_end_day_id: 503 });
const train = buildReservation({ id: 3, type: 'train', status: 'confirmed', reservation_time: '09:00', reservation_end_time: '11:00', day_id: 503 });
const lateTrain = buildReservation({ id: 4, type: 'train', status: 'confirmed', reservation_time: '13:00', day_id: 503 });
const overnight = buildReservation({ id: 5, type: 'bus', status: 'confirmed', reservation_time: '22:00', reservation_end_time: '06:00', day_id: 502, end_day_id: 503 });
expect(hasPassed(hotel, now, days)).toBe(true);
expect(hasPassed(stillThere, now, days)).toBe(false);
expect(hasPassed(train, now, days)).toBe(true);
expect(hasPassed(lateTrain, now, days)).toBe(false);
expect(hasPassed(overnight, now, days)).toBe(true);
const groups = groupTransports([hotel, stillThere, train, lateTrain, overnight], days, now);
expect(groups.past.map(r => r.id)).toEqual([3, 5, 1]);
expect(groups.confirmed.map(r => r.id)).toEqual([2, 4]);
});
});
@@ -252,21 +252,49 @@ export interface StatusGroups {
confirmed: Reservation[]
pending: Reservation[]
transit: Reservation[]
/** What is over already (#3156), latest first; empty unless the caller passes the time. */
past: Reservation[]
}
/**
* The phone tabs' three sections, each in date order: confirmed and pending, and
* Whether a booking is over: its end, or its start where it has none, lies
* before `now`. The times are local wall-clock values, as everywhere a booking
* is read. An end time without a date is on the start's day, and a date
* without a time counts until that day is over. A booking that carries no date
* of its own takes them from bookingDates, so a hotel ends on its stay's last
* day and a day-linked transport on its day. Without any date it is never over.
*/
export function hasPassed(r: Reservation, now: Date, days: Day[] = []): boolean {
const start = splitReservationDateTime(r.reservation_time)
const end = r.reservation_end_time ? splitReservationDateTime(r.reservation_end_time) : null
const own = end?.date || start.date
const linked = own ? null : bookingDates(r, days)
const endDate = own ? end?.date : linked?.end
const date = endDate || (own ? start.date : linked?.start)
if (!date) return false
const time = endDate || end?.time ? (end?.time ?? null) : start.time
const [y, m, d] = date.split('-').map(Number)
const [hh, mm] = time ? time.split(':').map(Number) : [23, 59]
return new Date(y, m - 1, d, hh, mm) < now
}
/**
* The phone tabs' sections, each in date order: confirmed and pending, and
* transit (automated public transport, #1065) on its own whatever its status.
* A booking type never matches `transit`, so the split fits the bookings tab too.
* Given the time, what is over leaves those and stands in `past` (#3156).
*/
export function groupTransports(list: Reservation[], days: Day[]): StatusGroups {
export function groupTransports(list: Reservation[], days: Day[], now?: Date): StatusGroups {
const sorted = sortReservations(list, days, 'date', 'asc', () => '')
const transit = sorted.filter(r => r.type === 'transit')
const nonTransit = sorted.filter(r => r.type !== 'transit')
const isPast = (r: Reservation) => !!now && hasPassed(r, now, days)
const current = sorted.filter(r => !isPast(r))
const transit = current.filter(r => r.type === 'transit')
const nonTransit = current.filter(r => r.type !== 'transit')
return {
confirmed: nonTransit.filter(r => r.status === 'confirmed'),
pending: nonTransit.filter(r => r.status !== 'confirmed'),
transit,
past: sorted.filter(isPast).reverse(),
}
}
@@ -1,7 +1,7 @@
// FE-PLANNER-RESLISTFILTER-001 to -004: the traveller filter and folded sections
// FE-PLANNER-RESLISTFILTER-001 to -005: the traveller filter and folded sections
// of the phone's bookings and transports tabs.
import { act, renderHook } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { buildDay, buildReservation } from '../../../../tests/helpers/factories';
import type { Reservation } from '../../../types';
@@ -24,6 +24,14 @@ const bob = buildReservation({
const ride = buildReservation({ id: 12, type: 'transit', status: 'confirmed', reservation_time: '2026-03-01T07:00' });
const ALL = [ann, bob, ride];
// The day before the trip: every booking above is still ahead.
beforeEach(() => {
vi.useFakeTimers({ toFake: ['Date'], now: new Date(2026, 1, 28, 12, 0) });
});
afterEach(() => {
vi.useRealTimers();
});
describe('useReservationListFilter', () => {
it('FE-PLANNER-RESLISTFILTER-001: without a filter every booking lands in its status section', () => {
const { result } = renderHook(() => useReservationListFilter(ALL, days, 2));
@@ -37,7 +45,7 @@ describe('useReservationListFilter', () => {
const { result } = renderHook(() => useReservationListFilter(ALL, days, 2));
act(() => result.current.toggleTravelerFilter(2));
expect([...result.current.travelerFilter]).toEqual([2]);
expect(result.current.groups).toEqual({ confirmed: [], pending: [bob], transit: [] });
expect(result.current.groups).toEqual({ confirmed: [], pending: [bob], transit: [], past: [] });
act(() => result.current.toggleTravelerFilter(1));
expect(result.current.groups.confirmed.map((r) => r.id)).toEqual([10]);
@@ -58,9 +66,24 @@ describe('useReservationListFilter', () => {
it('FE-PLANNER-RESLISTFILTER-004: a section folds and unfolds on its own', () => {
const { result } = renderHook(() => useReservationListFilter(ALL, days, 2));
act(() => result.current.toggleSection('pending'));
expect(result.current.collapsed).toEqual({ pending: true });
expect(result.current.collapsed).toEqual({ pending: true, past: true });
act(() => result.current.toggleSection('confirmed'));
act(() => result.current.toggleSection('pending'));
expect(result.current.collapsed).toEqual({ pending: false, confirmed: true });
expect(result.current.collapsed).toEqual({ pending: false, confirmed: true, past: true });
});
it('FE-PLANNER-RESLISTFILTER-005: what is over goes to Past, folded while something is ahead and open once all is over', () => {
vi.setSystemTime(new Date(2026, 2, 1, 12, 0));
const midTrip = renderHook(() => useReservationListFilter(ALL, days, 2)).result;
expect(midTrip.current.groups.past.map((r) => r.id)).toEqual([11, 12]);
expect(midTrip.current.groups.confirmed.map((r) => r.id)).toEqual([10]);
expect(midTrip.current.collapsed.past).toBe(true);
act(() => midTrip.current.toggleSection('past'));
expect(midTrip.current.collapsed.past).toBe(false);
vi.setSystemTime(new Date(2026, 2, 3, 12, 0));
const afterTrip = renderHook(() => useReservationListFilter(ALL, days, 2)).result;
expect(afterTrip.current.groups.past.map((r) => r.id)).toEqual([10, 11, 12]);
expect(afterTrip.current.collapsed.past).toBe(false);
});
});
@@ -1,7 +1,20 @@
import { useState } from 'react';
import type { Day, Reservation } from '../../../types';
import { groupTransports, onTravelers } from './bookingsModel';
import { groupTransports, onTravelers, type StatusGroups } from './bookingsModel';
/**
* The status sections both tabs list, in their order, leaving out the empty ones.
* Bookings never fill `transit`, so that section only ever shows among transports.
*/
export function listSections(groups: StatusGroups, t: (key: string) => string) {
return [
{ id: 'confirmed', label: t('reservations.confirmed'), rows: groups.confirmed },
{ id: 'pending', label: t('reservations.pending'), rows: groups.pending },
{ id: 'transit', label: t('reservations.type.transit'), rows: groups.transit },
{ id: 'past', label: t('reservations.past'), rows: groups.past },
].filter((s) => s.rows.length > 0);
}
/**
* The traveller filter and the folded sections of the phone's bookings and
@@ -15,9 +28,13 @@ import { groupTransports, onTravelers } from './bookingsModel';
*/
export function useReservationListFilter(all: Reservation[], days: Day[], memberCount: number) {
const [travelerFilter, setTravelerFilter] = useState<Set<number>>(new Set());
// The moment the tab opened: what was over by then moves into the folded Past
// section (#3156). Taken once, so a list does not reshuffle while it is read.
const [now] = useState(() => new Date());
const groups = groupTransports(
all.filter((r) => onTravelers(r, travelerFilter)),
days
days,
now
);
const showTravelerFilter = memberCount > 1 && all.some((r) => (r.travelers || []).length > 0);
const toggleTravelerFilter = (id: number) =>
@@ -29,8 +46,12 @@ export function useReservationListFilter(all: Reservation[], days: Day[], member
});
const clearTravelerFilter = () => setTravelerFilter(new Set());
const [collapsed, setCollapsed] = useState<Record<string, boolean>>({});
const toggleSection = (id: string) => setCollapsed((c) => ({ ...c, [id]: !c[id] }));
const [folded, setFolded] = useState<Record<string, boolean>>({});
// Past starts folded while something is still ahead, since mid-trip that is
// what counts; once the whole trip is over it opens, to look back on.
const ahead = groups.confirmed.length + groups.pending.length + groups.transit.length > 0;
const collapsed: Record<string, boolean> = { ...folded, past: folded.past ?? ahead };
const toggleSection = (id: string) => setFolded((c) => ({ ...c, [id]: !collapsed[id] }));
return {
travelerFilter,
@@ -0,0 +1,21 @@
import type { BookingImportPreviewItem } from '@trek/shared';
import { describe, expect, it } from 'vitest';
import { parsedItemToDraft } from './parsedItemToDraft';
const item = (metadata?: Record<string, unknown>): BookingImportPreviewItem => ({
type: 'flight',
title: 'Kuala Lumpur to Bangkok',
metadata,
source: { fileName: 'airasia.eml', index: 0 },
});
describe('parsedItemToDraft', () => {
// #3238: the review form opens with the status the document states.
it('FE-PARSED-DRAFT-001: a booking the document calls confirmed opens confirmed, anything else pending', () => {
expect(parsedItemToDraft(item({ reservationStatus: 'confirmed' })).status).toBe('confirmed');
expect(parsedItemToDraft(item({ reservationStatus: 'cancelled' })).status).toBe('pending');
expect(parsedItemToDraft(item({ reservationStatus: 'pending' })).status).toBe('pending');
expect(parsedItemToDraft(item()).status).toBe('pending');
});
});
@@ -1,4 +1,4 @@
import type { BookingImportPreviewItem, Reservation, ReservationEndpoint } from '@trek/shared'
import { importedReservationStatus, type BookingImportPreviewItem, type Reservation, type ReservationEndpoint } from '@trek/shared'
/**
* A pre-fill draft for the reservation/transport edit modals built from a parsed
@@ -29,7 +29,8 @@ export function parsedItemToDraft(item: BookingImportPreviewItem): BookingReview
return {
type: item.type,
title: item.title,
status: 'pending',
// Confirmed when the document said so, pending otherwise (#3238).
status: importedReservationStatus(item.metadata),
reservation_time: item.reservation_time ?? null,
reservation_end_time: item.reservation_end_time ?? null,
location: item.location ?? item._venue?.address ?? item._venue?.name ?? null,
@@ -0,0 +1,27 @@
// FE-PLANNER-STOPNUM-001 to -002: the one stop count the map's pins and the plan's rows read (#2584).
import { describe, expect, it } from 'vitest';
import type { Assignment } from '../../types';
import { stopNumbersOfDay } from './stopNumbers';
const stop = (id: number, order_index: number, place: Partial<NonNullable<Assignment['place']>> | null = {}) =>
({ id, order_index, place: place && { id: id * 10, ...place } }) as unknown as Assignment;
describe('stopNumbersOfDay', () => {
it('FE-PLANNER-STOPNUM-001: numbers the stops from 1 in their stored order', () => {
const numbers = stopNumbersOfDay([stop(3, 2), stop(1, 0), stop(2, 1)]);
expect([...numbers.entries()]).toEqual([
[1, 1],
[2, 2],
[3, 3],
]);
});
it('FE-PLANNER-STOPNUM-002: passes over service stops and rows without a place', () => {
const numbers = stopNumbersOfDay([stop(1, 0), stop(2, 1, { stop_type: 'fuel' }), stop(3, 2, null), stop(4, 3)]);
expect(numbers.get(1)).toBe(1);
expect(numbers.has(2)).toBe(false);
expect(numbers.has(3)).toBe(false);
expect(numbers.get(4)).toBe(2);
});
});
@@ -0,0 +1,22 @@
import type { Assignment } from '../../types';
import { isServiceStopType } from '../Roadtrip/roadtripModel';
/**
* The number each stop of a day carries, by assignment id: counted from 1 in the
* day's stored order. A service stop is passed over rather than counted: the map
* draws it without a badge and the rail gives it no number, so a number spent on
* it left the pin after a fuel stop wearing "3" where the rail said "2".
*
* The one count the map's pins and the plan's rows both read (#2584), so the
* number beside a stop in the list is the one on its pin.
*/
export function stopNumbersOfDay(dayAssignments: readonly Assignment[]): Map<number, number> {
const numbers = new Map<number, number>();
let counted = 0;
for (const a of [...dayAssignments].sort((x, y) => x.order_index - y.order_index)) {
if (!a.place?.id || isServiceStopType(a.place.stop_type)) continue;
counted += 1;
numbers.set(a.id, counted);
}
return numbers;
}
@@ -34,6 +34,15 @@ export function legModeMenuItems(
];
}
/**
* The menu of a leg no stop owns, a booking's arrival to the night's hotel: nothing
* keeps a mode for it, so it follows the day default and only public transit can be
* planned for it.
*/
export function transitOnlyMenuItems(planTransit: () => void, t: Translate): LegModeMenuItem[] {
return [{ label: t('transit.title'), icon: TramFront, onClick: planTransit }];
}
export interface LegModeDeps {
tripId: number;
toast: { error: (message: string) => void };
@@ -60,6 +60,8 @@ export interface PlaceSearchOptions {
* search ends the billing session, and a pick clears the typed-ahead list too.
*/
variant: 'dialog' | 'sheet';
/** What the field starts with, such as a map link shared to the app (#2582). */
initialQuery?: string;
/** Where the trip is happening: autocomplete is biased to the box, the full search to its centre. */
locationBias: LocationBiasBox | undefined;
t: ReturnType<typeof useTranslation>['t'];
@@ -101,6 +103,7 @@ export function usePlaceSearch({
onMapLink,
onCoordinates,
onResolvingChange,
initialQuery,
}: PlaceSearchOptions) {
const sheet = variant === 'sheet';
// Place names in the language the user picked for them, the app's otherwise (#1799).
@@ -110,7 +113,7 @@ export function usePlaceSearch({
// The same hint autocomplete gets, as a point instead of a box.
const biasPoint = pointFromBox(locationBias);
const [query, setQuery] = useState('');
const [query, setQuery] = useState(initialQuery ?? '');
const [results, setResults] = useState<MapsSearchRow[]>([]);
/** What answered the last full search. Only a fallback: a merged list carries the source per place. */
const [searchSource, setSearchSource] = useState('');
@@ -265,11 +268,12 @@ export function usePlaceSearch({
const pickPlace = (place: MapsPlace, pick?: PlaceSearchPick) =>
take(place, pick, sourceLabel(place, pick?.mode === 'search' ? searchSource : ''));
const runSearch = async (provider?: 'google') => {
const runSearch = async (provider?: 'google', text?: string) => {
// The retry sends the query the list came from, not the field: the list
// stays on screen while the field is edited or cleared, and the line under
// it promises the same query.
const trimmed = provider ? (searchMetaRef.current?.query ?? '') : query.trim();
// it promises the same query. A link shared into an open sheet is searched
// as given, before the field shows it.
const trimmed = provider ? (searchMetaRef.current?.query ?? '') : (text ?? query).trim();
if (!trimmed) return;
if (sheet) {
setSuggestions([]);
@@ -1,5 +1,6 @@
// FE-COMP-PLUGIN-USERSET-001 to -012: the per plugin user settings logic both settings shells share.
import { act, renderHook, waitFor } from '@testing-library/react';
import { locationAt } from '../../../tests/helpers/location';
import { pluginsApi, type PluginAction, type PluginUserSettingField } from '../../api/client';
import { SECRET_MASK } from './settingsForm';
import { usePluginOAuth, usePluginUserSettings } from './usePluginUserSettings';
@@ -150,7 +151,7 @@ describe('usePluginOAuth', () => {
it('FE-COMP-PLUGIN-USERSET-012: a connect hands off to the provider and keeps the button busy', async () => {
const realLocation = window.location;
const loc = { href: 'http://localhost/settings' };
const loc = locationAt('/settings');
Object.defineProperty(window, 'location', { writable: true, configurable: true, value: loc });
try {
vi.spyOn(pluginsApi, 'oauthConnect').mockResolvedValue({
@@ -0,0 +1,41 @@
// FE-COMP-ACCOUNT-APPS-001 to FE-COMP-ACCOUNT-APPS-002
import { http, HttpResponse } from 'msw';
import { describe, expect, it, vi } from 'vitest';
import { buildSettings, buildUser } from '../../../tests/helpers/factories';
import { server } from '../../../tests/helpers/msw/server';
import { render, screen } from '../../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { isNativeApp } from '../../native/platform';
import { useAuthStore } from '../../store/authStore';
import { useSettingsStore } from '../../store/settingsStore';
import AccountTab from './AccountTab';
vi.mock('../../sync/syncTriggers', () => ({ registerSyncTriggers: vi.fn(), unregisterSyncTriggers: vi.fn() }));
vi.mock('../../native/platform', async (importOriginal) => ({
...(await importOriginal<typeof import('../../native/platform')>()),
isNativeApp: vi.fn(() => false),
}));
beforeEach(() => {
resetAllStores();
server.use(http.get('/api/auth/app-config', () => HttpResponse.json({ version: '5.2.1', mfa_enabled: false })));
seedStore(useAuthStore, { user: buildUser({ username: 'testuser', role: 'user' }), isAuthenticated: true });
seedStore(useSettingsStore, { settings: buildSettings() });
});
describe('AccountTab app stores', () => {
it('FE-COMP-ACCOUNT-APPS-001: in a browser it offers both app stores with their QR codes', () => {
render(<AccountTab />);
expect(screen.getByText('TREK app')).toBeInTheDocument();
expect(screen.getByText('Scan a code with your phone, then connect the app to this server.')).toBeInTheDocument();
expect(document.querySelectorAll('a.asc-card')).toHaveLength(2);
});
it('FE-COMP-ACCOUNT-APPS-002: inside the app itself there is nothing to download', () => {
vi.mocked(isNativeApp).mockReturnValue(true);
render(<AccountTab />);
expect(screen.queryByText('TREK app')).toBeNull();
expect(document.querySelector('a.asc-card')).toBeNull();
vi.mocked(isNativeApp).mockReturnValue(false);
});
});
+10 -1
View File
@@ -1,5 +1,5 @@
import React, { useId } from 'react'
import { User, Save, Lock, KeyRound, AlertTriangle, Shield, Camera, Trash2, Copy, Download, Printer, ShieldCheck } from 'lucide-react'
import { User, Save, Lock, KeyRound, AlertTriangle, Shield, Camera, Trash2, Copy, Download, Printer, ShieldCheck, Smartphone } from 'lucide-react'
import { useTranslation } from '../../i18n'
import Section from './Section'
import PasskeysSection from './PasskeysSection'
@@ -12,6 +12,8 @@ import { EditorField, GRID_2, INPUT, PANEL } from '../shared/dialogParts'
import { SETTINGS_BUTTON, SETTINGS_BUTTON_DANGER, SETTINGS_BUTTON_PRIMARY, SettingRow, SettingRows, SettingsHint, StatusPill, SettingsColumns } from './settingsKit'
import { stripTrailingSlashes, useAccountSettings } from './useAccountSettings'
import AccountDemoLock from './AccountDemoLock'
import AppStoreCards from '../shared/AppStoreCards'
import { isNativeApp } from '../../native/platform'
/** The small turning ring a button shows while its request is on the way. */
const SPINNER = 'h-3.5 w-3.5 flex-none animate-spin rounded-full border-2 border-current border-t-transparent'
@@ -366,6 +368,13 @@ export default function AccountTab(): React.ReactElement {
{/* Passkeys */}
<PasskeysSection demoMode={demoMode} />
{/* Where to get the phone app; inside the app itself there is nothing to fetch. */}
{!isNativeApp() && (
<Section title={t('settings.apps.title')} icon={Smartphone} hint={t('settings.apps.hint')}>
<AppStoreCards />
</Section>
)}
</>}
/>
</AccountDemoLock>
@@ -1,10 +1,9 @@
// FE-SETTINGS-NATIVE-SERVER-001 to FE-SETTINGS-NATIVE-SERVER-008
// FE-SETTINGS-NATIVE-SERVER-001 to FE-SETTINGS-NATIVE-SERVER-006
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '../../../tests/helpers/render';
import MSettingsServer from '../../mobile/screens/settings/MSettingsServer';
import { nativeServerHost } from '../../native/platform';
import { TrekShell } from '../../native/trekShell';
import NativeServerLink from '../../pages/login/NativeServerLink';
import NativeServerSection from './NativeServerSection';
vi.mock('../../native/platform', () => ({ nativeServerHost: vi.fn() }));
@@ -40,18 +39,3 @@ describe.each([
expect(link).toHaveAttribute('target', '_blank');
});
});
describe('the sign-in screen link', () => {
it('renders nothing in a browser', () => {
vi.mocked(nativeServerHost).mockReturnValue(null);
const { container } = render(<NativeServerLink />);
expect(container).toBeEmptyDOMElement();
});
it('leads back to the address screen in the app', () => {
vi.mocked(nativeServerHost).mockReturnValue('trek.example.com');
render(<NativeServerLink />);
fireEvent.click(screen.getByRole('button', { name: 'Change server' }));
expect(TrekShell.resetServer).toHaveBeenCalled();
});
});
@@ -4,6 +4,7 @@ import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { render, screen, waitFor, within } from '../../../tests/helpers/render';
import { server } from '../../../tests/helpers/msw/server';
import { locationAt } from '../../../tests/helpers/location';
import { ToastContainer } from '../shared/Toast';
import { usePluginStore, type ActivePlugin } from '../../store/pluginStore';
import type { PluginAction, PluginUserSettingField } from '../../api/client';
@@ -367,7 +368,7 @@ describe('PluginSettingsTab', () => {
it('FE-COMP-PLUGINSETTINGS-020: an OAuth-only plugin gets a card and Connect hands off to the provider', async () => {
const user = userEvent.setup();
const loc = { href: 'http://localhost/settings', origin: 'http://localhost', pathname: '/settings' };
const loc = locationAt('/settings');
vi.stubGlobal('location', loc);
serve('weather', {}, { configured: true, connected: false });
server.use(http.post('/api/plugin-oauth/weather/connect', () =>
@@ -1,4 +1,4 @@
// FE-HOOK-AI-CONNECT-001 to FE-HOOK-AI-CONNECT-015: pasting a key, an own server, the ChatGPT sign-in and the OpenRouter return.
// FE-HOOK-AI-CONNECT-001 to FE-HOOK-AI-CONNECT-017: pasting a key, an own server, the ChatGPT sign-in and the OpenRouter return.
import { act, fireEvent, renderHook, waitFor } from '@testing-library/react';
import { createElement, type ReactNode } from 'react';
import { MemoryRouter, useLocation } from 'react-router';
@@ -20,6 +20,7 @@ vi.mock('../../shared/Toast', () => ({ useToast: () => toast }));
const { useChatgptConnect, useCustomConnect, useKeyConnect, useOpenrouterReturn, useOpenrouterStart } =
await import('./useAiConnect');
const { rememberOpenrouterFlow } = await import('./aiConnectModel');
const { OnlineOnlyError } = await import('../../../repo/onlineOnly');
function wrapperAt(url = '/settings') {
return ({ children }: { children: ReactNode }) =>
@@ -207,7 +208,7 @@ describe('useChatgptConnect', () => {
expect(repo.chatgptFinish).not.toHaveBeenCalled();
});
it('FE-HOOK-AI-CONNECT-010: an account ChatGPT will not share says so and keeps the flow', async () => {
it('FE-HOOK-AI-CONNECT-010: an account ChatGPT will not share says so, and the next try is a fresh sign-in', async () => {
repo.chatgptFinish.mockRejectedValueOnce(refused('not_eligible'));
const onConnected = vi.fn();
const { result } = renderHook(() => useChatgptConnect({ active: true, onConnected }), { wrapper: wrapperAt() });
@@ -216,7 +217,50 @@ describe('useChatgptConnect', () => {
await act(() => result.current.submit());
expect(result.current.error).toEqual({ messageKey: 'assistant.error.notEligible', code: 'not_eligible' });
expect(onConnected).not.toHaveBeenCalled();
expect(repo.chatgptStart).toHaveBeenCalledTimes(1);
// The server took the sign-in when it refused it.
await waitFor(() => expect(repo.chatgptStart).toHaveBeenCalledTimes(2));
});
it('FE-HOOK-AI-CONNECT-016: any refusal the server sent starts exactly one fresh sign-in; offline and a wrong address keep this one', async () => {
const generic = Object.assign(new Error('generic'), {
response: { status: 400, data: { error: 'ChatGPT refused the sign-in (invalid_client)', code: 'generic' } },
});
repo.chatgptFinish.mockRejectedValueOnce(generic).mockRejectedValueOnce(new OnlineOnlyError());
const { result } = renderHook(() => useChatgptConnect({ active: true, onConnected: vi.fn() }), {
wrapper: wrapperAt(),
});
await waitFor(() => expect(result.current.flow).not.toBeNull());
act(() => result.current.change(CALLBACK));
await act(() => result.current.submit());
expect(result.current.error?.code).toBe('generic');
await waitFor(() => expect(repo.chatgptStart).toHaveBeenCalledTimes(2));
await waitFor(() => expect(result.current.flow).not.toBeNull());
act(() => result.current.change(CALLBACK));
await act(() => result.current.submit());
expect(result.current.error?.code).toBe('offline');
expect(repo.chatgptStart).toHaveBeenCalledTimes(2);
// The server refuses a wrong address before it takes the sign-in, so the right one still works.
repo.chatgptFinish.mockRejectedValueOnce(refused('wrong_url'));
act(() => result.current.change(CALLBACK));
await act(() => result.current.submit());
expect(result.current.error?.code).toBe('wrong_url');
expect(repo.chatgptStart).toHaveBeenCalledTimes(2);
});
it('FE-HOOK-AI-CONNECT-017: the address pasted without http://, as the hint shows it, is taken and sent with it', async () => {
const onConnected = vi.fn();
const { result } = renderHook(() => useChatgptConnect({ active: true, onConnected }), { wrapper: wrapperAt() });
await waitFor(() => expect(result.current.flow).not.toBeNull());
const bare = CALLBACK.replace('http://', '');
let taken = false;
act(() => {
taken = result.current.paste(` ${bare} `);
});
expect(taken).toBe(true);
await waitFor(() => expect(onConnected).toHaveBeenCalledTimes(1));
expect(repo.chatgptFinish).toHaveBeenCalledWith({ flowId: FLOW.flowId, pastedUrl: CALLBACK });
});
it('FE-HOOK-AI-CONNECT-013: the clipboard fills the field where the browser lets it be read, else the field gets the cursor', async () => {
@@ -3,7 +3,7 @@ import { useEffect, useEffectEvent, useRef, useState } from 'react';
import { useSearchParams } from 'react-router';
import { useTranslation } from '../../../i18n';
import { aiConnectionsRepo } from '../../../repo/aiConnectionsRepo';
import { detectKeyKind, isChatgptCallback, providerLabel } from '../../Assistant/providerCatalog';
import { chatgptCallbackUrl, detectKeyKind, isChatgptCallback, providerLabel } from '../../Assistant/providerCatalog';
import { useToast } from '../../shared/Toast';
import {
callbackMatchesFlow,
@@ -243,9 +243,9 @@ export function useChatgptConnect({
};
const finish = async (raw: string) => {
const url = raw.trim();
const url = chatgptCallbackUrl(raw);
if (!flow || finishing.current) return;
if (!isChatgptCallback(url) || !callbackMatchesFlow(url, flow.authorizeUrl)) {
if (!url || !callbackMatchesFlow(url, flow.authorizeUrl)) {
setError({ messageKey: 'assistant.connect.chatgptWrong', code: 'wrong_url' });
return;
}
@@ -264,7 +264,9 @@ export function useChatgptConnect({
} catch (err) {
const code = refusalCode(err);
setError({ messageKey: connectErrorKey(err), code });
if (code === 'expired') restart();
// The server takes a sign-in once, whatever it answers: any refusal it sent
// used this one up. Offline the request never left, and a wrong address is refused before the flow is taken.
if (code !== null && code !== 'offline' && code !== 'wrong_url') restart();
} finally {
finishing.current = false;
setBusy(false);
@@ -298,7 +300,7 @@ export function useChatgptConnect({
useOnReturnToTab(opened, () => {
if (pasted.trim() || busy) return;
readClipboard((text) => {
if (flow && !callbackMatchesFlow(text, flow.authorizeUrl)) focusField();
if (flow && !callbackMatchesFlow(chatgptCallbackUrl(text) ?? text, flow.authorizeUrl)) focusField();
else if (!paste(text)) focusField();
}, focusField);
});
@@ -0,0 +1,14 @@
// FE-SETTINGS-TRIPOFFLINE-001: where a trip stands on this device, for its menu (#1580).
import { describe, expect, it } from 'vitest';
import { tripOfflineState } from './useTripOfflineStatus';
describe('tripOfflineState', () => {
it('FE-SETTINGS-TRIPOFFLINE-001: off when switched off or not kept, saved as of the last sync, else pending', () => {
expect(tripOfflineState(false, true, 1000)).toEqual({ kind: 'off' });
expect(tripOfflineState(true, false, 1000)).toEqual({ kind: 'off' });
expect(tripOfflineState(true, true, 1000)).toEqual({ kind: 'saved', at: 1000 });
expect(tripOfflineState(true, true, null)).toEqual({ kind: 'pending' });
expect(tripOfflineState(true, true, undefined)).toEqual({ kind: 'pending' });
});
});
@@ -0,0 +1,51 @@
import { useEffect, useState } from 'react';
import { offlineDb } from '../../db/offlineDb';
import { isTripOfflineEnabled, isTripPinned } from '../../sync/offlinePrefs';
import { isDateEligible } from '../../sync/tripSyncManager';
import type { Trip } from '../../types';
/** Where a trip stands on this device (#1580), as the trip's own menu says it. */
export type TripOfflineState = { kind: 'saved'; at: number } | { kind: 'pending' } | { kind: 'off' };
/**
* The trip's state from what decides it: switched off, or kept by neither the
* date rule nor a pin, it is not on the device; synced before, it is, as of then;
* otherwise the next sync brings it.
*/
export function tripOfflineState(
enabled: boolean,
kept: boolean,
lastSyncedAt: number | null | undefined
): TripOfflineState {
if (!enabled || !kept) return { kind: 'off' };
if (lastSyncedAt) return { kind: 'saved', at: lastSyncedAt };
return { kind: 'pending' };
}
/**
* The offline state of one trip, read again each time `active` turns on (the
* menu opening), so it shows the last sync rather than the one before it.
*/
export function useTripOfflineStatus(trip: Trip | null | undefined, active: boolean): TripOfflineState | null {
const [state, setState] = useState<TripOfflineState | null>(null);
useEffect(() => {
if (!active || !trip) return;
let cancelled = false;
const enabled = isTripOfflineEnabled(trip.id);
const kept = isTripPinned(trip.id) || isDateEligible(trip);
void offlineDb.syncMeta.get(trip.id).then(
(meta) => {
if (!cancelled) setState(tripOfflineState(enabled, kept, meta?.lastSyncedAt));
},
// An unreadable store says nothing about the trip: the line stays away.
() => {
if (!cancelled) setState(null);
}
);
return () => {
cancelled = true;
};
}, [trip, active]);
return state;
}
@@ -1,4 +1,4 @@
// FE-RN-001 to FE-RN-020
// FE-RN-001 to FE-RN-022
import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest';
import { render, screen } from '../../../tests/helpers/render';
@@ -295,4 +295,23 @@ describe('ReleaseNoticeModal', () => {
expect(document.querySelectorAll('.rn-vis-route-stop')).toHaveLength(5);
expect(document.querySelector('.rn-vis-route-line')).not.toBeNull();
});
it('FE-RN-021: an apps block draws one tile with its title and both store cards', () => {
renderModal(withRelease({ apps: { titleKey: 'rel.apps.title' } }));
const tile = document.querySelector('.rn-apps');
expect(tile).toHaveTextContent('rel.apps.title');
const stores = tile?.querySelectorAll('a.asc-card') ?? [];
expect([...stores].map((a) => a.getAttribute('href'))).toEqual([
'https://apps.apple.com/app/id6831237775',
'https://play.google.com/store/apps/details?id=com.liketrek.trek',
]);
// On the release column, which is dark in either theme.
expect(tile?.querySelector('.asc-row')).toHaveClass('asc-dark');
});
it('FE-RN-022: without an apps block there is no apps tile', () => {
renderModal();
expect(document.querySelector('.rn-apps')).toBeNull();
expect(document.querySelector('.asc-card')).toBeNull();
});
});
@@ -2,6 +2,7 @@ import { ArrowRight, Heart, Infinity as InfinityIcon, ShieldCheck, X } from 'luc
import React from 'react';
import { useTranslation } from '../../i18n/TranslationContext.js';
import type { SystemNoticeDTO } from '../../store/systemNoticeStore.js';
import AppStoreCards from '../shared/AppStoreCards';
import { PATREON_PATH } from '../shared/PatreonIcon';
import { ReleaseFeatureVisual } from './ReleaseNoticeVisuals.js';
import './releaseNotice.css';
@@ -127,6 +128,16 @@ export function ReleaseNoticeModal({ notice, visible, onDismiss, onCTA, onSecond
{withSponsorLink(t(release.introKey))}
</p>
{release.apps && (
<div className="rn-apps">
<div className="rn-feature-shine" aria-hidden="true" />
<div className="rn-apps-text">
<div className="rn-feature-title">{t(release.apps.titleKey)}</div>
</div>
<AppStoreCards tone="dark" className="rn-apps-stores" />
</div>
)}
<div className="rn-features-head">
<span className="rn-features-label">{t(release.featuresLabelKey)}</span>
<span className="rn-features-rule" aria-hidden="true" />
@@ -647,3 +647,28 @@
.rn-sponsor:hover {
text-decoration-color: currentColor;
}
/* ── The apps: one tile across the column, the text beside the store cards ── */
.rn-apps {
position: relative;
margin-top: 22px;
display: flex;
align-items: center;
gap: 22px;
padding: 16px 16px 16px 20px;
border-radius: 20px;
background: linear-gradient(160deg, oklch(1 0 0 / 0.1) 0%, oklch(1 0 0 / 0.045) 62%);
border: 1px solid oklch(1 0 0 / 0.13);
box-shadow: inset 0 1px 0 oklch(1 0 0 / 0.16), 0 12px 28px -16px oklch(0 0 0 / 0.7);
overflow: hidden;
}
.rn-apps-text { position: relative; flex: 1 1 200px; min-width: 0; }
.rn-apps-stores { position: relative; flex: 0 1 520px; min-width: 0; }
@media (max-width: 1280px) {
.rn-apps { flex-direction: column; align-items: stretch; }
.rn-apps-stores { flex-basis: auto; }
}
@@ -12,7 +12,7 @@ import type { Day } from '../../../types'
import { toggleTourPlacing } from '../../../store/tourPlaceToolStore'
import { publishTourFerrataCrossings } from '../../../store/tourFerrataCrossingStore'
import { TourPlannerRail, TourPlannerToursRail } from './TourPlannerPanels'
import { hikePlannerDefaults } from '../../../../tests/helpers/tourPlannerStub'
import { hikePlannerDefaults, mockTourEditorLayout } from '../../../../tests/helpers/tourPlannerStub'
import { tourRepo } from '../../../repo/tourRepo'
import { useTripStore } from '../../../store/tripStore'
import type { TourStage } from '../stages/tourStages'
@@ -132,6 +132,12 @@ beforeEach(() => {
seedStore(useSettingsStore, { settings: { distance_unit: 'metric' } })
})
function openDifficulty() {
const trigger = screen.getByRole('button', { name: 'Maximum trail difficulty' })
mockTourEditorLayout(trigger.parentElement ?? trigger)
fireEvent.click(trigger)
}
describe('TourPlannerToursRail', () => {
it('MDT-02: a multi-day tour unfolds its stages in the list, a day tour has nothing to unfold', async () => {
vi.spyOn(tourRepo, 'detail').mockResolvedValue({ tour, waypoints: [] })
@@ -702,6 +708,7 @@ describe('TourPlannerRail', () => {
render(<TourPlannerRail planner={controller} />)
expect(screen.getByLabelText('Tour name')).toBeDisabled()
expect(screen.getByTestId('tour-type-select')).toBeDisabled()
expect(screen.getByRole('button', { name: 'Maximum trail difficulty' })).toBeDisabled()
expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()
expect(screen.getByRole('button', { name: 'Back to Tours' })).toBeDisabled()
@@ -765,7 +772,7 @@ describe('TourPlannerRail', () => {
const controller = planner({ mode: { type: 'new-draft' }, setMaxHikingDifficulty: setDifficulty, acknowledgeAlpine: acknowledge })
const { unmount } = render(<TourPlannerRail planner={controller} />)
fireEvent.click(screen.getByRole('button', { name: 'Maximum trail difficulty' }))
openDifficulty()
fireEvent.click(screen.getByRole('button', { name: /T4: Alpine hiking/ }))
expect(screen.getByRole('heading', { name: 'Enable alpine routing?' })).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'Enable alpine routing' }))
@@ -775,7 +782,7 @@ describe('TourPlannerRail', () => {
// The planner remembers the answer, so a rail that mounts anew does not ask again.
render(<TourPlannerRail planner={planner({ mode: { type: 'new-draft' }, setMaxHikingDifficulty: setDifficulty, alpineAcknowledged: true })} />)
fireEvent.click(screen.getByRole('button', { name: 'Maximum trail difficulty' }))
openDifficulty()
fireEvent.click(screen.getByRole('button', { name: /T5: Demanding alpine hiking/ }))
expect(screen.queryByRole('heading', { name: 'Enable alpine routing?' })).not.toBeInTheDocument()
expect(setDifficulty).toHaveBeenLastCalledWith(5)
@@ -785,7 +792,7 @@ describe('TourPlannerRail', () => {
const setDifficulty = vi.fn()
render(<TourPlannerRail planner={planner({ mode: { type: 'new-draft' }, setMaxHikingDifficulty: setDifficulty })} />)
fireEvent.click(screen.getByRole('button', { name: 'Maximum trail difficulty' }))
openDifficulty()
fireEvent.click(screen.getByRole('button', { name: /T4: Alpine hiking/ }))
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
expect(setDifficulty).not.toHaveBeenCalled()
@@ -802,7 +809,7 @@ describe('TourPlannerRail', () => {
})} />
}
render(<StatefulDifficultyRail />)
fireEvent.click(screen.getByRole('button', { name: 'Maximum trail difficulty' }))
openDifficulty()
for (const label of [
'T1: Hiking',
@@ -818,6 +825,22 @@ describe('TourPlannerRail', () => {
expect(screen.getAllByRole('status').some(el => /T3 routes may include exposed/.test(el.textContent ?? ''))).toBe(true)
})
it('TOUR-PLANNER-RAIL-024: an open tour type list closes when saving locks the editor', () => {
const controller = planner({ mode: { type: 'new-draft' } })
const { rerender } = render(<TourPlannerRail planner={controller} />)
const trigger = screen.getByTestId('tour-type-select')
mockTourEditorLayout(trigger)
fireEvent.click(trigger)
expect(screen.getByRole('group', { name: 'Tour type' })).toBeInTheDocument()
rerender(<TourPlannerRail planner={{ ...controller, isSaving: true }} />)
expect(trigger).toBeDisabled()
expect(trigger).toHaveAttribute('aria-expanded', 'false')
expect(screen.queryByTestId('tour-type-option-hike')).not.toBeInTheDocument()
rerender(<TourPlannerRail planner={controller} />)
expect(trigger).toHaveAttribute('aria-expanded', 'false')
})
it('TOUR-PLANNER-RAIL-009: neutral shows only the Plan new entry and new-draft guidance hides after the first waypoint', () => {
const controller = planner({ mode: { type: 'neutral' } })
const { rerender } = render(<TourPlannerRail planner={controller} />)
@@ -12,6 +12,7 @@ import { useRailHeadProps } from './railHead'
import EmptyState from '../../shared/EmptyState'
import { useToast } from '../../shared/Toast'
import { Tooltip } from '../../shared/Tooltip'
import { PopoverBoundary } from '../../shared/useAnchoredPopover'
import { BOX } from '../../Planner/bookings/bookingParts'
import { BarButton, SoftPill } from '../../Planner/planParts'
import TourListRow from '../TourListRow'
@@ -335,6 +336,7 @@ export function TourPlannerRail({ planner,
const { t } = useTranslation()
const [confirmDiscard, setConfirmDiscard] = useState(false)
const [pendingDifficulty, setPendingDifficulty] = useState<1 | 2 | 3 | 4 | 5 | 6 | null>(null)
const editorScrollRef = useRef<HTMLDivElement>(null)
const isSaving = planner.isSaving
// Nothing in the editor changes while the viewer may not edit or a save is in flight.
const locked = !canEdit || isSaving
@@ -389,44 +391,46 @@ export function TourPlannerRail({ planner,
</BarButton>
</div>
<div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-3 py-3.5">
<TourRemoteChangeNotice planner={planner} />
<WalkImportDraftNotice planner={planner} />
<WalkRoutePendingNotice planner={planner} />
<TourNameField planner={planner} locked={locked} />
<div ref={editorScrollRef} data-testid="tour-planner-editor-scroll" className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-3 py-3.5">
<PopoverBoundary value={editorScrollRef}>
<TourRemoteChangeNotice planner={planner} />
<WalkImportDraftNotice planner={planner} />
<WalkRoutePendingNotice planner={planner} />
<TourNameField planner={planner} locked={locked} />
<TourTypeFields planner={planner} locked={locked} />
<TourTypeFields planner={planner} locked={locked} />
<TourStageModeField planner={planner} locked={locked} />
<TourStageModeField planner={planner} locked={locked} />
{recordedTrack?.available && <RecordedTrackCard recordedTrack={recordedTrack} disabled={isSaving} />}
{recordedTrack?.available && <RecordedTrackCard recordedTrack={recordedTrack} disabled={isSaving} />}
<UnreachableNotice planner={planner} />
<WalkFerryNotice planner={planner} />
<UnreachableNotice planner={planner} />
<WalkFerryNotice planner={planner} />
<TourStageLossNotice planner={planner} />
<TourStageDayNotice planner={planner} />
<TourStageLossNotice planner={planner} />
<TourStageDayNotice planner={planner} />
<TourWaypointList planner={planner} canEdit={canEdit} isSaving={isSaving} tourPlaceIds={tourPlaceIds} />
<TourWaypointList planner={planner} canEdit={canEdit} isSaving={isSaving} tourPlaceIds={tourPlaceIds} />
<BikeWaysCard planner={planner} />
<BikeWaysCard planner={planner} />
<RunWaysCard planner={planner} />
<RunWaysCard planner={planner} />
<HorseRoutesCard planner={planner} />
<HorseRoutesCard planner={planner} />
<SkiPlannerSummary planner={planner} />
<SkiPlannerSummary planner={planner} />
{planner.tourType === 'hike' && (
<HikeWaysCard tripId={planner.tripId} route={planner.route} routeCurrent={planner.routeCurrent}
routingLimit={planner.maxHikingDifficulty} />
)}
{planner.tourType === 'hike' && (
<HikeWaysCard tripId={planner.tripId} route={planner.route} routeCurrent={planner.routeCurrent}
routingLimit={planner.maxHikingDifficulty} />
)}
<TourPoiSearchCard planner={planner} />
<TourPoiSearchCard planner={planner} />
<PaddleEditorCards planner={planner} locked={locked} checklist={paddleChecklist} />
<PaddleEditorCards planner={planner} locked={locked} checklist={paddleChecklist} />
<TourDetailsSection planner={planner} locked={locked} onDifficultyChange={changeDifficulty} />
<TourDetailsSection planner={planner} locked={locked} onDifficultyChange={changeDifficulty} />
</PopoverBoundary>
</div>
<TourEditorRailFooter planner={planner} canEdit={canEdit} locked={locked} isSavedEdit={isSavedEdit} onDiscard={requestClose} />
@@ -111,7 +111,7 @@ function BikeProfileField({ planner }: { planner: TourPlannerController }) {
* discipline and, for cross-country, the technique, then what the piste router
* is asked for. A short line says how its legs are laid.
*/
function SkiFields({ planner }: { planner: TourPlannerController }) {
function SkiFields({ planner, locked }: TourTypeFieldsProps) {
const { t } = useTranslation();
const { choice } = planner.ski;
return (
@@ -121,7 +121,12 @@ function SkiFields({ planner }: { planner: TourPlannerController }) {
{t('tours.ski.plannedHint')}
</span>
{choice.discipline !== null && (
<SkiRouteOptions discipline={choice.discipline} options={choice.options} onChange={planner.ski.setOption} />
<SkiRouteOptions
discipline={choice.discipline}
options={choice.options}
onChange={planner.ski.setOption}
locked={locked}
/>
)}
</div>
);
@@ -157,7 +162,7 @@ export function TourTypeFields({ planner, locked }: TourTypeFieldsProps) {
{planner.isRun && <RunFields planner={planner} locked={locked} />}
{planner.isSki && <SkiFields planner={planner} />}
{planner.isSki && <SkiFields planner={planner} locked={locked} />}
{planner.isPaddle && (
<div data-testid="tour-planner-paddle-fields" className="flex min-w-0 flex-col gap-3">
@@ -47,7 +47,10 @@ export function TourTypeSelect<T extends ImportableTourType = PlannableTourType>
const { t } = useTranslation();
const valueId = useId();
const offered: readonly ImportableTourType[] = types ?? PLANNER_TOUR_TYPES;
const list = usePopoverList(offered.indexOf(value), { estimatedHeight: 50 * offered.length + 20 });
const list = usePopoverList(offered.indexOf(value), {
estimatedHeight: 50 * offered.length + 20,
disabled,
});
const { open, toggle, triggerRef, listId } = list;
const label = t('tours.planner.tourType');
const pick = (type: T) => {
@@ -47,6 +47,7 @@ interface SkiRouteOptionsProps {
discipline: SkiDiscipline;
options: SkiRouteOptionsInput | null | undefined;
onChange: (patch: Partial<SkiRouteOptionsInput>) => void;
locked?: boolean;
}
/** One switch of the piste router on its own row, its label beside it. */
@@ -102,7 +103,7 @@ function LiftClasses({ avoided, onChange }: { avoided: SkiLiftClass[]; onChange:
* weigh most for a downhill skier, groomed and lit trails for cross-country,
* the lifts for anyone who rides them. Every change plans the tour again.
*/
export function SkiRouteOptions({ discipline, options, onChange }: SkiRouteOptionsProps) {
export function SkiRouteOptions({ discipline, options, onChange, locked }: SkiRouteOptionsProps) {
const { t } = useTranslation();
const read = new Set(skiOptionsReadBy(discipline));
const current: Options = { ...DEFAULT_SKI_ROUTE_OPTIONS, ...options };
@@ -119,6 +120,7 @@ export function SkiRouteOptions({ discipline, options, onChange }: SkiRouteOptio
<CustomSelect
id="tour-planner-ski-difficulty"
ariaLabel={t('tours.ski.options.maxDifficulty')}
disabled={locked}
size="sm"
value={current.max_difficulty}
onChange={(value) => onChange({ max_difficulty: value as SkiDifficulty })}
@@ -11,7 +11,7 @@ import { analyzeRouteGeometry } from '../../utils/routeGeometry'
import TourListRow from './TourListRow'
import { TourPlannerRail, TourPlannerToursRail } from './planner/TourPlannerPanels'
import type { TourPlannerController } from './planner/useTourPlanner'
import { hikePlannerDefaults } from '../../../tests/helpers/tourPlannerStub'
import { hikePlannerDefaults, mockTourEditorLayout } from '../../../tests/helpers/tourPlannerStub'
vi.mock('../../../../server/src/config', () => { throw new Error('Config initialization is forbidden in client tests') })
vi.mock('../../../../server/src/db/database', () => { throw new Error('Legacy database imports are forbidden in client tests') })
@@ -151,7 +151,9 @@ describe('Tours English and German copy', () => {
}
rerender(<TourPlannerRail planner={planner({ mode: { type: 'new-draft' }, status: 'ready', error: 'save' })} />)
expect(screen.getByLabelText(toursText(de, 'tours.planner.status.saveFailed'))).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: toursText(de, 'tours.planner.maxDifficulty') }))
const difficulty = screen.getByRole('button', { name: toursText(de, 'tours.planner.maxDifficulty') })
mockTourEditorLayout(difficulty.parentElement ?? difficulty)
fireEvent.click(difficulty)
fireEvent.click(screen.getByRole('button', { name: toursText(de, 'tours.planner.difficulty.t4') }))
expect(screen.getByRole('heading', { name: toursText(de, 'tours.planner.difficulty.alpineTitle') })).toBeInTheDocument()
expect(screen.getByText(toursText(de, 'tours.planner.difficulty.alpineBody'))).toBeInTheDocument()
@@ -187,4 +189,4 @@ describe('Tours English and German copy', () => {
expect(await screen.findByText(toursText(fr, 'tours.planner.neutralTitle'))).toBeInTheDocument()
assertNoRawToursKeys()
})
})
})
@@ -284,6 +284,43 @@ describe('WalkStationsCard', () => {
expect(within(cafe).queryByText(/Open/)).not.toBeInTheDocument();
});
it('opens what the linked place has to tell under its stop, and leaves a stop without it as it is (#3205)', async () => {
seedStore(useTripStore, {
places: [
buildPlace({
id: 77,
name: 'Lenbachhaus',
description: 'Blue Rider collection',
address: 'Luisenstrasse 33',
website: 'https://lenbachhaus.de',
}),
],
});
vi.mocked(tourRepo.detail).mockImplementation(() =>
detail([
{ lat: 48, lng: 11, role: 'start', sequence: 0, key: 'stop-01', linked_place_id: 77, stay_minutes: 60 },
{ lat: 48.002, lng: 11, role: 'end', sequence: 1, key: 'stop-02', name: 'Cafe', stay_minutes: 0 },
])
);
card();
const museum = await rowOf('Lenbachhaus');
const toggle = within(museum).getByRole('button', { name: /Lenbachhaus/ });
expect(toggle).toHaveAttribute('aria-expanded', 'false');
expect(within(museum).queryByText('Blue Rider collection')).not.toBeInTheDocument();
fireEvent.click(toggle);
expect(toggle).toHaveAttribute('aria-expanded', 'true');
expect(within(museum).getByText('Blue Rider collection')).toBeInTheDocument();
expect(within(museum).getByText('Luisenstrasse 33')).toBeInTheDocument();
expect(within(museum).getByRole('link', { name: 'Open Website' })).toHaveAttribute(
'href',
'https://lenbachhaus.de'
);
const cafe = await rowOf('Cafe');
expect(within(cafe).queryByRole('button', { name: /Cafe/ })).not.toBeInTheDocument();
});
it('shows the times in the 12 hour format where the user chose it', async () => {
seedStore(useSettingsStore, { settings: { time_format: '12h' } });
card(onMonday());
@@ -1,10 +1,13 @@
import type { TourListItem, TourVisitStatus } from '@trek/shared';
import { Check, CheckCheck, Info, Redo2, SkipForward, Undo2 } from 'lucide-react';
import type { Place, TourListItem, TourVisitStatus } from '@trek/shared';
import { Check, CheckCheck, ChevronDown, ExternalLink, Info, MapPin, Redo2, SkipForward, Undo2 } from 'lucide-react';
import { useState } from 'react';
import { useTranslation } from '../../../i18n';
import { useTourVisitStore } from '../../../store/tourVisitStore';
import type { Assignment, AssignmentsMap, Day } from '../../../types';
import { safeHttpUrl } from '../../../utils/safeUrl';
import { SoftPill } from '../../Planner/planParts';
import { DialogSection, fs } from '../../shared/DialogShell';
import MarkdownText from '../../shared/MarkdownText';
import { useToast } from '../../shared/Toast';
import { stationMarkNote, stationRingClass } from '../planner/stationMarks';
import { StationPills, StationShield } from '../planner/stationParts';
@@ -83,23 +86,62 @@ function StatusActions({
* trip place it stands for), stay, the day's arrival and opening hours, and
* what can be marked.
*/
/** What a station's linked place has to tell (#3205): its description, address and website. */
function placeDetailsOf(place: Place | null | undefined) {
if (!place) return null;
const description = place.description?.trim() || '';
const address = place.address?.trim() || '';
const website = safeHttpUrl(place.website);
return description || address || website ? { description, address, website } : null;
}
/** The linked place's details, opened under its station without leaving the walk. */
function StationDetails({ details }: { details: NonNullable<ReturnType<typeof placeDetailsOf>> }) {
const { t } = useTranslation();
return (
<span className="flex flex-col gap-1 text-content-secondary" style={fs(11.5, 'body')}>
{details.description && <MarkdownText className="leading-[1.5]">{details.description}</MarkdownText>}
{details.address && (
<span className="flex items-start gap-1">
<MapPin size={11} strokeWidth={2.2} aria-hidden="true" className="mt-[2px] flex-none text-content-faint" />
<bdi className="min-w-0 [overflow-wrap:anywhere]">{details.address}</bdi>
</span>
)}
{details.website && (
<a
href={details.website}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 self-start font-semibold text-content underline-offset-2 hover:underline"
>
<ExternalLink size={11} strokeWidth={2.2} aria-hidden="true" />
{t('inspector.website')}
</a>
)}
</span>
);
}
function StationRow({
station,
index,
status,
placeName,
place,
schedule,
onMark,
}: {
station: TourPlannerWaypoint;
index: number;
status: TourVisitStatus | undefined;
placeName: string | undefined;
place: Place | null;
schedule: StationSchedule | undefined;
onMark: ((status: TourVisitStatus | 'planned') => void) | null;
}) {
const { t } = useTranslation();
const name = station.name ?? placeName ?? t('tours.walk.stationNumbered', { number: index + 1 });
const [open, setOpen] = useState(false);
const details = placeDetailsOf(place);
const name = station.name ?? place?.name ?? t('tours.walk.stationNumbered', { number: index + 1 });
const nameClass = `truncate font-semibold text-content ${status === 'skipped' ? 'line-through' : ''}`;
return (
<li
data-testid="walk-station"
@@ -121,13 +163,31 @@ function StationRow({
{station.protected && <StationShield />}
</span>
<span className="flex min-w-0 flex-1 flex-col gap-1">
<span
className={`truncate font-semibold text-content ${status === 'skipped' ? 'line-through' : ''}`}
style={fs(12.5, 'body')}
>
{name}
</span>
{details ? (
// A station that has more to tell opens it in place (#3205).
<button
type="button"
onClick={() => setOpen((v) => !v)}
aria-expanded={open}
className="flex min-w-0 items-center gap-1 self-start text-start"
>
<span className={nameClass} style={fs(12.5, 'body')}>
{name}
</span>
<ChevronDown
size={13}
strokeWidth={2.2}
aria-hidden="true"
className={`flex-none text-content-faint transition-transform ${open ? 'rotate-180' : ''}`}
/>
</button>
) : (
<span className={nameClass} style={fs(12.5, 'body')}>
{name}
</span>
)}
<StationPills point={station} />
{open && details && <StationDetails details={details} />}
<StationScheduleLine schedule={schedule} name={name} />
{status && (
<span className="text-content-faint" style={fs(11, 'body')}>
@@ -252,7 +312,7 @@ export function WalkStationsCard({
station={station}
index={index}
status={station.key ? visits?.[station.key] : undefined}
placeName={placeOf(station)?.name}
place={placeOf(station)}
schedule={schedule.byStation.get(station.id)}
onMark={marking === 'ready' && station.key ? (next) => onMark(station.key ?? '', next) : null}
/>
@@ -0,0 +1,15 @@
import { useTranslation } from '../../i18n';
/**
* What the waiting states show while the app hands over from its address
* screen (native/appBoot.ts): that screen's ground and its spinner, which only
* comes up when the wait is long enough to notice. Styled in native/nativeApp.css.
*/
export default function AppBootScreen() {
const { t } = useTranslation();
return (
<div className="app-boot" role="status" aria-label={t('common.loading')}>
<span aria-hidden="true" />
</div>
);
}
@@ -0,0 +1,39 @@
// FE-APPSTORE-001 to FE-APPSTORE-003
import { describe, expect, it } from 'vitest';
import { render } from '../../../tests/helpers/render';
import AppStoreCards from './AppStoreCards';
describe('AppStoreCards', () => {
it('FE-APPSTORE-001: links both stores in a new tab, each with its QR code', () => {
render(<AppStoreCards />);
const cards = [...document.querySelectorAll<HTMLAnchorElement>('a.asc-card')];
expect(cards.map((a) => a.href)).toEqual([
'https://apps.apple.com/app/id6831237775',
'https://play.google.com/store/apps/details?id=com.liketrek.trek',
]);
for (const a of cards) {
expect(a).toHaveAttribute('target', '_blank');
expect(a).toHaveAttribute('rel', 'noopener noreferrer');
expect(a.querySelector('.asc-qr path')?.getAttribute('d')).toMatch(/^M0 0\.5h7/);
}
});
it('FE-APPSTORE-002: names each store and translates the lines around it', () => {
render(<AppStoreCards />);
const [ios, android] = document.querySelectorAll('a.asc-card');
expect(ios).toHaveTextContent('Download on the');
expect(ios).toHaveTextContent('App Store');
expect(ios).toHaveTextContent('iPhone and iPad');
expect(android).toHaveTextContent('Get it on');
expect(android).toHaveTextContent('Google Play');
expect(android).toHaveTextContent('Phone and tablet');
});
it('FE-APPSTORE-003: the dark tone marks the row, the theme tone does not', () => {
const { unmount } = render(<AppStoreCards tone="dark" className="x" />);
expect(document.querySelector('.asc-row')).toHaveClass('asc-dark', 'x');
unmount();
render(<AppStoreCards />);
expect(document.querySelector('.asc-row')).not.toHaveClass('asc-dark');
});
});
@@ -0,0 +1,65 @@
import React from 'react';
import { useTranslation } from '../../i18n/TranslationContext.js';
import './appStoreCards.css';
/**
* The two app stores TREK is in, each as a card with its QR code: scanned with a
* phone it opens the store page, clicked it opens it here. The README draws the
* same cards. The QR codes are generated from the store addresses below (qrcode,
* margin 0, level M); regenerate them if an address changes.
*/
const APP_STORES = [
{
id: 'ios',
href: 'https://apps.apple.com/app/id6831237775',
store: 'App Store',
captionKey: 'settings.apps.downloadOn',
devicesKey: 'settings.apps.iosDevices',
logo: 'M12.152 6.896c-.948 0-2.415-1.078-3.96-1.04-2.04.027-3.91 1.183-4.961 3.014-2.117 3.675-.546 9.103 1.519 12.09 1.013 1.454 2.208 3.09 3.792 3.039 1.52-.065 2.09-.987 3.935-.987 1.831 0 2.35.987 3.96.948 1.637-.026 2.676-1.48 3.676-2.948 1.156-1.688 1.636-3.325 1.662-3.415-.039-.013-3.182-1.221-3.22-4.857-.026-3.04 2.48-4.494 2.597-4.559-1.429-2.09-3.623-2.324-4.39-2.376-2-.156-3.675 1.09-4.61 1.09zM15.53 3.83c.843-1.012 1.4-2.427 1.245-3.83-1.207.052-2.662.805-3.532 1.818-.78.896-1.454 2.338-1.273 3.714 1.338.104 2.715-.688 3.559-1.701',
qrSize: 29,
qr: 'M0 0.5h7m2 0h1m2 0h1m2 0h5m2 0h7M0 1.5h1m5 0h1m3 0h3m4 0h1m2 0h1m1 0h1m5 0h1M0 2.5h1m1 0h3m1 0h1m1 0h1m5 0h1m1 0h1m3 0h1m1 0h1m1 0h3m1 0h1M0 3.5h1m1 0h3m1 0h1m1 0h1m2 0h2m4 0h1m1 0h1m2 0h1m1 0h3m1 0h1M0 4.5h1m1 0h3m1 0h1m1 0h1m2 0h5m2 0h3m1 0h1m1 0h3m1 0h1M0 5.5h1m5 0h1m1 0h3m1 0h5m1 0h1m1 0h1m1 0h1m5 0h1M0 6.5h7m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h7M8 7.5h3m2 0h1m1 0h2m2 0h2M0 8.5h1m1 0h5m4 0h1m2 0h4m1 0h1m2 0h5M0 9.5h3m2 0h1m2 0h4m3 0h1m3 0h4m1 0h1m3 0h1M0 10.5h4m1 0h7m6 0h1m1 0h1m1 0h2M5 11.5h1m1 0h3m1 0h1m2 0h2m2 0h2m1 0h2m1 0h2m1 0h1M2 12.5h1m3 0h3m1 0h1m1 0h1m2 0h3m5 0h1m1 0h2M0 13.5h1m4 0h1m3 0h1m1 0h1m1 0h2m1 0h1m2 0h6m3 0h1M1 14.5h3m1 0h2m5 0h3m3 0h1m2 0h1m2 0h3M0 15.5h1m2 0h2m2 0h7m2 0h1m1 0h3m3 0h1m2 0h1M3 16.5h2m1 0h1m3 0h1m1 0h1m1 0h1m1 0h4m3 0h1m1 0h2M0 17.5h4m5 0h3m3 0h1m1 0h3m2 0h3m1 0h1m1 0h1M0 18.5h1m1 0h1m2 0h2m8 0h3m2 0h2m2 0h1m1 0h1M0 19.5h1m1 0h2m1 0h1m3 0h4m1 0h1m5 0h2m2 0h1m2 0h1M0 20.5h1m1 0h1m1 0h1m1 0h3m8 0h1m2 0h5m1 0h3M8 21.5h1m1 0h5m2 0h2m1 0h1m3 0h5M0 22.5h7m2 0h1m1 0h1m1 0h2m3 0h3m1 0h1m1 0h3M0 23.5h1m5 0h1m1 0h1m1 0h1m2 0h1m5 0h2m3 0h1M0 24.5h1m1 0h3m1 0h1m1 0h1m2 0h2m1 0h1m2 0h1m2 0h5m1 0h1m1 0h1M0 25.5h1m1 0h3m1 0h1m1 0h2m1 0h1m6 0h1m4 0h1m1 0h2M0 26.5h1m1 0h3m1 0h1m1 0h1m1 0h1m1 0h1m2 0h1m3 0h2m1 0h6M0 27.5h1m5 0h1m2 0h3m3 0h1m2 0h1m1 0h2m1 0h3m1 0h1M0 28.5h7m1 0h2m1 0h1m3 0h2m1 0h2m1 0h1m2 0h1m1 0h1',
},
{
id: 'android',
href: 'https://play.google.com/store/apps/details?id=com.liketrek.trek',
store: 'Google Play',
captionKey: 'settings.apps.getItOn',
devicesKey: 'settings.apps.androidDevices',
logo: 'M22.018 13.298l-3.919 2.218-3.515-3.493 3.543-3.521 3.891 2.202a1.49 1.49 0 0 1 0 2.594zM1.337.924a1.486 1.486 0 0 0-.112.568v21.017c0 .217.045.419.124.6l11.155-11.087L1.337.924zm12.207 10.065l3.258-3.238L3.45.195a1.466 1.466 0 0 0-.946-.179l11.04 10.973zm0 2.067l-11 10.933c.298.036.612-.016.906-.183l13.324-7.54-3.23-3.21z',
qrSize: 37,
qr: 'M0 0.5h7m2 0h1m3 0h1m1 0h1m2 0h1m1 0h3m1 0h2m4 0h7M0 1.5h1m5 0h1m4 0h1m2 0h1m2 0h3m5 0h4m1 0h1m5 0h1M0 2.5h1m1 0h3m1 0h1m1 0h2m2 0h5m2 0h4m1 0h1m1 0h1m3 0h1m1 0h3m1 0h1M0 3.5h1m1 0h3m1 0h1m1 0h2m1 0h1m1 0h1m2 0h5m1 0h1m2 0h2m3 0h1m1 0h3m1 0h1M0 4.5h1m1 0h3m1 0h1m1 0h2m3 0h1m4 0h3m1 0h2m1 0h1m2 0h1m1 0h1m1 0h3m1 0h1M0 5.5h1m5 0h1m1 0h6m4 0h1m3 0h1m2 0h4m1 0h1m5 0h1M0 6.5h7m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h7M8 7.5h1m1 0h4m2 0h1m6 0h1m4 0h1M0 8.5h1m1 0h5m2 0h1m3 0h3m2 0h1m1 0h7m3 0h5M0 9.5h5m5 0h1m4 0h3m3 0h1m4 0h1m1 0h1m2 0h1m3 0h1M0 10.5h3m1 0h4m1 0h3m1 0h1m3 0h1m2 0h9m1 0h1m2 0h1m1 0h2M2 11.5h2m3 0h1m5 0h1m2 0h1m4 0h1m1 0h1m2 0h3m1 0h4m2 0h1M1 12.5h1m1 0h1m2 0h1m3 0h1m1 0h2m2 0h2m2 0h1m1 0h6m1 0h4m1 0h3M0 13.5h1m6 0h1m1 0h3m1 0h1m2 0h6m1 0h2m3 0h1m2 0h1M2 14.5h1m3 0h2m1 0h1m1 0h5m1 0h1m3 0h1m4 0h3m2 0h3m1 0h2M2 15.5h2m3 0h1m1 0h1m2 0h7m2 0h2m5 0h5m2 0h2M1 16.5h1m2 0h3m3 0h2m1 0h2m1 0h1m4 0h1m1 0h1m1 0h3m1 0h2m1 0h1m1 0h1M2 17.5h1m2 0h1m2 0h2m1 0h2m2 0h1m2 0h1m1 0h1m1 0h1m1 0h3m1 0h1m2 0h1m2 0h2M1 18.5h1m4 0h1m3 0h2m2 0h3m2 0h1m2 0h1m3 0h2m1 0h1m2 0h1m2 0h2M1 19.5h3m4 0h5m2 0h1m2 0h5m1 0h1m5 0h3m3 0h1M0 20.5h1m1 0h1m1 0h1m1 0h2m2 0h1m4 0h1m1 0h1m1 0h2m1 0h1m1 0h4m1 0h2m1 0h3M1 21.5h1m6 0h2m1 0h1m1 0h2m1 0h1m1 0h3m1 0h2m4 0h1m4 0h1M2 22.5h1m1 0h5m1 0h1m2 0h4m1 0h1m1 0h1m1 0h1m2 0h1m1 0h1m3 0h3m1 0h2M0 23.5h1m2 0h1m1 0h1m5 0h2m2 0h1m7 0h1m4 0h2m1 0h2m2 0h1M1 24.5h2m3 0h1m3 0h4m4 0h1m1 0h7m1 0h3m1 0h1m1 0h2M0 25.5h4m1 0h1m2 0h4m3 0h2m4 0h1m6 0h1m4 0h1M0 26.5h1m2 0h1m1 0h2m3 0h1m1 0h3m5 0h1m2 0h2m1 0h2m2 0h2m2 0h3M0 27.5h1m1 0h3m3 0h2m6 0h1m4 0h1m1 0h1m2 0h7m2 0h1M0 28.5h1m1 0h1m1 0h1m1 0h1m1 0h2m1 0h2m1 0h1m2 0h1m4 0h4m1 0h9M8 29.5h6m2 0h2m1 0h3m1 0h1m3 0h2m3 0h2m1 0h1M0 30.5h7m2 0h1m5 0h3m2 0h2m4 0h1m1 0h1m1 0h1m1 0h1m1 0h1m1 0h1M0 31.5h1m5 0h1m1 0h1m1 0h6m1 0h8m1 0h3m3 0h2m1 0h1M0 32.5h1m1 0h3m1 0h1m1 0h2m1 0h1m1 0h1m1 0h2m2 0h1m1 0h1m2 0h9m1 0h1m1 0h1M0 33.5h1m1 0h3m1 0h1m1 0h1m2 0h1m1 0h3m2 0h1m1 0h3m1 0h2m3 0h2m1 0h1m1 0h2M0 34.5h1m1 0h3m1 0h1m1 0h1m3 0h1m2 0h2m2 0h1m1 0h2m2 0h5m4 0h1m1 0h1M0 35.5h1m5 0h1m5 0h1m1 0h2m2 0h7m3 0h3m1 0h1m3 0h1M0 36.5h7m1 0h1m1 0h1m1 0h1m1 0h2m1 0h1m1 0h1m3 0h4m2 0h2m1 0h5',
},
] as const;
interface Props {
/** `dark` for a surface that stays dark in either theme, like the release modal. */
tone?: 'theme' | 'dark';
className?: string;
}
export default function AppStoreCards({ tone = 'theme', className }: Props): React.ReactElement {
const { t } = useTranslation();
return (
<div className={['asc-row', tone === 'dark' ? 'asc-dark' : '', className ?? ''].filter(Boolean).join(' ')}>
{APP_STORES.map((s) => (
<a key={s.id} className="asc-card" href={s.href} target="_blank" rel="noopener noreferrer">
<span className="asc-qr" aria-hidden="true">
<svg viewBox={`0 0 ${s.qrSize} ${s.qrSize}`} shapeRendering="crispEdges">
<path className="asc-qr-dots" d={s.qr} />
</svg>
</span>
<span className="asc-text">
<span className="asc-caption">
<svg className="asc-logo" viewBox="0 0 24 24" aria-hidden="true">
<path d={s.logo} />
</svg>
{t(s.captionKey)}
</span>
<span className="asc-store">{s.store}</span>
<span className="asc-devices">{t(s.devicesKey)}</span>
</span>
</a>
))}
</div>
);
}
@@ -8,7 +8,7 @@ import type { TourPlannerController } from '../Tours/planner/useTourPlanner'
import ToursSidebar from '../Tours/ToursSidebar'
import type { Day } from '../../types'
import CustomSelect from './CustomSelect'
import { hikePlannerDefaults } from '../../../tests/helpers/tourPlannerStub'
import { hikePlannerDefaults, mockTourEditorLayout } from '../../../tests/helpers/tourPlannerStub'
vi.mock('../../repo/tourRepo', () => ({ tourRepo: {} }))
vi.mock('../../store/settingsStore', () => ({
@@ -57,6 +57,7 @@ describe('CustomSelect consumer contracts', () => {
expect(screen.getByLabelText('Maximum trail difficulty')).toBe(trigger)
expect(trigger).toHaveAttribute('id', 'tour-planner-difficulty')
expect(document.querySelectorAll('[id="tour-planner-difficulty"]')).toHaveLength(1)
mockTourEditorLayout(trigger.parentElement ?? trigger)
await user.click(trigger)
const menu = within(document.getElementById(trigger.getAttribute('aria-controls')!)!)
for (const difficulty of [1, 2, 3, 4, 5, 6]) {
@@ -132,4 +133,4 @@ describe('CustomSelect consumer contracts', () => {
await user.click(screen.getByRole('button', { name: /^Planned\s*1$/ }))
expect(setFilter).toHaveBeenLastCalledWith('planned')
})
})
})
+15 -11
View File
@@ -1,9 +1,10 @@
import React, { useState, useRef, useEffect, useId } from 'react'
import { createPortal } from 'react-dom'
import { ChevronDown, Check } from 'lucide-react'
import { useAnchoredPosition, scrollAnchorIntoView } from '../../hooks/useAnchoredPosition'
import { scrollAnchorIntoView } from '../../hooks/useAnchoredPosition'
import { useTranslation } from '../../i18n'
import { selectionHaptic } from '../../native/haptics'
import { useAnchoredPopover } from './useAnchoredPopover'
interface SelectOption {
// Callers use both string keys and numeric ids (e.g. day/place ids) as values, and
@@ -85,7 +86,6 @@ export default function CustomSelect({
menuFit = 'anchor',
id,
}: CustomSelectProps) {
const [open, setOpen] = useState(false)
const [search, setSearch] = useState('')
const ref = useRef<HTMLDivElement>(null)
const triggerRef = useRef<HTMLButtonElement>(null)
@@ -97,23 +97,24 @@ export default function CustomSelect({
// Follows the trigger while the sheet scrolls and while the on-screen keyboard
// resizes the viewport, instead of freezing at the rect measured on open (#1999).
const anchored = useAnchoredPosition(ref, open)
const { open, bounded, box: anchored, setOpen } = useAnchoredPopover(ref, { disabled })
const menuOpen = open && (!bounded || !!anchored)
useEffect(() => {
if (!open || !searchable || !searchRef.current) return
if (!menuOpen || !searchable || !searchRef.current) return
if (!keyboardDirection.current) searchRef.current.focus()
// Focusing raises the keyboard on a phone; scroll the trigger up so the list
// it just opened is not left underneath it (#2000).
scrollAnchorIntoView(ref.current)
}, [open, searchable])
}, [menuOpen, searchable])
useEffect(() => {
if (!open || !keyboardDirection.current) return
if (!menuOpen || !keyboardDirection.current) return
const buttons = dropRef.current?.querySelectorAll<HTMLButtonElement>('button')
const direction = keyboardDirection.current
keyboardDirection.current = null
if (buttons?.length) buttons[direction === 'last' ? buttons.length - 1 : 0].focus()
}, [open])
}, [menuOpen])
useEffect(() => {
const handleClick = (e: MouseEvent) => {
@@ -123,7 +124,7 @@ export default function CustomSelect({
}
if (open) document.addEventListener('mousedown', handleClick)
return () => document.removeEventListener('mousedown', handleClick)
}, [open])
}, [open, setOpen])
const selected = options.find(o => sameValue(value, o.value))
const filtered = searchable && search
@@ -152,6 +153,8 @@ export default function CustomSelect({
: options
const sm = size === 'sm'
const availableOptionsHeight = (anchored?.maxHeight ?? 220) - (searchable ? 38 : 0)
const optionsHeight = bounded ? Math.max(0, availableOptionsHeight - 2) : Math.max(96, availableOptionsHeight)
const closeMenu = () => {
setOpen(false)
@@ -223,7 +226,7 @@ export default function CustomSelect({
</button>
{/* Dropdown */}
{open && createPortal(
{menuOpen && createPortal(
<div ref={dropRef} id={menuId} role="group" aria-label={ariaLabel || selected?.label || placeholder || undefined} onKeyDown={handleKeyDown} style={{
position: 'fixed',
...(anchored
@@ -233,7 +236,7 @@ export default function CustomSelect({
// Never narrower than the trigger, and never past the right-hand edge of
// the window. The cap is read at render time rather than measured, and
// that is enough: every reason the anchor moved already re-renders this.
...(menuFit === 'content'
...(!bounded && menuFit === 'content'
? {
minWidth: anchored.width,
width: 'max-content',
@@ -251,6 +254,7 @@ export default function CustomSelect({
boxShadow: '0 8px 32px rgba(0,0,0,0.12)',
overflow: 'hidden',
animation: 'trek-menu-enter 200ms cubic-bezier(0.23, 1, 0.32, 1)',
overflowWrap: bounded ? 'anywhere' : undefined,
transformOrigin: anchored?.flipped ? 'bottom center' : 'top center',
willChange: 'transform, opacity',
}}>
@@ -277,7 +281,7 @@ export default function CustomSelect({
{/* Options — capped at whatever the viewport still shows, so a list opened
beside an on-screen keyboard shrinks instead of hiding under it (#2000). */}
<div style={{
maxHeight: Math.min(220, Math.max(96, (anchored?.maxHeight ?? 220) - (searchable ? 38 : 0))),
maxHeight: Math.min(220, optionsHeight),
overflowY: 'auto',
// The panel is portaled to document.body and positioned fixed, so its
// scroll chain runs to the viewport rather than to the sheet it looks
@@ -0,0 +1,124 @@
/* The store cards: a QR code on its white tile, the store's mark and name beside it.
The theme tone follows the appearance tokens; .asc-dark is for a surface that is
dark in either theme (the release modal). */
.asc-row {
display: grid;
/* Always side by side: two compact cards read as one row of stores. */
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px;
}
.asc-card {
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
padding: 8px 12px 8px 8px;
border-radius: 16px;
border: 1px solid var(--border-faint);
background: var(--bg-card);
color: var(--text-primary);
text-decoration: none;
transition:
transform 160ms ease,
border-color 160ms ease,
box-shadow 160ms ease;
}
.asc-card:hover {
transform: translateY(-1px);
border-color: var(--border-primary);
box-shadow: 0 10px 24px -14px rgb(0 0 0 / 0.35); /* a neutral lift shadow */
}
.asc-card:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
/* A QR code needs its light quiet zone in either theme to scan. */
.asc-qr {
flex: none;
display: grid;
place-items: center;
width: 56px;
height: 56px;
padding: 5px;
border-radius: 10px;
background: #ffffff; /* a QR code needs a white quiet zone to scan */
border: 1px solid var(--border-faint);
}
.asc-qr svg {
width: 100%;
height: 100%;
display: block;
}
.asc-qr-dots {
fill: none;
stroke: #0f172a;
} /* QR modules stay dark on their white tile */
.asc-text {
display: flex;
flex-direction: column;
min-width: 0;
line-height: 1.2;
}
.asc-caption {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: calc(10.5px * var(--fs-scale-caption, 1));
color: var(--text-muted);
white-space: nowrap;
}
.asc-logo {
width: 12px;
height: 12px;
flex: none;
fill: currentColor;
}
.asc-store {
margin-top: 2px;
font-size: calc(16px * var(--fs-scale-subtitle, 1));
font-weight: 700;
letter-spacing: -0.02em;
color: var(--text-primary);
white-space: nowrap;
}
.asc-devices {
margin-top: 2px;
font-size: calc(10.5px * var(--fs-scale-caption, 1));
color: var(--text-muted);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.asc-dark .asc-card {
background: linear-gradient(160deg, oklch(1 0 0 / 0.1) 0%, oklch(1 0 0 / 0.045) 62%);
border-color: oklch(1 0 0 / 0.13);
color: #f5f5f7; /* the release modal is dark in either theme */
box-shadow: inset 0 1px 0 oklch(1 0 0 / 0.16);
}
.asc-dark .asc-card:hover {
border-color: oklch(1 0 0 / 0.26);
}
.asc-dark .asc-qr {
border-color: transparent;
}
.asc-dark .asc-store {
color: #f5f5f7;
} /* the release modal is dark in either theme */
.asc-dark .asc-caption,
.asc-dark .asc-devices {
color: oklch(1 0 0 / 0.6);
}
@media (prefers-reduced-motion: reduce) {
.asc-card {
transition: none;
}
.asc-card:hover {
transform: none;
}
}
+6 -3
View File
@@ -161,12 +161,15 @@ export function PopoverListPanel({ list, label, className = '', children }: {
className?: string
children: ReactNode
}) {
const { open, box, menuRef, listId, onListKey } = list
const { open, box, bounded, menuRef, listId, onListKey } = list
if (!open || !box) return null
return createPortal(
<div ref={menuRef} id={listId} role="group" aria-label={label} onKeyDown={onListKey}
className={`fixed z-[var(--z-toast)] overflow-y-auto ${className}`}
style={{ ...POPOVER, top: box.top, bottom: box.bottom, left: box.left, maxHeight: box.maxHeight }}>
className={`fixed z-[var(--z-toast)] overflow-y-auto ${bounded ? 'overflow-x-hidden overscroll-contain [overflow-wrap:anywhere] [&>button]:shrink-0' : ''} ${className}`}
style={{
...POPOVER, top: box.top, bottom: box.bottom, left: box.left, width: box.width || undefined, maxHeight: box.maxHeight,
minWidth: bounded ? 0 : undefined,
}}>
{children}
</div>,
document.body,
@@ -0,0 +1,32 @@
import { createContext, use, useCallback, useState, type RefObject } from 'react';
import { useAnchoredPosition } from '../../hooks/useAnchoredPosition';
/** The scrolling content that contains a panel's dropdown triggers. */
export const PopoverBoundary = createContext<RefObject<HTMLElement | null> | null>(null);
export function useAnchoredPopover(
anchorRef: RefObject<HTMLElement | null>,
{
disabled = false,
estimatedHeight,
matchWidth = true,
}: {
disabled?: boolean;
estimatedHeight?: number;
matchWidth?: boolean;
}
) {
const boundaryRef = use(PopoverBoundary);
const bounded = !!boundaryRef;
const unavailable = bounded && disabled;
const [expanded, setOpen] = useState(false);
if (unavailable && expanded) setOpen(false);
const open = expanded && !unavailable;
const hide = useCallback(() => setOpen(false), []);
const box = useAnchoredPosition(anchorRef, open, {
matchWidth: bounded || matchWidth,
estimatedHeight,
boundary: boundaryRef ? { ref: boundaryRef, onAnchorHidden: hide } : undefined,
});
return { open, box, bounded, setOpen };
}

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