Compare commits

...

65 Commits

Author SHA1 Message Date
dependabot[bot] 246ddbac25 chore(deps): bump @noble/hashes from 1.8.0 to 2.4.0
Bumps [@noble/hashes](https://github.com/paulmillr/noble-hashes) from 1.8.0 to 2.4.0.
- [Release notes](https://github.com/paulmillr/noble-hashes/releases)
- [Changelog](https://github.com/paulmillr/noble-hashes/blob/main/CHANGELOG.md)
- [Commits](https://github.com/paulmillr/noble-hashes/compare/1.8.0...2.4.0)

---
updated-dependencies:
- dependency-name: "@noble/hashes"
  dependency-version: 2.4.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-28 13:03:19 +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
317 changed files with 7828 additions and 598 deletions
+3 -2
View File
@@ -107,8 +107,9 @@ jobs:
# 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). Held back
# while the app needs a server version that is not released yet.
# 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:
@@ -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 {
+1 -1
View File
@@ -102,7 +102,7 @@
"@fontsource/shrikhand": "^5.3.0",
"@fontsource/yellowtail": "^5.3.0",
"@maplibre/maplibre-gl-leaflet": "0.1.4",
"@noble/hashes": "^1.8.0",
"@noble/hashes": "^2.4.0",
"@simplewebauthn/browser": "^14.0.0",
"@trek/shared": "*",
"axios": "^1.21.0",
+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;
+1 -1
View File
@@ -8,7 +8,7 @@
"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,
+2 -2
View File
@@ -18,8 +18,8 @@
"src/index.css": 1636,
"src/mobile/screens/admin/MAdminPluginsPanel.tsx": 1503,
"src/pages/JourneyDetailPage.test.tsx": 3886,
"src/pages/LoginPage.tsx": 1294,
"src/pages/TripPlannerPage.tsx": 1128,
"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,
+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({
@@ -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,
@@ -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
@@ -317,8 +317,8 @@ async function valhallaOrOsrmDay(
const plain = (await storedRoute(keys.plain)) ?? await osrmWithLegs(waypoints, keys.coords, profile, signal)
cacheRoute(keys.plain, plain)
const drawn = withFallbackNoted(plain, avoiding)
// A day left before Valhalla answered was never refused by it.
if (standInKey && !signal?.aborted) keepStandIn(standInKey, drawn)
// 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
}
@@ -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`. */
@@ -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])
}
@@ -314,6 +314,21 @@ describe('the route cache keeps the engine apart', () => {
});
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,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 = [
@@ -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
@@ -1480,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)
@@ -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;
}
@@ -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,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();
});
});
@@ -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;
}
@@ -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>
);
}
@@ -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
+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 };
}
+22 -13
View File
@@ -1,5 +1,5 @@
import { useEffect, useId, useLayoutEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react';
import { useAnchoredPosition } from '../../hooks/useAnchoredPosition';
import { useEffect, useId, useLayoutEffect, useRef, type KeyboardEvent as ReactKeyboardEvent } from 'react';
import { useAnchoredPopover } from './useAnchoredPopover';
const itemsOf = (list: HTMLElement | null) => Array.from(list?.querySelectorAll('button') ?? []);
@@ -13,38 +13,47 @@ const EDGE = 8;
* it and goes on from the button; a click beside it closes it. The caller draws
* the button and the list and hands `currentIndex`, the choice held now.
*/
export function usePopoverList(currentIndex: number, options: { estimatedHeight?: number } = {}) {
const [open, setOpen] = useState(false);
export function usePopoverList(
currentIndex: number,
{
estimatedHeight = 320,
disabled,
}: {
estimatedHeight?: number;
disabled?: boolean;
} = {}
) {
const triggerRef = useRef<HTMLButtonElement>(null);
const menuRef = useRef<HTMLDivElement>(null);
const startAt = useRef(0);
const listId = useId();
const box = useAnchoredPosition(triggerRef, open, {
const { open, box, bounded, setOpen } = useAnchoredPopover(triggerRef, {
matchWidth: false,
estimatedHeight: options.estimatedHeight ?? 320,
estimatedHeight,
disabled,
});
const listShown = open && !!box;
const toggle = () => {
if (!open) startAt.current = Math.max(0, currentIndex);
setOpen((o) => !o);
setOpen((value) => !value);
};
useEffect(() => {
if (listShown) itemsOf(menuRef.current)[startAt.current]?.focus({ preventScroll: true });
}, [listShown]);
if (listShown) itemsOf(menuRef.current)[startAt.current]?.focus({ preventScroll: !bounded });
}, [listShown, bounded]);
// The list opens from its button's start; one wider than the room beside a button near the
// window's side moves back inside, as far as it must, before it is painted.
useLayoutEffect(() => {
const menu = menuRef.current;
if (!listShown || !menu) return;
if (!listShown || !menu || bounded) return;
menu.style.translate = '';
const rect = menu.getBoundingClientRect();
let shift = Math.min(0, window.innerWidth - EDGE - rect.right);
if (rect.left + shift < EDGE) shift = EDGE - rect.left;
if (shift) menu.style.translate = `${Math.round(shift)}px 0`;
}, [listShown, box]);
}, [listShown, box, bounded]);
useEffect(() => {
if (!open) return;
@@ -66,7 +75,7 @@ export function usePopoverList(currentIndex: number, options: { estimatedHeight?
document.removeEventListener('mousedown', onDown);
document.removeEventListener('keydown', onKey, true);
};
}, [open]);
}, [open, setOpen]);
/** Closes the list after a choice and hands the focus back to the button. */
const close = () => {
@@ -94,5 +103,5 @@ export function usePopoverList(currentIndex: number, options: { estimatedHeight?
items[next]?.focus();
};
return { open, box, toggle, close, onListKey, triggerRef, menuRef, listId };
return { open, box, bounded, toggle, close, onListKey, triggerRef, menuRef, listId };
}
+53 -23
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
import { useCallback, useEffect, useLayoutEffect, useState } from 'react'
export interface AnchoredBox {
/** Distance from the viewport top, when the panel hangs below the trigger. */
@@ -22,8 +22,38 @@ interface AnchoredOptions {
padding?: number
/** Adopt the trigger's width (selects) instead of measuring only its position. */
matchWidth?: boolean
/** Keep the panel inside a scroll area and dismiss it when the anchor leaves. */
boundary?: {
ref: React.RefObject<HTMLElement | null>
onAnchorHidden: () => void
}
}
function viewportBounds() {
// visualViewport excludes the area covered by an on-screen keyboard.
const viewport = window.visualViewport
const top = viewport?.offsetTop ?? 0
const left = viewport?.offsetLeft ?? 0
return { top, left, bottom: top + (viewport?.height ?? window.innerHeight), right: left + (viewport?.width ?? window.innerWidth) }
}
function anchorLimits(anchor: DOMRect, boundaryRef?: React.RefObject<HTMLElement | null>) {
const viewport = viewportBounds()
const rect = boundaryRef?.current?.getBoundingClientRect()
if (!rect) return { top: viewport.top, bottom: viewport.bottom, left: anchor.left, width: anchor.width, bounded: false }
const left = Math.max(anchor.left, rect.left, viewport.left)
return {
top: Math.max(viewport.top, rect.top),
bottom: Math.min(viewport.bottom, rect.bottom),
left,
width: Math.min(anchor.right, rect.right, viewport.right) - left,
bounded: true,
}
}
/** Below this much room, the list would barely display its own border and padding. */
const MIN_BOUNDED_HEIGHT = 24
/** How much the viewport must shrink before we treat it as an on-screen keyboard. */
const KEYBOARD_THRESHOLD = 120
@@ -47,37 +77,35 @@ const KEYBOARD_THRESHOLD = 120
export function useAnchoredPosition(
anchorRef: React.RefObject<HTMLElement | null>,
open: boolean,
{ estimatedHeight = 220, offset = 4, padding = 8, matchWidth = true }: AnchoredOptions = {},
{ estimatedHeight = 220, offset = 4, padding = 8, matchWidth = true, boundary }: AnchoredOptions = {},
): AnchoredBox | null {
const [box, setBox] = useState<AnchoredBox | null>(null)
// Read in the measure callback so it stays stable across renders.
const optsRef = useRef({ estimatedHeight, offset, padding, matchWidth })
optsRef.current = { estimatedHeight, offset, padding, matchWidth }
const boundaryRef = boundary?.ref
const onAnchorHidden = boundary?.onAnchorHidden
const measure = useCallback(() => {
const el = anchorRef.current
if (!el) return
const { estimatedHeight: wanted, offset: gap, padding: pad, matchWidth: match } = optsRef.current
const r = el.getBoundingClientRect()
// visualViewport is the part still visible next to an open keyboard; its
// offsetTop is how far the browser scrolled the layout viewport up to keep
// the focused field in sight, which shifts where "the bottom" really is.
const vv = typeof window !== 'undefined' ? window.visualViewport : null
const viewTop = typeof vv?.offsetTop === 'number' ? vv.offsetTop : 0
const viewHeight = typeof vv?.height === 'number' ? vv.height : window.innerHeight
const viewBottom = viewTop + viewHeight
const spaceBelow = viewBottom - r.bottom - gap - pad
const spaceAbove = r.top - viewTop - gap - pad
const limits = anchorLimits(r, boundaryRef)
const spaceBelow = limits.bottom - r.bottom - offset - padding
const spaceAbove = r.top - limits.top - offset - padding
// Only flip when below genuinely cannot hold the panel and above is roomier,
// which keeps the familiar downward direction in the ordinary case.
const flipped = spaceBelow < Math.min(wanted, 160) && spaceAbove > spaceBelow
const maxHeight = Math.max(96, Math.floor(flipped ? spaceAbove : spaceBelow))
const flipped = spaceBelow < Math.min(estimatedHeight, 160) && spaceAbove > spaceBelow
const availableHeight = Math.floor(flipped ? spaceAbove : spaceBelow)
if (limits.bounded && (r.bottom <= limits.top || r.top >= limits.bottom || limits.width <= 0 || availableHeight < MIN_BOUNDED_HEIGHT)) {
setBox(null)
onAnchorHidden?.()
return
}
const maxHeight = limits.bounded ? availableHeight : Math.max(96, availableHeight)
const { left } = limits
const width = matchWidth ? limits.width : 0
const next: AnchoredBox = flipped
? { bottom: Math.round(window.innerHeight - r.top + gap), left: r.left, width: r.width, maxHeight, flipped }
: { top: Math.round(r.bottom + gap), left: r.left, width: r.width, maxHeight, flipped }
if (!match) next.width = 0
? { bottom: Math.round(window.innerHeight - r.top + offset), left, width, maxHeight, flipped }
: { top: Math.round(r.bottom + offset), left, width, maxHeight, flipped }
setBox(prev =>
prev
@@ -87,7 +115,7 @@ export function useAnchoredPosition(
? prev
: next,
)
}, [anchorRef])
}, [anchorRef, boundaryRef, estimatedHeight, matchWidth, offset, onAnchorHidden, padding])
// Measure before paint so the panel never shows up at a stale spot first.
useLayoutEffect(() => {
@@ -110,6 +138,8 @@ export function useAnchoredPosition(
// The trigger can change size on its own (a select whose label grows).
const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(measure) : null
if (el && ro) ro.observe(el)
const boundaryEl = boundaryRef?.current
if (boundaryEl && ro) ro.observe(boundaryEl)
return () => {
window.removeEventListener('scroll', measure, true)
window.removeEventListener('resize', measure)
@@ -117,7 +147,7 @@ export function useAnchoredPosition(
vv?.removeEventListener('scroll', measure)
ro?.disconnect()
}
}, [open, measure, anchorRef])
}, [open, measure, anchorRef, boundaryRef])
return box
}
+1
View File
@@ -146,6 +146,7 @@ export function useResizablePanels() {
// dragged on a big screen comes back untouched once there is room for it again.
leftWidth: shownLeft,
rightWidth: shownRight,
viewportWidth,
leftCollapsed, rightCollapsed, setLeftCollapsed, setRightCollapsed,
leftHidden, rightHidden, toggleLeft, toggleRight, narrow,
startResizeLeft, startResizeRight, nudgeLeft, nudgeRight, resizing,
@@ -22,7 +22,7 @@ beforeEach(() => {
// A second spyOn returns the first spy with its calls; start every test clean.
vi.restoreAllMocks();
navigate.mockReset();
useSharedImportStore.setState({ file: null, tripId: null, link: null });
useSharedImportStore.setState({ file: null, tripId: null, link: null, placeLink: null });
useAddonStore.setState({ addons: [{ id: 'collab', enabled: true }] as never, loaded: true });
useTripAddonsStore.setState({ trips: {} });
// Every trip follows the instance switch unless a test says otherwise; answered at once, so no read outlives its test.
@@ -217,6 +217,35 @@ describe('NativeImportSheet', () => {
expect(saveSharedLink).toHaveBeenCalledTimes(1);
});
it('offers a shared map link as a place first, and hands it to the trip picked (#2582)', async () => {
const maps = {
url: 'https://www.google.com/maps/place/Time+Out+Market',
title: 'Time Out Market',
presetTripId: null,
};
render(<NativeImportSheet />);
act(() => useSharedImportStore.getState().setFile(page(), maps));
const choices = await screen.findAllByRole('button', {
name: /Add it as a place|Save to the trip's links|Read a booking/,
});
expect(choices[0]).toHaveAccessibleName(/Add it as a place/);
fireEvent.click(choices[0]);
expect(screen.getByText('Add the place to which trip?')).toBeInTheDocument();
fireEvent.click(await screen.findByRole('button', { name: /Japan/ }));
expect(useSharedImportStore.getState().placeLink).toEqual({ tripId: 2, url: maps.url });
expect(useSharedImportStore.getState().file).toBeNull();
expect(navigate).toHaveBeenCalledWith('/trips/2');
expect(saveSharedLink).not.toHaveBeenCalled();
});
it('offers no place for a link that is not a map', async () => {
render(<NativeImportSheet />);
act(() => useSharedImportStore.getState().setFile(page(), link()));
await screen.findByText('What should TREK do with this link?');
expect(screen.queryByRole('button', { name: /Add it as a place/ })).not.toBeInTheDocument();
});
it('stays closed with nothing shared', () => {
render(<NativeImportSheet />);
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
@@ -7,11 +7,14 @@
* (Collaboration, Links), or read as a booking. A bare link, whose page the phone
* could not read, can only be kept; with Collaboration off, a page can only be read.
* Collaboration counts per trip: a link goes only to a trip that has it on.
* A map link (Google Maps, Amap) can also become a place of the
* trip (#2582): the trip's new place sheet opens and looks the link up.
*/
import { ChevronRight, FileText, Link2, ScanText } from 'lucide-react';
import { ChevronRight, FileText, Link2, MapPin, ScanText } from 'lucide-react';
import React, { useEffect, useEffectEvent, useRef, useState } from 'react';
import { useLocation, useNavigate } from 'react-router';
import { useShallow } from 'zustand/react/shallow';
import { isMapUrl } from '../../components/Planner/PlaceFormModal.helpers';
import { useToast } from '../../components/shared/Toast';
import { useTranslation } from '../../i18n';
import { saveSharedLink, useSharedImportStore, type SharedLink } from '../../native/sharedFiles';
@@ -31,11 +34,15 @@ interface TripRow {
end_date?: string | null;
}
type LinkChoice = 'link' | 'booking';
type LinkChoice = 'link' | 'booking' | 'place';
/** What to offer for a shared link: the links when Collaboration is on, the import when there is a page to read. */
function linkChoicesOf(file: File, collabOn: boolean): LinkChoice[] {
/**
* What to offer for a shared link: a place first when it points at a map, the links
* when Collaboration is on, the import when there is a page to read.
*/
function linkChoicesOf(file: File, collabOn: boolean, url: string): LinkChoice[] {
const choices: LinkChoice[] = [];
if (isMapUrl(url)) choices.push('place');
if (collabOn) choices.push('link');
if (file.type !== 'text/uri-list') choices.push('booking');
return choices;
@@ -54,19 +61,22 @@ interface StageInput {
/** Where the sheet stands for the shared item: what it asks, and what a tap on a trip does. */
function stageOf({ file, link, collabOn, picked, presetFailed, settled }: StageInput) {
if (!file || !link) return { choice: 'booking' as LinkChoice | null, asking: false, nowhere: false, showTrips: true };
if (!settled) return { choice: null, asking: false, nowhere: false, showTrips: false };
const choices = linkChoicesOf(file, collabOn);
const none: LinkChoice[] = [];
if (!file || !link)
return { choice: 'booking' as LinkChoice | null, asking: false, nowhere: false, choices: none, showTrips: true };
if (!settled) return { choice: null, asking: false, nowhere: false, choices: none, showTrips: false };
const choices = linkChoicesOf(file, collabOn, link.url);
const choice = picked ?? (choices.length === 1 ? choices[0] : null);
const asking = choice == null && choices.length > 1;
const nowhere = choices.length === 0;
// While the share sheet's trip takes the link there is nothing to choose.
const presetTakes = link.presetTripId != null && choice === 'link' && !presetFailed;
return { choice, asking, nowhere, showTrips: !asking && !nowhere && !presetTakes };
return { choice, asking, nowhere, choices, showTrips: !asking && !nowhere && !presetTakes };
}
function sheetTitle(t: (key: string) => string, asking: boolean, choice: LinkChoice | null): string {
if (asking) return t('native.share.linkTitle');
if (choice === 'place') return t('native.share.placeTrip');
return choice === 'link' ? t('native.share.linkTrip') : t('native.share.title');
}
@@ -151,6 +161,7 @@ export default function NativeImportSheet(): React.ReactElement | null {
const tripId = useSharedImportStore((s) => s.tripId);
const link = useSharedImportStore((s) => s.link);
const chooseTrip = useSharedImportStore((s) => s.chooseTrip);
const choosePlaceTrip = useSharedImportStore((s) => s.choosePlaceTrip);
const setFile = useSharedImportStore((s) => s.setFile);
const instanceCollab = useAddonStore((s) => s.isEnabled('collab'));
const open = !!file && tripId == null;
@@ -164,7 +175,7 @@ export default function NativeImportSheet(): React.ReactElement | null {
// The save in flight, kept off the state: it guards a second tap, it is not shown.
const savingRef = useRef<File | null>(null);
const picked = pick && pick.file === file ? pick.choice : null;
const { choice, asking, nowhere, showTrips } = stageOf({
const { choice, asking, nowhere, choices, showTrips } = stageOf({
file,
link,
collabOn,
@@ -198,17 +209,28 @@ export default function NativeImportSheet(): React.ReactElement | null {
);
};
// The trip's new place sheet takes the map link from here (MTripShell, MPlaceEditSheet).
const addPlace = (id: number) => {
choosePlaceTrip(id);
void navigate(`/trips/${id}`);
};
// The trip the share sheet picked, used as soon as it is clear what the link is for.
const preset = link?.presetTripId ?? null;
const applyPreset = useEffectEvent((id: number, use: LinkChoice) => {
if (use === 'booking') chooseTrip(id);
else if (use === 'place') addPlace(id);
else if (failedFile !== file) saveLink(id);
});
useEffect(() => {
if (preset != null && choice != null && file) applyPreset(preset, choice);
}, [preset, choice, file]);
const pickTrip = (id: number) => (choice === 'link' ? saveLink(id) : chooseTrip(id));
const pickTrip = (id: number) => {
if (choice === 'link') saveLink(id);
else if (choice === 'place') addPlace(id);
else chooseTrip(id);
};
return (
<MSheet open={open} onClose={() => setFile(null)} variant="bottom" ariaLabel={t('native.share.title')}>
@@ -222,7 +244,7 @@ export default function NativeImportSheet(): React.ReactElement | null {
closeLabel={t('common.close')}
/>
</div>
{asking && file && <LinkQuestion onPick={(use) => setPick({ file, choice: use })} />}
{asking && file && <LinkQuestion choices={choices} onPick={(use) => setPick({ file, choice: use })} />}
{nowhere && (
<p className="px-1 text-[length:calc(12px*var(--fs-scale-body,1))] text-m-muted">
{t('native.share.linkUnsupported')}
@@ -234,22 +256,40 @@ export default function NativeImportSheet(): React.ReactElement | null {
);
}
function LinkQuestion({ onPick }: { onPick: (choice: LinkChoice) => void }): React.ReactElement {
function LinkQuestion({
choices,
onPick,
}: {
choices: LinkChoice[];
onPick: (choice: LinkChoice) => void;
}): React.ReactElement {
const { t } = useTranslation();
return (
<div className="flex flex-col gap-2">
<ChoiceRow
icon={<Link2 size={17} strokeWidth={2} />}
label={t('native.share.saveLink')}
hint={t('native.share.saveLinkHint')}
onClick={() => onPick('link')}
/>
<ChoiceRow
icon={<ScanText size={17} strokeWidth={2} />}
label={t('native.share.readBooking')}
hint={t('native.share.readBookingHint')}
onClick={() => onPick('booking')}
/>
{choices.includes('place') && (
<ChoiceRow
icon={<MapPin size={17} strokeWidth={2} />}
label={t('native.share.addPlace')}
hint={t('native.share.addPlaceHint')}
onClick={() => onPick('place')}
/>
)}
{choices.includes('link') && (
<ChoiceRow
icon={<Link2 size={17} strokeWidth={2} />}
label={t('native.share.saveLink')}
hint={t('native.share.saveLinkHint')}
onClick={() => onPick('link')}
/>
)}
{choices.includes('booking') && (
<ChoiceRow
icon={<ScanText size={17} strokeWidth={2} />}
label={t('native.share.readBooking')}
hint={t('native.share.readBookingHint')}
onClick={() => onPick('booking')}
/>
)}
</div>
);
}
+20
View File
@@ -925,3 +925,23 @@ html:has(.m-shell) ::-webkit-scrollbar {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
/* A stop's number in the plan, as its pin on the map carries it (#2584):
at the foot of its picture, on the trailing side. */
.m-root .m-stop-num {
position: absolute;
inset-inline-end: -4px;
bottom: -3px;
display: grid;
place-items: center;
min-width: 16px;
height: 16px;
padding-inline: 4px;
border-radius: 999px;
background: var(--m-act);
color: var(--m-actfg);
box-shadow: 0 0 0 1.5px var(--m-bg);
font: 700 0.5625rem/1 'Geist Sans', Poppins, system-ui, sans-serif;
font-variant-numeric: tabular-nums;
pointer-events: none;
}
@@ -35,7 +35,7 @@ interface MCollPlaceSheetProps {
labels: CollectionLabel[]
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; 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; address?: string | null }) => Promise<void>
onUploadImage?: (file: File) => Promise<void>
onCopyToTrip: () => void
onRemove: () => void
@@ -57,7 +57,7 @@ export default function MCollPlaceSheet({
const [navOpen, setNavOpen] = useState(false)
const navBtnRef = useRef<HTMLButtonElement | null>(null)
const {
shown: held, editing, setEditing, name, setName, address, setAddress, categoryId, setCategoryId, description, setDescription,
shown: held, editing, setEditing, name, setName, address, setAddress, categoryId, setCategoryId, description, setDescription, notes, setNotes,
links, setLinks, labelIds, toggleLabel, saving, imgBusy, cover, assignedLabels, handleImagePick, handleImageRemove, cancelEdit, save,
} = useCollectionPlaceForm({
place, labels, onSave, onUploadImage, t, normalizeLinkUrl, holdLastPlace: true, dropPhotoOnPlaceUpdate: true,
@@ -195,6 +195,8 @@ export default function MCollPlaceSheet({
)}
<Eyebrow className="mb-[6px] mt-[14px]">{t('collections.description').toUpperCase()}</Eyebrow>
<textarea rows={4} value={description} onChange={e => setDescription(e.target.value)} placeholder={t('collections.descriptionPlaceholder')} className={TEXTAREA_CLS} />
<Eyebrow className="mb-[6px] mt-[14px]">{t('collections.notes').toUpperCase()}</Eyebrow>
<textarea rows={3} value={notes} onChange={e => setNotes(e.target.value)} placeholder={t('collections.notesPlaceholder')} className={TEXTAREA_CLS} />
<Eyebrow className="mb-[6px] mt-[14px]">{t('collections.links').toUpperCase()}</Eyebrow>
<MCollLinksEditor links={links} onChange={setLinks} t={t} />
<div className="mt-4 flex items-center gap-2">
@@ -228,6 +230,15 @@ export default function MCollPlaceSheet({
<Markdown remarkPlugins={[remarkGfm, remarkBreaks]}>{held.description}</Markdown>
</div>
)}
{/* The traveller's own notes (#3168), the way the place sheet of a trip shows them. */}
{held.notes?.trim() && (
<>
<Eyebrow className="mb-[6px] mt-[14px]">{t('collections.notes').toUpperCase()}</Eyebrow>
<p className="m-0 whitespace-pre-wrap rounded-[14px] bg-m-card px-[13px] py-[10px] font-geist text-caption leading-[1.55] text-m-muted [overflow-wrap:anywhere]">
{held.notes}
</p>
</>
)}
{held.links && held.links.length > 0 && (
<div className="mt-3 flex flex-wrap gap-[6px]">
{held.links.map((l, i) => (
@@ -138,6 +138,13 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
[current?.entries, hideSkeletons],
)
// An existing entry opens to be read, also for those who may edit it (#3007);
// the pencil in its sheet switches to the editor. New entries and suggestions
// open in the editor straight away.
const [editEntryId, setEditEntryId] = useState<number | null>(null)
const readingEntry = !!editingEntry && canEditEntries && editingEntry.id !== 0
&& editingEntry.type !== 'skeleton' && editEntryId !== editingEntry.id
const {
mapRef, carouselRef, cardRefs, activeIndex, focusIndex, setActiveIndex, scrubberDays,
syncMapToCard, handleMarkerClick, handleCardTap, openEntryById, jumpToDay,
@@ -698,7 +705,8 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
entry={editingEntry}
galleryPhotos={gallery}
quickCapture={editingEntry.id === 0}
readOnly={!canEditEntries}
readOnly={!canEditEntries || readingEntry}
onEdit={readingEntry ? () => setEditEntryId(editingEntry.id) : undefined}
showVerdict={current.show_verdict !== 0}
showMood={current.show_mood !== 0}
showWeather={current.show_weather !== 0}
@@ -706,12 +714,12 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
trips={current.trips}
photoProviders={availableProviders}
onMoveEarlier={
canEditEntries && editingEntry.id !== 0 && editingEntry.type !== 'skeleton' && dayNeighbours(editingEntry).canMoveUp
canEditEntries && !readingEntry && editingEntry.id !== 0 && editingEntry.type !== 'skeleton' && dayNeighbours(editingEntry).canMoveUp
? () => { void moveWithinDay(editingEntry, -1) }
: undefined
}
onMoveLater={
canEditEntries && editingEntry.id !== 0 && editingEntry.type !== 'skeleton' && dayNeighbours(editingEntry).canMoveDown
canEditEntries && !readingEntry && editingEntry.id !== 0 && editingEntry.type !== 'skeleton' && dayNeighbours(editingEntry).canMoveDown
? () => { void moveWithinDay(editingEntry, 1) }
: undefined
}
@@ -720,7 +728,7 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
? () => { setEditingEntry(null); void dismissSuggestion(editingEntry) }
: undefined
}
onClose={() => setEditingEntry(null)}
onClose={() => { setEditingEntry(null); setEditEntryId(null) }}
onSave={async (data, existingEntryId) => {
// existingEntryId is what the sheet already persisted in an earlier
// save attempt — without it a retry would create a second entry.
@@ -1,5 +1,9 @@
import { useRef, useState, type CSSProperties } from 'react'
import { Briefcase, Camera, Plus, Image, Images, X, MapPin, Locate, Trash2, CheckCircle2, MinusCircle, ChevronUp, ChevronDown, EyeOff, Play, NotebookPen } from 'lucide-react'
import { Briefcase, Camera, Plus, Image, Images, X, MapPin, Locate, Trash2, CheckCircle2, MinusCircle, ChevronUp, ChevronDown, EyeOff, Play, NotebookPen, Pencil } from 'lucide-react'
import { useIsTouch } from '../../../hooks/useIsTouch'
import { useTouchDragBridge } from '../../../hooks/useTouchDragBridge'
import { useSettingsStore } from '../../../store/settingsStore'
import { formatClockTime } from '../../../utils/formatters'
import MSheet from '../../components/MSheet'
import MIconBtn from '../../components/MIconBtn'
import MToggle from '../../components/MToggle'
@@ -48,6 +52,11 @@ interface MJourneyEntrySheetProps {
galleryPhotos: GalleryPhoto[]
quickCapture?: boolean
readOnly?: boolean
/**
* Given to an editor reading an entry (#3007): the sheet opens as the read view
* and a pencil in its header switches to the editor, without closing it.
*/
onEdit?: () => void
userId?: number
trips?: JourneyTrip[]
/**
@@ -87,16 +96,16 @@ interface MJourneyEntrySheetProps {
*/
export default function MJourneyEntrySheet({
entry, galleryPhotos, quickCapture = false, readOnly = false, userId = 0, trips = [], photoProviders: providers = NO_PROVIDERS,
showVerdict = true, showMood = true, showWeather = true, onMoveEarlier, onMoveLater, onDismiss,
showVerdict = true, showMood = true, showWeather = true, onEdit, onMoveEarlier, onMoveLater, onDismiss,
onClose, onSave, onUploadPhotos, onAddProviderPhotos, onDelete, onDone,
}: MJourneyEntrySheetProps) {
const { t } = useTranslation()
const { t, language } = useTranslation()
const {
title, setTitle, story, setStory, entryDate, setEntryDate, entryTime, setEntryTime,
locationName, locationLat, locationQuery, locationResults, showLocationResults, setShowLocationResults,
locating, locationError, mood, setMood, weather, setWeather, statsExcluded, setStatsExcluded, tripSuggestion,
isDraft, setIsDraft, pros, setPros, cons, setCons, tags, setTags, tagInput, setTagInput, saving, uploadProgress,
photos, photoOrder, pendingFiles, setPendingFiles, pendingPreviews, setPendingProviderGroups,
photos, photoOrder, canReorder, pendingFiles, setPendingFiles, pendingPreviews, setPendingProviderGroups,
showGalleryPick, setShowGalleryPick, isDirty, availableGalleryPhotos, queuedProviderPhotos, providerAssetIds,
contextLocation, offersStatsToggle, addVerdictRow, verdictRowRef, addTag, handleSave, handleFileChange,
pickGalleryPhoto, removePhoto, searchLocation, pickLocation, handleUseCurrentLocation,
@@ -104,6 +113,11 @@ export default function MJourneyEntrySheet({
entry, journeyId: entry.journey_id, trips, galleryPhotos, onSave, onUploadPhotos, onAddProviderPhotos, onDone,
readOnly, quickCapture, withTags: true, inlineLocateError: true,
})
// A long press picks a photo up and a drag sets its place (#2851), on the
// touch bridge the plan's rows use: a finger never starts an HTML5 drag.
const sortable = canReorder && !readOnly
const isTouch = useIsTouch()
useTouchDragBridge(isTouch && sortable)
const [showExternal, setShowExternal] = useState(false)
const [externalProvider, setExternalProvider] = useState<string | null>(null)
const [captureOnly, setCaptureOnly] = useState(quickCapture)
@@ -121,6 +135,20 @@ export default function MJourneyEntrySheet({
onClose()
}
// An editor reading the entry: the read view, with the way into the editor.
const reading = readOnly && !!onEdit
const is12h = useSettingsStore(s => s.settings.time_format === '12h')
// Read, the date and time head the entry instead of standing in locked fields.
const readingWhen = reading && entryDate
? [
new Date(`${entryDate}T00:00:00Z`).toLocaleDateString(language, { weekday: 'short', day: 'numeric', month: 'long', timeZone: 'UTC' }),
entryTime ? formatClockTime(entryTime, is12h) : '',
].filter(Boolean).join(', ')
: ''
const heading = entry.id === 0
? t('journey.detail.newEntry')
: readingWhen || t('journey.detail.editEntry')
const eyebrow = 'font-geist text-[0.625rem] font-bold uppercase tracking-[.09em] text-m-faint'
const fieldShell = 'rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)]'
@@ -130,7 +158,7 @@ export default function MJourneyEntrySheet({
onClose={handleClose}
variant="card"
form
ariaLabel={entry.id === 0 ? t('journey.detail.newEntry') : t('journey.detail.editEntry')}
ariaLabel={heading}
>
{/* FormSheetHeader's shape, with the move buttons between the title and the close. */}
<div className="m-fs-head flex flex-none items-center gap-3 px-[18px] pb-2 pt-4">
@@ -138,8 +166,13 @@ export default function MJourneyEntrySheet({
<NotebookPen size={19} strokeWidth={1.8} />
</span>
<span className="line-clamp-2 min-w-0 flex-1 break-words text-[1.0625rem] font-bold leading-tight">
{entry.id === 0 ? t('journey.detail.newEntry') : t('journey.detail.editEntry')}
{heading}
</span>
{reading && (
<MIconBtn variant="neutral" size={34} onClick={onEdit} ariaLabel={t('common.edit')} className="me-1">
<Pencil size={15} strokeWidth={2.2} />
</MIconBtn>
)}
{(onMoveEarlier || onMoveLater) && (
<span className="me-1 flex items-center gap-1">
<MIconBtn variant="neutral" size={34} onClick={() => onMoveEarlier?.()} disabled={!onMoveEarlier} ariaLabel={t('dayplan.moveUp')}>
@@ -348,9 +381,15 @@ export default function MJourneyEntrySheet({
)}
{(photos.length > 0 || pendingFiles.length > 0) && (
<div className="mt-[10px] flex flex-wrap gap-2">
<div className="mt-[10px] flex flex-wrap gap-2" data-touch-drag={sortable ? '' : undefined}>
{photos.map((p, idx) => (
<div key={p.id} className="relative h-16 w-16 overflow-hidden rounded-[13px]">
<div
key={p.id}
{...(sortable ? photoOrder.dragProps(idx) : {})}
className={`relative h-16 w-16 overflow-hidden rounded-[13px] transition-opacity ${
photoOrder.dragIndex === idx ? 'opacity-40' : ''
} ${photoOrder.overIndex === idx && photoOrder.dragIndex !== idx ? 'ring-2 ring-[color:var(--m-act)]' : ''}`}
>
{posterlessVideo(p) ? (
<ClipTile />
) : (
@@ -514,7 +553,7 @@ export default function MJourneyEntrySheet({
{/* Date + Time. Split in the date's favour: a localized date needs the
room ("10. Sept. 2026"), a clock never does. */}
<div className="mt-3 grid grid-cols-[minmax(0,1fr)_104px] gap-2">
{!reading && <div className="mt-3 grid grid-cols-[minmax(0,1fr)_104px] gap-2">
<div className="min-w-0">
<div className={`${eyebrow} mb-[5px]`}>{t('journey.editor.date')}</div>
{/* TREK's own picker, like the time field beside it: a native
@@ -529,9 +568,9 @@ export default function MJourneyEntrySheet({
brings its own shell, so fieldShell goes with the input. */}
<CustomTimePicker value={entryTime} onChange={setEntryTime} disabled={readOnly} />
</div>
</div>
</div>}
{tripSuggestion.trip && (
{!reading && tripSuggestion.trip && (
<div className={`mt-3 flex items-center gap-3 px-3 py-[10px] ${fieldShell}`}>
<Briefcase size={15} strokeWidth={2} className="flex-none text-m-muted" />
<div className="min-w-0 flex-1">
@@ -545,7 +584,13 @@ export default function MJourneyEntrySheet({
</div>
)}
{/* Location */}
{/* Location: read, a line under the story rather than a locked field. */}
{reading ? (locationName && (
<div className="mt-3 flex items-center gap-2 text-body font-semibold text-m-ink">
<MapPin size={14} strokeWidth={2.2} className="flex-none text-m-muted" />
<bdi className="min-w-0 [overflow-wrap:anywhere]">{locationName}</bdi>
</div>
)) : (
<div className="relative mt-3">
<div className={`${eyebrow} mb-[5px]`}>{t('journey.editor.location')}</div>
<div className={`flex items-center gap-2 px-3 py-[10px] ${fieldShell}`}>
@@ -594,11 +639,13 @@ export default function MJourneyEntrySheet({
{locating && <div className="mt-[5px] font-geist text-[0.65625rem] text-m-muted">{t('common.loading')}</div>}
{locationError && <div className="mt-[5px] font-geist text-[0.65625rem] text-[color:var(--m-st-danger)]">{locationError}</div>}
</div>
)}
{/* Off the route: the same switch the desktop editor and the Studio
travel panel offer (#2064). Read-only keeps it visible but locked,
like the date and the mood above and below it. */}
{offersStatsToggle && (
{/* Settings of the entry, not its content: an editor reading it does not need them locked in view. */}
{offersStatsToggle && !reading && (
<div className={`mt-3 flex items-center gap-3 px-3 py-[10px] ${fieldShell}`}>
<div className="min-w-0 flex-1">
<div className="text-[0.75rem] font-semibold text-m-ink">{t('journey.editor.statsExcluded')}</div>
@@ -609,19 +656,22 @@ export default function MJourneyEntrySheet({
)}
{/* Kept among the contributors until it is ready (#696). */}
<div className={`mt-3 flex items-center gap-3 px-3 py-[10px] ${fieldShell}`}>
<div className="min-w-0 flex-1">
<div className="text-[0.75rem] font-semibold text-m-ink">{t('journey.editor.draft')}</div>
<div className="mt-[2px] font-geist text-[0.65625rem] leading-[1.4] text-m-muted">{t('journey.editor.draftHint')}</div>
{!reading && (
<div className={`mt-3 flex items-center gap-3 px-3 py-[10px] ${fieldShell}`}>
<div className="min-w-0 flex-1">
<div className="text-[0.75rem] font-semibold text-m-ink">{t('journey.editor.draft')}</div>
<div className="mt-[2px] font-geist text-[0.65625rem] leading-[1.4] text-m-muted">{t('journey.editor.draftHint')}</div>
</div>
<MToggle checked={isDraft} onChange={setIsDraft} disabled={readOnly} ariaLabel={t('journey.editor.draft')} />
</div>
<MToggle checked={isDraft} onChange={setIsDraft} disabled={readOnly} ariaLabel={t('journey.editor.draft')} />
</div>
)}
{/* Mood */}
{showMood && !captureOnly && <>
{/* Read, only what was chosen shows, and nothing when nothing was. */}
{showMood && !captureOnly && (!reading || MOBILE_MOODS.some(m => m.id === mood)) && <>
<div className={`${eyebrow} mb-[6px] mt-3`}>{t('journey.editor.mood')}</div>
<div className="flex flex-wrap gap-[6px]">
{MOBILE_MOODS.map(m => {
{(reading ? MOBILE_MOODS.filter(m => m.id === mood) : MOBILE_MOODS).map(m => {
const active = mood === m.id
return (
<button
@@ -644,10 +694,10 @@ export default function MJourneyEntrySheet({
</>}
{/* Weather */}
{showWeather && <>
{showWeather && (!reading || MOBILE_WEATHERS.some(w => w.id === weather)) && <>
<div className={`${eyebrow} mb-[6px] mt-3`}>{t('journey.editor.weather')}</div>
<div className="flex flex-wrap gap-[6px]">
{MOBILE_WEATHERS.map(w => {
{(reading ? MOBILE_WEATHERS.filter(w => w.id === weather) : MOBILE_WEATHERS).map(w => {
const active = weather === w.id
return (
<button
@@ -746,7 +796,7 @@ export default function MJourneyEntrySheet({
onClick={handleClose}
className={`${SHEET_SECONDARY} ms-auto`}
>
{t('common.cancel')}
{t(reading ? 'common.close' : 'common.cancel')}
</button>
{!readOnly && (
<button
+10 -10
View File
@@ -9,7 +9,7 @@ import { pickDockTabs } from './dockTabs'
import MBadge from '../../components/MBadge'
import MIconBtn from '../../components/MIconBtn'
import { useActivePill } from '../../components/useActivePill'
import { useSharedImportStore } from '../../../native/sharedFiles'
import { useSharedIntoTrip } from '../../../native/useSharedIntoTrip'
import MPlanTimeline from './plan/MPlanTimeline'
import MMapArea from './map/MMapArea'
import MPlacesBrowser from './places/MPlacesBrowser'
@@ -316,14 +316,11 @@ export default function MTripShell({
})
}, [railDayId, days, dayRail])
// The active day's pill glides to the next chip rather than jumping there.
// A booking document shared to TREK, and this trip picked for it: open the import.
const sharedTripId = useSharedImportStore(s => s.tripId)
const { setBookingImportKind, setShowBookingImport } = planner
useEffect(() => {
if (sharedTripId == null || sharedTripId !== Number(tripId)) return
setBookingImportKind('bookings')
setShowBookingImport(true)
}, [sharedTripId, tripId, setBookingImportKind, setShowBookingImport])
// Something shared to TREK and sent to this trip: the booking import, or a new place (#2582).
useSharedIntoTrip(Number(tripId), {
bookingImport: () => { planner.setBookingImportKind('bookings'); planner.setShowBookingImport(true) },
newPlace: () => { planner.setEditingPlace(null); planner.setEditingAssignmentId(null); planner.setPrefillCoords(null); planner.setShowPlaceForm(true) },
})
// The day strip says when it runs on past an edge (a long trip, a narrow pane).
const dayFade = useEdgeFade(dayRail)
const dayPill = useActivePill(dayRail, '[aria-current="true"]', `${railDayId}:${days.map(d => d.id).join(',')}:${language}`)
@@ -481,7 +478,10 @@ export default function MTripShell({
return () => clearTimeout(timer)
}, [boxKey, frameDayId])
const openSheet = (id: string, payload?: unknown) => setSheet({ id, payload })
const openSheet = (id: string, payload?: unknown) => {
if (id === 'day' && trTab === 'plan') planner.hideOverview()
setSheet({ id, payload })
}
const closeSheet = () => setSheet(null)
// A hardware keyboard: ⌘1 to ⌘9 for the trip's sections in rail order, ⌥← and
@@ -1,9 +1,10 @@
import { useEffect, useState, type MouseEvent } from 'react'
import { useEffect, useMemo, useState, type MouseEvent } from 'react'
import { ArrowRight, BedDouble, CalendarDays, CalendarRange, ChevronRight, LogIn, LogOut, Map as MapIcon, MapPin, Pencil, PencilLine, Route, Ticket, TrainFront, Undo2 } from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
import { useContextMenu, ContextMenu } from '../../../../components/shared/ContextMenu'
import MarkdownText from '../../../../components/shared/MarkdownText'
import { fmtTransitDuration } from '../../../../components/Planner/transitDisplay'
import { stopNumbersOfDay } from '../../../../components/Planner/stopNumbers'
import { legModeMenuItems, transitOnlyMenuItems } from '../../../../components/Planner/useLegModeActions'
import { formatTime } from '../../../../utils/formatters'
import { useMPlanTimeline, type MPlanTimelineController } from './useMPlanTimeline'
@@ -197,6 +198,9 @@ function PlanDayPage({ planner, shell, dayId: pageDayId, active, editing, legMen
}
const chrome = { editing, t, language: tl.language, timeFormat: tl.timeFormat }
// The numbers the map's pins carry, beside each stop (#2584).
const dayAssignments = planner.assignments[String(pageDayId)]
const stopNumbers = useMemo(() => stopNumbersOfDay(dayAssignments || []), [dayAssignments])
const [cardScroll, setCardScroll] = useState<HTMLDivElement | null>(null)
const cardFade = useEdgeFade(cardScroll, 'y')
@@ -273,6 +277,7 @@ function PlanDayPage({ planner, shell, dayId: pageDayId, active, editing, legMen
<Fragment key={row.key}>
<PlaceRow
assignment={row.assignment}
stopNumber={stopNumbers.get(row.assignment.id)}
tour={planner.toursEnabled ? planner.tours.find(tour => tour.place_id === row.assignment.place_id) : undefined}
fullPlace={tl.fullPlaceOf(row.assignment)}
linkedReservations={row.linkedReservations}
@@ -129,8 +129,10 @@ const ROW_CODE = 'flex-none whitespace-nowrap font-geist text-[0.71875rem] text-
// ── b3) Place row ────────────────────────────────────────────────────────────
export function PlaceRow({ assignment, fullPlace, tour, linkedReservations, chrome, reorder, drag, onOpen, onEdit, onRemove, overrun }: {
export function PlaceRow({ assignment, stopNumber, fullPlace, tour, linkedReservations, chrome, reorder, drag, onOpen, onEdit, onRemove, overrun }: {
assignment: Assignment
/** Its number on the map (#2584); none for a service stop. */
stopNumber?: number
fullPlace: Place | undefined
tour?: TourListItem
/** TIME-02: the day's next timed item this tour runs into, or null. */
@@ -182,6 +184,7 @@ export function PlaceRow({ assignment, fullPlace, tour, linkedReservations, chro
className={`flex cursor-pointer items-center gap-2.5 py-1.5 ${dragClass(drag)}`}
>
{!chrome.editing && (
<span className="relative flex-none">
<AvatarRing className="shadow-[0_3px_8px_-3px_rgba(0,0,0,.4)]">
{tour ? <TourDayRowIcon type={tour.tour_type} /> : <PlaceAvatar
place={fullPlace ?? {
@@ -197,6 +200,8 @@ export function PlaceRow({ assignment, fullPlace, tour, linkedReservations, chro
category={place?.category ? { color: place.category.color ?? undefined, icon: place.category.icon ?? undefined } : null}
/>}
</AvatarRing>
{stopNumber != null && <span className="m-stop-num" aria-hidden="true">{stopNumber}</span>}
</span>
)}
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
@@ -1,6 +1,7 @@
import { ChevronRight, FileDown, Settings, Settings2, Sparkles } from 'lucide-react'
import { ChevronRight, CloudDownload, FileDown, Settings, Settings2, Sparkles } from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
import { useState } from 'react'
import { useNavigate } from 'react-router'
import MSheet from '../../../components/MSheet'
import { edgeFadeClass, useEdgeFade } from '../../../components/useEdgeFade'
import type { MTripSheetsProps } from '../MTripShell'
@@ -9,6 +10,8 @@ import { useIsWide } from '../../../../hooks/sizeClass'
import { useTranslation } from '../../../../i18n'
import { useAssistantAsk } from '../../../../components/Assistant/useAssistantAsk'
import { useAssistantHints } from '../../../../components/Assistant/useAssistantHints'
import { useTripOfflineStatus, type TripOfflineState } from '../../../../components/Settings/useTripOfflineStatus'
import { useSettingsStore } from '../../../../store/settingsStore'
/** Demo tile tints per legacy tab id; plugins share the files neutral. */
const TILE_COLORS: Record<string, string> = {
@@ -27,9 +30,25 @@ const TILE_COLORS: Record<string, string> = {
* transparent scrim. Grid of the trip sections that did not fit the dock
* (files/collab/plugins, with short stats) plus the share/export/settings rows.
*/
/** The offline line under the trip's own menu entry (#1580): saved as of when, or why not. */
function offlineLine(state: TripOfflineState | null, t: (key: string, params?: Record<string, string>) => string, language: string, is12h: boolean): string | undefined {
if (!state) return undefined
if (state.kind === 'off') return t('mobileTrip.offlineOff')
if (state.kind === 'pending') return t('mobileTrip.offlineNotSaved')
const at = new Date(state.at)
const today = new Date().toDateString() === at.toDateString()
const time = today
? at.toLocaleTimeString(language, { hour: 'numeric', minute: '2-digit', hour12: is12h })
: at.toLocaleDateString(language, { day: 'numeric', month: 'short' })
return t('mobileTrip.offlineSaved', { time })
}
export default function MMehrSheet({ planner, shell }: MTripSheetsProps) {
const { t } = useTranslation()
const { t, language } = useTranslation()
const navigate = useNavigate()
const open = shell.sheet?.id === 'mehr'
const offline = useTripOfflineStatus(planner.trip, open)
const is12h = useSettingsStore(s => s.settings.time_format === '12h')
const canEditTrip = planner.can('trip_edit', planner.trip)
const assistant = useAssistantAsk(planner.tripId)
// Warnings not shown yet turn the tile's line into a count; the dock gets no dot.
@@ -61,9 +80,20 @@ export default function MMehrSheet({ planner, shell }: MTripSheetsProps) {
shell.setTrTab(id)
}
const actions: { id: string; icon: LucideIcon; label: string; go: () => void }[] = [
const actions: { id: string; icon: LucideIcon; label: string; sub?: string; go: () => void }[] = [
{ id: 'members', icon: Settings2, label: t('trip.settings.title'), go: () => shell.openSheet('members') },
{ id: 'export', icon: FileDown, label: t('mobileTrip.export'), go: () => shell.openSheet('export') },
// Whether this trip is on the device, without a trip to the settings to find out (#1580).
{
id: 'offline',
icon: CloudDownload,
label: t('settings.tabs.offline'),
sub: offlineLine(offline, t, language, is12h),
go: () => {
shell.closeSheet()
void navigate('/settings?tab=offline')
},
},
...(canEditTrip
? [{ id: 'tripedit', icon: Settings, label: t('dashboard.editTrip'), go: () => shell.openSheet('tripedit') }]
: []),
@@ -139,7 +169,10 @@ export default function MMehrSheet({ planner, shell }: MTripSheetsProps) {
<div className="flex h-[34px] w-[34px] flex-none items-center justify-center rounded-[10px] bg-[color:var(--m-ic)]">
<action.icon size={17} strokeWidth={1.9} />
</div>
<span className="min-w-0 flex-1 truncate text-[0.875rem] font-semibold">{action.label}</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-[0.875rem] font-semibold">{action.label}</span>
{action.sub && <span className="block truncate text-caption text-m-muted">{action.sub}</span>}
</span>
<ChevronRight size={16} strokeWidth={2} className="flex-none text-m-faint" />
</button>
))}
@@ -34,6 +34,7 @@ import { usePlaceImageField } from '../../../../components/Planner/usePlaceImage
import { useTranslation } from '../../../../i18n'
import { useAuthStore } from '../../../../store/authStore'
import { useSettingsStore } from '../../../../store/settingsStore'
import { useSharedImportStore } from '../../../../native/sharedFiles'
import type { Assignment, AssignmentsMap, Place } from '../../../../types'
import type { TripPlanner } from '../MTripShell'
import { useLocationBias } from '../../../../hooks/useLocationBias'
@@ -103,6 +104,9 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
const tagField = usePlaceTags({ tripId: planner.tripId, place: sheetPlace, tags: form.tags, setForm, t, toast })
const placesEnrichEnabled = useAuthStore(s => s.placesEnrichEnabled)
// A map link shared to TREK for this trip (#2582): a new place starts from it.
const sharedPlaceUrl = useSharedImportStore(s => (s.placeLink?.tripId === planner.tripId ? s.placeLink.url : null))
const clearSharedPlace = useSharedImportStore(s => s.clearPlaceLink)
const { language, locale } = useTranslation()
const timeFormat = useSettingsStore(s => s.settings.time_format) || '24h'
@@ -266,6 +270,8 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
onPick={applyPick}
onSuggestionName={name => setForm(prev => ({ ...prev, name }))}
onResolvingChange={setResolvingPick}
initialQuery={!sheetPlace && sharedPlaceUrl ? sharedPlaceUrl : undefined}
onInitialQueryRun={clearSharedPlace}
/>
{placesEnrichEnabled && (
@@ -1,7 +1,7 @@
import { useMemo, useRef, useState } from 'react'
import { useMemo, useRef, useState, type KeyboardEvent } from 'react'
import DawarichIcon from '../../../../components/shared/DawarichIcon'
import {
Bookmark, ChevronRight, ExternalLink, Map as MapIcon, MapPinOff, Navigation, Paperclip,
ArrowLeftRight, Bookmark, ChevronRight, ExternalLink, Map as MapIcon, MapPinOff, Navigation, Paperclip,
Pencil, Phone, Plus, Route, RouteOff, Sparkles, Trash2, Upload, X,
} from 'lucide-react'
import MSheet from '../../../components/MSheet'
@@ -26,7 +26,7 @@ import { filesForPlace } from '../../../../utils/placeFiles'
import { navigationTargetLabel, getNavigationTargets, openNavigationTarget } from '../../../../components/Planner/placeNavigation'
import { addressWithoutCoordinates } from '../../../../components/Planner/placeCoordinates'
import { NavigationMenu } from '../../../../components/shared/NavigationMenu'
import { getPlaceBookings } from '../../../../utils/dayMerge'
import { getPlaceBookings, timedSlot } from '../../../../utils/dayMerge'
import type { Assignment, Day, Reservation, TripMember } from '../../../../types'
import PlacePhotoGallery from '../../../../components/Planner/PlacePhotoGallery'
import { ActionCircle, Eyebrow, INNER_CLS } from './MTripSheetUi'
@@ -61,6 +61,9 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
uploading, filesExpanded, setFilesExpanded, fileInputRef, handleUpload,
} = usePlaceFileUpload(place && !isTourPlace ? place.id : null, fd => planner.tripActions.addFile(planner.tripId, fd), planner.toast)
const [dayPickerOpen, setDayPickerOpen] = useState(false)
// A day of this place picked to move from (#2583): the day list then moves it there instead of adding it.
// Only the ids are kept, so a stop a collaborator moved or removed meanwhile is read as it is now.
const [movingIds, setMovingIds] = useState<{ placeId: number; assignmentId: number } | null>(null)
const [participantPickerOpen, setParticipantPickerOpen] = useState(false)
const [navOpen, setNavOpen] = useState(false)
const navBtnRef = useRef<HTMLButtonElement>(null)
@@ -70,6 +73,7 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
planner.setSelectedPlaceId(null)
setFilesExpanded(false)
setDayPickerOpen(false)
setMovingIds(null)
setParticipantPickerOpen(false)
setColorPickerOpen(false)
}
@@ -91,7 +95,20 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
return rows
}, [place, planner.days, planner.assignments])
const moving = movingIds && movingIds.placeId === place?.id
? placeAssignments.find(r => r.assignment.id === movingIds.assignmentId) ?? null
: null
if (movingIds && !moving) setMovingIds(null)
const unassignedDays = planner.days.filter(d => !placeAssignments.some(r => r.day.id === d.id))
const dayLabel = (d: Day) => d.title || t('planner.dayN', { n: (d.day_number ?? planner.days.indexOf(d) + 1) || '?' })
// Lands where its time belongs on the new day, as a move on the desktop does;
// without a time it goes to the end.
const moveToDay = ({ assignment, day }: { assignment: Assignment; day: Day }, toDayId: number) => {
const slot = timedSlot(planner.storedAssignments[String(toDayId)] || [], planner.tripAccommodations, assignment.place?.place_time) ?? undefined
planner.handleMoveToDay(assignment.id, day.id, toDayId, slot)
.catch((err: unknown) => planner.toast.error(err instanceof Error ? err.message : t('common.unknownError')))
}
// Participants belong to the assignment in the selected day (desktop parity).
const dayAssignments = planner.selectedDayId ? (planner.assignments[String(planner.selectedDayId)] || []) : []
@@ -220,8 +237,28 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
</span>
)}
</div>
{/* A tap on the address opens directions, as the navigation button does:
on the road the address is what the eye lands on. */}
{place.address && (
<div className="mt-[2px] font-geist text-[0.6875rem] leading-[1.4] text-m-muted"><bdi>{place.address}</bdi></div>
<div
className={`mt-[2px] font-geist text-[0.6875rem] leading-[1.4] text-m-muted${navTargets.length > 0 ? ' cursor-pointer underline decoration-dotted underline-offset-2' : ''}`}
{...(navTargets.length > 0
? {
role: 'button',
tabIndex: 0,
'aria-label': `${navTargets.length === 1 ? navigationTargetLabel(navTargets[0], t) : t('inspector.navigation')}: ${place.address}`,
onClick: openDirections,
onKeyDown: (e: KeyboardEvent) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
openDirections()
}
},
}
: {})}
>
<bdi>{place.address}</bdi>
</div>
)}
{/* A typed address that never got coordinates: no marker, and the sheet says why (#2837). */}
{addressWithoutCoordinates(place) && (
@@ -328,7 +365,20 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
key={assignment.id}
className={`flex items-center gap-1 rounded-full py-1 ps-[10px] text-[0.75rem] font-semibold ${INNER_CLS} ${canEditDays ? 'pe-1' : 'pe-[10px]'}`}
>
{day.title || t('planner.dayN', { n: (day.day_number ?? planner.days.indexOf(day) + 1) || '?' })}
{canEditDays && unassignedDays.length > 0 ? (
// The day itself moves the stop to another one, keeping its time
// and notes, where removing and adding it again would lose them.
<button
type="button"
onClick={() => { setDayPickerOpen(false); setMovingIds(moving?.assignment.id === assignment.id ? null : { placeId: place.id, assignmentId: assignment.id }) }}
aria-label={t('mobileTrip.moveToDay')}
aria-expanded={moving?.assignment.id === assignment.id}
className="flex items-center gap-1"
>
{dayLabel(day)}
<ArrowLeftRight size={10} strokeWidth={2.4} aria-hidden="true" className="text-m-muted" />
</button>
) : dayLabel(day)}
{canEditDays && !isTourPlace && place.lat != null && place.lng != null && (
// In or out of that day's route (#2532); the icon says which it is.
<button
@@ -356,7 +406,7 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
{canEditDays && unassignedDays.length > 0 && (
<button
type="button"
onClick={() => setDayPickerOpen(v => !v)}
onClick={() => { setMovingIds(null); setDayPickerOpen(v => !v) }}
aria-label={t('inspector.addToDay')}
aria-expanded={dayPickerOpen}
className="flex h-[26px] w-[26px] items-center justify-center rounded-full border-[1.5px] border-dashed border-[color:var(--m-faint)] text-m-muted"
@@ -365,18 +415,22 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
</button>
)}
</div>
{dayPickerOpen && (
{(dayPickerOpen || moving) && (
<div className="mt-[6px] max-h-[180px] overflow-y-auto rounded-[14px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheetop)] p-[6px]">
{moving && <Eyebrow className="px-[10px] pb-1 pt-[6px] uppercase">{t('mobileTrip.moveToDay')}</Eyebrow>}
{unassignedDays.map(d => (
<button
key={d.id}
type="button"
onClick={() => { planner.handleAssignToDay(place.id, d.id); setDayPickerOpen(false) }}
onClick={() => {
if (moving) moveToDay(moving, d.id)
else planner.handleAssignToDay(place.id, d.id)
setDayPickerOpen(false)
setMovingIds(null)
}}
className="flex w-full items-center gap-2 rounded-[10px] px-[10px] py-[9px] text-start text-[0.78125rem] font-semibold"
>
<span className="min-w-0 flex-1 truncate">
{d.title || t('planner.dayN', { n: (d.day_number ?? planner.days.indexOf(d) + 1) || '?' })}
</span>
<span className="min-w-0 flex-1 truncate">{dayLabel(d)}</span>
{d.date && (
<span className="flex-none font-geist text-[0.65625rem] text-m-faint">
{new Date(`${d.date.slice(0, 10)}T00:00:00Z`).toLocaleDateString(planner.language, { day: 'numeric', month: 'short', timeZone: 'UTC' })}
@@ -1,4 +1,5 @@
import { Loader2, RotateCcw, Search } from 'lucide-react'
import { useEffect, useEffectEvent } from 'react'
import { offersGoogleRetry } from '../../../../utils/placeSource'
import { usePlaceSearch, type MapsPlace } from '../../../../components/Planner/usePlaceSearch'
import { FIELD_CLS } from './PlSheetChrome'
@@ -48,6 +49,10 @@ interface PlPlaceSearchProps {
onSuggestionName: (name: string) => void
/** True while a suggestion's details are being resolved (name spinner). */
onResolvingChange?: (resolving: boolean) => void
/** A query the field starts with and runs once, such as a shared map link (#2582). */
initialQuery?: string
/** The starting query was sent, so whoever held it can let it go. */
onInitialQueryRun?: () => void
}
function placeToPick(place: MapsPlace): PlSearchPick {
@@ -73,7 +78,7 @@ function placeToPick(place: MapsPlace): PlSearchPick {
* detection — the mobile counterpart of PlaceFormModal's search block, on the
* same search logic (usePlaceSearch).
*/
export default function PlPlaceSearch({ planner, locationBias, onPick, onSuggestionName, onResolvingChange }: PlPlaceSearchProps) {
export default function PlPlaceSearch({ planner, locationBias, onPick, onSuggestionName, onResolvingChange, initialQuery, onInitialQueryRun }: PlPlaceSearchProps) {
const { t, toast } = planner
const {
query, setQuery, results, suggestions, setSuggestions, acSource, searchSource, searching, googleAnswers,
@@ -94,8 +99,21 @@ export default function PlPlaceSearch({ planner, locationBias, onPick, onSuggest
}),
onCoordinates: (lat, lng) => onPick({ lat, lng }),
onResolvingChange,
initialQuery,
})
// A map link shared to the app (#2582) is looked up as soon as the sheet opens,
// as if it had been pasted and searched. The sheet may be open already, its
// field holding something else, so the link itself is what is searched.
const runInitial = useEffectEvent((link: string) => {
setQuery(link)
void handleSearch(undefined, link)
onInitialQueryRun?.()
})
useEffect(() => {
if (initialQuery) runInitial(initialQuery)
}, [initialQuery])
return (
<div className="relative">
<div className="flex items-center gap-2">
@@ -1,4 +1,5 @@
import { MapPin } from 'lucide-react'
import { MapPin, Navigation } from 'lucide-react'
import { useState } from 'react'
import MDancingTrek from '../../../components/MDancingTrek'
import { RES_ICONS } from '../../../../components/Planner/DayPlanSidebar.constants'
import { formatTime, formatPriceText } from '../../../../utils/formatters'
@@ -9,10 +10,12 @@ import { CardGrid, Field, ReservationPluginSlots, SectionHeader, StatusDot, TabS
import { STATUS_COLOR, type MTabScreenProps } from './tabModel'
import { cardWhen, parseTransportMeta, timeRange } from './transportsModel'
import { BOOKING_TYPE_COLOR, hotelStayTimes } from '../../../../components/Planner/bookings/bookingsModel'
import { useReservationListFilter } from '../../../../components/Planner/bookings/useReservationListFilter'
import { listSections, useReservationListFilter } from '../../../../components/Planner/bookings/useReservationListFilter'
import { useReservationCard } from '../../../../components/Planner/bookings/useReservationCard'
import { orderedEndpoints, seatCells } from '../../../../utils/flightLegs'
import { filesFor } from '../../../../utils/reservationFiles'
import { getNavigationTargets, openNavigationTarget } from '../../../../components/Planner/placeNavigation'
import { NavigationMenu } from '../../../../components/shared/NavigationMenu'
/**
* Tab 2 — Buchungen. Real `planner.reservations` filtered to the non-transport
@@ -30,10 +33,7 @@ export default function MBookingsTab({ planner, shell }: MTabScreenProps) {
} = useReservationListFilter(allBookings, days, planner.tripMembers.length)
const canEdit = planner.can('reservation_edit', planner.trip)
const sections = [
{ id: 'confirmed', label: t('reservations.confirmed'), rows: groups.confirmed },
{ id: 'pending', label: t('reservations.pending'), rows: groups.pending },
].filter(s => s.rows.length > 0)
const sections = listSections(groups, t)
return (
<TabScroller wide="full">
@@ -176,17 +176,16 @@ function BookingCard({ res, planner, canEdit, compact, onView }: {
)}
<TravelerAvatars travelers={res.travelers || []} label={t('reservations.travelers.label')} />
{res.location && (
<div className="mt-2 flex items-center gap-[6px] rounded-[10px] border border-[color:var(--m-rowbr)] bg-m-card px-[10px] py-[7px]">
<MapPin size={12} strokeWidth={2} className="flex-none text-m-muted" />
<span dir="auto" className="truncate text-[0.71875rem] font-semibold text-m-ink">{res.location}</span>
</div>
)}
<CardNotes notes={res.notes} />
</button>
<CardLocation location={res.location} />
{res.notes?.trim() && (
<button type="button" onClick={onView} className="block w-full text-start">
<CardNotes notes={res.notes} />
</button>
)}
<CardFiles files={files} card={card} t={t} />
</div>
)}
@@ -196,3 +195,40 @@ function BookingCard({ res, planner, canEdit, compact, onView }: {
</div>
)
}
/**
* Where the booking is (the hotel, the rental desk): a tap opens directions to
* it, as the address of a place does, in the traveller's map app or with the
* same choice of apps.
*/
function CardLocation({ location }: { location: string | null | undefined }) {
const { t } = useTranslation()
const [anchor, setAnchor] = useState<HTMLButtonElement | null>(null)
const [menuOpen, setMenuOpen] = useState(false)
const text = location?.trim()
if (!text) return null
const targets = getNavigationTargets({ name: text, address: text, lat: null, lng: null, google_place_id: null, google_ftid: null })
const openDirections = () => {
if (targets.length === 1) openNavigationTarget(targets[0])
else if (targets.length > 1) setMenuOpen(true)
}
return (
<>
<button
ref={setAnchor}
type="button"
onClick={openDirections}
disabled={targets.length === 0}
aria-label={`${t('inspector.navigation')}: ${text}`}
className="mt-2 flex w-full items-center gap-[6px] rounded-[10px] border border-[color:var(--m-rowbr)] bg-m-card px-[10px] py-[7px] text-start"
>
<MapPin size={12} strokeWidth={2} className="flex-none text-m-muted" />
<span dir="auto" className="min-w-0 flex-1 truncate text-[0.71875rem] font-semibold text-m-ink">{text}</span>
{targets.length > 0 && <Navigation size={12} strokeWidth={2} aria-hidden="true" className="flex-none text-m-muted" />}
</button>
{menuOpen && (
<NavigationMenu targets={targets} anchor={anchor} onClose={() => setMenuOpen(false)} title={t('inspector.openWith')} />
)}
</>
)
}
@@ -45,13 +45,20 @@ export default function MFileLightbox({ files, index, onIndexChange, onClose, t
// tap-to-dismiss. Escape / arrow keys and the header buttons are the
// keyboard equivalents, wired up in useMediaLightbox.
role="presentation"
className="m-root fixed inset-0 z-[65] flex flex-col bg-black/[.92]"
className="m-root fixed inset-0 z-[65] flex flex-col bg-black/[.92] pb-[env(safe-area-inset-bottom,0px)]"
onClick={onClose}
onTouchStart={onTouchStart}
onTouchEnd={onTouchEnd}
>
{/* Header */}
<div role="presentation" className="flex flex-none items-center justify-between px-4 py-[10px]" onClick={e => e.stopPropagation()}>
{/* Below the status bar and a notch, and clear of a side inset in landscape,
so the close button is always there to tap. The insets are the screen's
sides, so right to left takes them the other way round. */}
<div
role="presentation"
className="flex flex-none items-center justify-between gap-2 pb-[10px] pe-[calc(var(--m-safe-r)+12px)] ps-[calc(var(--m-safe-l)+16px)] pt-[calc(var(--m-safe-t)+10px)] rtl:pe-[calc(var(--m-safe-l)+12px)] rtl:ps-[calc(var(--m-safe-r)+16px)]"
onClick={e => e.stopPropagation()}
>
<span className="min-w-0 flex-1 truncate font-geist text-[0.75rem] text-white/70">
{file.original_name}
<span className="ms-2 text-white/40">{index + 1} / {files.length}</span>
@@ -73,8 +80,13 @@ export default function MFileLightbox({ files, index, onIndexChange, onClose, t
>
<Download size={16} strokeWidth={2} />
</button>
<button type="button" onClick={onClose} aria-label={t('common.close')} className="flex h-8 w-8 items-center justify-center text-white/70">
<X size={18} strokeWidth={2.2} />
<button
type="button"
onClick={onClose}
aria-label={t('common.close')}
className="ms-1 flex h-10 w-10 items-center justify-center rounded-full bg-[var(--m-viewer-btn)] text-[var(--m-viewer-ink)]"
>
<X size={20} strokeWidth={2.2} />
</button>
</div>
</div>
@@ -8,7 +8,7 @@ import { CardGrid, Field, ReservationPluginSlots, SectionHeader, StatusDot, TabS
import { STATUS_COLOR, type MTabScreenProps } from './tabModel'
import { cardWhen, parseTransportMeta } from './transportsModel'
import { TRANSPORT_TYPE_COLOR } from '../../../../components/Planner/bookings/bookingsModel'
import { useReservationListFilter } from '../../../../components/Planner/bookings/useReservationListFilter'
import { listSections, useReservationListFilter } from '../../../../components/Planner/bookings/useReservationListFilter'
import { useReservationCard } from '../../../../components/Planner/bookings/useReservationCard'
import { orderedEndpoints, seatCells } from '../../../../utils/flightLegs'
import { filesFor } from '../../../../utils/reservationFiles'
@@ -30,11 +30,7 @@ export default function MTransportsTab({ planner, shell }: MTabScreenProps) {
} = useReservationListFilter(allTransports, days, planner.tripMembers.length)
const canEdit = planner.can('day_edit', planner.trip)
const sections = [
{ 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 },
].filter(s => s.rows.length > 0)
const sections = listSections(groups, t)
return (
<TabScroller wide="full">
+109
View File
@@ -0,0 +1,109 @@
// FE-NATIVE-APPBOOT-001 to FE-NATIVE-APPBOOT-006
import { StatusBar, Style } from '@capacitor/status-bar';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { endAppBoot, handOverToApp, isAppBoot, lightStatusBarIcons, pageUnderStatusBar } from './appBoot';
import { isNativeAndroid, isNativeApp } from './platform';
vi.mock('./platform', () => ({ isNativeApp: vi.fn(), isNativeAndroid: vi.fn() }));
vi.mock('@capacitor/status-bar', () => ({
StatusBar: { setStyle: vi.fn(async () => {}) },
Style: { Dark: 'DARK', Light: 'LIGHT' },
}));
const root = document.documentElement;
const realAgent = Object.getOwnPropertyDescriptor(window.navigator, 'userAgent');
function webViewVersion(major: number) {
Object.defineProperty(window.navigator, 'userAgent', {
configurable: true,
get: () => `Mozilla/5.0 (Linux; Android 16; wv) AppleWebKit/537.36 Chrome/${major}.0.0.0 Mobile Safari/537.36`,
});
}
beforeEach(() => {
vi.mocked(isNativeApp).mockReturnValue(true);
vi.mocked(isNativeAndroid).mockReturnValue(false);
vi.mocked(StatusBar.setStyle).mockClear();
});
afterEach(() => {
vi.useRealTimers();
for (const name of ['data-app-boot', 'data-app-handover', 'data-app-enter']) root.removeAttribute(name);
root.style.removeProperty('background-color');
root.classList.remove('dark');
if (realAgent) Object.defineProperty(window.navigator, 'userAgent', realAgent);
});
describe('appBoot', () => {
it('FE-NATIVE-APPBOOT-001: ends the handover colour once someone is signed in', () => {
root.setAttribute('data-app-boot', '');
root.style.backgroundColor = '#fffaf5';
expect(isAppBoot()).toBe(true);
endAppBoot();
expect(isAppBoot()).toBe(false);
expect(root.style.backgroundColor).toBe('');
});
it('FE-NATIVE-APPBOOT-002: leaves a page alone that never was in the handover', () => {
root.style.backgroundColor = 'red';
endAppBoot();
expect(root.style.backgroundColor).toBe('red');
});
it('FE-NATIVE-APPBOOT-003: lets the app rise in after the sign-in screen stepped back', async () => {
vi.useFakeTimers();
const go = vi.fn();
const done = handOverToApp(Promise.resolve(), go);
await vi.advanceTimersByTimeAsync(400);
expect(go).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(100);
await done;
expect(go).toHaveBeenCalledTimes(1);
endAppBoot();
expect(root.hasAttribute('data-app-enter')).toBe(true);
expect(root.style.backgroundColor).not.toBe('');
await vi.advanceTimersByTimeAsync(600);
expect(root.hasAttribute('data-app-enter')).toBe(false);
expect(root.style.backgroundColor).toBe('');
});
it('FE-NATIVE-APPBOOT-004: does not wait for settings that never come, nor stop on ones that fail', async () => {
vi.useFakeTimers();
const hanging = vi.fn();
void handOverToApp(new Promise(() => {}), hanging);
await vi.advanceTimersByTimeAsync(1600);
expect(hanging).toHaveBeenCalled();
const failing = vi.fn();
void handOverToApp(Promise.reject(new Error('offline')), failing);
await vi.advanceTimersByTimeAsync(500);
expect(failing).toHaveBeenCalled();
});
it('FE-NATIVE-APPBOOT-005: knows where the page reaches under the status bar', () => {
expect(pageUnderStatusBar()).toBe(true);
vi.mocked(isNativeAndroid).mockReturnValue(true);
webViewVersion(133);
expect(pageUnderStatusBar()).toBe(false);
webViewVersion(142);
expect(pageUnderStatusBar()).toBe(true);
});
it('FE-NATIVE-APPBOOT-006: turns the status bar icons light over the landscape and back after', () => {
root.classList.add('dark');
const restore = lightStatusBarIcons();
expect(StatusBar.setStyle).toHaveBeenLastCalledWith({ style: Style.Dark });
root.classList.remove('dark');
restore();
expect(StatusBar.setStyle).toHaveBeenLastCalledWith({ style: Style.Light });
vi.mocked(StatusBar.setStyle).mockClear();
vi.mocked(isNativeAndroid).mockReturnValue(true);
webViewVersion(133);
lightStatusBarIcons()();
expect(StatusBar.setStyle).not.toHaveBeenCalled();
});
});
+115
View File
@@ -0,0 +1,115 @@
import { StatusBar, Style } from '@capacitor/status-bar';
import { isNativeAndroid, isNativeApp } from './platform';
import { reportNativeFailure } from './reportFailure';
import { isUnimplemented } from './trekShell';
/**
* The handover from the app's address screen to this server's UI.
*
* The app picks a server, restarts its view on it, and the page then needs a
* moment for its scripts, the session check and the sign-in chunk. Each of
* those used to paint its own surface (a blank page, a grey spinner, an empty
* fallback), so the step from the warm address screen to the sign-in screen
* flashed white several times. public/theme-boot.js marks <html> with
* data-app-boot before the first paint, when the page runs inside the app and
* nobody has signed in on this server from here yet (no appearance snapshot):
* the page then starts on the address screen's own colour, the waiting states
* show the address screen's spinner on it (AppBootScreen), and the sign-in
* screen fades in on the same ground. The mark goes once someone is signed in,
* and the UI's own appearance takes over.
*/
const ATTRIBUTE = 'data-app-boot';
export function isAppBoot(): boolean {
return typeof document !== 'undefined' && document.documentElement.hasAttribute(ATTRIBUTE);
}
/** Set once the sign-in screen hands over, so the app rises in instead of cutting in. */
const HANDOVER = 'data-app-handover';
/** Set while the app rises in (native/nativeApp.css). */
const ENTER = 'data-app-enter';
/** The sign-in screen stepping back (appLogin.css .al-leaving). */
const LEAVE_MS = 420;
/** How long the handover waits for the settings before it goes anyway. */
const SETTINGS_WAIT_MS = 1500;
const ENTER_MS = 520;
/** The address screen's page colour (native-shell/shell.css --page), as public/theme-boot.js paints it. */
const PAGE_COLOUR = '#fffaf5';
const wait = (ms: number): Promise<void> => new Promise((resolve) => window.setTimeout(resolve, ms));
/**
* Signed in from the app's sign-in screen: it steps back into the page colour
* while the settings load (the start page depends on them), then `go` opens
* the app, which rises in once its first screen is there (endAppBoot).
*/
export function handOverToApp(settings: Promise<unknown>, go: () => void): Promise<void> {
// allSettled: settings that fail to load must not hold the app back either.
const ready = Promise.race([Promise.allSettled([settings]), wait(SETTINGS_WAIT_MS)]);
return Promise.all([ready, wait(LEAVE_MS)]).then(() => {
document.documentElement.setAttribute(HANDOVER, '');
go();
});
}
/**
* Back to the UI's own appearance, once a signed-in screen is up.
* theme-boot.js painted the page itself, so this clears that too; after a
* handover the app first rises in on the page colour.
*/
export function endAppBoot(): void {
const root = document.documentElement;
const handover = root.hasAttribute(HANDOVER);
if (!isAppBoot() && !handover) return;
root.removeAttribute(ATTRIBUTE);
if (!handover) {
root.style.removeProperty('background-color');
return;
}
// The page colour stays under the app while it rises in, whatever scheme the
// account brings, so nothing flashes between the two.
root.removeAttribute(HANDOVER);
root.style.backgroundColor = PAGE_COLOUR;
root.setAttribute(ENTER, '');
window.setTimeout(() => {
root.removeAttribute(ENTER);
root.style.removeProperty('background-color');
}, ENTER_MS);
}
/**
* Whether the page reaches under the status bar. iOS always lays it out there.
* Android does once the system WebView is 140 or newer (Capacitor's SystemBars
* hands the insets through from that version on); an older one sits between
* the bars, on the window's plain colour (MainActivity), where light icons
* would vanish. Shared with the address screen (native-shell/main.ts).
*/
export function pageUnderStatusBar(): boolean {
if (!isNativeAndroid()) return true;
const chrome = /Chrome\/(\d+)/.exec(navigator.userAgent);
return !!chrome && Number(chrome[1]) >= ANDROID_WEBVIEW_UNDER_BARS;
}
const ANDROID_WEBVIEW_UNDER_BARS = 140;
/**
* The sign-in screen has the landscape under the status bar, as the address
* screen does, so the clock and icons turn light while it is up. The returned
* function puts them back to the scheme's own (native/nativeApp.ts keeps them
* following it from then on). Where the page stops below the bar, the icons
* stay as they are, readable on the plain colour there.
*/
export function lightStatusBarIcons(): () => void {
if (!isNativeApp() || !pageUnderStatusBar()) return () => undefined;
setStatusBarStyle(Style.Dark);
return () => {
const dark = document.documentElement.classList.contains('dark');
setStatusBarStyle(dark ? Style.Dark : Style.Light);
};
}
/** Where there is no status bar to style (a build without the plugin) nothing is wrong. */
function setStatusBarStyle(style: Style): void {
StatusBar.setStyle({ style }).catch((err: unknown) => {
if (!isUnimplemented(err)) reportNativeFailure(err);
});
}
+47
View File
@@ -81,3 +81,50 @@ html[data-touch-input]
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
}
/* The handover from the app's address screen to this server's UI
(native/appBoot.ts): the waiting states stand on that screen's colour, with
its spinner, which fades in only once the wait is long enough to notice. */
html[data-app-boot] .app-boot {
position: fixed;
inset: 0;
display: grid;
place-items: center;
background: #fffaf5;
}
html[data-app-boot] .app-boot span {
width: 24px;
height: 24px;
border-radius: 50%;
border: 2.5px solid #6b5f57;
border-top-color: transparent;
animation:
trek-boot-spin 0.8s linear infinite,
trek-image-in 0.3s ease-out 0.6s both;
}
@keyframes trek-boot-spin {
to {
transform: rotate(360deg);
}
}
/* Signed in from the app's sign-in screen: the app rises in on the page
colour instead of cutting in (native/appBoot.ts endAppBoot). */
html[data-app-enter] #root {
animation: trek-app-enter 0.5s cubic-bezier(0.2, 0.8, 0.2, 1) both;
}
@keyframes trek-app-enter {
from {
opacity: 0;
transform: scale(0.97);
}
to {
opacity: 1;
transform: none;
}
}
@media (prefers-reduced-motion: reduce) {
html[data-app-enter] #root {
animation-duration: 0.01s;
}
}
+18
View File
@@ -22,13 +22,25 @@ export interface SharedLink {
presetTripId: number | null;
}
/** A shared map link on its way to a trip's new place (#2582). */
interface SharedPlaceLink {
tripId: number;
url: string;
}
interface SharedImportState {
file: File | null;
/** The trip whose booking import takes the file; the planner of that trip takes it from here. */
tripId: number | null;
link: SharedLink | null;
/** A map link picked to become a place: the trip's new place sheet looks it up. */
placeLink: SharedPlaceLink | null;
setFile: (file: File | null, link?: SharedLink | null) => void;
chooseTrip: (tripId: number) => void;
/** The shared link goes to this trip as a place; the sheet's queue is done with it. */
choosePlaceTrip: (tripId: number) => void;
/** The trip's place sheet took the link up. */
clearPlaceLink: () => void;
/** The booking import took the file: the queue is empty again. */
take: () => File | null;
}
@@ -37,8 +49,14 @@ export const useSharedImportStore = create<SharedImportState>((set, get) => ({
file: null,
tripId: null,
link: null,
placeLink: null,
setFile: (file, link = null) => set({ file, tripId: null, link: file ? link : null }),
chooseTrip: (tripId) => set({ tripId }),
choosePlaceTrip: (tripId) => {
const { link } = get();
set({ file: null, tripId: null, link: null, placeLink: link ? { tripId, url: link.url } : null });
},
clearPlaceLink: () => set({ placeLink: null }),
take: () => {
const { file } = get();
set({ file: null, tripId: null, link: null });
+21
View File
@@ -0,0 +1,21 @@
import { useEffect, useEffectEvent } from 'react';
import { useSharedImportStore } from './sharedFiles';
/**
* What was shared to TREK and sent to this trip (native/sharedFiles.ts), opened
* where it belongs once the trip is on screen: a booking document in the booking
* import, a map link in the new place sheet, whose search looks it up (#2582).
*/
export function useSharedIntoTrip(tripId: number, open: { bookingImport: () => void; newPlace: () => void }): void {
const bookingTripId = useSharedImportStore((s) => s.tripId);
const placeTripId = useSharedImportStore((s) => s.placeLink?.tripId ?? null);
const openBookingImport = useEffectEvent(() => open.bookingImport());
const openNewPlace = useEffectEvent(() => open.newPlace());
useEffect(() => {
if (bookingTripId != null && bookingTripId === tripId) openBookingImport();
}, [bookingTripId, tripId]);
useEffect(() => {
if (placeTripId != null && placeTripId === tripId) openNewPlace();
}, [placeTripId, tripId]);
}
@@ -0,0 +1,27 @@
// FE-PAGE-LOGIN-NATIVE-001: LoginPage inside the iOS/Android app
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { render, screen, waitFor } from '../../tests/helpers/render';
import { resetAllStores } from '../../tests/helpers/store';
import LoginPage from './LoginPage';
vi.mock('../native/platform', async (importOriginal) => ({
...(await importOriginal<typeof import('../native/platform')>()),
isNativeApp: () => true,
nativeServerHost: () => 'trek.example.com',
}));
vi.mock('../../native-shell/scenery', () => ({ startScenery: vi.fn(), cameraForPlan: () => [0, 0] }));
beforeEach(() => {
resetAllStores();
});
describe('LoginPage in the app', () => {
it('FE-PAGE-LOGIN-NATIVE-001: shows the app sign-in screen, without the language menu or the web layout', async () => {
const { container } = render(<LoginPage />);
await waitFor(() => expect(screen.getByLabelText('Email')).toBeInTheDocument());
expect(container.querySelector('.app-login')).toBeInTheDocument();
expect(screen.getByText('trek.example.com')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Change language' })).not.toBeInTheDocument();
expect(container.querySelector('.lg-panel')).not.toBeInTheDocument();
});
});
+15 -36
View File
@@ -16,7 +16,8 @@ import ToggleSwitch from '../components/Settings/ToggleSwitch';
import { SUPPORTED_LANGUAGES, useTranslation } from '../i18n';
import { IDP_LOGIN_URL, useLogin } from './login/useLogin';
import LoginWorld from './login/LoginWorld';
import NativeServerLink from './login/NativeServerLink';
import AppLogin from './login/AppLogin';
import { heading as headingOf, submitLabel } from './login/loginModel';
import MfaCodeStep from './login/MfaCodeStep';
import { LANGUAGE_CORNER_CLASS } from './login/languageCorner';
import PasswordChecklist from '../components/shared/PasswordChecklist';
@@ -44,8 +45,10 @@ const STARFIELD = [
export default function LoginPage(): React.ReactElement {
const { t, language } = useTranslation();
// Page = wiring container: the whole auth surface lives in the useLogin hook.
const login = useLogin();
const {
navigate,
nativeApp,
mode,
setMode,
username,
@@ -87,8 +90,10 @@ export default function LoginPage(): React.ReactElement {
idpSlow,
idpName,
handleDemoLogin, handleSubmit, handlePasskeyLogin, handleSsoClick,
} = useLogin();
} = login;
const step = { mode, mfaStep, passwordChangeStep, hasUsers: !!appConfig?.has_users };
const heading = headingOf(step, t);
const oidcButtonShown = !!(appConfig?.oidc_configured && appConfig?.oidc_login && !oidcOnly);
const passkeyAvailable = !!(
appConfig?.passkey_login &&
@@ -115,7 +120,7 @@ export default function LoginPage(): React.ReactElement {
transition: 'border-color 0.15s',
};
if (showTakeoff) {
if (showTakeoff && !nativeApp) {
return (
<div
className="takeoff-overlay"
@@ -227,6 +232,9 @@ export default function LoginPage(): React.ReactElement {
);
}
// In the app: the screen continuing its address screen (login/AppLogin.tsx).
if (nativeApp) return <AppLogin login={login} />;
return (
<div style={{ minHeight: '100vh', display: 'flex', fontFamily: 'var(--font-system)', position: 'relative' }}>
<div className={LANGUAGE_CORNER_CLASS}>
@@ -576,26 +584,10 @@ export default function LoginPage(): React.ReactElement {
color: '#111827',
}}
>
{passwordChangeStep
? t('login.setNewPassword')
: mode === 'login' && mfaStep
? t('login.mfaTitle')
: mode === 'register'
? !appConfig?.has_users
? t('login.createAdmin')
: t('login.createAccount')
: t('login.title')}
{heading.title}
</h2>
<p style={{ margin: '0 0 28px', fontSize: 'calc(13.5px * var(--fs-scale-body, 1))', color: '#9ca3af' }}>
{passwordChangeStep
? t('login.setNewPasswordHint')
: mode === 'login' && mfaStep
? t('login.mfaSubtitle')
: mode === 'register'
? !appConfig?.has_users
? t('login.createAdminHint')
: t('login.createAccountHint')
: t('login.subtitle')}
{heading.subtitle}
</p>
<form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
@@ -1014,24 +1006,12 @@ export default function LoginPage(): React.ReactElement {
animation: 'spin 0.7s linear infinite',
}}
/>
{passwordChangeStep
? t('settings.updatePassword')
: mode === 'register'
? t('login.creating')
: mode === 'login' && mfaStep
? t('login.mfaVerify')
: t('login.signingIn')}
{submitLabel(step, true, t)}
</>
) : (
<>
<Plane size={16} />
{passwordChangeStep
? t('settings.updatePassword')
: mode === 'register'
? t('login.createAccount')
: mode === 'login' && mfaStep
? t('login.mfaVerify')
: t('login.signIn')}
{submitLabel(step, false, t)}
</>
)}
</button>
@@ -1222,7 +1202,6 @@ export default function LoginPage(): React.ReactElement {
{t('login.demoHint')}
</button>
)}
<NativeServerLink />
</div>
</div>
+15 -16
View File
@@ -69,7 +69,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
pushUndo, undo, canUndo, lastActionLabel, handleUndo,
enabledAddons, collabFeatures, journalId, tripAccommodations, setTripAccommodations,
roadtripMode, toggleRoadtripMode, roadtripActive, roadtripRoutes, roadtripLineColors, roadtripMapLines, roadtripMapPlaces, collapsedRoadtripDays, toggleRoadtripDay, roadtripCorridor,
overviewActive, tripOverview, toggleOverview, overviewShown,
overviewActive, tripOverview, overviewShown,
dawarichEnabled, dawarichTrailShown, toggleDawarichTrail, dawarichTrail, dawarichHiddenDates,
followTrack, roadtripViaCounts,
allowedFileTypes, tripMembers, setTripMembers, refreshMembers, loadAccommodations,
@@ -77,8 +77,8 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
leftWidth, rightWidth,
leftHidden, rightHidden, toggleLeft, toggleRight,
startResizeLeft, startResizeRight, nudgeLeft, nudgeRight, resizing, resizeMin, resizeMaxLeft, resizeMaxRight,
selectedPlaceId, selectedAssignmentId, setSelectedPlaceId, selectAssignment,
showDayDetail, setShowDayDetail, dayDetailCollapsed, setDayDetailCollapsed,
selectedPlaceId, selectedAssignmentId, setSelectedPlaceId,
showDayDetail, dayDetailCollapsed, setDayDetailCollapsed,
stayPickerDayId, setStayPickerDayId,
showPlaceForm, setShowPlaceForm, editingPlace, setEditingPlace, setPlaceFormDayId,
prefillCoords, editingAssignmentId, setEditingAssignmentId, setRoadtripStopKind,
@@ -139,6 +139,10 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
locationSearch,
dayPlanTours,
placeForm,
planMap: {
leftPanelPx, rightPanelPx, mapInsetLeft, mapInsetRight, overviewRightGap,
dayCardRef, overviewCardRef, handleToggleOverview, handleDayDetail, closeDayDetail, openSelectedDayDetail,
},
} = pageState
// Tablets run this very layout but cannot start an HTML5 drag with a finger,
// so a long press stands in for one (#1616). Only where the pointer is
@@ -195,14 +199,6 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
}
if (!trip) return null
// What each panel actually occupies right now, and where that leaves the
// strip of map between them. The panels float 10px inside the map, so the
// corridor starts past that margin.
const leftPanelPx = leftHidden ? 0 : leftWidth
const rightPanelPx = rightHidden ? 0 : rightWidth
const mapInsetLeft = leftPanelPx ? leftPanelPx + 10 : 0
const mapInsetRight = rightPanelPx ? rightPanelPx + 10 : 0
// The place inspector and the tour dialog open on the selected place, beside
// the panels or in the phone-width sheet. What every one of them gets; each
// call site adds what differs.
@@ -276,7 +272,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
roadtripRoutes={roadtripRoutes} roadtripConnections={roadtripConnections} roadtripVias={roadtripVias}
dayBoundaryControls={dayBoundaryControls} dropPoiOnRoute={dropPoiOnRoute} addRoadtripVia={addRoadtripVia} moveRoadtripVia={moveRoadtripVia} removeRoadtripVia={removeRoadtripVia}
routeAlternatives={routeAlternatives} alternativeOverlays={alternativeOverlays} highlightedAlternative={highlightedAlternative} chooseRouteAlternative={chooseRouteAlternative} setHighlightedAlternative={setHighlightedAlternative}
overviewActive={overviewActive} tripOverview={tripOverview} overviewShown={overviewShown} toggleOverview={toggleOverview}
overviewActive={overviewActive} tripOverview={tripOverview} overviewShown={overviewShown} toggleOverview={handleToggleOverview} overviewCardRef={overviewCardRef}
dawarichEnabled={dawarichEnabled} dawarichTrail={dawarichTrail} dawarichHiddenDates={dawarichHiddenDates} dawarichTrailShown={dawarichTrailShown} toggleDawarichTrail={toggleDawarichTrail}
mobileSidebarOpen={mobileSidebarOpen} showPlaceForm={showPlaceForm} showMembersModal={showMembersModal} showReservationModal={showReservationModal}
poi={poi} tourMap={tourMap} leftPanelPx={leftPanelPx} rightPanelPx={rightPanelPx} mapInsetLeft={mapInsetLeft} mapInsetRight={mapInsetRight}
@@ -343,6 +339,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
categories={categories}
assignments={storedAssignments}
selectedDayId={selectedDayId}
openSelectedDayDetail={openSelectedDayDetail}
selectedPlaceId={selectedPlaceId}
selectedAssignmentId={selectedAssignmentId}
onSelectDay={handleSelectDay}
@@ -374,8 +371,8 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
onEditReservation={can('reservation_edit', trip) ? (r) => { setEditingReservation(r); setShowReservationModal(true) } : undefined}
// The narrow layout keeps what a booking row opened before.
onOpenBooking={isMobile ? undefined : openBookingFromDayList}
onDayDetail={(day) => { setShowDayDetail(day); setSelectedPlaceId(null); selectAssignment(null) }}
onAddAccommodation={can('day_edit', trip) ? (day) => { handleSelectDay(day.id); setShowDayDetail(day); setSelectedPlaceId(null); selectAssignment(null); setStayPickerDayId(day.id) } : undefined}
onDayDetail={handleDayDetail}
onAddAccommodation={can('day_edit', trip) ? (day) => { handleSelectDay(day.id); handleDayDetail(day); setStayPickerDayId(day.id) } : undefined}
onRemoveAssignment={handleRemoveAssignment}
onEditPlace={(place, assignmentId) => {
// The day is cleared on the way in: the form assigns to whatever
@@ -523,10 +520,12 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
lat={weatherLat}
lng={weatherLng}
weatherPlaceName={weatherPlaceName}
onClose={() => { setShowDayDetail(null); handleSelectDay(null) }}
panelRef={dayCardRef}
onClose={() => { closeDayDetail(); handleSelectDay(null) }}
onAccommodationChange={loadAccommodations}
leftWidth={isMobile ? 0 : leftPanelPx}
rightWidth={isMobile ? 0 : rightPanelPx}
rightGap={isMobile || roadtripActive ? undefined : overviewRightGap}
collapsed={dayDetailCollapsed}
onToggleCollapse={() => setDayDetailCollapsed(c => !c)}
mobile={isMobile}
@@ -607,7 +606,7 @@ function TripPlannerPageDesktop(): React.ReactElement | null {
</div>
<div style={{ flex: 1, overflow: 'auto', paddingBottom: 'env(safe-area-inset-bottom, 0px)' }}>
{mobileSidebarOpen === 'left'
? <DayPlanSidebar tripId={tripId} trip={trip} days={days} places={places} {...dayPlanTours} categories={categories} assignments={storedAssignments} selectedDayId={selectedDayId} selectedPlaceId={selectedPlaceId} selectedAssignmentId={selectedAssignmentId} onSelectDay={(id) => { handleSelectDay(id); setMobileSidebarOpen(null) }} onPlaceClick={(placeId, assignmentId) => { handlePlaceClick(placeId, assignmentId) }} onReorder={handleReorder} onReorderDays={handleReorderDays} onAddDay={handleAddDay} dayAdd={dayAdd} onDeleteDay={handleDeleteDay} deleteDayQuestion={deleteDayQuestion} onClearDay={can('day_edit', trip) ? handleClearDay : undefined} onUpdateDayTitle={handleUpdateDayTitle} onAssignToDay={handleAssignToDay} onMoveToDay={handleMoveToDay} onRouteCalculated={(r) => { if (r) { setRoute([r.coordinates]); setRouteInfo(r) } else { setRoute(null); setRouteInfo(null) } }} reservations={reservations} visibleConnectionIds={visibleConnections} onToggleConnection={toggleConnection} allConnectionsShown={allConnectionsShown} onToggleAllConnections={toggleAllConnections} onAddReservation={(dayId) => { setEditingReservation(null); tripActions.setSelectedDay(dayId); setShowReservationModal(true); setMobileSidebarOpen(null) }} onAddTransport={can('day_edit', trip) ? (dayId) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill(null); setTransportModalAutomated(false); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onOpenTransit={(r) => { setTransitJourney(r); setMobileSidebarOpen(null) }} onPlanTransit={can('day_edit', trip) && tripHasDates ? (dayId) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill(null); setTransportModalAutomated(true); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onPlanTransitLeg={can('day_edit', trip) && tripHasDates ? ({ dayId, ...leg }) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill(leg); setTransportModalAutomated(true); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onAddPlace={() => { setEditingPlace(null); setPlaceFormDayId(null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onCreatePlaceForDay={can('place_edit', trip) ? (dayId) => { setEditingPlace(null); setPlaceFormDayId(dayId); setShowPlaceForm(true); setMobileSidebarOpen(null) } : undefined} onDayDetail={(day) => { setShowDayDetail(day); setSelectedPlaceId(null); selectAssignment(null) }} onRemoveAssignment={handleRemoveAssignment} onEditPlace={(place, assignmentId) => { setEditingPlace(place); setEditingAssignmentId(assignmentId || null); setPlaceFormDayId(null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onDeletePlace={(placeId) => handleDeletePlace(placeId)} accommodations={tripAccommodations} routeShown={routeShown} routeProfile={routeProfile} roadtripViasByDay={roadtripVias.byDay} onToggleRoute={() => setRouteShown(v => !v)} onSetRouteProfile={setRouteProfile} onNavigateToFiles={() => { setMobileSidebarOpen(null); handleTabChange('dateien') }} onExpandedDaysChange={setExpandedDayIds} pushUndo={pushUndo} canUndo={canUndo} lastActionLabel={lastActionLabel} onUndo={handleUndo} onEditTransport={can('day_edit', trip) ? (reservation) => { setEditingTransport(reservation); setTransportModalDayId(reservation.day_id ?? null); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onEditReservation={can('reservation_edit', trip) ? (r) => { setEditingReservation(r); setShowReservationModal(true); setMobileSidebarOpen(null) } : undefined} initialScrollTop={mobilePlanScrollTopRef.current} onScrollTopChange={(top) => { mobilePlanScrollTopRef.current = top }} showRouteToolsWhenExpanded isMobile />
? <DayPlanSidebar tripId={tripId} trip={trip} days={days} places={places} {...dayPlanTours} categories={categories} assignments={storedAssignments} selectedDayId={selectedDayId} openSelectedDayDetail={openSelectedDayDetail} selectedPlaceId={selectedPlaceId} selectedAssignmentId={selectedAssignmentId} onSelectDay={(id) => { handleSelectDay(id); setMobileSidebarOpen(null) }} onPlaceClick={(placeId, assignmentId) => { handlePlaceClick(placeId, assignmentId) }} onReorder={handleReorder} onReorderDays={handleReorderDays} onAddDay={handleAddDay} dayAdd={dayAdd} onDeleteDay={handleDeleteDay} deleteDayQuestion={deleteDayQuestion} onClearDay={can('day_edit', trip) ? handleClearDay : undefined} onUpdateDayTitle={handleUpdateDayTitle} onAssignToDay={handleAssignToDay} onMoveToDay={handleMoveToDay} onRouteCalculated={(r) => { if (r) { setRoute([r.coordinates]); setRouteInfo(r) } else { setRoute(null); setRouteInfo(null) } }} reservations={reservations} visibleConnectionIds={visibleConnections} onToggleConnection={toggleConnection} allConnectionsShown={allConnectionsShown} onToggleAllConnections={toggleAllConnections} onAddReservation={(dayId) => { setEditingReservation(null); tripActions.setSelectedDay(dayId); setShowReservationModal(true); setMobileSidebarOpen(null) }} onAddTransport={can('day_edit', trip) ? (dayId) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill(null); setTransportModalAutomated(false); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onOpenTransit={(r) => { setTransitJourney(r); setMobileSidebarOpen(null) }} onPlanTransit={can('day_edit', trip) && tripHasDates ? (dayId) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill(null); setTransportModalAutomated(true); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onPlanTransitLeg={can('day_edit', trip) && tripHasDates ? ({ dayId, ...leg }) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill(leg); setTransportModalAutomated(true); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onAddPlace={() => { setEditingPlace(null); setPlaceFormDayId(null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onCreatePlaceForDay={can('place_edit', trip) ? (dayId) => { setEditingPlace(null); setPlaceFormDayId(dayId); setShowPlaceForm(true); setMobileSidebarOpen(null) } : undefined} onDayDetail={handleDayDetail} onRemoveAssignment={handleRemoveAssignment} onEditPlace={(place, assignmentId) => { setEditingPlace(place); setEditingAssignmentId(assignmentId || null); setPlaceFormDayId(null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onDeletePlace={(placeId) => handleDeletePlace(placeId)} accommodations={tripAccommodations} routeShown={routeShown} routeProfile={routeProfile} roadtripViasByDay={roadtripVias.byDay} onToggleRoute={() => setRouteShown(v => !v)} onSetRouteProfile={setRouteProfile} onNavigateToFiles={() => { setMobileSidebarOpen(null); handleTabChange('dateien') }} onExpandedDaysChange={setExpandedDayIds} pushUndo={pushUndo} canUndo={canUndo} lastActionLabel={lastActionLabel} onUndo={handleUndo} onEditTransport={can('day_edit', trip) ? (reservation) => { setEditingTransport(reservation); setTransportModalDayId(reservation.day_id ?? null); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onEditReservation={can('reservation_edit', trip) ? (r) => { setEditingReservation(r); setShowReservationModal(true); setMobileSidebarOpen(null) } : undefined} initialScrollTop={mobilePlanScrollTopRef.current} onScrollTopChange={(top) => { mobilePlanScrollTopRef.current = top }} showRouteToolsWhenExpanded isMobile />
: <PlacesSidebar tripId={tripId} places={places} toursEnabled={toursEnabled} excludePlaceIds={toursEnabled ? tourPlaceIds : undefined} onToursChanged={placeIds => invalidateTourPlaceIds(placeIds ? { placeIds } : undefined)} categories={categories} assignments={assignments} accommodations={tripAccommodations} selectedDayId={selectedDayId} onClearSelectedDay={() => handleSelectDay(null)} selectedPlaceId={selectedPlaceId} onPlaceClick={(placeId) => { handlePlaceClick(placeId); setMobileSidebarOpen(null) }} onAddPlace={() => { setEditingPlace(null); setPlaceFormDayId(null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onAssignToDay={handleAssignToDay} onEditPlace={(place) => { openPlaceEditor(place); setMobileSidebarOpen(null) }} onDeletePlace={(placeId) => handleDeletePlace(placeId)} onBulkDeletePlaces={(ids) => setDeletePlaceIds(ids)} onBulkDeleteConfirm={(ids) => confirmDeletePlaces(ids)} onBulkChangeCategory={(ids, catId) => confirmChangeCategory(ids, catId)} days={days} isMobile pushUndo={pushUndo} initialScrollTop={mobilePlacesScrollTopRef.current} onScrollTopChange={(top) => { mobilePlacesScrollTopRef.current = top }} />
}
</div>
@@ -50,7 +50,7 @@ export function useJourneyDetail({ journeyId, embedded = false }: JourneyDetailO
const navigate = useNavigate()
const toast = useToast()
const { t, locale } = useTranslation()
const { current, loading, notFound, loadJourney, updateEntry, deleteEntry, reorderEntries, uploadPhotos, deletePhoto } = useJourneyStore()
const { current, loading, notFound, loadJourney, refreshJourney, updateEntry, deleteEntry, reorderEntries, uploadPhotos, deletePhoto } = useJourneyStore()
const mapRef = useRef<JourneyMapHandle>(null)
const fullMapRef = useRef<JourneyMapHandle>(null)
/** The gallery hands its file picker up here, so the hero button can open it. */
@@ -341,7 +341,7 @@ export function useJourneyDetail({ journeyId, embedded = false }: JourneyDetailO
// Provider photos from the gallery picker and from the entry editor, the same
// way on desktop and phone (#1587).
const providerPhotos = useProviderPhotoAdds(() => { void loadJourney(Number(id)) })
const providerPhotos = useProviderPhotoAdds(() => { void refreshJourney(Number(id)) })
const restoreSuggestions = useCallback(async () => {
if (!current) return
@@ -539,7 +539,7 @@ export function useJourneyDetail({ journeyId, embedded = false }: JourneyDetailO
recordingPrep, recordings, canTakeOverRecording, recordingNeedsConnection, mapTracks, mapLayers, entryTitleOf,
dayImport, dayImportDates,
} = useJourneyDetailLayers({
journey: current, loaded: journeyLoaded, canEditEntries, loadJourney, dawarich, dawarichByDate, dawarichTrail,
journey: current, loaded: journeyLoaded, canEditEntries, loadJourney: refreshJourney, dawarich, dawarichByDate, dawarichTrail,
tripDates, sidebarMapItems, photoCount: mapPhotos.length, showTripTracks,
})
@@ -592,7 +592,8 @@ export function useJourneyDetail({ journeyId, embedded = false }: JourneyDetailO
recordings, canTakeOverRecording, recordingNeedsConnection, dayImport, dayImportDates, recordingPrep,
mapPhotos, openMapPhotos,
feedEdge, scrollFeedTo,
loadJourney, updateEntry, deleteEntry, reorderEntries, uploadPhotos, deletePhoto,
// The views reload after their own changes; such a read never rejects.
loadJourney: refreshJourney, updateEntry, deleteEntry, reorderEntries, uploadPhotos, deletePhoto,
addPickedProviderPhotos: providerPhotos.addPickedPhotos,
addEntryProviderPhotos: providerPhotos.addEntryPhotos,
// A planned place picked on the map that nothing was written about yet: write it up.
@@ -63,7 +63,7 @@ export function useJourneyStudio() {
const location = useLocation()
const { t, locale } = useTranslation()
const isMobile = useIsMobile()
const { current, loading, loadJourney } = useJourneyStore()
const { current, loading, refreshJourney } = useJourneyStore()
const doc = useStudioStore(s => s.doc)
const loadDoc = useStudioStore(s => s.load)
@@ -211,8 +211,8 @@ export function useJourneyStudio() {
useEffect(() => {
if (!Number.isFinite(journeyId)) return
if (!current || current.id !== journeyId) void loadJourney(journeyId)
}, [journeyId, current, loadJourney])
if (!current || current.id !== journeyId) void refreshJourney(journeyId)
}, [journeyId, current, refreshJourney])
// Lay the book out once, from the journey. After that it is an ordinary
// document and this must not run again, or it would throw away the user's
@@ -672,7 +672,7 @@ export function useJourneyStudio() {
* the new ones the way it shows an upload.
*/
const photoProviders = useConnectedPhotoProviders(canEdit)
const providerAdds = useProviderPhotoAdds(() => { void loadJourney(journeyId) })
const providerAdds = useProviderPhotoAdds(() => { void refreshJourney(journeyId) })
const [providerPick, setProviderPick] = useState<{ provider: string; entryId: number | null } | null>(null)
const pickAnswer = useRef<((photoIds: number[]) => void) | null>(null)
const answerPick = (photoIds: number[]) => {
+231
View File
@@ -0,0 +1,231 @@
// FE-LOGIN-APP-001 to FE-LOGIN-APP-011: the sign-in screen inside the iOS/Android app
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { buildAppConfig } from '../../../tests/helpers/factories';
import { fireEvent, render, screen } from '../../../tests/helpers/render';
import { resetAllStores } from '../../../tests/helpers/store';
import { nativeServerHost } from '../../native/platform';
import { TrekShell } from '../../native/trekShell';
import AppLogin from './AppLogin';
import type { useLogin } from './useLogin';
type Login = ReturnType<typeof useLogin>;
type LoginConfig = NonNullable<Login['appConfig']>;
/** The sign-in page's own config shape, on top of the shared factory's. */
function appConfigOf(overrides: Partial<LoginConfig> = {}): LoginConfig {
return { ...buildAppConfig({ has_users: true }), setup_complete: true, ...overrides } as LoginConfig;
}
vi.mock('../../native/platform', async (importOriginal) => ({
...(await importOriginal<typeof import('../../native/platform')>()),
nativeServerHost: vi.fn(),
}));
vi.mock('../../native/trekShell', () => ({ TrekShell: { resetServer: vi.fn() } }));
// The landscape is a WebGL loop, which jsdom cannot draw.
vi.mock('../../../native-shell/scenery', () => ({ startScenery: vi.fn(), cameraForPlan: () => [0, 0] }));
function buildLogin(overrides: Partial<Login> = {}): Login {
const login = {
navigate: vi.fn(),
nativeApp: true,
mode: 'login',
setMode: vi.fn(),
username: '',
setUsername: vi.fn(),
email: '',
setEmail: vi.fn(),
password: '',
setPassword: vi.fn(),
rememberMe: true,
setRememberMe: vi.fn(),
showPassword: false,
setShowPassword: vi.fn(),
isLoading: false,
error: '',
setError: vi.fn(),
insecureCookie: false,
appConfig: appConfigOf(),
inviteToken: '',
langDropdownOpen: false,
setLangDropdownOpen: vi.fn(),
setLanguageLocal: vi.fn(),
showTakeoff: false,
mfaStep: false,
setMfaStep: vi.fn(),
mfaToken: '',
setMfaToken: vi.fn(),
mfaCode: '',
setMfaCode: vi.fn(),
passwordChangeStep: false,
newPassword: '',
setNewPassword: vi.fn(),
confirmPassword: '',
setConfirmPassword: vi.fn(),
noRedirect: false,
showRegisterOption: false,
oidcOnly: false,
redirectScreen: false,
configWait: false,
idpSlow: false,
idpName: 'SSO',
handleDemoLogin: vi.fn(),
handleSubmit: vi.fn((e: React.FormEvent) => e.preventDefault()),
handlePasskeyLogin: vi.fn(),
handleSsoClick: vi.fn(),
...overrides,
};
return login as unknown as Login;
}
beforeEach(() => {
resetAllStores();
vi.mocked(nativeServerHost).mockReturnValue('trek.example.com');
vi.mocked(TrekShell.resetServer).mockReset().mockResolvedValue();
});
describe('AppLogin', () => {
it('FE-LOGIN-APP-001: shows the server it signs in to, no language menu, and leads back to the address screen', () => {
render(<AppLogin login={buildLogin()} />);
expect(screen.getByText('trek.example.com')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Change language' })).not.toBeInTheDocument();
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Change server' }));
expect(TrekShell.resetServer).toHaveBeenCalled();
});
it('FE-LOGIN-APP-002: signs in with email and password, with the fields password managers fill', () => {
// Filled, as the hook would hold them: the form refuses to submit with its required fields empty.
const login = buildLogin({ email: 'old@example.com', password: 'old' });
render(<AppLogin login={login} />);
expect(screen.getByRole('heading', { name: 'Sign In' })).toBeInTheDocument();
expect(screen.queryByText('Welcome back')).not.toBeInTheDocument();
const email = screen.getByLabelText('Email');
const password = screen.getByLabelText('Password');
expect(email).toHaveAttribute('autocomplete', 'username');
expect(password).toHaveAttribute('autocomplete', 'current-password');
fireEvent.change(email, { target: { value: 'me@example.com' } });
fireEvent.change(password, { target: { value: 'secret' } });
expect(login.setEmail).toHaveBeenCalledWith('me@example.com');
expect(login.setPassword).toHaveBeenCalledWith('secret');
fireEvent.click(screen.getByRole('button', { name: 'Sign In' }));
expect(login.handleSubmit).toHaveBeenCalled();
});
it('FE-LOGIN-APP-003: shows the password, remembers the login and keeps the way to a new password last', () => {
const login = buildLogin();
render(<AppLogin login={login} />);
fireEvent.click(screen.getByRole('button', { name: 'Show password' }));
expect(login.setShowPassword).toHaveBeenCalled();
fireEvent.click(screen.getByRole('button', { name: 'Remember me' }));
expect(login.setRememberMe).toHaveBeenCalledWith(false);
const forgot = screen.getByRole('button', { name: 'Forgot password?' });
const buttons = screen.getAllByRole('button');
expect(buttons[buttons.length - 1]).toBe(forgot);
fireEvent.click(forgot);
expect(login.navigate).toHaveBeenCalledWith('/forgot-password');
});
it('FE-LOGIN-APP-004: offers SSO beside the password, carrying the remember-me choice', () => {
const login = buildLogin({
rememberMe: false,
appConfig: appConfigOf({
has_users: true,
oidc_configured: true,
oidc_login: true,
oidc_display_name: 'Pocket ID',
}),
});
render(<AppLogin login={login} />);
const sso = screen.getByRole('link', { name: 'Sign in with Pocket ID' });
expect(sso).toHaveAttribute('href', '/api/auth/oidc/login?remember=0');
fireEvent.click(sso);
expect(login.handleSsoClick).toHaveBeenCalled();
});
it('FE-LOGIN-APP-005: offers only SSO on an OIDC-only install', () => {
render(
<AppLogin
login={buildLogin({
oidcOnly: true,
inviteToken: 'abc',
appConfig: appConfigOf({ has_users: true, oidc_display_name: 'Authentik' }),
})}
/>
);
expect(screen.getByRole('link', { name: 'Sign in with Authentik' })).toHaveAttribute(
'href',
'/api/auth/oidc/login?invite=abc&remember=1'
);
expect(screen.queryByLabelText('Password')).not.toBeInTheDocument();
});
it('FE-LOGIN-APP-006: offers a passkey where the server allows one', () => {
const login = buildLogin({
appConfig: appConfigOf({ has_users: true, passkey_login: true, passkey_configured: true }),
});
render(<AppLogin login={login} />);
fireEvent.click(screen.getByRole('button', { name: 'Sign in with a passkey' }));
expect(login.handlePasskeyLogin).toHaveBeenCalled();
});
it('FE-LOGIN-APP-007: asks for the one-time code in the second step, with the way back', () => {
const login = buildLogin({ mfaStep: true, email: 'me@example.com' });
render(<AppLogin login={login} />);
expect(screen.queryByLabelText('Password')).not.toBeInTheDocument();
const code = document.getElementById('totp') as HTMLInputElement;
expect(code).toHaveAttribute('autocomplete', 'one-time-code');
fireEvent.change(code, { target: { value: 'ab12cd' } });
expect(login.setMfaCode).toHaveBeenCalledWith('AB12CD');
fireEvent.click(screen.getByRole('button', { name: '← Back to sign in' }));
expect(login.setMfaStep).toHaveBeenCalledWith(false);
expect(login.setMfaCode).toHaveBeenCalledWith('');
});
it('FE-LOGIN-APP-008: sets a new password when the account must change it', () => {
const login = buildLogin({ passwordChangeStep: true });
render(<AppLogin login={login} />);
fireEvent.change(screen.getByLabelText('New password'), { target: { value: 'Abcdefgh1!' } });
fireEvent.change(screen.getByLabelText('Confirm new password'), { target: { value: 'Abcdefgh1!' } });
expect(login.setNewPassword).toHaveBeenCalledWith('Abcdefgh1!');
expect(login.setConfirmPassword).toHaveBeenCalledWith('Abcdefgh1!');
expect(screen.queryByRole('button', { name: 'Forgot password?' })).not.toBeInTheDocument();
});
it('FE-LOGIN-APP-009: switches to registering where the server allows it', () => {
const login = buildLogin({ showRegisterOption: true });
const { rerender } = render(<AppLogin login={login} />);
fireEvent.click(screen.getByRole('button', { name: 'Register' }));
expect(login.setMode).toHaveBeenCalled();
rerender(<AppLogin login={buildLogin({ showRegisterOption: true, mode: 'register' })} />);
expect(screen.getByLabelText('Username')).toBeInTheDocument();
expect(screen.getByLabelText('Password')).toHaveAttribute('autocomplete', 'new-password');
});
it('FE-LOGIN-APP-010: shows errors and waits in the address screen style', () => {
const { rerender } = render(<AppLogin login={buildLogin({ error: 'Invalid credentials' })} />);
expect(screen.getByRole('alert')).toHaveTextContent('Invalid credentials');
rerender(<AppLogin login={buildLogin({ redirectScreen: true, idpSlow: true, idpName: 'Authentik' })} />);
expect(screen.getByRole('status')).toHaveTextContent('Authentik');
expect(screen.queryByLabelText('Email')).not.toBeInTheDocument();
rerender(<AppLogin login={buildLogin({ configWait: true })} />);
expect(screen.getByRole('status', { name: 'Loading...' })).toBeInTheDocument();
});
it('FE-LOGIN-APP-011: steps back once signed in instead of playing the takeoff', () => {
const { container } = render(<AppLogin login={buildLogin({ showTakeoff: true })} />);
expect(container.querySelector('.app-login')).toHaveClass('al-leaving');
expect(container.querySelector('.takeoff-overlay')).not.toBeInTheDocument();
});
});
+423
View File
@@ -0,0 +1,423 @@
import { AlertCircle, Eye, EyeOff, Fingerprint, Globe, Lock, Shield } from 'lucide-react';
import React, { useEffect, useRef } from 'react';
import ToggleSwitch from '../../components/Settings/ToggleSwitch';
import { useNativeServer } from '../../components/Settings/useNativeServer';
import PasswordChecklist from '../../components/shared/PasswordChecklist';
import { useTranslation } from '../../i18n';
import { lightStatusBarIcons } from '../../native/appBoot';
import { reportNativeFailure } from '../../native/reportFailure';
import './appLogin.css';
import { heading as headingOf, oidcLoginHref, oidcOnlyHref, submitLabel, type LoginStep } from './loginModel';
import { mfaCodeInputProps } from './mfaCodeInput';
import { IDP_LOGIN_URL, type useLogin } from './useLogin';
type Login = ReturnType<typeof useLogin>;
/**
* The sign-in screen inside the iOS and Android app. It follows the app's own
* address screen (native-shell/), so it continues it instead of looking like a
* web page: the same landscape on top, the card with the server just connected
* to, the same fields and buttons. Everything it does comes from useLogin, as
* on the browser's LoginPage; only the look and the missing language menu
* (the device decides, see useLogin) differ.
*/
export default function AppLogin({ login }: { login: Login }) {
useEffect(() => lightStatusBarIcons(), []);
return (
<div className={login.showTakeoff ? 'app-login al-leaving' : 'app-login'}>
<AppLoginHero />
<main className="al-body">
<AppLoginContent login={login} />
</main>
</div>
);
}
function AppLoginContent({ login }: { login: Login }) {
const { t } = useTranslation();
if (login.redirectScreen) {
return (
<div className="al-wait" role="status" aria-live="polite">
<span className="al-spin" aria-hidden="true" />
<p>{t('login.oidcRedirecting', { name: login.idpName })}</p>
{login.idpSlow && (
<a href={IDP_LOGIN_URL} onClick={login.handleSsoClick}>
{t('login.oidcRedirectSlow', { name: login.idpName })}
</a>
)}
</div>
);
}
if (login.configWait) {
return (
<div className="al-wait" role="status" aria-label={t('common.loading')}>
<span className="al-spin" aria-hidden="true" />
</div>
);
}
if (login.oidcOnly) return <OidcOnly login={login} />;
return <Credentials login={login} />;
}
/** The landscape of the address screen, with the server this screen signs in to. */
function AppLoginHero() {
const { t } = useTranslation();
const { host, changeServer } = useNativeServer();
const hero = useRef<HTMLDivElement>(null);
useEffect(() => {
const box = hero.current;
if (!box) return;
let cancelled = false;
// The same camera the address screen ends on, so the picture holds still
// across the change of screens. The scene stops drawing once its canvas
// has left the page.
void import('../../../native-shell/scenery')
.then(({ startScenery, cameraForPlan }) => {
if (!cancelled) startScenery(box, { frame: 320, camera: cameraForPlan(1), haze: false });
})
// Without the landscape the box keeps its plain sea colour.
.catch(reportNativeFailure);
return () => {
cancelled = true;
box.querySelector('canvas.scenery')?.remove();
};
}, []);
return (
<div className="al-hero" ref={hero}>
<img className="al-logo" src="/logo-light.svg" alt="TREK" />
{host && (
<div className="al-card">
<div className="al-card-text">
<small>
<Lock size={12} strokeWidth={2.6} aria-hidden="true" />
{t('native.connect.yourTrek')}
</small>
<div className="al-host" dir="ltr">
<Globe size={17} aria-hidden="true" />
<span>{host}</span>
</div>
</div>
<button type="button" className="al-change" onClick={changeServer} aria-label={t('native.changeServer')}>
{t('common.change')}
</button>
</div>
)}
</div>
);
}
function Notice({ tone, children }: { tone?: 'warn'; children: React.ReactNode }) {
return (
<div className={tone ? `al-notice ${tone}` : 'al-notice'} role={tone ? undefined : 'alert'}>
<AlertCircle size={18} aria-hidden="true" />
<div>{children}</div>
</div>
);
}
/**
* A field on a white card, the label above the input, as on the address screen.
* A control beside the input (the password's eye) sits outside the label, so
* the label names the input alone.
*/
function Field({
label,
after,
...input
}: { label: string; after?: React.ReactNode } & React.InputHTMLAttributes<HTMLInputElement>) {
return (
<div className={after ? 'al-fld-wrap with-after' : 'al-fld-wrap'}>
<label className="al-fld">
<span className="al-lab">{label}</span>
<input {...input} />
</label>
{after && <span className="al-after">{after}</span>}
</div>
);
}
function OidcOnly({ login }: { login: Login }) {
const { t } = useTranslation();
return (
<div className="al-form">
<h1 className="al-title">{t('login.title')}</h1>
<p className="al-sub">{login.noRedirect ? t('login.oidcLoggedOut') : t('login.oidcOnly')}</p>
{login.error && <Notice>{login.error}</Notice>}
<a className="al-cta" href={oidcOnlyHref(login.inviteToken)} onClick={login.handleSsoClick}>
<Shield size={18} aria-hidden="true" />
{t('login.oidcSignIn', { name: login.appConfig?.oidc_display_name || 'SSO' })}
</a>
</div>
);
}
function stepOf(login: Login): LoginStep {
return {
mode: login.mode,
mfaStep: login.mfaStep,
passwordChangeStep: login.passwordChangeStep,
hasUsers: !!login.appConfig?.has_users,
};
}
function Credentials({ login }: { login: Login }) {
const { t } = useTranslation();
const step = stepOf(login);
const heading = headingOf(step, t);
const onMfa = login.mode === 'login' && login.mfaStep && !login.passwordChangeStep;
const onAccount = !(login.mode === 'login' && login.mfaStep) && !login.passwordChangeStep;
return (
<>
<form className="al-form" onSubmit={(e) => void login.handleSubmit(e)}>
<h1 className="al-title">{heading.title}</h1>
{/* The plain sign-in needs no line under its heading; the other steps say what they ask for. */}
{!heading.plain && <p className="al-sub">{heading.subtitle}</p>}
<Notices login={login} />
{login.passwordChangeStep && <NewPassword login={login} />}
{onMfa && <MfaCode login={login} />}
{onAccount && <Account login={login} />}
<button type="submit" className="al-cta" disabled={login.isLoading}>
{login.isLoading && <span className="al-spin" aria-hidden="true" />}
{submitLabel(step, login.isLoading, t)}
</button>
</form>
<OtherWays login={login} />
<ModeSwitch login={login} />
{login.mode === 'login' && onAccount && (
<button type="button" className="al-forgot" onClick={() => void login.navigate('/forgot-password')}>
{t('login.forgotPassword')}
</button>
)}
</>
);
}
function Notices({ login }: { login: Login }) {
const { t } = useTranslation();
return (
<>
{login.error && <Notice>{login.error}</Notice>}
{login.insecureCookie && !login.appConfig?.managed && (
<Notice tone="warn">
<b>{t('login.insecureCookie.title')}</b>
{t('login.insecureCookie.body')}
<br />
<a href="https://github.com/liketrek/TREK/wiki/Troubleshooting" target="_blank" rel="noopener noreferrer">
{t('login.insecureCookie.link')}
</a>
</Notice>
)}
{login.passwordChangeStep && <Notice tone="warn">{t('settings.mustChangePassword')}</Notice>}
</>
);
}
function NewPassword({ login }: { login: Login }) {
const { t } = useTranslation();
return (
<>
<Field
label={t('settings.newPassword')}
type="password"
autoComplete="new-password"
value={login.newPassword}
onChange={(e) => login.setNewPassword(e.target.value)}
required
/>
<PasswordChecklist password={login.newPassword} className="al-check" tone="light" />
<Field
label={t('settings.confirmPassword')}
type="password"
autoComplete="new-password"
value={login.confirmPassword}
onChange={(e) => login.setConfirmPassword(e.target.value)}
required
/>
</>
);
}
function MfaCode({ login }: { login: Login }) {
const { t } = useTranslation();
const back = () => {
login.setMfaStep(false);
login.setMfaToken('');
login.setMfaCode('');
login.setError('');
};
return (
<>
{/* The account the code belongs to, for password managers (see MfaCodeStep). */}
<input
type="text"
name="username"
autoComplete="username"
value={login.email}
readOnly
tabIndex={-1}
aria-hidden="true"
className="sr-only"
/>
<Field
label={t('login.mfaCodeLabel')}
{...mfaCodeInputProps(login.mfaCode, login.setMfaCode, t('login.mfaPlaceholder'))}
/>
<p className="al-hint">{t('login.mfaHint')}</p>
<button type="button" className="al-back" onClick={back}>
{t('login.mfaBack')}
</button>
</>
);
}
function Account({ login }: { login: Login }) {
const { t } = useTranslation();
const registering = login.mode === 'register';
return (
<>
{registering && (
<Field
label={t('login.username')}
type="text"
autoComplete="username"
autoCapitalize="none"
value={login.username}
onChange={(e) => login.setUsername(e.target.value)}
required
placeholder="admin"
/>
)}
<Field
label={t('common.email')}
type="email"
autoComplete={registering ? 'email' : 'username'}
inputMode="email"
autoCapitalize="none"
value={login.email}
onChange={(e) => login.setEmail(e.target.value)}
required
placeholder={t('login.emailPlaceholder')}
/>
<Field
label={t('common.password')}
type={login.showPassword ? 'text' : 'password'}
autoComplete={registering ? 'new-password' : 'current-password'}
value={login.password}
onChange={(e) => login.setPassword(e.target.value)}
required
placeholder="••••••••"
after={
<button
type="button"
className="al-eye"
onClick={() => login.setShowPassword((v) => !v)}
aria-label={t('native.claim.showPassword')}
aria-pressed={login.showPassword}
>
{login.showPassword ? <EyeOff size={19} /> : <Eye size={19} />}
</button>
}
/>
{registering && <PasswordChecklist password={login.password} className="al-check" tone="light" />}
{!registering && <LoginOptions login={login} />}
</>
);
}
function LoginOptions({ login }: { login: Login }) {
const { t } = useTranslation();
const toggle = () => login.setRememberMe(!login.rememberMe);
return (
<div className="al-options">
<div className="al-remember">
<ToggleSwitch on={login.rememberMe} onToggle={toggle} label={t('login.rememberMe')} />
{/* The caption repeats the switch's own name; a tap on it is a shortcut for the switch. */}
<span aria-hidden="true" onClick={toggle}>
{t('login.rememberMe')}
</span>
</div>
</div>
);
}
/** Which of the ways in besides the password this server offers on this step. */
function otherWaysOf(login: Login): { sso: boolean; passkey: boolean; demo: boolean } {
const config = login.appConfig;
const onFirstStep = login.mode === 'login' && !login.mfaStep && !login.passwordChangeStep;
return {
sso: !!(config?.oidc_configured && config.oidc_login && !login.oidcOnly),
passkey: !!(config?.passkey_login && config.passkey_configured && onFirstStep),
demo: !!config?.demo_mode,
};
}
/** SSO, a passkey and the demo: the ways in besides the password. */
function OtherWays({ login }: { login: Login }) {
const { t } = useTranslation();
const ways = otherWaysOf(login);
if (!ways.sso && !ways.passkey && !ways.demo) return null;
return (
<div className="al-alt">
{(ways.sso || ways.passkey) && <div className="al-or">{t('common.or')}</div>}
{ways.sso && <SsoButton login={login} />}
{ways.passkey && (
<button
type="button"
className="al-cta2"
onClick={() => void login.handlePasskeyLogin()}
disabled={login.isLoading}
>
<Fingerprint size={18} aria-hidden="true" />
{t('login.passkey.signIn')}
</button>
)}
{ways.demo && (
<button
type="button"
className="al-cta al-demo"
onClick={() => void login.handleDemoLogin()}
disabled={login.isLoading}
>
{t('login.demoHint')}
</button>
)}
</div>
);
}
function SsoButton({ login }: { login: Login }) {
const { t } = useTranslation();
return (
<a
className="al-cta2"
href={oidcLoginHref(login.inviteToken, login.mode, login.rememberMe)}
onClick={login.handleSsoClick}
>
<Shield size={18} aria-hidden="true" />
{t('login.oidcSignIn', { name: login.appConfig?.oidc_display_name || 'SSO' })}
</a>
);
}
function ModeSwitch({ login }: { login: Login }) {
const { t } = useTranslation();
const config = login.appConfig;
if (!login.showRegisterOption || !config?.has_users || config?.demo_mode || login.passwordChangeStep) return null;
const toggle = () => {
login.setMode((m) => (m === 'login' ? 'register' : 'login'));
login.setError('');
login.setMfaStep(false);
login.setMfaToken('');
login.setMfaCode('');
};
return (
<p className="al-switch">
{t(login.mode === 'login' ? 'login.noAccount' : 'login.hasAccount')}{' '}
<button type="button" onClick={toggle}>
{t(login.mode === 'login' ? 'login.register' : 'login.signIn')}
</button>
</p>
);
}
+2 -17
View File
@@ -1,6 +1,7 @@
import { KeyRound } from 'lucide-react';
import React from 'react';
import { useTranslation } from '../../i18n';
import { mfaCodeInputProps } from './mfaCodeInput';
interface MfaCodeStepProps {
/** The account being signed in, kept in the form for password managers. */
@@ -53,23 +54,7 @@ export default function MfaCodeStep({ email, code, onCode, inputStyle, onBack }:
}}
/>
<input
type="text"
id="totp"
name="totp"
// Text, not numeric: backup codes carry letters. The hints are set here
// rather than left to native/keyboardFields.ts, because autoFocus gives
// the field focus before any touch could prepare it.
inputMode="text"
autoComplete="one-time-code"
autoCapitalize="characters"
autoCorrect="off"
spellCheck={false}
enterKeyHint="go"
value={code}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => onCode(e.target.value.toUpperCase().slice(0, 24))}
placeholder={t('login.mfaPlaceholder')}
required
autoFocus
{...mfaCodeInputProps(code, onCode, t('login.mfaPlaceholder'))}
style={inputStyle}
onFocus={(e: React.FocusEvent<HTMLInputElement>) => (e.target.style.borderColor = '#111827')}
onBlur={(e: React.FocusEvent<HTMLInputElement>) => (e.target.style.borderColor = '#e5e7eb')}
@@ -1,18 +0,0 @@
import { useNativeServer } from '../../components/Settings/useNativeServer';
import { useTranslation } from '../../i18n';
/** Inside the iOS/Android app only: the way from the sign-in screen back to the address screen. */
export default function NativeServerLink() {
const { t } = useTranslation();
const { host, changeServer } = useNativeServer();
if (!host) return null;
return (
<button
type="button"
onClick={changeServer}
className="mt-4 w-full cursor-pointer border-none bg-transparent p-2 text-caption text-content-muted"
>
{t('native.changeServer')}
</button>
);
}
+652
View File
@@ -0,0 +1,652 @@
/*
* The sign-in screen inside the iOS and Android app (AppLogin.tsx). It is the
* next screen after the app's own address screen (native-shell/), so it wears
* that screen's look: the same landscape on top, the same glass card with the
* server on it, the same type, fields and buttons on the same warm page. The
* values mirror native-shell/shell.css; keep the two in step.
*
* Light on purpose, like the screens before it: the user's appearance is not
* known before signing in. The tokens the shared controls read (ToggleSwitch,
* PasswordChecklist) are pinned to the light values inside the screen, so a
* dark scheme left on the device does not reach into it.
*
* Every side is a logical one, so Arabic mirrors the layout on its own.
*/
/*
* The text face of the address screen, from the same files it bundles. Loaded
* only once a letter of the range is on this screen; Cyrillic and the scripts
* it does not cover fall back to the app's own face.
*/
@font-face {
font-family: 'Plus Jakarta Sans';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url('../../../native-shell/fonts/plus-jakarta-sans-latin-500.woff2') format('woff2');
unicode-range:
U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC,
U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Plus Jakarta Sans';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url('../../../native-shell/fonts/plus-jakarta-sans-latin-600.woff2') format('woff2');
unicode-range:
U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC,
U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Plus Jakarta Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url('../../../native-shell/fonts/plus-jakarta-sans-latin-700.woff2') format('woff2');
unicode-range:
U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC,
U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
@font-face {
font-family: 'Plus Jakarta Sans';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url('../../../native-shell/fonts/plus-jakarta-sans-latin-ext-500.woff2') format('woff2');
unicode-range:
U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F,
U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Plus Jakarta Sans';
font-style: normal;
font-weight: 600;
font-display: swap;
src: url('../../../native-shell/fonts/plus-jakarta-sans-latin-ext-600.woff2') format('woff2');
unicode-range:
U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F,
U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
@font-face {
font-family: 'Plus Jakarta Sans';
font-style: normal;
font-weight: 700;
font-display: swap;
src: url('../../../native-shell/fonts/plus-jakarta-sans-latin-ext-700.woff2') format('woff2');
unicode-range:
U+0100-02BA, U+02BD-02C5, U+02C7-02CC, U+02CE-02D7, U+02DD-02FF, U+0304, U+0308, U+0329, U+1D00-1DBF, U+1E00-1E9F,
U+1EF2-1EFF, U+2020, U+20A0-20AB, U+20AD-20C0, U+2113, U+2C60-2C7F, U+A720-A7FF;
}
.app-login {
--al-page: #fffaf5;
--al-ink: #1f1a17;
--al-text: #6b5f57;
--al-muted: #8a7b6f;
--al-faint: #b9ab9e;
--al-line: #efe4d8;
--al-line-soft: #f3ebe1;
--al-sand: #f6efe6;
--al-dark: #111827;
--al-good: #1d7a46;
--al-bad: #b42318;
--al-bad-soft: #fbeeec;
--al-bad-ink: #8f2a1d;
--al-warn-soft: #fdf3e2;
--al-warn-ink: #8a5a12;
--al-sea: #cfe3ef;
--al-text-face: 'Plus Jakarta Sans', var(--font-system);
--al-display: 'Poppins', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
--al-safe-top: max(env(safe-area-inset-top, 0px), var(--safe-area-inset-top, 0px), var(--trek-native-safe-top, 0px));
--al-safe-bottom: max(
env(safe-area-inset-bottom, 0px),
var(--safe-area-inset-bottom, 0px),
var(--trek-native-safe-bottom, 0px)
);
--al-safe-start: max(
env(safe-area-inset-left, 0px),
var(--safe-area-inset-left, 0px),
var(--trek-native-safe-left, 0px)
);
--al-safe-end: max(
env(safe-area-inset-right, 0px),
var(--safe-area-inset-right, 0px),
var(--trek-native-safe-right, 0px)
);
/* What the shared controls inside read. */
--accent: var(--al-dark);
--accent-text: #fff;
--text-primary: var(--al-ink);
--border-primary: #e6dccf;
--bg-card: #fff;
position: fixed;
inset: 0;
overflow-x: hidden;
overflow-y: auto;
overscroll-behavior: none;
scrollbar-width: none;
display: flex;
flex-direction: column;
background: var(--al-page);
color: var(--al-ink);
color-scheme: light;
font-family: var(--al-text-face);
-webkit-tap-highlight-color: transparent;
animation: al-in 0.42s cubic-bezier(0.2, 0.8, 0.2, 1) both;
}
.app-login::-webkit-scrollbar {
display: none;
}
.app-login *,
.app-login *::before,
.app-login *::after {
box-sizing: border-box;
}
@keyframes al-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
/* ── The landscape and the server card on it ── */
.al-hero {
position: relative;
flex: none;
overflow: hidden;
height: min(272px, 33svh);
min-height: 200px;
margin-bottom: -1px;
background: var(--al-sea);
}
.al-hero .scenery {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
animation: al-in 0.6s ease-out both;
}
/* The status bar's clock and icons stay readable on the sea. */
.al-hero::before {
content: '';
position: absolute;
z-index: 1;
inset-inline: 0;
top: 0;
height: calc(var(--al-safe-top) + 36px);
background: linear-gradient(180deg, rgba(8, 24, 40, 0.28), rgba(8, 24, 40, 0));
pointer-events: none;
}
.al-hero::after {
content: '';
position: absolute;
inset-inline: 0;
bottom: -2px;
height: 110px;
background: linear-gradient(180deg, rgba(255, 250, 245, 0) 0%, rgba(255, 250, 245, 0.8) 55%, #fffaf5 82%);
pointer-events: none;
}
.al-logo {
position: absolute;
z-index: 2;
top: calc(var(--al-safe-top) + 10px);
inset-inline-start: calc(24px + var(--al-safe-start));
height: 40px;
filter: drop-shadow(0 1px 6px rgba(7, 40, 70, 0.45));
}
.al-card {
position: absolute;
z-index: 2;
inset-inline: calc(20px + var(--al-safe-start)) calc(20px + var(--al-safe-end));
bottom: 44px;
display: flex;
align-items: center;
gap: 12px;
padding-block: 12px 13px;
padding-inline: 16px 12px;
border-radius: 18px;
background: rgba(255, 255, 255, 0.8);
-webkit-backdrop-filter: blur(16px) saturate(1.5);
backdrop-filter: blur(16px) saturate(1.5);
box-shadow:
0 18px 36px -18px rgba(17, 24, 39, 0.55),
inset 0 0 0 1px rgba(255, 255, 255, 0.6);
}
.al-card-text {
flex: 1;
min-width: 0;
}
.al-card small {
display: flex;
align-items: center;
gap: 6px;
font-size: 11px;
font-weight: 700;
letter-spacing: 0.1em;
text-transform: uppercase;
color: var(--al-good);
}
.al-host {
display: flex;
align-items: center;
gap: 8px;
margin-top: 5px;
min-width: 0;
font-family: var(--al-display);
font-size: 20px;
font-weight: 600;
letter-spacing: -0.02em;
color: var(--al-dark);
}
.al-host svg {
flex: none;
}
.al-host span {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.al-change {
flex: none;
min-height: 36px;
padding: 0 13px;
border: 0;
border-radius: 11px;
background: #fff;
color: var(--al-dark);
font: 700 13.5px var(--al-text-face);
cursor: pointer;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12);
}
/* ── The content ── */
.al-body {
position: relative;
z-index: 2;
flex: 1;
display: flex;
flex-direction: column;
padding-block: 6px calc(28px + var(--al-safe-bottom));
padding-inline: calc(24px + var(--al-safe-start)) calc(24px + var(--al-safe-end));
}
.al-form {
display: flex;
flex-direction: column;
gap: 12px;
}
.al-title {
margin: 0;
font-family: var(--al-display);
font-size: calc(28px * var(--fs-scale-title, 1));
font-weight: 600;
letter-spacing: -0.02em;
line-height: 1.12;
text-wrap: balance;
}
.al-sub {
margin: 4px 0 6px;
font-size: calc(15px * var(--fs-scale-body, 1));
line-height: 1.5;
color: var(--al-text);
}
/* A field on a white card: the label above, the input below it. */
.al-fld {
position: relative;
display: flex;
flex-direction: column;
gap: 2px;
padding: 10px 16px 11px;
border-radius: 16px;
background: #fff;
box-shadow: 0 0 0 1px var(--al-line);
cursor: text;
transition: box-shadow 0.2s;
}
.al-fld:focus-within {
box-shadow: 0 0 0 2px var(--al-dark);
}
.al-lab {
font-size: calc(12px * var(--fs-scale-body, 1));
font-weight: 700;
color: var(--al-muted);
}
.al-fld-wrap {
position: relative;
}
.al-fld-wrap.with-after .al-fld input {
padding-inline-end: 40px;
}
.al-after {
position: absolute;
inset-inline-end: 8px;
bottom: 4px;
}
.al-fld input {
flex: 1;
min-width: 0;
width: 100%;
border: 0;
outline: none;
background: transparent;
padding: 0;
/* 16 px or more, or iOS zooms into the field on focus. */
font: 600 16px var(--al-text-face);
color: var(--al-ink);
}
.al-fld input::placeholder {
color: var(--al-faint);
font-weight: 500;
}
.al-eye {
display: grid;
place-items: center;
width: 44px;
height: 44px;
border: 0;
border-radius: 10px;
background: transparent;
color: var(--al-muted);
cursor: pointer;
}
.al-check {
margin-top: -4px;
}
.al-options {
display: flex;
align-items: center;
gap: 12px;
min-height: 44px;
}
.al-remember {
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
font-size: calc(14px * var(--fs-scale-body, 1));
font-weight: 600;
color: var(--al-text);
cursor: pointer;
user-select: none;
}
.al-forgot {
align-self: center;
min-height: 44px;
margin-top: 6px;
padding: 0 8px;
border: 0;
background: none;
color: var(--al-text);
font: 600 calc(14px * var(--fs-scale-body, 1)) var(--al-text-face);
cursor: pointer;
}
/* ── Buttons ── */
.al-cta,
.al-cta2 {
width: 100%;
border: 0;
border-radius: 16px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
text-align: center;
text-decoration: none;
transition:
transform 0.15s,
opacity 0.15s;
}
.al-cta {
min-height: 56px;
margin-top: 4px;
background: var(--al-dark);
color: #fff;
font: 700 calc(17px * var(--fs-scale-body, 1)) var(--al-text-face);
box-shadow: 0 14px 28px -14px rgba(17, 24, 39, 0.55);
}
.al-cta2 {
min-height: 52px;
background: #fff;
color: var(--al-dark);
font: 700 calc(16px * var(--fs-scale-body, 1)) var(--al-text-face);
box-shadow: 0 0 0 1.5px var(--al-line);
}
.al-cta:active,
.al-cta2:active {
transform: scale(0.985);
}
.al-cta:disabled,
.al-cta2:disabled {
opacity: 0.7;
cursor: default;
}
.al-demo {
background: linear-gradient(135deg, #f59e0b, #d97706);
color: #451a03;
box-shadow: 0 10px 24px -14px rgba(217, 119, 6, 0.7);
}
.al-spin {
width: 18px;
height: 18px;
border-radius: 50%;
border: 2px solid currentColor;
border-top-color: transparent;
animation: al-spin 0.8s linear infinite;
}
@keyframes al-spin {
to {
transform: rotate(360deg);
}
}
.al-or {
display: flex;
align-items: center;
gap: 12px;
margin: 10px 0 2px;
font-size: calc(13px * var(--fs-scale-body, 1));
font-weight: 600;
color: var(--al-faint);
}
.al-or::before,
.al-or::after {
content: '';
flex: 1;
height: 1px;
background: var(--al-line);
}
.al-alt {
display: flex;
flex-direction: column;
gap: 10px;
margin-top: 10px;
}
.al-switch {
margin: 16px 0 0;
text-align: center;
font-size: calc(14px * var(--fs-scale-body, 1));
color: var(--al-muted);
}
.al-switch button {
min-height: 44px;
padding: 0 4px;
border: 0;
background: none;
color: var(--al-ink);
font: 700 calc(14px * var(--fs-scale-body, 1)) var(--al-text-face);
cursor: pointer;
}
/* ── Messages ── */
.al-notice {
display: flex;
gap: 10px;
align-items: flex-start;
margin: 0;
padding: 12px 14px;
border-radius: 14px;
background: var(--al-bad-soft);
color: var(--al-bad-ink);
font-size: calc(13.5px * var(--fs-scale-body, 1));
font-weight: 600;
line-height: 1.45;
}
.al-notice svg {
flex: none;
margin-top: 1px;
}
.al-notice.warn {
background: var(--al-warn-soft);
color: var(--al-warn-ink);
}
.al-notice b {
display: block;
margin-bottom: 2px;
}
.al-notice a {
display: inline-block;
margin-top: 4px;
color: inherit;
font-weight: 700;
}
.al-hint {
margin: 0;
font-size: calc(12.5px * var(--fs-scale-body, 1));
line-height: 1.5;
color: var(--al-muted);
}
.al-back {
align-self: flex-start;
min-height: 40px;
padding: 0;
border: 0;
background: none;
color: var(--al-text);
font: 600 calc(14px * var(--fs-scale-body, 1)) var(--al-text-face);
cursor: pointer;
}
/* Waiting: on the way to the sign-in provider, or for the server's settings. */
.al-wait {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 14px;
min-height: 180px;
padding-bottom: 40px;
text-align: center;
color: var(--al-text);
}
.al-wait .al-spin {
width: 24px;
height: 24px;
border-width: 2.5px;
}
.al-wait p {
margin: 0;
font-size: calc(16px * var(--fs-scale-body, 1));
font-weight: 600;
color: var(--al-ink);
}
.al-wait a {
font-size: calc(14px * var(--fs-scale-body, 1));
color: var(--al-text);
}
.app-login :focus-visible {
outline: 2px solid var(--al-dark);
outline-offset: 2px;
}
/*
* An iPad, an unfolded phone, a phone on its side: the landscape fills one side
* and the form stands in a column of its own beside it, as on the address screen.
*/
@media (min-width: 900px), (orientation: landscape) and (max-height: 500px) {
.app-login {
flex-direction: row;
overflow: hidden;
}
.al-hero {
flex: 1 1 auto;
height: 100%;
min-height: 0;
margin: 0;
}
.al-hero::after {
display: none;
}
.al-card {
inset-inline: calc(32px + var(--al-safe-start)) auto;
width: min(420px, calc(100% - 64px));
bottom: 40px;
}
.al-logo {
top: calc(var(--al-safe-top) + 24px);
inset-inline-start: calc(32px + var(--al-safe-start));
height: 46px;
}
.al-body {
flex: none;
width: 460px;
height: 100%;
overflow-x: hidden;
overflow-y: auto;
scrollbar-width: none;
justify-content: center;
padding-block: calc(var(--al-safe-top) + 32px) calc(32px + var(--al-safe-bottom));
padding-inline: 32px calc(32px + var(--al-safe-end));
background: var(--al-page);
box-shadow: -1px 0 0 rgba(31, 26, 23, 0.06);
}
}
@media (orientation: landscape) and (max-height: 500px) {
.al-body {
width: min(420px, 52vw);
justify-content: flex-start;
padding-top: calc(var(--al-safe-top) + 20px);
}
}
@media (prefers-reduced-motion: reduce) {
.app-login,
.app-login * {
animation: none !important;
transition: none !important;
}
.al-spin {
animation: al-spin 1.6s linear infinite !important;
}
}
/* Signed in: the screen steps back into the page colour, and the app rises in
from it (native/appBoot.ts handOverToApp). */
.app-login.al-leaving .al-body {
animation: al-leave-body 0.34s cubic-bezier(0.4, 0, 1, 1) both;
}
.app-login.al-leaving .al-hero {
animation: al-leave-hero 0.42s ease-in both;
}
@keyframes al-leave-body {
to {
opacity: 0;
transform: translateY(14px);
}
}
@keyframes al-leave-hero {
to {
opacity: 0;
}
}
+46
View File
@@ -0,0 +1,46 @@
// FE-LOGIN-MODEL-001 to FE-LOGIN-MODEL-004
import { describe, expect, it } from 'vitest';
import { heading, oidcLoginHref, oidcOnlyHref, submitLabel, type LoginStep } from './loginModel';
/** Returns the key itself, so the assertions read the keys. */
const t = (key: string) => key;
const step = (overrides: Partial<LoginStep> = {}): LoginStep => ({
mode: 'login',
mfaStep: false,
passwordChangeStep: false,
hasUsers: true,
...overrides,
});
describe('loginModel', () => {
it('FE-LOGIN-MODEL-001: names each step of the sign-in', () => {
expect(heading(step(), t)).toEqual({ title: 'login.title', subtitle: 'login.subtitle', plain: true });
expect(heading(step({ mfaStep: true }), t).title).toBe('login.mfaTitle');
expect(heading(step({ passwordChangeStep: true, mfaStep: true }), t).title).toBe('login.setNewPassword');
expect(heading(step({ mode: 'register' }), t).title).toBe('login.createAccount');
expect(heading(step({ mode: 'register', hasUsers: false }), t).title).toBe('login.createAdmin');
});
it('FE-LOGIN-MODEL-002: labels the submit button for the step and while it runs', () => {
expect(submitLabel(step(), false, t)).toBe('login.signIn');
expect(submitLabel(step(), true, t)).toBe('login.signingIn');
expect(submitLabel(step({ mfaStep: true }), true, t)).toBe('login.mfaVerify');
expect(submitLabel(step({ mode: 'register' }), false, t)).toBe('login.createAccount');
expect(submitLabel(step({ mode: 'register' }), true, t)).toBe('login.creating');
expect(submitLabel(step({ passwordChangeStep: true }), true, t)).toBe('settings.updatePassword');
});
it('FE-LOGIN-MODEL-003: carries the invite and the remember-me choice to SSO, only when signing in', () => {
expect(oidcLoginHref('', 'login', true)).toBe('/api/auth/oidc/login?remember=1');
expect(oidcLoginHref('', 'login', false)).toBe('/api/auth/oidc/login?remember=0');
expect(oidcLoginHref('a b', 'login', true)).toBe('/api/auth/oidc/login?invite=a%20b&remember=1');
expect(oidcLoginHref('', 'register', true)).toBe('/api/auth/oidc/login');
expect(oidcLoginHref('tok', 'register', false)).toBe('/api/auth/oidc/login?invite=tok');
});
it('FE-LOGIN-MODEL-004: always asks for the remembered session on an OIDC-only install', () => {
expect(oidcOnlyHref('')).toBe('/api/auth/oidc/login?remember=1');
expect(oidcOnlyHref('tok')).toBe('/api/auth/oidc/login?invite=tok&remember=1');
});
});
+61
View File
@@ -0,0 +1,61 @@
// What the sign-in screens say and where their buttons lead, shared by the
// browser's LoginPage and the app's AppLogin, so the two cannot drift apart.
export type LoginMode = 'login' | 'register';
export interface LoginStep {
mode: LoginMode;
mfaStep: boolean;
passwordChangeStep: boolean;
/** False on a fresh install, where the first account becomes the admin. */
hasUsers: boolean;
}
type Translate = (key: string) => string;
/**
* The heading and the line under it. `plain` is the plain sign-in, whose line
* the app's screen leaves out. Translated here, with the keys written out, so
* the i18n key check sees every one of them.
*/
export function heading(step: LoginStep, t: Translate): { title: string; subtitle: string; plain: boolean } {
if (step.passwordChangeStep) {
return { title: t('login.setNewPassword'), subtitle: t('login.setNewPasswordHint'), plain: false };
}
if (step.mode === 'login' && step.mfaStep) {
return { title: t('login.mfaTitle'), subtitle: t('login.mfaSubtitle'), plain: false };
}
if (step.mode === 'register') {
return step.hasUsers
? { title: t('login.createAccount'), subtitle: t('login.createAccountHint'), plain: false }
: { title: t('login.createAdmin'), subtitle: t('login.createAdminHint'), plain: false };
}
return { title: t('login.title'), subtitle: t('login.subtitle'), plain: true };
}
/** The submit button's label; another while the request runs. */
export function submitLabel(step: LoginStep, loading: boolean, t: Translate): string {
if (step.passwordChangeStep) return t('settings.updatePassword');
if (step.mode === 'register') return loading ? t('login.creating') : t('login.createAccount');
if (step.mfaStep) return t('login.mfaVerify');
return loading ? t('login.signingIn') : t('login.signIn');
}
/**
* The SSO button beside the password form. The remember-me switch only shows in
* login mode; in register mode the parameter stays off so the server default applies.
*/
export function oidcLoginHref(inviteToken: string, mode: LoginMode, rememberMe: boolean): string {
const params: string[] = [];
if (inviteToken) params.push('invite=' + encodeURIComponent(inviteToken));
if (mode === 'login') params.push('remember=' + (rememberMe ? '1' : '0'));
return '/api/auth/oidc/login' + (params.length ? '?' + params.join('&') : '');
}
/**
* The only button in OIDC-only mode. No remember-me switch there: the IdP owns
* the session policy, so it always asks for the remembered lifetime (#1927).
*/
export function oidcOnlyHref(inviteToken: string): string {
return `/api/auth/oidc/login${inviteToken ? '?invite=' + encodeURIComponent(inviteToken) + '&' : '?'}remember=1`;
}
+30
View File
@@ -0,0 +1,30 @@
import type React from 'react';
/**
* The one-time code field, for this step and the app's sign-in screen alike.
* Text, not numeric: backup codes carry letters. The hints are set here rather
* than left to native/keyboardFields.ts, because autoFocus gives the field
* focus before any touch could prepare it.
*/
export function mfaCodeInputProps(
code: string,
onCode: (code: string) => void,
placeholder: string
): React.InputHTMLAttributes<HTMLInputElement> {
return {
type: 'text',
id: 'totp',
name: 'totp',
inputMode: 'text',
autoComplete: 'one-time-code',
autoCapitalize: 'characters',
autoCorrect: 'off',
spellCheck: false,
enterKeyHint: 'go',
value: code,
onChange: (e: React.ChangeEvent<HTMLInputElement>) => onCode(e.target.value.toUpperCase().slice(0, 24)),
placeholder,
required: true,
autoFocus: true,
};
}
@@ -1,4 +1,4 @@
// FE-LOGIN-NATIVE-001 to FE-LOGIN-NATIVE-008: useLogin inside the iOS/Android app
// FE-LOGIN-NATIVE-001 to FE-LOGIN-NATIVE-012: useLogin inside the iOS/Android app
import { startAuthentication } from '@simplewebauthn/browser';
import { http, HttpResponse } from 'msw';
import React from 'react';
@@ -11,7 +11,9 @@ import { act, renderHook, waitFor } from '../../../tests/helpers/render';
import { resetAllStores } from '../../../tests/helpers/store';
import { TranslationProvider } from '../../i18n/TranslationContext';
import { BrowserSignInCancelled, resumeBrowserSignIn, signInThroughBrowser } from '../../native/browserSignIn';
import { toastHaptic } from '../../native/haptics';
import { useAuthStore } from '../../store/authStore';
import { useSettingsStore } from '../../store/settingsStore';
import { markSignedOut, wasSignedOut } from '../../utils/signedOut';
import { useLogin } from './useLogin';
@@ -23,12 +25,18 @@ vi.mock('react-router', async () => {
});
vi.mock('@simplewebauthn/browser', () => ({ startAuthentication: vi.fn() }));
vi.mock('../../native/platform', () => ({ isNativeApp: () => true }));
vi.mock('../../native/haptics', () => ({ toastHaptic: vi.fn() }));
vi.mock('../../native/browserSignIn', async () => {
const actual = await vi.importActual<typeof import('../../native/browserSignIn')>('../../native/browserSignIn');
return { ...actual, signInThroughBrowser: vi.fn(), resumeBrowserSignIn: vi.fn() };
});
const realLocation = window.location;
const realLanguages = Object.getOwnPropertyDescriptor(window.navigator, 'languages');
function deviceLanguages(languages: string[]) {
Object.defineProperty(window.navigator, 'languages', { configurable: true, get: () => languages });
}
const loadUser = vi.fn(async () => {});
function renderLogin() {
@@ -50,6 +58,7 @@ beforeEach(() => {
vi.mocked(signInThroughBrowser).mockReset();
vi.mocked(resumeBrowserSignIn).mockReset().mockResolvedValue(false);
vi.mocked(startAuthentication).mockReset();
vi.mocked(toastHaptic).mockClear();
loadUser.mockClear();
useAuthStore.setState({ loadUser });
Object.defineProperty(window, 'location', {
@@ -61,6 +70,10 @@ beforeEach(() => {
afterEach(() => {
vi.useRealTimers();
if (realLanguages) Object.defineProperty(window.navigator, 'languages', realLanguages);
else delete (window.navigator as { languages?: readonly string[] }).languages;
localStorage.removeItem('app_language');
document.documentElement.removeAttribute('data-app-handover');
Object.defineProperty(window, 'location', { configurable: true, writable: true, value: realLocation });
});
@@ -152,4 +165,37 @@ describe('useLogin in the native app', () => {
await waitFor(() => expect(result.current.error).toBe('Signing in did not work. Please try again.'));
expect(result.current.showTakeoff).toBe(false);
});
it('FE-LOGIN-NATIVE-009: speaks the device language when no language was chosen', async () => {
deviceLanguages(['de-DE', 'en-US']);
renderLogin();
await waitFor(() => expect(useSettingsStore.getState().settings.language).toBe('de'));
});
it('FE-LOGIN-NATIVE-010: falls back to English on a device language TREK has no translation for', async () => {
deviceLanguages(['pt-PT']);
useSettingsStore.setState((state) => ({ settings: { ...state.settings, language: 'fr' } }));
renderLogin();
await waitFor(() => expect(useSettingsStore.getState().settings.language).toBe('en'));
});
it('FE-LOGIN-NATIVE-011: opens the app after signing in without the takeoff, with the success tap', async () => {
vi.mocked(resumeBrowserSignIn).mockResolvedValue(true);
mockNavigate.mockClear();
const { result } = renderLogin();
await waitFor(() => expect(result.current.showTakeoff).toBe(true));
expect(toastHaptic).toHaveBeenCalledWith('success');
await waitFor(() => expect(mockNavigate).toHaveBeenCalledWith('/'), { timeout: 2500 });
expect(document.documentElement.hasAttribute('data-app-handover')).toBe(true);
});
it('FE-LOGIN-NATIVE-012: keeps a language once picked on this page over the device language', async () => {
localStorage.setItem('app_language', 'fr');
useSettingsStore.setState((state) => ({ settings: { ...state.settings, language: 'fr' } }));
deviceLanguages(['de-DE', 'en-US']);
const { result } = renderLogin();
await waitFor(() => expect(result.current.appConfig).not.toBeNull());
expect(useSettingsStore.getState().settings.language).toBe('fr');
});
});
+24 -5
View File
@@ -9,6 +9,8 @@ import { authApi, configApi } from '../../api/client'
import { getApiErrorMessage } from '../../types'
import { START_DESTINATION_ROUTE } from '../../utils/startDestination'
import { passwordErrorKey } from '../../utils/passwordError'
import { handOverToApp } from '../../native/appBoot'
import { toastHaptic } from '../../native/haptics'
import { isNativeApp } from '../../native/platform'
import {
BrowserSignInCancelled,
@@ -164,6 +166,15 @@ export function useLogin() {
*/
const takeOff = (): void => {
setShowTakeoff(true)
if (nativeApp) {
// The app has no takeoff: the sign-in screen steps back and the app rises in
// as soon as the settings are there (native/appBoot.ts).
toastHaptic('success')
void handOverToApp(loadSettings(), () => {
void navigate(redirectTarget)
})
return
}
loadSettings()
setTimeout(() => navigate(redirectTarget), 2600)
}
@@ -289,8 +300,16 @@ export function useLogin() {
// 2. Browser/OS language (navigator.languages)
// 3. Server default (DEFAULT_LANGUAGE env var)
// 4. 'en' → hardcoded fallback already in store
// Inside the iOS and Android app the sign-in screen has no language menu: unless
// a language was chosen before, it speaks the device's language, as the address
// screen before it does, and English where TREK has no translation for it. The
// account's own language takes over once signed in.
useEffect(() => {
if (hasStoredLanguage()) return
if (nativeApp) {
setLanguageTransient(detectBrowserLanguage() ?? 'en')
return
}
const detected = detectBrowserLanguage()
if (detected) {
@@ -301,7 +320,7 @@ export function useLogin() {
configApi.getPublicConfig()
.then(({ defaultLanguage }) => { if (defaultLanguage) setLanguageTransient(defaultLanguage) })
.catch((err) => console.warn('Failed to fetch default language config:', err))
}, [setLanguageTransient])
}, [setLanguageTransient, nativeApp])
useEffect(() => {
if (!langDropdownOpen) return
@@ -332,10 +351,10 @@ export function useLogin() {
if (!signedIn) return
await loadUser({ silent: true })
setShowTakeoff(true)
void loadSettings()
setTimeout(() => {
toastHaptic('success')
void handOverToApp(loadSettings(), () => {
void navigate(redirectTarget)
}, 2600)
})
})
.catch(() => setError(t('native.login.failed')))
}, [nativeApp, loadUser, loadSettings, navigate, redirectTarget, t])
@@ -457,7 +476,7 @@ export function useLogin() {
const oidcOnly = !appConfig?.password_login && appConfig?.oidc_login && appConfig?.oidc_configured
return {
navigate,
navigate, nativeApp,
mode, setMode,
username, setUsername, email, setEmail, password, setPassword, rememberMe, setRememberMe, showPassword, setShowPassword,
isLoading, error, setError, insecureCookie, appConfig, inviteToken,
@@ -18,7 +18,8 @@ const stub = vi.hoisted(() => (name: string, testId: string) => (props: Record<s
vi.mock('../../components/Map/MapViewAuto', () => ({ MapViewAuto: stub('map', 'map-view') }))
vi.mock('../../components/Map/MapCompassPill', () => ({ MapCompassPill: stub('compass', 'compass-pill') }))
vi.mock('../../components/Map/PoiCategoryPill', () => ({ default: stub('poiPill', 'poi-pill') }))
vi.mock('../../components/Map/TripRouteOverview', () => ({
vi.mock('../../components/Map/TripRouteOverview', async (importOriginal) => ({
...await importOriginal<typeof import('../../components/Map/TripRouteOverview')>(),
TripRouteOverviewPill: stub('overviewPill', 'overview-pill'),
TripRouteOverviewPanel: stub('overviewPanel', 'overview-panel'),
}))
@@ -1,8 +1,8 @@
import type { Dispatch, ReactElement, SetStateAction } from 'react'
import type { Dispatch, ReactElement, Ref, SetStateAction } from 'react'
import { createPortal } from 'react-dom'
import { MapViewAuto as MapView } from '../../components/Map/MapViewAuto'
import { MapCompassPill, type CompassMap } from '../../components/Map/MapCompassPill'
import { TripRouteOverviewPill, TripRouteOverviewPanel } from '../../components/Map/TripRouteOverview'
import { TripRouteOverviewPill, TripRouteOverviewPanel, TRIP_OVERVIEW_INSET } from '../../components/Map/TripRouteOverview'
import { DawarichTrailPill } from '../../components/Map/DawarichTrailPill'
import PoiCategoryPill from '../../components/Map/PoiCategoryPill'
import ActivityCompareLegend from '../../components/Tours/activity/ActivityCompareLegend'
@@ -42,6 +42,7 @@ interface StagePageLocals {
rightPanelPx: number
mapInsetLeft: number
mapInsetRight: number
overviewCardRef?: Ref<HTMLDivElement>
glMap: CompassMap | null
setGlMap: Dispatch<SetStateAction<CompassMap | null>>
poiPillEnabled: boolean
@@ -74,7 +75,7 @@ export function PlanMapStage({
overviewActive, tripOverview, overviewShown, toggleOverview,
dawarichEnabled, dawarichTrail, dawarichHiddenDates, dawarichTrailShown, toggleDawarichTrail,
mobileSidebarOpen, showPlaceForm, showMembersModal, showReservationModal,
poi, tourMap, leftPanelPx, rightPanelPx, mapInsetLeft, mapInsetRight,
poi, tourMap, leftPanelPx, rightPanelPx, mapInsetLeft, mapInsetRight, overviewCardRef,
glMap, setGlMap, poiPillEnabled, mapPois, distanceUnit, inspectorHeight = 0,
}: Readonly<PlanMapStageProps>): ReactElement {
// ACT-02: a tour compared with its actual track lays the track into the day's lines, dotted.
@@ -181,13 +182,14 @@ export function PlanMapStage({
renderers: the locate button that lives there is phone-only. */}
{(!roadtripActive || dawarichEnabled) && (
<div className="hidden md:flex" style={{
position: 'absolute', bottom: 18, right: mapInsetRight + 14, zIndex: 26, // rtl-lint-disable: measured from the right panel's inset
position: 'absolute', bottom: 18, right: mapInsetRight + TRIP_OVERVIEW_INSET, zIndex: 26, // rtl-lint-disable: measured from the right panel's inset
pointerEvents: 'none', flexDirection: 'column', alignItems: 'flex-end', gap: 8,
}}>
{compared.legend && <ActivityCompareLegend legend={compared.legend} />}
{!roadtripActive && overviewActive && (
<TripRouteOverviewPanel
overview={tripOverview}
cardRef={overviewCardRef}
unit={distanceUnit}
selectedDayId={selectedDayId}
onSelectDay={handleSelectDay}
+8 -11
View File
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useState } from 'react'
import { isServiceStopType } from '../../components/Roadtrip/roadtripModel'
import { stopNumbersOfDay } from '../../components/Planner/stopNumbers'
import { useTourMapVisibility } from '../../components/Tours/useTourMapVisibility'
import { useSettingsStore } from '../../store/settingsStore'
import { useTripStore, type TripStoreState } from '../../store/tripStore'
@@ -106,21 +106,18 @@ export function useMapPlaces(options: MapPlacesOptions) {
if (placesFilter === 'tracks' && !hasTracks) setPlacesFilter('all')
}, [placesFilter, hasTracks, setPlacesFilter])
// Build placeId → order-number map from the selected day's assignments. 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".
// Build placeId → order-number map from the selected day's assignments, through the
// count the plan's rows read too (stopNumbersOfDay), so a pin and its row agree.
const dayOrderMap = useMemo(() => {
if (!selectedDayId) return {}
const da = assignments[String(selectedDayId)] || []
const sorted = [...da].sort((a, b) => a.order_index - b.order_index)
const numbers = stopNumbersOfDay(da)
const map = {}
let counted = 0
sorted.forEach(a => {
if (!a.place?.id || isServiceStopType(a.place.stop_type)) return
counted += 1
;[...da].sort((a, b) => a.order_index - b.order_index).forEach(a => {
const n = numbers.get(a.id)
if (n === undefined || !a.place?.id) return
if (!map[a.place.id]) map[a.place.id] = []
map[a.place.id].push(counted)
map[a.place.id].push(n)
})
return map
}, [selectedDayId, assignments])
@@ -0,0 +1,105 @@
import { act, renderHook } from '@testing-library/react';
import { buildDay, buildTrip } from '../../../tests/helpers/factories';
import { summariseTripRoute } from '../../components/Map/tripRouteGeometry';
import { useTripMapCards } from './useTripMapCards';
const day = buildDay({ id: 1 });
const pendingOverview = { ...summariseTripRoute([]), hasPlannedRoute: true, loading: true };
const tripOverview = {
...pendingOverview,
loading: false,
days: [
{
dayId: day.id,
dayNumber: 1,
date: day.date ?? null,
title: day.title ?? null,
color: { line: '#0a84ff', casing: '#0a5cc2' },
lines: [],
segments: [],
distance: 12000,
duration: 900,
modes: ['driving'],
},
],
};
function setup() {
const planner: Parameters<typeof useTripMapCards>[0] = {
activeTab: 'plan',
hideOverview: vi.fn(),
isLoading: false,
isMobile: false,
leftHidden: false,
leftWidth: 340,
overviewActive: false,
overviewShown: false,
rightHidden: false,
rightWidth: 300,
roadtripActive: false,
selectAssignment: vi.fn(),
selectedDayId: day.id,
selectedPlace: null,
setSelectedPlaceId: vi.fn(),
setShowDayDetail: vi.fn(),
showDayDetail: day,
toggleOverview: vi.fn(),
trip: buildTrip(),
tripOverview: pendingOverview,
viewportWidth: 1920,
};
const { result, rerender } = renderHook(useTripMapCards, { initialProps: planner });
const dayCard = document.createElement('div');
const overviewCard = document.createElement('div');
vi.spyOn(dayCard, 'getBoundingClientRect').mockReturnValue(new DOMRect(580, 500, 800, 200));
const measureOverview = vi.spyOn(overviewCard, 'getBoundingClientRect');
result.current.dayCardRef.current = dayCard;
const openCards = { ...planner, overviewActive: true, overviewShown: true };
return { openCards, result, rerender, overviewCard, measureOverview };
}
describe('useTripMapCards', () => {
it('waits for the first route card before checking the actual gap', () => {
const { openCards, result, rerender, overviewCard, measureOverview } = setup();
act(() => result.current.handleToggleOverview());
rerender(openCards);
expect(openCards.setShowDayDetail).not.toHaveBeenCalled();
result.current.overviewCardRef.current = overviewCard;
measureOverview.mockReturnValue(new DOMRect(1388, 500, 208, 150));
rerender({ ...openCards, tripOverview });
expect(openCards.setShowDayDetail).not.toHaveBeenCalled();
expect(openCards.hideOverview).not.toHaveBeenCalled();
measureOverview.mockReturnValue(new DOMRect(1387, 500, 209, 150));
rerender({ ...openCards, tripOverview, leftWidth: 341 });
expect(openCards.setShowDayDetail).toHaveBeenCalledExactlyOnceWith(null);
expect(openCards.hideOverview).not.toHaveBeenCalled();
});
it('keeps the day details when the overview no longer fits after a viewport resize', () => {
const { openCards, result, rerender, overviewCard, measureOverview } = setup();
result.current.overviewCardRef.current = overviewCard;
measureOverview.mockReturnValue(new DOMRect(1400, 500, 196, 150));
rerender({ ...openCards, tripOverview });
expect(openCards.hideOverview).not.toHaveBeenCalled();
act(() => result.current.handleDayDetail(day));
measureOverview.mockReturnValue(new DOMRect(1370, 500, 196, 150));
rerender({ ...openCards, tripOverview, viewportWidth: 1890 });
expect(openCards.hideOverview).toHaveBeenCalledOnce();
expect(openCards.setShowDayDetail).not.toHaveBeenCalledWith(null);
});
it('uses reserved overview space while the trip has no route', () => {
const { openCards, result, rerender } = setup();
act(() => result.current.handleToggleOverview());
const emptyOverview = { ...openCards, tripOverview: { ...pendingOverview, hasPlannedRoute: false } };
rerender({ ...emptyOverview, viewportWidth: 2100 });
expect(openCards.setShowDayDetail).not.toHaveBeenCalled();
rerender(emptyOverview);
expect(openCards.setShowDayDetail).toHaveBeenCalledExactlyOnceWith(null);
});
});

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