Compare commits

..

54 Commits

Author SHA1 Message Date
Maurice b6e3c9bf39 feat(native): the app needs TREK 5.1.4 on the server
nativeApi goes to 3 with 5.1.4, whose UI follows a widget or Live Activity
tap that starts the app. The apps refuse an older server with the hint to
update, and check a server they remember once more.
2026-11-12 20:21:16 +01:00
Maurice 736dc5dda9 chore(lint): lower the non-null assertion baseline the AirTrail test change freed 2026-11-12 17:47:05 +01:00
Maurice ae26a6c61c refactor(airtrail): save the settings in one transaction
The address and the key it may no longer carry now change together, as
they do for Dawarich, so the transaction ratchet drops the AirTrail entry.
The tests that pinned the old no-transaction shape now pin the new one.
2026-11-12 17:31:56 +01:00
Maurice 8979bd1fcd test(airtrail): one case per key field instead of a loop of awaits 2026-11-12 17:14:54 +01:00
Maurice 74d243d8e0 fix(airtrail): a new host does not inherit the stored API key
Saving the AirTrail settings with a different URL and the key field left
masked or blank kept the stored key, so the next sync sent the old
instance's key to the new host. The key now goes with the host, as it
already did for the connection test and for Dawarich: a new origin without
a new key clears it, a path edit on the same origin keeps it. The key is
cleared before the new address is written.
2026-11-12 16:58:24 +01:00
Maurice 56b9bac031 fix(native): a widget tap that starts the app opens what it points at
A tap on a widget or a Live Activity hands the app
com.liketrek.trek://navigate/<path>. A running app gets it as appUrlOpen;
an app started by the tap gets it as its launch URL, which nothing read, so
the path was lost and the app opened its start page (the packing widget
landed on the trip's plan instead of its lists). The launch link is now
followed once per launch.
2026-11-12 16:53:04 +01:00
Maurice 4983b3407c fix(planner): a flight without airports keeps its day and times on save
A flight created with a day and times but no endpoints (over MCP) showed
them in the form, but buildTransportPayload took a flight's span only from
rows with an airport, so a save sent day, end day and both times as null.
Like a train without stations, such a flight now takes its day, times,
airline, flight number and seat from the raw rows. Endpoints and legs still
come only from rows with an airport.

Fixes #3070
2026-11-12 16:49:29 +01:00
Maurice ed1728feec refactor(admin): the SSO unlink section is a component of its own
The edit dialog's component crossed the complexity limit with the section's
conditions; the section and its confirm step now live in SsoUnlinkSection,
which decides itself when it shows.
2026-11-12 16:14:34 +01:00
Maurice 11472c05ff fix(native): a failed SSO round trip from the app still hands back on the retry
A sign-in the app starts runs through the server's handoff page in the
system browser. When the SSO callback failed (an expired or overwritten
state), the login page dropped the way back to that page, so the retry from
there was a plain web login and ended in the web app inside the app's
browser sheet instead of signing in the app. The login page now keeps a way
back that points at the handoff page, and only that, and renews its
fallback copy for a slow retry. State, nonce, PKCE and the handoff verifier
are unchanged; the handoff page still asks for a tap before it passes
anything on.
2026-11-12 16:10:14 +01:00
Maurice f2ac12ca4f fix: hold the ratchets after the SSO unlink and the day pager window
- The SSO unlink answers with a response contract (adminSsoUnlinkResponseSchema).
- It reuses linkOidcIdentity with nulls instead of a new repository method,
  so UsersRepository keeps its method count and size.
- The client calls the route through apiClient, so api/client.ts does not
  grow, and its confirm dialog takes no async callback.
- The pager's preview step and pagesFor keep their complexity.
2026-11-12 15:56:59 +01:00
Maurice b53130ca0d feat(admin): remove the SSO link of an account whose provider changed its subject
A sign-in with another subject of the same provider is refused, so an
account whose provider re-issued the subject (a migrated or rebuilt IdP, a
changed sub format) was locked out: editing the email, as the wiki advised,
never touched the stored link. The edit dialog now offers "Remove SSO link"
for other accounts while SSO is set up (DELETE /api/admin/users/:id/sso,
audit admin.user_sso_unlink). The next SSO sign-in links again under the
rules of a first one, so it still needs a verified, not self-set email.
The log line names the remedy, and the wiki tells the two refusals apart.

Fixes #3065
2026-11-12 15:39:21 +01:00
Maurice a3a4f7cf79 fix(mobile): days drawn ahead of a fast swipe through the day pager
Only the selected day and two on either side were drawn, and the selection
moves only once the strip comes to rest, which iOS takes a while for. A run
of fast swipes ran past the drawn pages into blank ones until it settled.
The drawn window now also follows the day the swipe is heading for, so the
next days are there before they slide in. At most two windows of five pages
are mounted, however long the trip.

Fixes #3067
2026-11-12 15:39:20 +01:00
Maurice ac7094df05 fix(planner): a refresh of the trip no longer wipes an open transport or booking form
The transport form re-seeded itself whenever the trip's costs arrived as a
new array, and the booking form whenever days, places or stays did. A
socket reconnect re-reads the whole trip, so behind a proxy that drops idle
sockets every 15 to 30 seconds everything typed so far was wiped. Both forms
now re-seed only for what opens a different form; the data is read when the
form is seeded, as before.

Fixes #3069
2026-11-12 15:39:20 +01:00
Maurice 80130f7946 fix: the provisioning line reads as a key reference, the safe-area test follows margin-inline
lint:i18n-keys took the spread in front of t() for a member call and did not
see native.provisioning.sub; the sentence is its own constant now. The
shell chrome test asks for the logical margins and their right-to-left swap.
2026-11-12 14:52:42 +01:00
Maurice fc648bc7e4 fix: green checks after the first-screen redesign and the safe-area floor
- native-shell/amount.ts: the no-break spaces in the price pattern were
  written out as characters; \s already matches them.
- widgets.ts: the Live Activity's lead time stays inside the module.
- i18n: the count strings of the new plan tiles replace the removed ones
  on NOT_PLURAL, and the address placeholders of the non-Latin locales
  are their own instead of English copies.
- mobile.css: the side safe-area margins of the floating bars use
  margin-inline, swapped for right to left, instead of physical sides.
2026-11-12 14:36:13 +01:00
Maurice 9005d6b333 fix(native): name TREK without an article in the first screens
TREK is the application, not a thing one has a copy of: "I already have
TREK", not "a TREK". The same for the not-TREK messages in German and
Dutch and the agreement title in French, Spanish, Italian and Catalan.
2026-11-12 14:18:42 +01:00
Maurice 52f0fb882f feat(native): redesign the app's first screens around a living landscape
The screens the app ships itself (welcome, plans, address, own server and
the states between) move from the dark card layout to a light design on an
animated aerial landscape drawn by a WebGL shader (native-shell/scenery.ts):
an island, a coastal town, farmland and mountains in one world.

- Welcome: the landscape with the TREK wordmark, three perks in one card,
  "Explore cloud plans" and "I already have a TREK" as two buttons.
- Plans: one tab per plan; choosing one flies the camera to its place,
  further inland with every plan. Each plan reads as a kind of trip, the
  price sits in a card with a monthly/yearly switch and counts to its new
  amount in the store's own format (native-shell/amount.ts), and a yearly
  price shows what it makes a month. Restore purchases, the renewal terms
  and the links stay as the store rules require.
- Address: the address writes itself on a glass card over the landscape;
  free, the password rules and the agreement sit on white cards.
- Own server: the server address on the glass card; a failed check turns
  the card red with what went wrong, proxy sign-in and client certificate
  panels in the same style.
- States: server not reachable, certificate needed, already subscribed,
  setting up (with its steps, then "Arrived") and the slow setup.
- iPad, an unfolded phone and a phone on its side get two columns, the
  landscape beside the content; on a dual-screen device each half takes
  one screen. Arabic and Hebrew mirror through logical sides only.
- The shader caps the pixel ratio at 2, drops to a lower resolution on a
  slow device, stops in the background and is one still frame with
  reduced motion.
- The sign-in and error page bars over a proxy's page (iOS and Android)
  take the same look: a white card and a dark button.
- Plus Jakarta Sans is bundled for the text, with Montserrat standing in
  for Cyrillic; the wordmark fonts and the old preview images are gone.
- New strings in all 28 languages; the keys of the old screens removed.
- The dev sample plans follow the cloud's plans (start, basis, plus, pro).
2026-11-12 14:18:42 +01:00
Maurice b8ec428ad1 fix(native): show the travel day's Live Activity from three hours before its first stop
The Live Activity started with the first sync of a travel day and stayed on
the lock screen all day, so a day whose first stop is an evening flight held
it from the early morning on. It now appears three hours before the day's
first timed stop and stays until the day is done; liveDayDue() decides.
2026-11-12 14:00:47 +01:00
Maurice a1d3ffc2ce feat(native): the 'server not reachable' screen names the cause, small, for a report
A load that failed sent the app to the address screen with a general message only, and a tester's screenshot told nothing. The web view's own error (net::ERR_..., an HTTP status, NSURLErrorDomain and its code, a client certificate the proxy asked for) is kept natively and shown under the message once.
2026-11-12 10:11:01 +01:00
Maurice 46b9df54bf feat(native): the TREK Cloud screens show the app and make the choice of a plan easy
The cloud screen shows real screens of the app. The plans are a choice now: one tap marks a plan, the recommended one is marked, what every plan has is said once above them, storage says how many photos it holds, and the yearly switch shows what a year saves; one button at the foot carries the chosen plan on. The claim screen names the plan with a way to change it, shows the address as it will be once it is free, ticks off the password rules while typing, says in three words where the servers are, that it can be cancelled and that there are no ads, and puts the photo behind the form away.
2026-11-12 10:04:31 +01:00
Maurice 3c0c3b3f6e fix(native): a store account with a running TREK Cloud subscription buys no second one
One subscription per Apple ID or Google account. Choosing another plan in the app changed the running subscription on the App Store, and the redeem then failed with 'We could not set up your TREK'. The app now asks the store first and shows a screen of its own: the account already has TREK Cloud, a new one can be taken out once it has ended, with Open my TREK and the store's page to manage it. The native purchase refuses as well; a paid one that was never set up is still redeemed. On the address screens the link 'What is a TREK server?' is gone, and the small print under a purchase is set in the system text face at regular weight.
2026-11-12 09:28:56 +01:00
Maurice 5395d53332 fix(native): the top bar keeps clear of a camera in the corner of the screen
The iOS app hands the page the safe area it measures, a floor under env() where WebKit reports none, and on a phone the floating bars keep clear of the side insets as well.
2026-11-12 08:42:17 +01:00
Maurice ec08032e98 fix(native): SSO in the Android app survives Android ending the app while the browser is open
A Samsung phone may end the app while the sign-in runs in the browser. The browser's return then started the app anew without the call that waited for it, the first page load failed while the network was still held back, and the user came back to 'server not reachable' and then to the sign-in page, in a loop. The return is now kept natively and redeemed by the sign-in page with the verifier kept until then, and a page that failed on the network is loaded once more before the app gives up.
2026-11-12 08:42:17 +01:00
Maurice cc5eca5553 feat(native): a client certificate can be added on the address screen before connecting
The import was only offered once the check saw the proxy ask for a certificate during the handshake. A proxy that refuses without asking left no way in. The wiki also points to the certificate's new place in Settings and explains why a certificate from an iOS configuration profile cannot be used by the app.
2026-11-12 08:42:16 +01:00
Maurice 1323183cce fix(assistant): Claude Sonnet 5.5 no longer ends a turn with 'came back without an answer'
Sonnet 5.5 hands back the words written before a tool call as a hidden thinking block. After the ask for the answer, an empty step got the general push with tools open again; the model answered, offered follow-ups once more, and the answer was lost a second time. That push now asks for the answer as text and stays text-only.
2026-11-12 08:42:16 +01:00
Maurice 009be05d22 fix(mobile): a sheet no longer shows the page through it while it opens
The dim faded in on the sheet's own parent, and opacity multiplies down the tree, so for its first frames even the opaque sheet let the list behind read through as ghost text (Android tester, expense editor). The dim now fades on a layer of its own beside the sheet, and the card is opaque halfway through its pop.
2026-11-12 08:42:16 +01:00
Maurice 860ffc1dee fix(planner): the drag state setters are stable, so the sidebar's dragend listener lists them and is still set up once 2026-11-12 08:42:15 +01:00
Maurice c515f95d17 fix(ci): the drag hook lists its dependencies, closeOnDone stays module-private, and the weight test waits for its save 2026-11-12 07:10:18 +00:00
Maurice 855bf8610a refactor(planner): the day plan's drag state lives in a hook of its own; the holiday provider cases get a suite of their own
DayPlanSidebar grew past its size baseline with the Firefox drag fix. Its drag state (what is dragged, the drop line, the day under the drag, whether a drag happened) and the effect that ends a lost drag move into useDayPlanDragState, typed, which also lowers the file's strict-mode count; size and strict baselines are lowered with it.

vacay.service.test.ts went past the 2000-line limit once the Nager v4 cases were back in it. They move into vacay.holiday-provider.test.ts, which takes VacayService from a Nest testing module over a snapshot db, so neither the db mock nor a hand-built service is needed.
2026-11-11 22:38:59 +00:00
Maurice 742edc4a79 fix(ci): today's changes pass the release gates
- iOS: the navigation proxy reports an error page through a callback the controller sets; it called the controller's method on itself and did not build.
- keyboard: the done key reads the field's text in the capture phase, before the field's own handler, so a list that adds an item on Enter and clears itself keeps the keyboard; the tests wire it as the app does.
- Ireland migration: the queued writes use addSql instead of awaiting inside loops; only table constants and integer ids reach the SQL.
- tests: the Dawarich GL test types its two layer specs once (strict baseline lowered), the collab test reads the id off the listed message, the reasoning test runs its four servers in parallel, and a wasm copy covers the precompressed branch without a charset.
- en wording: the deviations agreement no longer calls TREK self-hosted.
2026-11-11 22:06:50 +00:00
Maurice 1975a23aab fix(mobile): the settings group headings follow the text size setting
They used a fixed 10px size, which theme:lint refuses; they take the caption tier now.
2026-11-11 21:32:05 +00:00
Maurice 80c8d9c602 feat(mobile): settings group their sections by what they reach: your account or this device
A tester could not tell which settings follow the account to every device and which stay on the phone, and looked for offline mode for a while. The section list and dropdown now stand under two headings, "Your account" and "This device". The server the app opens, the app lock and a client certificate move out of Account into a section of their own, "App", shown only in the app, next to Offline; About stands under TREK. Labels in all locales. TestFlight feedback, 5.1.3.
2026-11-11 21:31:14 +00:00
Maurice 948c9ef57b fix(atlas): show Ireland's 26 counties instead of its four provinces
geoBoundaries has no county layer for Ireland: its ADM1 is the four
provinces and its ADM2 the 166 local electoral areas, so the Atlas showed
Ireland as four provinces next to a UK of counties.

The Atlas builder can now take a country's regions from another source.
Ireland's come from Tailte Éireann's 26 counties (CC BY 4.0), with Dublin,
Cork, Galway and Limerick each one county, under their ISO 3166-2:IE
codes. Those outlines come at full detail, so the builder simplifies them
itself and keeps the borders two counties share identical on both sides,
so no point between them falls into neither. ATLAS_ONLY rebuilds just the
named countries without downloading the whole world.

A migration clears Ireland's cached place regions so they are worked out
again as counties, moves visited rows that name a county onto its code,
and hides each county of a province a user had hidden. Provinces a user
marked as visited are kept as they are.

Fixes #2922
2026-11-11 21:26:31 +00:00
Maurice bac968c0bf fix(ai): retry chat requests with reasoning_effort none when a server refuses tools with reasoning
Azure AI Foundry reasoning deployments behind an "Own server" connection
reject function tools on /v1/chat/completions at their default reasoning
effort and answer HTTP 400 naming reasoning_effort. The Responses API
switch from #2792 only covers direct OpenAI keys, so the assistant could
not run on these deployments at all.

The chat client still never sends reasoning_effort, so servers that do not
know the field (Ollama, LM Studio, vLLM, OpenRouter) see unchanged
requests. When a request with tools is refused over reasoning_effort, it
goes out once more with reasoning_effort "none", and the rest of the turn
keeps sending it. The refused field is now carried on AiProviderError
instead of only being logged.

Fixes #3043
2026-11-11 21:26:20 +00:00
Maurice 520562ef86 fix(planner): keep day plan drags alive in Firefox
Firefox fires dragstart while it handles the mouse move that starts the
drag and delivers that move to the page afterwards, button still held.
The listener that clears a drag whose dragend never arrived took that
move as the end of the drag and dropped the drag data at pick-up, so a
stop could only be reordered with its arrows. The same held-button moves
come from the touch polyfill on hybrid laptops throughout a drag. Only a
move with no button held now counts as the drag being over.

The day list also switched its stagger animation back on whenever a drag
ended, which replayed the entrance of every day card ("weird reload").
It now plays once on mount and stays off after the first drag.

Fixes #3041
2026-11-11 21:26:15 +00:00
Maurice 001253c39b fix(ios): the strip above the page carries the page colour on releases that lay the web view out below the status bar
On iOS 27.0.x the web view started below the status bar, and the strip above it showed the view controller's black instead of the screen background. The colour behind the web view now follows the theme the UI reports through StatusBar.setStyle (the top colour of --m-scr), so the strip reads as part of the page on every release. TestFlight feedback, 5.1.3.
2026-11-11 21:24:35 +00:00
Maurice 5345b50d17 test(vacay): the holiday provider cases live in the existing suites again
The two new test files mocked the db module and built VacayService by hand,
which the test-mocks and new-service ratchets refuse for files without a
baseline entry. The cases move back into vacay.service.test.ts and
vacay.test.ts unchanged; VACAY-037 asks for a year no other case caches. The
unrelated admin addon test change is reverted and two comments name the new
provider.
2026-11-11 21:06:29 +00:00
Luffy a3622e91b6 feat(vacay): implement Nager.Holidays v4 integration and adapt holiday data structure 2026-11-11 21:04:07 +00:00
Luffy be305c3daf fix(vacay): move holiday lookups to Nager.Holidays v4 2026-11-11 21:04:07 +00:00
Sebastian Fischer ec78cfbdd0 feat(tours): find bakeries and groceries on the map and along a hike
A multi-day hike restocks on the way: bread in the morning, food for
lunch and supper every day or two. Neither could be searched for.

- Explore pill: new `bakery` and `supermarket` chips. `supermarket`
  already existed on the server (shop=supermarket|convenience) but no
  pill offered it; `bakery` is new (shop=bakery).
- Along the tour: `bakery` and `supermarket` are offered to a hike,
  after its existing kinds so a new hike still starts on the same three.
- TREK places index: `bakery` maps to food_and_drink>casual_eatery>bakery;
  `supermarket` is narrowed to grocery and convenience stores, since the
  whole food_and_beverage_store branch also brought tobacconists and
  wine shops. Both paths checked against a live answer of the index.
  As the more specific term, a bakery is no longer listed as a place to
  eat when only `food` is asked along a tour.
- Category guess: a bakery or grocer picked from the map was preselected
  as Bar/Cafe or Shopping even where the admin had made a Bakery or
  Groceries category. The guess now looks for such a category first, by
  name in the usual languages or by icon, and keeps the broad one when
  there is none. The category icon picker offers Croissant and
  ShoppingBasket, the icons the map chips use.
- Labels in every locale; MCP tool description names the new kinds.
2026-11-11 20:59:59 +00:00
Ibrahim Roshdy 8023be452a fix(atlas): give a point no polygon contains to the nearest border
A point just off a simplified coastline lies in no admin0 polygon, and the
fallback then took the candidate with the smallest bounding box. Nice and
Menton sit ~80 m outside France's coast and 20+ km from Italy, but Italy's
box is the smaller one, so they resolved to IT. The fallback now ranks the
candidates by distance to their border. A deferred loose box (PS/XK) keeps
its priority. The parity test's reference lookup mirrors the new rule.

Closes #3048
2026-11-11 20:59:53 +00:00
John Jahn 5112c96c05 perf(places): the country lookup skips polygons whose box misses the point and remembers its answers
The places list and the trip bundle resolve the country of every place
without a cached region on each read, and that lookup was about 90% of
their CPU time: it ray-cast every polygon of each candidate country, which
is thousands of rings for a country that is mostly islands.

A polygon whose outer ring's box does not hold the point is now skipped
without walking it, and an answer is kept by coordinate pair (20,000 pairs,
oldest out first), since the borders never change while the process runs.
The answers are the ones the ray-cast alone gives; ATLAS-SVC-051 and
ATLAS-SVC-055 compare every country against the reference lookup.

Measured on a production build with a 360-place trip: GET places
22.7 ms -> 3.5 ms, GET bundle 27.5 ms -> 6.2 ms. A first lookup of a
pair is about 1.8 times faster (90 us -> 50 us over 20 cities).
2026-11-11 20:59:47 +00:00
John Jahn 04b1fb72bb perf(static): serve the hashed assets from Brotli copies written at build time
Every file under assets/ was compressed again on each download, at the low
level a request path can afford. They carry their content hash in the name
and never change, so the client build now writes a Brotli copy beside each
compressible one (postbuild, scripts/precompress.mjs) and production points
a browser that accepts Brotli at that copy before express.static serves it.

Measured on a production build of 5.1.2, fetching the 652 precached files
the way a service worker install does: 16.3 MB -> 13.9 MB on the wire and
about 1.0 s -> 0.2 s of server CPU per install. A client without Brotli, a
range request and a build without copies are served exactly as before.
2026-11-11 20:59:40 +00:00
John Jahn a9d11ccb2e fix(plugins): grant plugin children the network on Node 25 and newer
From Node 25 the permission model covers the network, so a plugin child
forked with --permission and no --allow-net gets ERR_ACCESS_DENIED on every
lookup and connect, and no plugin can reach a host it was granted. Node 24
is unaffected and rejects the flag as a bad option, so it is passed only
where process.allowedNodeEnvironmentFlags knows it.

Which hosts a plugin may reach is still decided by the egress guard inside
the child.

Fixes #3045
2026-11-11 20:59:34 +00:00
John Jahn 848e3f90e1 perf(client): the icons the first load needs ship as one chunk instead of 187
Every lucide icon is its own module, and the plugin icon lookup reaches all
of them by name from the navigation. The bundler therefore put each icon
another chunk also uses into a chunk of its own: 187 files of a few hundred
bytes, each one a request on a first visit and an entry in the precache.

A `vendor-icons` group collects them. The first load asks for 32 script
files instead of 224 (the bytes stay the same, 3.9 MB before compression),
and the service worker installs 460 files instead of 652. With 50 ms added
to every response the login page reaches DOMContentLoaded in 0.5 s
instead of 3.8 s.
2026-11-11 20:59:27 +00:00
Botond Rakoczi e83b6741ad docs: add TrueNAS SCALE installation guide 2026-11-11 20:57:42 +00:00
Maurice 0a3d93b59b fix(collab): a deleted chat message keeps no text
Deleting a message set the flag and kept the text in the row and in every backup; only the client hid it. The delete now blanks the text with the flag, and a migration clears what earlier deletes left. The row stays for the placeholder.
2026-11-11 20:41:25 +00:00
Maurice 102e2141ec fix(mobile): screens with pull-to-refresh bounce like every other iOS list
The dashboard, journeys and notifications switched the iOS bounce off entirely so it would not race the pull. The pull now holds only a clearly downward move from the very top, from its first pixel, and the page bounces everywhere else, its end included. TestFlight feedback, 5.1.3.
2026-11-11 20:41:25 +00:00
Maurice 768fd6f439 fix(mobile): a plugin's page in the phone shell sits below the status bar and above the dock
The page took 100vh with no top inset inside the touch shell, so the plugin's header ran under the status bar and the frame reached past the screen and under the dock. It now takes the visible height (100dvh) less the dock, after the safe area and the rail, and the plugin's own document scrolls. TestFlight feedback, 5.1.3 (Trip Importer).
2026-11-11 20:41:24 +00:00
Maurice 231a610466 fix(map): the recorded Dawarich route reads on a busy street map
A thin, translucent dash over a nearly opaque white casing read as a pale trace and was barely visible on past trips. Full colour, a wider line and longer dashes, shared by the Leaflet and GL layers. TestFlight feedback, 5.1.3.
2026-11-11 20:41:24 +00:00
Maurice 7db5ec0721 fix(native): the keyboard's done key closes the keyboard
A field outside a form gets enterkeyhint="done", but a web view only sends Enter and nothing listened, so the key did nothing. When no handler took the Enter (same text, still focused a moment later) the field lets go of the focus; a field that acts on Enter and clears itself keeps it. TestFlight feedback, 5.1.3.
2026-11-11 20:41:24 +00:00
Maurice a2b9d96e86 fix(ios): the system sign-in prompt names the app TREK, not "App"
ASWebAuthenticationSession's prompt reads CFBundleName, which was $(PRODUCT_NAME), the Xcode target "App". TestFlight feedback, 5.1.3.
2026-11-11 20:41:24 +00:00
Maurice e0022c12c4 fix(native): an error page in place of the server's keeps a way back to the address screen
A proxy's block page or a refused client certificate (Cloudflare's "Sorry, you have been blocked") left the app on a page without TREK's UI and no way to change the server. Any 4xx main-frame page that the client-certificate path does not handle now shows the sign-in bar with its own hint and "Change server", on iOS and Android. TestFlight feedback, 5.1.2.
2026-11-11 20:41:24 +00:00
Maurice 66b8f2c906 feat(native): ask for the separate TREK Cloud deviations agreement before an in-app purchase
The claim screen loads the agreement text and its version from /api/iap/consent, shows it with its own checkbox and buys nothing until it is ticked. The redeem sends consent { acceptedDeviations, version }; a refusal for an outdated text reloads it and asks again without a second purchase.
2026-11-11 20:41:23 +00:00
316 changed files with 9827 additions and 2989 deletions
+17 -1
View File
@@ -20,7 +20,23 @@ geoBoundaries is licensed under **CC BY 4.0**
The bundled files are simplified (coordinate-quantized) and re-tagged with the
property names TREK consumes. Country borders (`admin0`) derive from the geoBoundaries
CGAZ composite; sub-national regions (`admin1`) derive from the per-country open
(gbOpen) release.
(gbOpen) release, except for Ireland (below).
## Tailte Éireann — counties of Ireland
Ireland's regions in the same files (`admin1/IE.geojson.gz`, and its features in
`admin1.geojson.gz`) are the 26 counties from Tailte Éireann's *Counties - National
Statutory Boundaries - 2019 - Generalised 20m*, because geoBoundaries has no county
layer for Ireland.
Contains Tailte Éireann data, © Tailte Éireann, licensed under **CC BY 4.0**
(https://creativecommons.org/licenses/by/4.0/). Source:
https://data-osi.opendata.arcgis.com/
The outlines are simplified, coordinate-quantized and re-tagged with ISO 3166-2:IE
codes by `server/scripts/build-atlas-geo.mjs`. Tailte Éireann publishes the
generalised boundaries for reference only; they may not match the statutory
boundaries exactly.
## OpenStreetMap — geocoding, place details & descriptions
+7 -4
View File
@@ -146,7 +146,7 @@ Most of what follows is an addon an admin switches on or off. Lists, Costs, Docu
#### 🗺️ Atlas, Vacay and Collections
- **Atlas**: countries and regions visited on [geoBoundaries](https://www.geoboundaries.org/) outlines, a bucket list, travel stats, and a tour activities tab with planned against recorded totals
- **Vacay**: leave calendar with half days, public holidays from date.nager.at, school holidays for 16 European countries, company holidays, carry-over between years, and joint or read-only sharing
- **Vacay**: leave calendar with half days, public holidays from [nagerholidays.com](https://nagerholidays.com), school holidays for 16 European countries, company holidays, carry-over between years, and joint or read-only sharing
- **Collections** (off by default): a place library outside any trip with lists, labels, ratings, a status per place, cover images, GPX and file export, copy into a trip, and sharing by invite
- **Dawarich** (off by default): link a Dawarich instance for recorded tracks, suggested stays and countries for the Atlas
@@ -276,6 +276,8 @@ Open `http://localhost:3000`, or `http://<server-ip>:3000` from another machine.
`COOKIE_SECURE=false` is only for trying TREK over plain HTTP: without it the browser drops the session cookie and the login does not stick. Once TREK sits behind HTTPS (see [Reverse Proxy](#reverse-proxy)), remove it.
**TrueNAS SCALE:** Install TREK directly from the Community catalog. See the [TrueNAS SCALE installation guide](https://github.com/liketrek/TREK/wiki/Install-TrueNAS-SCALE).
> [!TIP]
> **No server yet?** TREK's own public services run on [**dataforest cloud**](https://cloud.dataforest.net/en?mtm_campaign=trek), our infrastructure sponsor. A small seed is plenty for a TREK instance and is ready within a minute.
@@ -348,7 +350,7 @@ TREK then launches fullscreen with its own icon, just like a native app.
## Updating
See [Updating](https://github.com/liketrek/TREK/wiki/Updating) — Docker Compose,
Docker run, Helm, Portainer, Unraid and Proxmox, plus the encryption-key note.
Docker run, Helm, Portainer, Unraid, TrueNAS SCALE and Proxmox, plus the encryption-key note.
<br />
@@ -437,8 +439,9 @@ Every variable, its default and what it does: see
The Atlas map's country and sub-national (province/county) boundaries come from
[**geoBoundaries**](https://www.geoboundaries.org/) (Runfola et al., 2020), licensed
[CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). See [NOTICE.md](NOTICE.md)
for full third-party attributions.
[CC BY 4.0](https://creativecommons.org/licenses/by/4.0/); Ireland's counties come from
[**Tailte Éireann**](https://data-osi.opendata.arcgis.com/), also CC BY 4.0. See
[NOTICE.md](NOTICE.md) for full third-party attributions.
<br />
+1 -1
View File
@@ -6,7 +6,7 @@ Scope: the **`@trek/client`** workspace (React 19 + Vite + Zustand + Tailwind PW
```bash
npm run dev # Vite dev server; proxies the API/ws/uploads/MCP/OAuth paths → http://localhost:3001
npm run build # prebuild generates PWA icons, then vite build
npm run build # prebuild generates PWA icons, then vite build; postbuild writes a Brotli copy beside each hashed asset for the server to hand out
npm run typecheck # tsc --noEmit (CI)
npm run lint:strict # tsc over tsconfig.strict.json (strictNullChecks + noImplicitAny): errors per file may only shrink against scripts/strict-baseline.json, a new file starts at zero (CI gate; --list shows them, --update lowers it)
npm run lint # eslint . (CI runs lint:warnings instead, which fails on the same errors)
@@ -47,7 +47,13 @@ public class MainActivity extends BridgeActivity {
// Set before any WebView callback can run: they are posted to this thread.
if (onServer) {
bridge.setWebViewClient(
new TrekWebViewClient(bridge, this::showAddressScreen, this::showSignInBar, TrekServerStore.getSignInHosts(this))
new TrekWebViewClient(
bridge,
this::showAddressScreen,
this::showSignInBar,
this::showErrorPageBar,
TrekServerStore.getSignInHosts(this)
)
);
}
TrekSharedFiles.receive(this, getIntent());
@@ -84,7 +90,10 @@ public class MainActivity extends BridgeActivity {
private View signInBar;
/** Whether the page is a proxy's sign-in page, and whether the keyboard is up over it. */
private boolean onSignInPage;
/** Whether the page is an error page in place of the server's (TrekWebViewClient.onReceivedHttpError). */
private boolean onErrorPage;
private boolean keyboardUp;
private TextView signInHint;
/**
* Over a proxy's sign-in page (Pangolin, authentik, ...): the server's UI is
@@ -100,9 +109,22 @@ public class MainActivity extends BridgeActivity {
});
}
/** The same bar over an error page in place of the server's, with words for that. */
private void showErrorPageBar(boolean show) {
runOnUiThread(() -> {
onErrorPage = show;
if (show && signInBar == null) signInBar = buildSignInBar();
updateSignInBar();
});
}
/** Out of the way while the keyboard is up: the form needs the room, and the bar is there again once it closes. */
private void updateSignInBar() {
if (signInBar != null) signInBar.setVisibility(onSignInPage && !keyboardUp ? View.VISIBLE : View.GONE);
if (signInBar == null) return;
if (signInHint != null) {
signInHint.setText(onSignInPage ? TrekServerStore.signInHintLabel(this) : TrekServerStore.errorPageHintLabel(this));
}
signInBar.setVisibility((onSignInPage || onErrorPage) && !keyboardUp ? View.VISIBLE : View.GONE);
}
private View buildSignInBar() {
@@ -110,16 +132,20 @@ public class MainActivity extends BridgeActivity {
LinearLayout bar = new LinearLayout(this);
bar.setOrientation(LinearLayout.HORIZONTAL);
bar.setGravity(Gravity.CENTER_VERTICAL);
bar.setPadding(Math.round(14 * dp), Math.round(10 * dp), Math.round(8 * dp), Math.round(10 * dp));
bar.setPaddingRelative(Math.round(16 * dp), Math.round(10 * dp), Math.round(10 * dp), Math.round(10 * dp));
// The look of the app's own first screens: a white card with a sand edge,
// warm grey text and a dark button, over whatever page the proxy shows.
GradientDrawable background = new GradientDrawable();
background.setColor(0xF2111827);
background.setCornerRadius(16 * dp);
background.setColor(0xF7FFFFFF);
background.setCornerRadius(18 * dp);
background.setStroke(Math.max(1, Math.round(dp)), 0xFFEFE4D8);
bar.setBackground(background);
bar.setElevation(6 * dp);
bar.setElevation(8 * dp);
TextView hint = new TextView(this);
signInHint = hint;
hint.setText(TrekServerStore.signInHintLabel(this));
hint.setTextColor(0xFFE5E7EB);
hint.setTextColor(0xFF6B5F57);
hint.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12.5f);
bar.addView(hint, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f));
@@ -127,12 +153,21 @@ public class MainActivity extends BridgeActivity {
change.setText(TrekServerStore.changeServerLabel(this));
change.setAllCaps(false);
change.setTextColor(0xFFFFFFFF);
GradientDrawable pill = new GradientDrawable();
pill.setColor(0xFF111827);
pill.setCornerRadius(12 * dp);
change.setBackground(pill);
change.setMinHeight(0);
change.setMinimumHeight(0);
change.setPaddingRelative(Math.round(14 * dp), Math.round(9 * dp), Math.round(14 * dp), Math.round(9 * dp));
LinearLayout.LayoutParams changeParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
changeParams.setMarginStart(Math.round(10 * dp));
change.setOnClickListener((v) -> {
TrekServerStore.setUrl(this, null);
TrekServerStore.markRestart(this);
recreate();
});
bar.addView(change, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
bar.addView(change, changeParams);
int margin = Math.round(12 * dp);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
@@ -26,6 +26,7 @@ final class TrekServerStore {
private static final String KEY_SERVER_CHECK = "server_check";
private static final String KEY_LABEL_SIGN_IN_HINT = "label_sign_in_hint";
private static final String KEY_LABEL_CHANGE_SERVER = "label_change_server";
private static final String KEY_LABEL_ERROR_PAGE_HINT = "label_error_page_hint";
/**
* The server API this build needs (MIN_NATIVE_API in serverAddress.ts). A
@@ -33,7 +34,7 @@ final class TrekServerStore {
* launch after an update that raised it puts the address screen back up,
* filled in with that server (getPreviousUrl). Raise both together.
*/
private static final int SERVER_CHECK = 2;
private static final int SERVER_CHECK = 3;
private static final String KEY_SIGN_IN_HOSTS = "sign_in_hosts";
private static final String KEY_SHELL_ONCE = "shell_once";
private static final String KEY_RESTART = "restart";
@@ -83,13 +84,21 @@ final class TrekServerStore {
* as the address screen passed them (setServer's `labels`): the server's UI
* is not there to say them. Null keeps the English fallback.
*/
static void setLabels(Context context, String signInHint, String changeServer) {
static void setLabels(Context context, String signInHint, String changeServer, String errorPageHint) {
SharedPreferences.Editor editor = prefs(context).edit();
if (signInHint != null) editor.putString(KEY_LABEL_SIGN_IN_HINT, signInHint);
if (changeServer != null) editor.putString(KEY_LABEL_CHANGE_SERVER, changeServer);
if (errorPageHint != null) editor.putString(KEY_LABEL_ERROR_PAGE_HINT, errorPageHint);
editor.commit();
}
static String errorPageHintLabel(Context context) {
return prefs(context).getString(
KEY_LABEL_ERROR_PAGE_HINT,
"This page is not from TREK: the server or a proxy in front of it refused the app. Check your proxy or certificate, or change the server."
);
}
static String signInHintLabel(Context context) {
return prefs(context).getString(
KEY_LABEL_SIGN_IN_HINT,
@@ -147,6 +156,24 @@ final class TrekServerStore {
}
/** Start the next launch on the bundled address screen, even with a server remembered. */
private static final String KEY_FAILURE = "last_failure";
/**
* Why the server's page did not load, in the WebView's own terms
* ("net::ERR_NAME_NOT_RESOLVED (-2)", "HTTP 503"): the address screen shows
* it small under its message, so a report carries the cause.
*/
static void setFailure(Context context, String failure) {
prefs(context).edit().putString(KEY_FAILURE, failure).commit();
}
/** The failure behind this address screen, once. */
static String takeFailure(Context context) {
String failure = prefs(context).getString(KEY_FAILURE, null);
if (failure != null) prefs(context).edit().remove(KEY_FAILURE).commit();
return failure;
}
static void showShellOnce(Context context) {
prefs(context).edit().putBoolean(KEY_SHELL_ONCE, true).commit();
}
@@ -2,6 +2,7 @@ package com.liketrek.trek;
import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
@@ -314,6 +315,8 @@ public class TrekShellPlugin extends Plugin {
JSObject result = new JSObject();
result.put("url", url == null ? JSONObject.NULL : url);
result.put("previousUrl", previous == null ? JSONObject.NULL : previous);
String failure = TrekServerStore.takeFailure(getContext());
result.put("failure", failure == null ? JSONObject.NULL : failure);
call.resolve(result);
}
@@ -328,7 +331,12 @@ public class TrekShellPlugin extends Plugin {
TrekServerStore.setServer(getContext(), url, signInHostsOf(call));
JSObject labels = call.getObject("labels");
if (labels != null) {
TrekServerStore.setLabels(getContext(), labels.getString("signInHint"), labels.getString("changeServer"));
TrekServerStore.setLabels(
getContext(),
labels.getString("signInHint"),
labels.getString("changeServer"),
labels.getString("errorPageHint")
);
}
// A TREK Cloud purchase: the code that signs the buyer in, opened once after the first page.
String welcome = call.getString("welcome");
@@ -428,7 +436,11 @@ public class TrekShellPlugin extends Plugin {
}
Uri data = intent.getData();
PluginCall call = pendingAuthCall();
if (call == null || data == null || !authScheme.equals(data.getScheme())) return;
if (call == null) {
keepOrphanAuthReturn(intent);
return;
}
if (data == null || !authScheme.equals(data.getScheme())) return;
JSObject result = new JSObject();
result.put("url", data.toString());
call.resolve(result);
@@ -454,6 +466,48 @@ public class TrekShellPlugin extends Plugin {
}, CANCEL_GRACE_MS);
}
private static final String AUTH_PREFS = "trek_auth_return";
/** As long as the server keeps the code it carries (NATIVE_HANDOFF_CODE_TTL_MS), with room to spare. */
private static final long ORPHAN_AUTH_TTL_MS = 2 * 60 * 1000;
/**
* A return to the sign-in scheme with no call waiting for it: Android ended
* the app while the browser was in front, and the browser's return started
* it anew (the launch intent comes through here as well). Kept on disk, as
* the process may be new too, until the sign-in page takes it. The return
* is then taken off the activity's intent: Capacitor hands the launch intent
* in again whenever the activity is created, and Android does as well when
* it rebuilds the task from the recent apps.
*/
private void keepOrphanAuthReturn(Intent intent) {
Uri data = intent.getData();
if (data == null || !"auth".equals(data.getHost())) return;
if (!getContext().getString(R.string.custom_url_scheme).equals(data.getScheme())) return;
if (getActivity() != null && getActivity().getIntent() != null && getActivity().getIntent().getData() != null
&& data.equals(getActivity().getIntent().getData())) {
getActivity().setIntent(new Intent(getActivity().getIntent()).setData(null));
}
if ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) return;
getContext().getSharedPreferences(AUTH_PREFS, Context.MODE_PRIVATE)
.edit()
.putString("url", data.toString())
.putLong("at", System.currentTimeMillis())
.commit();
}
/** The kept return of a sign-in (keepOrphanAuthReturn), once and while fresh; null otherwise. */
@PluginMethod
public void takeAuthCallback(PluginCall call) {
android.content.SharedPreferences prefs = getContext().getSharedPreferences(AUTH_PREFS, Context.MODE_PRIVATE);
String url = prefs.getString("url", null);
long at = prefs.getLong("at", 0);
prefs.edit().clear().commit();
boolean fresh = url != null && System.currentTimeMillis() - at <= ORPHAN_AUTH_TTL_MS;
JSObject result = new JSObject();
result.put("url", fresh ? url : JSONObject.NULL);
call.resolve(result);
}
private PluginCall pendingAuthCall() {
return authCallId == null ? null : getBridge().getSavedCall(authCallId);
}
@@ -679,6 +733,12 @@ public class TrekShellPlugin extends Plugin {
com.liketrek.trek.billing.TrekBilling.INSTANCE.restore(getContext(), call);
}
/** Whether this Google account already holds a delivered cloud subscription. */
@PluginMethod
public void storeHeld(PluginCall call) {
com.liketrek.trek.billing.TrekBilling.INSTANCE.held(getContext(), call);
}
/** A paid subscription never delivered (it cleared while the app was closed), for the shell to redeem. */
@PluginMethod
public void storeUnfinished(PluginCall call) {
@@ -1,11 +1,13 @@
package com.liketrek.trek;
import android.net.Uri;
import android.util.Log;
import android.webkit.ClientCertRequest;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.getcapacitor.Bridge;
import com.getcapacitor.BridgeWebViewClient;
import com.liketrek.trek.clientcert.TrekClientIdentity;
@@ -27,14 +29,29 @@ class TrekWebViewClient extends BridgeWebViewClient {
private final Runnable onUnreachable;
/** Told whether the page now shown is a proxy's sign-in page, for the bar with the way out. */
private final Consumer<Boolean> onSignInPage;
/** Told whether the page now shown is an error page in place of the server's, for the same bar. */
private final Consumer<Boolean> onErrorPage;
/** The main-frame address that last came back as a 4xx page nobody else handled. */
private String errorPageUrl;
private final Set<String> signInHosts;
/** A page of the server has shown since launch; from then on no sign-in host is learned (SignInRedirect). */
private boolean serverShown;
/** The page itself failed on the network once already; the next failure goes to the address screen. */
private boolean retriedMainFrame;
/** The page loaded again after a network error, until that load starts: its error page counts for nothing. */
private String retryUrl;
TrekWebViewClient(Bridge bridge, Runnable onUnreachable, Consumer<Boolean> onSignInPage, Set<String> signInHosts) {
TrekWebViewClient(
Bridge bridge,
Runnable onUnreachable,
Consumer<Boolean> onSignInPage,
Consumer<Boolean> onErrorPage,
Set<String> signInHosts
) {
super(bridge);
this.onUnreachable = onUnreachable;
this.onSignInPage = onSignInPage;
this.onErrorPage = onErrorPage;
this.signInHosts = new HashSet<>(signInHosts);
}
@@ -69,13 +86,22 @@ class TrekWebViewClient extends BridgeWebViewClient {
@Override
public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
super.doUpdateVisitedHistory(view, url, isReload);
if (retryUrl != null) return;
onSignInPage.accept(url != null && isSignInHost(Uri.parse(url)));
// The 4xx answer arrives before this commit or after it; either way the
// flag is read once here, so the next page clears the bar again.
boolean error = url != null && url.equals(errorPageUrl);
errorPageUrl = null;
onErrorPage.accept(error);
}
/** After the server's first page, a pending welcome code opens the welcome page once (TrekServerStore.takeWelcomeUrl). */
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// The error page of a load that is about to be retried: not the server's
// first page, so no welcome page and no learning of sign-in hosts yet.
if (retryUrl != null) return;
if (SignInRedirect.onServer(TrekServerStore.getUrl(view.getContext()), url)) serverShown = true;
String welcome = TrekServerStore.takeWelcomeUrl(view.getContext());
if (welcome != null) view.loadUrl(welcome);
@@ -117,13 +143,35 @@ class TrekWebViewClient extends BridgeWebViewClient {
String server = TrekServerStore.getUrl(view.getContext());
Uri serverUri = server == null ? null : Uri.parse(server);
if (serverUri != null && TrekClientIdentity.matches(String.valueOf(serverUri.getHost()), serverUri.getPort() > 0 ? serverUri.getPort() : 443, request.getHost(), request.getPort())) {
com.liketrek.trek.clientcert.ClientCertWatch.serverAsked(view.getContext(), server, onUnreachable);
com.liketrek.trek.clientcert.ClientCertWatch.serverAsked(view.getContext(), server, () -> {
TrekServerStore.setFailure(view.getContext(), "client certificate requested");
onUnreachable.run();
});
}
}
/**
* A page that failed on the network is loaded once more before the app says
* the server is unreachable. Started from the background, as when the
* browser hands a sign-in back to an app Android had ended, a Samsung phone
* may hold its network back for a moment, and the first load fails with the
* server there all along. The error is logged, as a report has nothing else.
*/
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
if (request.isForMainFrame()) {
Log.w("TrekShell", "Page failed: " + error.getErrorCode() + " " + error.getDescription());
if (!retriedMainFrame && isNetworkError(error.getErrorCode())) {
retriedMainFrame = true;
retryUrl = request.getUrl().toString();
view.postDelayed(() -> {
String url = retryUrl;
retryUrl = null;
view.loadUrl(url);
}, 1500);
return;
}
TrekServerStore.setFailure(view.getContext(), error.getDescription() + " (" + error.getErrorCode() + ")");
onUnreachable.run();
return;
}
@@ -132,10 +180,12 @@ class TrekWebViewClient extends BridgeWebViewClient {
/**
* Only a 5xx on the page itself means the server is down (a proxy's 502 or
* 503 while TREK restarts). A 4xx page is left alone: the server answered,
* and TREK serves its UI for every other path. The exception is a proxy
* that asked this page for a client certificate and got none, as Cloudflare
* does with a 403: the address screen then says so and offers to add one.
* 503 while TREK restarts). A 4xx page is not TREK's, which serves its UI for
* every path: a proxy that asked this page for a client certificate and got
* none, as Cloudflare does with a 403, sends the app to the address screen,
* which says so and offers to add one. Any other 4xx page (a proxy's block
* page, a certificate it refused) stays up with the bar and its way out, so
* the app is never stuck on a page without TREK's UI.
*/
@Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
@@ -143,10 +193,22 @@ class TrekWebViewClient extends BridgeWebViewClient {
if (!request.isForMainFrame()) {
super.onReceivedHttpError(view, request, errorResponse);
} else if (status >= 500 || (status >= 400 && wantedCertificate(request.getUrl()))) {
TrekServerStore.setFailure(view.getContext(), "HTTP " + status);
onUnreachable.run();
} else if (status >= 400) {
errorPageUrl = request.getUrl().toString();
onErrorPage.accept(true);
}
}
private static boolean isNetworkError(int code) {
return code == WebViewClient.ERROR_HOST_LOOKUP
|| code == WebViewClient.ERROR_CONNECT
|| code == WebViewClient.ERROR_TIMEOUT
|| code == WebViewClient.ERROR_IO
|| code == WebViewClient.ERROR_UNKNOWN;
}
private static boolean wantedCertificate(Uri url) {
TrekClientIdentity.Request asked = TrekClientIdentity.INSTANCE.getLastRequest();
return asked != null && !asked.getServed() && TrekClientIdentity.matches(asked.getHost(), asked.getPort(), url.getHost(), url.getPort());
@@ -119,23 +119,38 @@ object TrekBilling {
val id = call.getString("productId") ?: return call.reject("productId is required")
ready(activity) { ok ->
if (!ok) return@ready call.resolve(JSObject().put("kind", "failed"))
details(activity, listOf(id)) { found ->
val product = found.firstOrNull()
val offer = product?.let(::baseOffer)
if (product == null || offer == null) return@details call.resolve(JSObject().put("kind", "failed"))
pendingPurchase?.resolve(JSObject().put("kind", "cancelled"))
pendingPurchase = call
pendingProduct = id
val params = BillingFlowParams.newBuilder()
.setProductDetailsParamsList(
listOf(BillingFlowParams.ProductDetailsParams.newBuilder().setProductDetails(product).setOfferToken(offer.offerToken).build()),
)
.build()
activity.runOnUiThread {
val launch = client(activity).launchBillingFlow(activity, params)
if (launch.responseCode != BillingClient.BillingResponseCode.OK) {
settle(if (launch.responseCode == BillingClient.BillingResponseCode.USER_CANCELED) "cancelled" else "failed", null)
}
// One subscription per Google account: a second plan would run beside the first.
// A delivered one stops the purchase here; one that was paid but never set up is
// handed back as bought, so its instance is set up now.
val params = QueryPurchasesParams.newBuilder().setProductType(BillingClient.ProductType.SUBS).build()
client(activity).queryPurchasesAsync(params) { result, purchases ->
val held = if (result.responseCode == BillingClient.BillingResponseCode.OK) newest(purchases, PREFIX) else null
when {
held == null -> launchPurchase(activity, call, id)
held.isAcknowledged -> call.resolve(JSObject().put("kind", "subscribed"))
else -> call.resolve(receipt(held).put("kind", "bought"))
}
}
}
}
private fun launchPurchase(activity: Activity, call: PluginCall, id: String) {
details(activity, listOf(id)) { found ->
val product = found.firstOrNull()
val offer = product?.let(::baseOffer)
if (product == null || offer == null) return@details call.resolve(JSObject().put("kind", "failed"))
pendingPurchase?.resolve(JSObject().put("kind", "cancelled"))
pendingPurchase = call
pendingProduct = id
val params = BillingFlowParams.newBuilder()
.setProductDetailsParamsList(
listOf(BillingFlowParams.ProductDetailsParams.newBuilder().setProductDetails(product).setOfferToken(offer.offerToken).build()),
)
.build()
activity.runOnUiThread {
val launch = client(activity).launchBillingFlow(activity, params)
if (launch.responseCode != BillingClient.BillingResponseCode.OK) {
settle(if (launch.responseCode == BillingClient.BillingResponseCode.USER_CANCELED) "cancelled" else "failed", null)
}
}
}
@@ -208,6 +223,19 @@ object TrekBilling {
}
}
/** Whether this Google account holds a delivered subscription under `prefix`; while one runs, the shell offers no purchase. */
fun held(context: Context, call: PluginCall) {
val prefix = call.getString("prefix") ?: PREFIX
ready(context) { ok ->
if (!ok) return@ready call.resolve(JSObject().put("held", false))
val params = QueryPurchasesParams.newBuilder().setProductType(BillingClient.ProductType.SUBS).build()
client(context).queryPurchasesAsync(params) { result, purchases ->
val found = if (result.responseCode == BillingClient.BillingResponseCode.OK) newest(purchases, prefix) else null
call.resolve(JSObject().put("held", found?.isAcknowledged == true))
}
}
}
/** The newest active subscription under `prefix` on this Google account, if any. */
fun restore(context: Context, call: PluginCall) {
val prefix = call.getString("prefix") ?: "cloud."
+18
View File
@@ -0,0 +1,18 @@
// The chunk group that holds the lucide icons the app loads at startup (vite.config.js).
//
// Every lucide icon is a module of its own, and the plugin icon lookup
// (src/components/shared/PluginIcon.tsx) reaches all of them by name, from the navigation
// every page renders. Left to itself the bundler puts each icon that some other chunk
// also uses into a chunk of its own, so that neither side holds a copy: 187 files of a few
// hundred bytes each, every one a request of its own on a first visit and an entry of its
// own in the service worker's precache. In one group they are one file, whose hash changes
// only when lucide-react does.
//
// `tags: ['$initial']` for the reason the other groups carry it: without it the group would
// also take icons that today sit behind a lazy route and make them part of the first load.
export const ICON_CHUNK = {
name: 'vendor-icons',
priority: 20,
tags: ['$initial'],
test: /[\\/]node_modules[\\/]lucide-react[\\/]/,
};
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<string>TREK</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
+149 -10
View File
@@ -41,6 +41,8 @@ class TrekBridgeViewController: CAPBridgeViewController {
// reachable" with a server that was there all along.
if let webView, let inner = webView.navigationDelegate {
let proxy = TrekNavigationProxy(inner: inner)
proxy.onErrorPage = { [weak self] error in self?.errorPageChanged(error) }
proxy.onPageShown = { [weak self] in self?.publishSafeArea(force: true) }
navigationProxy = proxy
webView.navigationDelegate = proxy
}
@@ -55,6 +57,79 @@ class TrekBridgeViewController: CAPBridgeViewController {
// A long press on a link would lift a preview of the page it points to,
// which no native list does; the press means "drag" or nothing here.
webView?.allowsLinkPreview = false
paintBehindWebView()
}
// MARK: - What shows where the web view does not reach
/// The UI reports its theme through StatusBar.setStyle (native/nativeApp.ts),
/// which lands here; the colour behind the web view follows it.
override func setNeedsStatusBarAppearanceUpdate() {
super.setNeedsStatusBarAppearanceUpdate()
paintBehindWebView()
}
/// Some iOS releases (27.0.x) lay the web view out below the status bar
/// instead of under it, and the strip above the page then showed this
/// view's black. It now carries the top colour of the screen background
/// (mobile.css --m-scr), so the strip reads as part of the page on every
/// release, and the rubber band at the ends shows the same colour.
private func paintBehindWebView() {
let dark: Bool
switch preferredStatusBarStyle {
case .lightContent: dark = true
case .darkContent: dark = false
default: dark = traitCollection.userInterfaceStyle == .dark
}
let color = dark
? UIColor(red: 0x17 / 255, green: 0x17 / 255, blue: 0x1C / 255, alpha: 1)
: UIColor(red: 0xFB / 255, green: 0xFA / 255, blue: 0xF7 / 255, alpha: 1)
view.backgroundColor = color
webView?.scrollView.backgroundColor = color
webView?.underPageBackgroundColor = color
}
// MARK: - The safe area the page keeps clear of
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
publishSafeArea()
}
override func viewSafeAreaInsetsDidChange() {
super.viewSafeAreaInsetsDidChange()
publishSafeArea()
}
private var publishedSafeArea: UIEdgeInsets?
/// WebKit's env(safe-area-inset-*) is the window's safe area only where the
/// web view overlaps it. Where a release lays the web view out below the
/// status bar it reports 0, yet a camera in a corner can still reach into
/// the page. The part of the window's safe area (and of the status bar) that
/// falls inside the web view goes to the page as --trek-native-safe-*, which
/// mobile.css takes as a floor under env(), never in its place.
func publishSafeArea(force: Bool = false) {
guard let webView, let window = view.window else { return }
let frame = webView.convert(webView.bounds, to: window)
let safe = window.safeAreaInsets
let statusBar = window.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
let insets = UIEdgeInsets(
top: max(0, max(safe.top, statusBar) - frame.minY),
left: max(0, safe.left - frame.minX),
bottom: max(0, safe.bottom - (window.bounds.maxY - frame.maxY)),
right: max(0, safe.right - (window.bounds.maxX - frame.maxX))
)
if !force, insets == publishedSafeArea { return }
publishedSafeArea = insets
let px = { (v: CGFloat) in "'\(Int(v.rounded(.up)))px'" }
let js = "(function(s){"
+ "s.setProperty('--trek-native-safe-top',\(px(insets.top)));"
+ "s.setProperty('--trek-native-safe-left',\(px(insets.left)));"
+ "s.setProperty('--trek-native-safe-right',\(px(insets.right)));"
+ "s.setProperty('--trek-native-safe-bottom',\(px(insets.bottom)));"
+ "})(document.documentElement.style)"
webView.evaluateJavaScript(js, completionHandler: nil)
}
// MARK: - A proxy's sign-in page
@@ -68,6 +143,10 @@ class TrekBridgeViewController: CAPBridgeViewController {
private var urlObservation: NSKeyValueObservation?
private var insetObservation: NSKeyValueObservation?
private var onSignInPage = false
/// Whether the main frame shows an error page in place of the server's (a 4xx
/// nobody else handled: a proxy's block page, a client certificate it refused).
private var onErrorPage = false
private var signInHint: UILabel?
private var keyboardUp = false
/// How far the keyboard reaches into the view while it is up.
private var keyboardRoom: CGFloat = 0
@@ -97,9 +176,20 @@ class TrekBridgeViewController: CAPBridgeViewController {
updateSignInBar()
}
private func errorPageChanged(_ error: Bool) {
onErrorPage = error
if error && signInBar == nil { signInBar = makeSignInBar() }
updateSignInBar()
}
/// Out of the way while the keyboard is up: the form needs the room.
private func updateSignInBar() {
signInBar?.isHidden = !(onSignInPage && !keyboardUp)
let labels = TrekServerStore.labels
signInHint?.text = onSignInPage
? labels["signInHint"]
?? "Passkeys and security keys do not work on this page in the app. Sign in with a password, or let the app through your proxy."
: labels["errorPageHint"] ?? "This page is not from TREK: the server or a proxy in front of it refused the app. Check your proxy or certificate, or change the server."
signInBar?.isHidden = !((onSignInPage || onErrorPage) && !keyboardUp)
applyInset()
}
@@ -108,7 +198,7 @@ class TrekBridgeViewController: CAPBridgeViewController {
private func applyInset() {
guard let scrollView = webView?.scrollView else { return }
let wanted: CGFloat
if onSignInPage {
if onSignInPage || onErrorPage {
if keyboardUp {
wanted = keyboardRoom
} else if let bar = signInBar {
@@ -159,24 +249,38 @@ class TrekBridgeViewController: CAPBridgeViewController {
private func makeSignInBar() -> UIView {
let labels = TrekServerStore.labels
// The look of the app's own first screens: a white card with a sand edge,
// warm grey text and a dark button, over whatever page the proxy shows.
let bar = UIView()
bar.backgroundColor = UIColor(red: 17 / 255, green: 24 / 255, blue: 39 / 255, alpha: 0.95)
bar.layer.cornerRadius = 16
bar.backgroundColor = UIColor(white: 1, alpha: 0.97)
bar.layer.cornerRadius = 18
bar.layer.cornerCurve = .continuous
bar.layer.borderWidth = 1
bar.layer.borderColor = UIColor(red: 0xEF / 255, green: 0xE4 / 255, blue: 0xD8 / 255, alpha: 1).cgColor
bar.layer.shadowColor = UIColor(red: 0x1F / 255, green: 0x1A / 255, blue: 0x17 / 255, alpha: 1).cgColor
bar.layer.shadowOpacity = 0.18
bar.layer.shadowRadius = 18
bar.layer.shadowOffset = CGSize(width: 0, height: 10)
bar.translatesAutoresizingMaskIntoConstraints = false
let hint = UILabel()
hint.text = labels["signInHint"]
?? "Passkeys and security keys do not work on this page in the app. Sign in with a password, or let the app through your proxy."
hint.textColor = UIColor(white: 0.9, alpha: 1)
hint.textColor = UIColor(red: 0x6B / 255, green: 0x5F / 255, blue: 0x57 / 255, alpha: 1)
hint.font = .preferredFont(forTextStyle: .footnote)
hint.adjustsFontForContentSizeCategory = true
hint.numberOfLines = 0
signInHint = hint
hint.translatesAutoresizingMaskIntoConstraints = false
let change = UIButton(type: .system)
var look = UIButton.Configuration.filled()
look.baseBackgroundColor = UIColor(red: 0x11 / 255, green: 0x18 / 255, blue: 0x27 / 255, alpha: 1)
look.baseForegroundColor = .white
look.cornerStyle = .fixed
look.background.cornerRadius = 12
look.contentInsets = NSDirectionalEdgeInsets(top: 9, leading: 14, bottom: 9, trailing: 14)
let change = UIButton(configuration: look)
change.setTitle(labels["changeServer"] ?? "Change server", for: .normal)
change.setTitleColor(.white, for: .normal)
change.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold)
change.addTarget(self, action: #selector(changeServerFromSignIn), for: .touchUpInside)
change.translatesAutoresizingMaskIntoConstraints = false
@@ -308,6 +412,22 @@ enum TrekKeyCommands {
enum TrekServerStore {
private static let key = "TrekServerURL"
private static let failureKey = "TrekLastFailure"
/// Why the server's page did not load ("NSURLErrorDomain -1003"): the
/// address screen shows it small under its message, so a report carries
/// the cause. Taken once.
static func noteFailure(_ error: Error) {
let ns = error as NSError
UserDefaults.standard.set("\(ns.domain) \(ns.code)", forKey: failureKey)
}
static func takeFailure() -> String? {
let failure = UserDefaults.standard.string(forKey: failureKey)
UserDefaults.standard.removeObject(forKey: failureKey)
return failure
}
private static let previousKey = "TrekPreviousServerURL"
private static let checkedKey = "TrekServerCheck"
@@ -326,7 +446,7 @@ enum TrekServerStore {
/// A server remembered under a lower value is checked once more: the first
/// launch after an update that raised it puts the address screen back up,
/// filled in with that server (previousURL). Raise both together.
private static let serverCheck = 2
private static let serverCheck = 3
/// Runs before the first bridge is built, so a server picked under an older
/// minimum is not loaded unchecked.
@@ -665,6 +785,10 @@ final class TrekNavigationProxy: NSObject, WKNavigationDelegate {
private let inner: WKNavigationDelegate
/// A page of the server has shown since launch; from then on no sign-in host is learned (TrekSignInRedirect).
private var serverShown = false
/// Told on the main thread whether the main frame now shows an error page in place of the server's.
var onErrorPage: ((Bool) -> Void)?
/// Told when a page has finished loading: a new document starts without the safe area the controller handed the last one.
var onPageShown: (() -> Void)?
init(inner: WKNavigationDelegate) {
self.inner = inner
@@ -717,7 +841,12 @@ final class TrekNavigationProxy: NSObject, WKNavigationDelegate {
/// page once (TrekServerStore.takeWelcomeURL); it is on the server's origin.
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
inner.webView?(webView, didFinish: navigation)
if TrekSignInRedirect.onServer(server: TrekServerStore.url, url: webView.url) { serverShown = true }
onPageShown?()
if TrekSignInRedirect.onServer(server: TrekServerStore.url, url: webView.url) {
serverShown = true
// The server's page is up: an earlier failure is no cause any more.
_ = TrekServerStore.takeFailure()
}
if let welcome = TrekServerStore.takeWelcomeURL() {
webView.load(URLRequest(url: welcome))
}
@@ -733,6 +862,7 @@ final class TrekNavigationProxy: NSObject, WKNavigationDelegate {
TrekClientCertWatch.serverAsked(host: space.host, port: space.port) { [weak self, weak webView] in
guard let self, let webView else { return }
// Capacitor's own answer to a failed load: the address screen (errorPath).
TrekServerStore.noteFailure(URLError(.clientCertificateRejected))
self.inner.webView?(webView, didFailProvisionalNavigation: nil, withError: URLError(.clientCertificateRejected))
}
return
@@ -748,16 +878,23 @@ final class TrekNavigationProxy: NSObject, WKNavigationDelegate {
/// A proxy that asked the page for a client certificate, got none and
/// answered with its own refusal (Cloudflare's 403, nginx's 400) sends the
/// app to the address screen, which says so and offers to add one, rather
/// than leaving the proxy's error page up.
/// than leaving the proxy's error page up. Any other 4xx page is not TREK's,
/// which serves its UI for every path (a proxy's block page, a certificate it
/// refused): it stays up with the bar and its way out to another server.
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse,
decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
if navigationResponse.isForMainFrame, let http = navigationResponse.response as? HTTPURLResponse,
http.statusCode >= 400, http.statusCode < 500, let asked = TrekClientIdentity.lastRequest, !asked.served,
let url = http.url, url.host?.lowercased() == asked.host, (url.port ?? 443) == asked.port {
decisionHandler(.cancel)
TrekServerStore.noteFailure(URLError(.clientCertificateRequired))
inner.webView?(webView, didFailProvisionalNavigation: nil, withError: URLError(.clientCertificateRequired))
return
}
if navigationResponse.isForMainFrame, let http = navigationResponse.response as? HTTPURLResponse {
let error = http.statusCode >= 400 && http.statusCode < 500
DispatchQueue.main.async { [weak self] in self?.onErrorPage?(error) }
}
let selector = NSSelectorFromString("webView:decidePolicyForNavigationResponse:decisionHandler:")
guard (inner as AnyObject).responds(to: selector) else {
decisionHandler(.allow)
@@ -768,11 +905,13 @@ final class TrekNavigationProxy: NSObject, WKNavigationDelegate {
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
if Self.isReplaced(error) { return }
TrekServerStore.noteFailure(error)
inner.webView?(webView, didFail: navigation, withError: error)
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
if Self.isReplaced(error) { return }
TrekServerStore.noteFailure(error)
inner.webView?(webView, didFailProvisionalNavigation: navigation, withError: error)
}
}
+40 -4
View File
@@ -46,6 +46,7 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
CAPPluginMethod(name: "storePurchase", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "storeFinish", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "storeRestore", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "storeHeld", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "addToWallet", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "setWatchSnapshot", returnType: CAPPluginReturnPromise),
CAPPluginMethod(name: "takeWatchActions", returnType: CAPPluginReturnPromise),
@@ -351,6 +352,7 @@ public class TrekShellPlugin: CAPPlugin, CAPBridgedPlugin, ASWebAuthenticationPr
call.resolve([
"url": TrekServerStore.url ?? NSNull(),
"previousUrl": TrekServerStore.previousURL ?? NSNull(),
"failure": TrekServerStore.takeFailure() ?? NSNull(),
])
}
@@ -679,6 +681,17 @@ extension TrekShellPlugin {
return
}
Task {
// One subscription per Apple ID: another plan would change it, not add one.
// A held one that was delivered stops the purchase here. One that was paid
// but never set up is handed back as bought, so its instance is set up now.
if let held = await TrekStore.currentEntitlement(prefix: "cloud.") {
if await TrekStore.isUnfinished(held.id) {
call.resolve(["kind": "bought", "jws": held.jws, "transactionId": String(held.id), "productId": held.productId])
} else {
call.resolve(["kind": "subscribed"])
}
return
}
do {
guard let product = try await Product.products(for: [id]).first else {
call.resolve(["kind": "failed"])
@@ -735,6 +748,21 @@ extension TrekShellPlugin {
call.resolve(["jws": found.jws, "transactionId": String(found.id)])
}
}
/// Feature storeKit: whether this Apple ID holds a delivered subscription under
/// `prefix`. Read from the entitlements on the device, so no password is asked;
/// while one runs, the shell offers no purchase.
@objc func storeHeld(_ call: CAPPluginCall) {
let prefix = call.getString("prefix") ?? "cloud."
Task {
guard let held = await TrekStore.currentEntitlement(prefix: prefix) else {
call.resolve(["held": false])
return
}
let unfinished = await TrekStore.isUnfinished(held.id)
call.resolve(["held": !unfinished])
}
}
}
enum TrekStore {
@@ -765,17 +793,25 @@ enum TrekStore {
}
}
static func currentEntitlement(prefix: String) async -> (jws: String, id: UInt64)? {
var newest: (date: Date, jws: String, id: UInt64)?
static func currentEntitlement(prefix: String) async -> (jws: String, id: UInt64, productId: String)? {
var newest: (date: Date, jws: String, id: UInt64, productId: String)?
for await result in Transaction.currentEntitlements {
guard case .verified(let transaction) = result,
transaction.productID.hasPrefix(prefix),
transaction.revocationDate == nil else { continue }
if newest == nil || transaction.purchaseDate > newest!.date {
newest = (transaction.purchaseDate, result.jwsRepresentation, transaction.id)
newest = (transaction.purchaseDate, result.jwsRepresentation, transaction.id, transaction.productID)
}
}
return newest.map { ($0.jws, $0.id) }
return newest.map { (jws: $0.jws, id: $0.id, productId: $0.productId) }
}
/// Paid but not delivered yet: the shell finishes a transaction once its instance exists.
static func isUnfinished(_ id: UInt64) async -> Bool {
for await result in Transaction.unfinished {
if case .verified(let transaction) = result, transaction.id == id { return true }
}
return false
}
}
+43
View File
@@ -0,0 +1,43 @@
/**
* The amount inside a price as the store writes it ("4,90 €", "$4.99",
* "CHF 12.90", "1.290 ₽"), and a way to write another amount the same way: the
* same currency, the same decimal mark, the same digit grouping. The plan picker
* counts a price up to its new value with it, and turns a yearly price into what
* it makes a month, without knowing the store's locale.
*/
interface Amount {
/** The amount as a number, in the price's own unit (4.9 for "4,90 €"). */
value: number;
/** The price written for another amount, in the same format. */
render(value: number): string;
}
// Digits with the marks stores put between them: . , any space (\s takes the
// no-break ones too) and the apostrophes Swiss formats group thousands with.
const NUMBER = /\d[\d.,\s'’]*\d|\d/;
export function amountIn(label: string): Amount | null {
const match = NUMBER.exec(label);
if (!match) return null;
const raw = match[0];
// The decimal mark is the last . or , followed by one or two digits to the end.
const decimal = /([.,])(\d{1,2})$/.exec(raw);
const decimals = decimal ? decimal[2].length : 0;
const mark = decimal ? decimal[1] : '';
const whole = decimal ? raw.slice(0, raw.length - decimal[0].length) : raw;
const group = /[.,\s'’]/.exec(whole)?.[0] ?? '';
const digits = whole.replace(/\D/g, '') + (decimal ? `.${decimal[2]}` : '');
const value = Number(digits);
if (!Number.isFinite(value)) return null;
const before = label.slice(0, match.index);
const after = label.slice(match.index + raw.length);
return {
value,
render(next: number) {
const fixed = Math.max(0, next).toFixed(decimals);
const [int, frac] = fixed.split('.');
const grouped = group ? int.replace(/\B(?=(\d{3})+(?!\d))/g, group) : int;
return `${before}${grouped}${frac !== undefined ? mark + frac : ''}${after}`;
},
};
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

+2 -2
View File
@@ -3,8 +3,8 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover" />
<meta name="color-scheme" content="dark light" />
<meta name="theme-color" content="#09090b" />
<meta name="color-scheme" content="light" />
<meta name="theme-color" content="#fffaf5" />
<title>TREK</title>
</head>
<body>
+1005 -541
View File
File diff suppressed because it is too large Load Diff
+585
View File
@@ -0,0 +1,585 @@
/**
* The landscape behind the first screens of the app: one world seen from above,
* an island out at sea, the coast with its town, the farmland behind it and the
* mountains at the back. A fragment shader draws it every frame (water, surf,
* boats, a car on the road), so it is never a photo and never the same twice.
*
* The plan picker moves the camera through that world, one place per plan, so
* choosing reads as travelling further inland. The scenes are framed for a phone
* 390 px wide: a wider or taller box (iPad, an unfolded phone) shows more of the
* world around the same centre.
*
* Kept light for the phone it runs on: the device pixel ratio is capped at 2,
* the picture drops to a lower resolution when frames come slow, the loop stops
* while the app is in the background or the canvas has left the page, and with
* reduced motion it is one still frame. Without WebGL the box keeps its plain
* sea colour from the stylesheet.
*/
/** Where the camera stands for a place, in world pixels, for a 390 px frame. */
export type Camera = readonly [number, number];
export const WELCOME_CAMERA: Camera = [0, 0];
/** One place per plan, in the order the plans come: island, coast, farmland, mountains. */
const PLAN_CAMERAS: readonly Camera[] = [
[62, -392],
[0, 24],
[60, 290],
[70, 660],
];
export function cameraForPlan(index: number): Camera {
return PLAN_CAMERAS[Math.max(0, Math.min(PLAN_CAMERAS.length - 1, index))];
}
const FRAME_WIDTH = 390;
const FRAGMENT = `
precision highp float;
uniform vec2 uRes; uniform float uDpr; uniform float uT; uniform vec2 uCam; uniform float uHaze;
float coast(float x) { return 128.0 + 12.0 * sin(x * 0.018 + 0.6) + 7.0 * sin(x * 0.051 + 2.1) + 4.0 * sin(x * 0.11); }
float riverX(float y) { return 168.0 - (y - 120.0) * 0.30 + 9.0 * sin(y * 0.035 + 0.8) + 4.0 * sin(y * 0.09); }
float hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
vec2 hash2(vec2 p) { return fract(sin(vec2(dot(p, vec2(127.1, 311.7)), dot(p, vec2(269.5, 183.3)))) * 43758.5453); }
float noise(vec2 p) { vec2 i = floor(p), f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f);
return mix(mix(hash(i), hash(i + vec2(1, 0)), u.x), mix(hash(i + vec2(0, 1)), hash(i + vec2(1, 1)), u.x), u.y); }
float fbm(vec2 p) { float v = 0.0, a = 0.5; for (int i = 0; i < 5; i++) { v += a * noise(p); p = p * 2.03 + vec2(1.7, 9.2); a *= 0.5; } return v; }
float fbm3(vec2 p) { float v = 0.0, a = 0.5; for (int i = 0; i < 3; i++) { v += a * noise(p); p = p * 2.03 + vec2(1.7, 9.2); a *= 0.5; } return v; }
float wave(vec2 p, float t) {
return 0.55 * sin(dot(p, vec2(0.040, 0.085)) - t * 1.10) + 0.35 * sin(dot(p, vec2(-0.070, 0.050)) - t * 1.45)
+ 0.22 * sin(dot(p, vec2(0.110, 0.130)) - t * 2.10) + 0.12 * sin(dot(p, vec2(-0.170, 0.190)) - t * 2.90)
+ 0.90 * fbm(p * 0.055 + vec2(t * 0.18, t * 0.32));
}
float ridged(vec2 p) { float v = 0.0, a = 0.5; for (int i = 0; i < 5; i++) { float n = 1.0 - abs(noise(p) * 2.0 - 1.0); v += a * n * n; p = p * 2.07 + vec2(3.1, 1.7); a *= 0.5; } return v; }
/* Height: gentle near the shore, sharp ridges further inland. */
float peaks(vec2 p) { float v = 0.0, a = 0.55; for (int i = 0; i < 7; i++) { v += a * (1.0 - abs(noise(p) * 2.0 - 1.0)); p = p * 2.13 + vec2(1.3, 4.7); a *= 0.5; } return v; }
float ground(vec2 p) {
float inland = smoothstep(10.0, 170.0, p.y - coast(p.x));
return fbm(p * 0.011) * 0.4 + ridged(p * 0.014 + 5.0) * 1.15 * inland + fbm3(p * 0.06) * 0.08;
}
/* The island out at sea: signed distance to its shore in px (> 0 on land),
a round main body with an uneven coast and a headland to the east. */
float islD(vec2 p) {
vec2 q = (p - vec2(230.0, -250.0)) / vec2(1.5, 1.0);
float r = length(q);
float rad = 66.0 + 46.0 * (fbm(q * 0.016 + 4.0) - 0.5) + 30.0 * (fbm(q * 0.045 + 8.0) - 0.5) + 10.0 * (fbm(p * 0.09) - 0.5);
vec2 q2 = (p - vec2(372.0, -222.0)) / vec2(1.6, 1.0);
float head = 15.0 + 10.0 * (fbm(p * 0.04 + 9.0) - 0.5) - length(q2);
return max(rad - r, head);
}
float islH(vec2 p) {
float s = islD(p);
return smoothstep(0.0, 60.0, s) * (0.5 + 0.7 * fbm(p * 0.018 + 2.0)) + ridged(p * 0.03) * 0.22 * smoothstep(8.0, 50.0, s);
}
/* Trees: one per cell at most, a round crown of varying size. Returns the
crown's cover (0..1) and how far from its centre, for the shading. */
vec3 tree(vec2 p, float cell) {
vec2 c = floor(p / cell);
float best = 9.0; vec2 off = vec2(0.0); float sz = 0.0;
for (int j = -1; j <= 1; j++) for (int i = -1; i <= 1; i++) {
vec2 g = c + vec2(float(i), float(j));
vec2 h = hash2(g);
vec2 o = (g + 0.15 + 0.7 * h) * cell;
float r = cell * (0.38 + 0.22 * hash(g + 3.1));
float d = length(p - o) / r;
if (d < best) { best = d; off = (p - o) / r; sz = r; }
}
return vec3(1.0 - smoothstep(0.86, 1.0, best), off);
}
/* A Mediterranean town: one house per cell, a rectangle turned the way
the lane runs there (the direction drifts across town, so lanes curve),
sized at random and packed close. Whitewashed cubes with a parapet and
now and then a water tank, pastel walls, terracotta roofs pitched along
the long side, and the odd blue dome. */
float town(vec2 p, out vec3 roof, out vec2 hid) {
float cell = 9.0;
vec2 c = floor(p / cell);
roof = vec3(0.0);
hid = c;
float got = 0.0;
for (int j = -1; j <= 1; j++) for (int i = -1; i <= 1; i++) {
vec2 g = c + vec2(float(i), float(j));
if (hash(g + 2.7) < 0.07) continue;
vec2 o = (g + 0.5 + 0.35 * (hash2(g) - 0.5)) * cell;
float ang = (noise(o * 0.018) - 0.5) * 2.4 + (hash(g + 7.7) - 0.5) * 0.25;
vec2 cs = vec2(cos(ang), sin(ang));
vec2 rel = p - o;
vec2 l = vec2(dot(rel, cs), dot(rel, vec2(-cs.y, cs.x)));
vec2 hs = cell * vec2(0.36 + 0.16 * hash(g + 1.3), 0.27 + 0.14 * hash(g + 4.1));
if (abs(l.x) < hs.x && abs(l.y) < hs.y) {
float k = hash(g + 5.3);
vec3 col = k < 0.44 ? vec3(0.96, 0.95, 0.91) : k < 0.68 ? vec3(0.80, 0.46, 0.32) : k < 0.80 ? vec3(0.93, 0.79, 0.56) : k < 0.90 ? vec3(0.94, 0.75, 0.67) : vec3(0.88, 0.86, 0.80);
float rim = min(hs.x - abs(l.x), hs.y - abs(l.y));
if (k >= 0.44 && k < 0.68) {
// pitched roof: the ridge runs along the long side, one slope lit, one shaded
float lit = dot(vec2(-cs.y, cs.x), vec2(-0.67, -0.73)) * sign(l.y);
col *= lit > 0.0 ? 1.08 : 0.80;
col *= 0.95 + 0.05 * sin(l.x * 3.6);
col *= 1.0 - 0.25 * (1.0 - smoothstep(0.0, 0.5, abs(l.y)));
} else {
// flat roof: a parapet round the edge, a water tank on some
col *= 1.0 - 0.13 * (1.0 - smoothstep(0.4, 1.1, rim));
vec2 tk = vec2(hs.x * 0.45, -hs.y * 0.35);
if (hash(g + 6.2) < 0.35 && length(l - tk) < 0.95) col = vec3(0.45, 0.47, 0.50) + 0.25 * step(0.0, -(l - tk).x - (l - tk).y);
if (k < 0.44 && hash(g + 4.4) < 0.08 && length(l) < min(hs.x, hs.y) * 0.85) {
col = mix(vec3(0.12, 0.30, 0.64), vec3(0.58, 0.76, 0.98), clamp(0.55 - dot(rel / (min(hs.x, hs.y) * 0.85), vec2(-0.67, -0.73)) * 0.6, 0.0, 1.0));
}
}
col *= 0.93 + 0.1 * hash(g + 9.9);
roof = col;
hid = g;
got = 1.0;
}
}
return got;
}
void main() {
vec2 sp = vec2(gl_FragCoord.x, uRes.y - gl_FragCoord.y) / uDpr;
vec2 p = sp + uCam;
float t = uT;
vec3 L = normalize(vec3(-0.55, -0.6, 0.62));
float d = coast(p.x) - p.y; // > 0 at sea, < 0 inland, in px
float wash = 6.0 + 4.0 * sin(t * 1.2 + p.x * 0.045) + 3.0 * fbm3(vec2(p.x * 0.08, t * 0.6));
vec3 col;
if (d > -2.0) {
/* ── sea ── */
float e = 0.9, h = wave(p, t);
vec3 n = normalize(vec3(-(wave(p + vec2(e, 0.0), t) - h) * 1.6, -(wave(p + vec2(0.0, e), t) - h) * 1.6, 1.0));
float depth = smoothstep(0.0, 120.0, d);
col = mix(vec3(0.47, 0.83, 0.82), vec3(0.17, 0.58, 0.72), smoothstep(0.0, 0.45, depth));
col = mix(col, vec3(0.07, 0.33, 0.55), smoothstep(0.45, 1.0, depth));
col *= 0.78 + 0.32 * clamp(dot(n, -vec3(L.x, L.y, -L.z)), 0.0, 1.0);
vec3 Ls = normalize(vec3(0.45, -0.55, 0.70));
vec3 R = reflect(-Ls, n);
col += vec3(1.0, 0.97, 0.9) * (pow(clamp(R.z, 0.0, 1.0), 90.0) * 0.45 + pow(clamp(R.z, 0.0, 1.0), 900.0) * step(0.55, noise(p * 0.6 + t * 2.0)) * 1.4);
float ca = pow(1.0 - abs(sin(fbm(p * 0.09 + vec2(t * 0.35, -t * 0.25)) * 9.0)), 6.0);
col += vec3(0.85, 1.0, 0.95) * ca * 0.22 * (1.0 - smoothstep(0.0, 40.0, d));
float runs = smoothstep(0.82, 1.0, sin(d * 0.32 + t * 2.2 + fbm3(p * 0.05) * 3.0)) * (1.0 - smoothstep(6.0, 46.0, d));
float lace = smoothstep(0.45, 0.75, fbm3(p * 0.22 + vec2(t * 0.5, 0.0)));
float foam = max(1.0 - smoothstep(wash - 4.0, wash + 3.0, d), runs * lace * 0.8);
col = mix(col, vec3(0.97, 0.99, 1.0), clamp(foam, 0.0, 1.0) * 0.92);
// boats crossing, each in a lane of its own (46 px apart, wider than any
// wake), at a speed that swells and eases but never turns back
for (int k = 0; k < 2; k++) {
float fk = float(k);
float dir = fk < 0.5 ? 1.0 : -1.0;
float speed = 10.0 + fk * 4.0;
float run = speed * t + 14.0 * sin(t * 0.23 + fk * 2.0) + 6.0 * sin(t * 0.61 + fk * 4.0);
float lane = 36.0 + fk * 46.0;
float drift = 2.6 * sin(t * 0.31 + fk * 1.7);
vec2 bp = vec2(mod(fk * 190.0 + run * dir, 480.0) - 45.0, lane + drift);
float yaw = 2.6 * 0.31 * cos(t * 0.31 + fk * 1.7) / speed;
vec2 q = p - bp;
q = vec2(q.x * dir, q.y);
q = vec2(q.x + yaw * q.y, q.y - yaw * q.x);
float back = -q.x;
float open = 0.29 + 0.05 * sin(t * 1.3 + fk * 3.0 + back * 0.05);
float spread = back * open;
float churn = smoothstep(0.25, 0.65, noise(vec2(back * 0.35 - t * 1.6, q.y * 0.45 + fk * 7.0)));
float edgeW = 0.7 + 0.8 * noise(vec2(back * 0.2 + fk * 3.0, t * 0.8));
float fade = step(0.0, back) * (1.0 - smoothstep(8.0, 64.0, back));
float wake = (1.0 - smoothstep(edgeW * 0.6, edgeW * 1.8, abs(abs(q.y) - spread))) * fade * (0.55 + 0.45 * churn);
wake += (1.0 - smoothstep(0.0, 2.4, abs(q.y))) * step(0.0, back) * (1.0 - smoothstep(4.0, 30.0, back)) * 0.7 * churn;
col = mix(col, vec3(0.96, 0.98, 1.0), clamp(wake, 0.0, 1.0) * 0.78);
float hull = length(q / vec2(6.5, 2.4));
col = mix(col, vec3(0.20, 0.30, 0.40), (1.0 - smoothstep(1.0, 1.5, length((q - vec2(-1.0, 1.4)) / vec2(6.5, 2.4)))) * 0.25);
col = mix(col, mix(vec3(0.98), vec3(0.80, 0.82, 0.85), step(0.0, q.y)), 1.0 - smoothstep(0.92, 1.0, hull));
col = mix(col, vec3(0.55, 0.36, 0.24), 1.0 - smoothstep(0.9, 1.0, length((q - vec2(-1.0, 0.0)) / vec2(2.4, 1.2))));
}
// the island: a shelf of shallow water, a reef, surf, a beach, a wooded hill
if (abs(p.y + 250.0) < 175.0 && abs(p.x - 265.0) < 310.0) {
float sI = islD(p);
if (sI < 0.0) {
float sd = -sI;
float shelf = 1.0 - smoothstep(4.0, 78.0, sd);
float ripple = 0.5 + 0.5 * sin(dot(p, vec2(0.42, 0.25)) + fbm(p * 0.05) * 6.0);
vec3 sh = mix(vec3(0.13, 0.52, 0.66), vec3(0.40, 0.83, 0.81), smoothstep(62.0, 10.0, sd));
sh = mix(sh, vec3(0.80, 0.86, 0.74), smoothstep(26.0, 0.0, sd) * 0.4);
sh *= 0.95 + 0.08 * ripple * smoothstep(50.0, 4.0, sd);
float swell = sin(sd * 0.3 + t * 1.8 + fbm3(p * 0.03) * 4.0);
sh *= 1.0 + 0.09 * swell * smoothstep(70.0, 20.0, sd) * smoothstep(0.0, 8.0, sd);
float reef = smoothstep(0.57, 0.68, fbm(p * 0.045 + 13.0)) * smoothstep(12.0, 22.0, sd) * (1.0 - smoothstep(46.0, 60.0, sd));
sh = mix(sh, vec3(0.18, 0.40, 0.42) * (0.82 + 0.3 * noise(p * 0.5)), reef * 0.75);
float lw = 0.85 + 0.3 * clamp(dot(n, -vec3(L.x, L.y, -L.z)), 0.0, 1.0);
col = mix(col, sh * lw, shelf);
float cs = pow(1.0 - abs(sin(fbm(p * 0.12 + vec2(t * 0.4, -t * 0.3)) * 10.0)), 7.0);
col += vec3(0.9, 1.0, 0.95) * cs * 0.24 * smoothstep(45.0, 4.0, sd);
// surf breaking along the reef edge, in pieces
float reefLine = 44.0 + 12.0 * (fbm(p * 0.02 + 5.0) - 0.5);
float brk = (1.0 - smoothstep(0.0, 2.0 + 2.5 * fbm3(p * 0.04 + vec2(t * 0.25, 0.0)), abs(sd - reefLine - 2.5 * sin(t * 0.8 + p.x * 0.03))));
brk *= smoothstep(0.35, 0.62, noise(p * 0.08 + vec2(t * 0.6, 0.0))) * smoothstep(0.42, 0.56, fbm(p * 0.03 + 13.0));
col = mix(col, vec3(0.96, 0.99, 1.0), brk * 0.6);
// waves rolling in, foam lines thinning out as they come, the swash on the sand
float lace2 = smoothstep(0.42, 0.72, fbm3(p * 0.25 + vec2(t * 0.4, 0.0)));
float roll = smoothstep(0.9, 1.0, swell) * (1.0 - smoothstep(5.0, 26.0, sd));
float iw = 4.5 + 3.5 * sin(t * 1.1 + fbm(p * 0.03) * 6.0);
float swash = 1.0 - smoothstep(iw - 3.0, iw + 2.5, sd);
col = mix(col, vec3(0.97, 0.99, 1.0), clamp(max(swash * (0.55 + 0.45 * lace2), roll * lace2 * 0.8), 0.0, 1.0) * 0.9);
} else {
float hI = islH(p);
vec3 nI = normalize(vec3(-(islH(p + vec2(1.0, 0.0)) - hI) * 110.0, -(islH(p + vec2(0.0, 1.0)) - hI) * 110.0, 1.0));
float shI = clamp(dot(nI, normalize(vec3(-L.x, -L.y, L.z))), 0.0, 1.0);
float bwI = 5.0 + 15.0 * fbm(p * 0.03 + 2.0);
vec3 sandI = vec3(0.95, 0.89, 0.74) + (hash(floor(p * 3.0)) - 0.5) * 0.05;
sandI = mix(sandI, vec3(0.76, 0.69, 0.56), (1.0 - smoothstep(0.0, 4.5, sI)) * 0.75);
float big = step(0.55, fbm(p * 0.025 + 6.0));
vec3 tr = big > 0.5 ? tree(p, 8.0) : tree(p, 4.6);
vec3 trS = big > 0.5 ? tree(p - vec2(2.6, 3.0), 8.0) : tree(p - vec2(1.7, 2.0), 4.6);
float lit = clamp(0.62 - dot(tr.yz, vec2(L.x, L.y)) * 0.55, 0.0, 1.0);
float jung = smoothstep(bwI, bwI + 8.0, sI);
vec3 under = mix(vec3(0.46, 0.55, 0.28), vec3(0.28, 0.42, 0.19), noise(p * 0.1)) * (1.0 - 0.35 * trS.x);
vec3 canopy = mix(vec3(0.09, 0.27, 0.12), vec3(0.42, 0.62, 0.28), lit) * (0.9 + 0.2 * noise(p * 2.0));
vec3 landI = mix(sandI, under, jung);
landI *= 1.0 - 0.3 * trS.x * smoothstep(bwI - 4.0, bwI, sI) * (1.0 - jung);
landI = mix(landI, canopy, tr.x * smoothstep(bwI - 3.0, bwI + 5.0, sI) * (0.35 + 0.65 * smoothstep(0.22, 0.36, fbm(p * 0.035 + 1.0))));
// bare rock on the steep top and boulders where the headland meets the sea
float slI = 1.0 - nI.z;
landI = mix(landI, vec3(0.62, 0.58, 0.50) * (0.9 + 0.15 * noise(p * 0.8)), smoothstep(0.7, 0.88, slI) * 0.6);
vec3 bo = tree(p, 4.0);
float blit = clamp(0.6 - dot(bo.yz, vec2(L.x, L.y)) * 0.6, 0.0, 1.0);
vec3 rocks = mix(vec3(0.30, 0.29, 0.27), mix(vec3(0.52, 0.50, 0.46), vec3(0.80, 0.77, 0.71), blit), bo.x);
float rk = smoothstep(0.6, 0.7, fbm(p * 0.05 + 4.0)) * (1.0 - smoothstep(bwI - 2.0, bwI + 4.0, sI));
landI = mix(landI, rocks, rk);
landI *= 0.5 + 0.7 * shI;
col = mix(vec3(0.90, 0.95, 0.93), landI, smoothstep(0.0, 1.4, sI));
}
// a sailboat going round, well outside the reef
float sa = t * 0.06;
vec2 sb = vec2(230.0, -250.0) + vec2(cos(sa) * 1.5, sin(sa)) * 140.0;
vec2 tang = normalize(vec2(-sin(sa) * 1.5, cos(sa)));
vec2 q = p - sb;
q = vec2(dot(q, tang), dot(q, vec2(-tang.y, tang.x)));
float back = -q.x;
float wk = (1.0 - smoothstep(0.5, 1.6, abs(abs(q.y) - back * 0.22))) * step(0.0, back) * (1.0 - smoothstep(6.0, 44.0, back));
col = mix(col, vec3(0.96, 0.98, 1.0), wk * 0.7);
col = mix(col, vec3(0.10, 0.22, 0.32), (1.0 - smoothstep(1.0, 1.4, length((q - vec2(-1.5, 2.6)) / vec2(5.0, 3.0)))) * 0.25);
col = mix(col, vec3(0.98), 1.0 - smoothstep(0.9, 1.0, length(q / vec2(4.8, 1.7))));
float sail = max(abs(q.x + 0.4) - 2.6, abs(q.y + 1.2 - (q.x + 0.4) * 0.15) - 0.7);
col = mix(col, vec3(0.88, 0.86, 0.82), 1.0 - smoothstep(-0.2, 0.3, sail));
}
} else {
/* ── land: hillside, macchia, and the town down at the water ── */
float e = 1.2, h = ground(p);
vec3 n = normalize(vec3(-(ground(p + vec2(e, 0.0)) - h) * 17.0, -(ground(p + vec2(0.0, e)) - h) * 17.0, 1.0));
float shade = clamp(dot(n, normalize(vec3(-L.x, -L.y, L.z))), 0.0, 1.0);
float slope = 1.0 - n.z;
float veg = fbm(p * 0.03 + 2.0);
vec3 base = mix(vec3(0.78, 0.72, 0.53), vec3(0.50, 0.56, 0.33), smoothstep(0.42, 0.58, veg));
base = mix(base, vec3(0.36, 0.45, 0.25), smoothstep(0.6, 0.7, veg) * 0.8);
base *= 0.9 + 0.16 * noise(p * 1.4) + 0.06 * (hash(floor(p * 2.0)) - 0.5);
float shrub = smoothstep(0.42, 0.6, fbm(p * 0.022 + 11.0));
vec3 shT = tree(p - vec2(2.0, 2.4), 6.0);
base *= 1.0 - 0.34 * shT.x * shrub;
vec3 tr = tree(p, 6.0);
float lit = clamp(0.62 - dot(tr.yz, vec2(L.x, L.y)) * 0.55, 0.0, 1.0);
vec3 leaf = mix(vec3(0.16, 0.27, 0.14), vec3(0.45, 0.55, 0.30), lit) * (0.9 + 0.2 * noise(p * 2.3));
base = mix(base, leaf, tr.x * shrub * (1.0 - smoothstep(0.35, 0.6, slope)));
vec3 limestone = mix(vec3(0.70, 0.66, 0.58), vec3(0.88, 0.85, 0.78), noise(p * 0.7)) * (0.92 + 0.12 * noise(p * 3.1));
base = mix(base, limestone, smoothstep(0.3, 0.6, slope) * 0.75);
// the town: dense by the water, thinning out up the hill, house by house
vec3 roof, tmpRoof; vec2 hid, tmpId;
float occ = town(p, roof, hid);
float occS = town(p - vec2(2.4, 3.0), tmpRoof, tmpId);
float near = exp(d / 150.0);
float want = fbm(p * 0.011 + 3.0) * 0.75 * exp(d / 420.0) + near * 0.6;
float here = step(0.55 + 0.12 * hash(hid + 6.6), want);
float hereS = step(0.55 + 0.12 * hash(tmpId + 6.6), want);
// lanes are paved only in the dense heart; where no house stands the hillside shows
float dense = smoothstep(0.62, 0.7, want);
vec3 stone = vec3(0.87, 0.84, 0.77) * (0.95 + 0.07 * noise(p * 1.6));
vec3 open = roof.x < -0.5 ? mix(stone, vec3(0.48, 0.57, 0.34), step(0.5, hash(hid + 3.0))) : stone;
col = mix(base, open, dense);
if (occ * here > 0.5) col = roof;
else if (occS * hereS > 0.5) col *= 0.64;
// the hinterland: parcels with their own crop and row direction, hedges between
float farm = smoothstep(150.0, 200.0, -d) * (1.0 - smoothstep(450.0, 510.0, -d));
if (farm > 0.0) {
vec2 fp = (p + vec2(fbm(p * 0.015), fbm(p * 0.015 + 7.0)) * 10.0) * vec2(0.62, 1.0);
vec2 fc = floor(fp / 58.0);
float b1 = 99.0, b2 = 99.0; vec2 fid = vec2(0.0);
for (int fj = -1; fj <= 1; fj++) for (int fi = -1; fi <= 1; fi++) {
vec2 g = fc + vec2(float(fi), float(fj));
float dd = length(fp - (g + 0.25 + 0.5 * hash2(g)) * 58.0);
if (dd < b1) { b2 = b1; b1 = dd; fid = g; } else if (dd < b2) { b2 = dd; }
}
float kind = hash(fid + 1.7);
float ang = hash(fid + 4.2) * 3.1416;
vec2 dir = vec2(cos(ang), sin(ang));
float u = dot(p, dir), v = dot(p, vec2(-dir.y, dir.x));
vec3 parcel;
if (kind < 0.36) {
float r = smoothstep(-0.2, 0.6, sin(u * 6.2831 / 4.0));
vec3 vine = mix(vec3(0.24, 0.36, 0.16), vec3(0.44, 0.54, 0.25), noise(p * 1.4)) * (0.85 + 0.2 * noise(vec2(u * 0.3, v * 1.6)));
parcel = mix(vec3(0.67, 0.57, 0.42), vine, r);
} else if (kind < 0.56) {
parcel = mix(vec3(0.88, 0.78, 0.52), vec3(0.80, 0.68, 0.43), 0.5 + 0.5 * sin(u * 6.2831 / 2.4)) * (0.94 + 0.1 * noise(p * 0.5));
} else if (kind < 0.74) {
vec2 q = vec2(u, v) / 9.0;
vec2 qc = fract(q) - 0.5 + (hash2(floor(q)) - 0.5) * 0.18;
float olive = 1.0 - smoothstep(0.2, 0.33, length(qc));
float oshadow = 1.0 - smoothstep(0.2, 0.36, length(qc - vec2(0.12, 0.16)));
vec3 soil = vec3(0.76, 0.68, 0.52) * (1.0 - 0.28 * oshadow);
parcel = mix(soil, mix(vec3(0.36, 0.42, 0.28), vec3(0.56, 0.60, 0.42), clamp(0.6 - dot(qc, vec2(L.x, L.y)) * 1.4, 0.0, 1.0)), olive);
} else if (kind < 0.88) {
parcel = mix(vec3(0.50, 0.39, 0.28), vec3(0.63, 0.51, 0.37), 0.5 + 0.5 * sin(u * 6.2831 / 1.9)) * (0.95 + 0.08 * noise(p * 0.6));
} else {
parcel = mix(vec3(0.47, 0.57, 0.29), vec3(0.58, 0.63, 0.33), noise(p * 0.08));
}
// hedgerows and the odd cypress along the field edges
float edgeD = (b2 - b1) * 0.5;
parcel *= 0.92 + 0.16 * hash(fid + 5.5);
float hedge = 1.0 - smoothstep(0.5, 1.5, edgeD);
vec3 cy = tree(p, 5.0);
parcel = mix(parcel, vec3(0.30, 0.35, 0.20), hedge * 0.75);
parcel = mix(parcel, vec3(0.12, 0.20, 0.10), cy.x * (1.0 - smoothstep(1.5, 3.5, edgeD)) * step(0.7, hash(fid + 9.0)));
float level = 1.0 - smoothstep(0.38, 0.6, slope);
col = mix(col, parcel, farm * level * (1.0 - step(0.5, occ * here)));
// a country road winding through, a car on it
float ry = 425.0 + 26.0 * sin(p.x * 0.011 + 1.0) + 9.0 * sin(p.x * 0.029);
float rd = abs(p.y - ry);
col = mix(col, vec3(0.86, 0.82, 0.72), (1.0 - smoothstep(4.6, 5.6, rd)) * farm);
col = mix(col, vec3(0.36, 0.36, 0.37) * (0.95 + 0.08 * noise(p * 2.0)), (1.0 - smoothstep(3.4, 4.2, rd)) * farm);
col = mix(col, vec3(0.95), (1.0 - smoothstep(0.25, 0.6, rd)) * step(0.5, fract(p.x / 9.0)) * farm);
float cx = mod(t * 22.0 + 6.0 * sin(t * 0.4), 760.0) - 120.0;
float cyy = 425.0 + 26.0 * sin(cx * 0.011 + 1.0) + 9.0 * sin(cx * 0.029) - 1.6;
float slopeR = 26.0 * 0.011 * cos(cx * 0.011 + 1.0) + 9.0 * 0.029 * cos(cx * 0.029);
vec2 cq = p - vec2(cx, cyy);
float ca = atan(slopeR);
cq = vec2(cq.x * cos(ca) + cq.y * sin(ca), -cq.x * sin(ca) + cq.y * cos(ca));
float body = max(abs(cq.x) - 3.4, abs(cq.y) - 1.4);
col = mix(col, vec3(0.14, 0.14, 0.15), (1.0 - smoothstep(0.0, 1.4, max(abs(cq.x - 0.8) - 3.6, abs(cq.y - 0.9) - 1.6))) * 0.35);
col = mix(col, vec3(0.78, 0.16, 0.13), 1.0 - smoothstep(-0.2, 0.4, body));
col = mix(col, vec3(0.20, 0.24, 0.30), (1.0 - smoothstep(-0.2, 0.3, max(abs(cq.x - 0.9) - 1.0, abs(cq.y) - 1.0))));
}
col *= 0.64 + 0.5 * shade;
col *= 1.0 - 0.1 * smoothstep(0.55, 0.0, h);
// the high country: broad massifs, conifers in the valley, snow on the tops
float alpine = smoothstep(470.0, 590.0, -d);
if (alpine > 0.0) {
float lakeD = length((p - vec2(250.0, 790.0)) / vec2(2.3, 1.0));
float valley = mix(0.35, 1.0, smoothstep(26.0, 80.0, lakeD));
float hA = (peaks(p * 0.006 + 5.0) * 1.3 - 0.2 + fbm(p * 0.035) * 0.05) * valley;
float hX = (peaks((p + vec2(1.5, 0.0)) * 0.006 + 5.0) * 1.3 - 0.2 + fbm((p + vec2(1.5, 0.0)) * 0.035) * 0.05) * valley;
float hY = (peaks((p + vec2(0.0, 1.5)) * 0.006 + 5.0) * 1.3 - 0.2 + fbm((p + vec2(0.0, 1.5)) * 0.035) * 0.05) * valley;
vec3 nA = normalize(vec3(-(hX - hA) * 95.0, -(hY - hA) * 95.0, 1.0));
float shA = clamp(dot(nA, normalize(vec3(-L.x, -L.y, L.z))), 0.0, 1.0);
float slA = 1.0 - nA.z;
vec3 rockA = mix(vec3(0.46, 0.43, 0.39), vec3(0.62, 0.58, 0.52), noise(p * 0.05)) * (0.94 + 0.08 * noise(p * 0.9));
vec3 trA = tree(p, 4.4);
vec3 trS = tree(p - vec2(1.6, 2.0), 4.4);
float conifer = (1.0 - smoothstep(0.40, 0.50, hA + (noise(p * 0.06) - 0.5) * 0.08)) * (1.0 - smoothstep(0.5, 0.75, slA));
vec3 meadow = mix(vec3(0.42, 0.50, 0.28), vec3(0.52, 0.56, 0.32), noise(p * 0.1));
vec3 forestA = meadow * (1.0 - 0.4 * trS.x);
forestA = mix(forestA, mix(vec3(0.07, 0.15, 0.09), vec3(0.20, 0.33, 0.18), clamp(0.6 - dot(trA.yz, vec2(L.x, L.y)) * 0.6, 0.0, 1.0)), trA.x * smoothstep(0.2, 0.5, fbm(p * 0.02 + 3.0) + 0.25));
vec3 alp = mix(rockA, forestA, conifer);
float snowA = smoothstep(0.75, 0.81, hA + (noise(p * 0.09) - 0.5) * 0.1) * (1.0 - smoothstep(0.55, 0.8, slA));
snowA = max(snowA, smoothstep(0.86, 0.94, hA));
alp *= 0.36 + 0.86 * shA;
alp = mix(alp * vec3(0.8, 0.87, 1.05), alp * vec3(1.04, 1.0, 0.95), smoothstep(0.35, 0.8, shA));
vec3 snowC = mix(vec3(0.70, 0.77, 0.88), vec3(0.98, 0.98, 0.97), smoothstep(0.2, 0.75, shA)) * (0.96 + 0.05 * noise(p * 0.6));
alp = mix(alp, snowC, snowA);
col = mix(col, alp, alpine);
}
// a mountain lake in a valley
vec2 lc = vec2(250.0, 790.0);
float ld = length((p - lc) / vec2(2.3, 1.0)) + (fbm(p * 0.05) - 0.5) * 14.0;
if (ld < 34.0) {
float lw = wave(p * 1.3, t * 0.6);
vec3 lake = mix(vec3(0.12, 0.36, 0.48), vec3(0.24, 0.55, 0.62), smoothstep(34.0, 12.0, ld));
lake *= 0.86 + 0.12 * lw;
lake += vec3(1.0, 0.98, 0.92) * pow(noise(p * 0.6 + t * 1.2), 14.0) * 0.7;
col = mix(col, lake, smoothstep(34.0, 31.0, ld));
col = mix(col, vec3(0.82, 0.80, 0.74), (1.0 - smoothstep(0.0, 1.8, abs(ld - 32.0))) * 0.8);
}
// the shore: small coves of sand between rocks, wet where the wash runs
float bw = 17.0 + 10.0 * fbm3(vec2(p.x * 0.03, 1.0));
float shore = 1.0 - smoothstep(bw - 3.0, bw + 2.0, -d);
float rock = smoothstep(0.56, 0.66, fbm(p * 0.05 + 4.0));
vec3 sand = vec3(0.93, 0.86, 0.71) + (hash(floor(p * 3.0)) - 0.5) * 0.06;
float wet = 1.0 - smoothstep(0.0, 6.0 + wash * 0.4, -d);
sand = mix(sand, vec3(0.74, 0.67, 0.55), wet * 0.8);
// boulders: round stones lit from the top left, darker in the cracks between
vec3 bo = tree(p, 4.5);
float blit = clamp(0.6 - dot(bo.yz, vec2(L.x, L.y)) * 0.6, 0.0, 1.0);
vec3 rocks = mix(vec3(0.30, 0.29, 0.27), mix(vec3(0.52, 0.50, 0.46), vec3(0.80, 0.77, 0.71), blit), bo.x);
vec3 edgeCol = mix(sand, rocks, rock);
col = mix(col, edgeCol, shore);
}
// haze into the page below: a long, uneven edge that drifts slowly
float H = uRes.y / uDpr;
float edge = H - 118.0 + 42.0 * (fbm3(vec2(sp.x * 0.011, t * 0.04)) - 0.5) * 2.0 + 22.0 * (fbm(sp * 0.028 + vec2(t * 0.05, 0.0)) - 0.5) * 2.0;
float mist = smoothstep(edge - 34.0, edge + 84.0, sp.y);
mist = clamp(mist + smoothstep(H - 24.0, H, sp.y), 0.0, 1.0);
col = mix(col, vec3(1.0, 0.98, 0.961), mist * uHaze);
gl_FragColor = vec4(col, 1.0);
}`;
const VERTEX = 'attribute vec2 a; void main(){ gl_Position = vec4(a, 0.0, 1.0); }';
export interface Scenery {
/** Glides the camera to another place; a still picture jumps there. */
flyTo(camera: Camera): void;
}
interface SceneryOptions {
/** The height the scene is framed for; the box may be taller or shorter. */
frame: number;
camera?: Camera;
/** The soft fade into the page at the foot of the picture; off beside a column. */
haze?: boolean;
}
const reducedMotion = (): boolean =>
typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
export function startScenery(box: HTMLElement, opts: SceneryOptions): Scenery | null {
const canvas = document.createElement('canvas');
canvas.className = 'scenery';
canvas.setAttribute('aria-hidden', 'true');
box.prepend(canvas);
const gl = canvas.getContext('webgl', { antialias: false, premultipliedAlpha: false, powerPreference: 'low-power' });
if (!gl) {
canvas.remove();
return null;
}
const compile = (type: number, src: string): WebGLShader | null => {
const shader = gl.createShader(type);
if (!shader) return null;
gl.shaderSource(shader, src);
gl.compileShader(shader);
return shader;
};
const program = gl.createProgram();
const vs = compile(gl.VERTEX_SHADER, VERTEX);
const fs = compile(gl.FRAGMENT_SHADER, FRAGMENT);
if (!program || !vs || !fs) {
canvas.remove();
return null;
}
gl.attachShader(program, vs);
gl.attachShader(program, fs);
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
canvas.remove();
return null;
}
gl.useProgram(program);
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), gl.STATIC_DRAW);
const position = gl.getAttribLocation(program, 'a');
gl.enableVertexAttribArray(position);
gl.vertexAttribPointer(position, 2, gl.FLOAT, false, 0, 0);
const uRes = gl.getUniformLocation(program, 'uRes');
const uDpr = gl.getUniformLocation(program, 'uDpr');
const uT = gl.getUniformLocation(program, 'uT');
const uCam = gl.getUniformLocation(program, 'uCam');
gl.uniform1f(gl.getUniformLocation(program, 'uHaze'), opts.haze === false ? 0 : 1);
// The picture's resolution: the screen's, capped at 2, scaled down when frames come slow.
let quality = 1;
let offset: [number, number] = [0, 0];
const resize = () => {
const cssWidth = box.clientWidth || FRAME_WIDTH;
const cssHeight = box.clientHeight || opts.frame;
const ratio = Math.min(2, Math.max(1, window.devicePixelRatio || 1)) * quality;
canvas.width = Math.max(1, Math.round(cssWidth * ratio));
canvas.height = Math.max(1, Math.round(cssHeight * ratio));
canvas.style.height = `${cssHeight}px`;
gl.viewport(0, 0, canvas.width, canvas.height);
gl.uniform2f(uRes, canvas.width, canvas.height);
gl.uniform1f(uDpr, canvas.width / cssWidth);
// The scene is framed for a phone: a bigger box shows more around the same
// centre, a smaller one (a small iPhone) the middle of it.
offset = [(cssWidth - FRAME_WIDTH) / 2, (cssHeight - opts.frame) / 2];
};
resize();
const still = reducedMotion();
const born = performance.now();
let camera: [number, number] = [opts.camera?.[0] ?? 0, opts.camera?.[1] ?? 0];
let flight: { from: [number, number]; to: Camera; start: number; duration: number } | null = null;
let running = false;
let lastFrame = 0;
let measured = 0;
let slowFrames = 0;
const draw = (now: number) => {
if (flight) {
const k = Math.min(1, (now - flight.start) / flight.duration);
const e = k < 0.5 ? 4 * k * k * k : 1 - Math.pow(-2 * k + 2, 3) / 2;
camera = [
flight.from[0] + (flight.to[0] - flight.from[0]) * e,
flight.from[1] + (flight.to[1] - flight.from[1]) * e,
];
if (k >= 1) flight = null;
}
gl.uniform2f(uCam, camera[0] - offset[0], camera[1] - offset[1]);
gl.uniform1f(uT, still ? 4 : (now - born) / 1000 + 4);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
};
const frame = (now: number) => {
if (!canvas.isConnected || document.hidden) {
running = false;
return;
}
// A device that cannot keep up gets a smaller picture once, rather than a stutter.
if (lastFrame && quality === 1 && measured < 90) {
measured += 1;
if (now - lastFrame > 24) slowFrames += 1;
if (measured === 90 && slowFrames > 45) {
quality = 0.7;
resize();
}
}
lastFrame = now;
draw(now);
if (!still || flight) requestAnimationFrame(frame);
else running = false;
};
const run = () => {
if (running) return;
running = true;
lastFrame = 0;
requestAnimationFrame(frame);
};
run();
// The loop stops in the background (document.hidden) and starts again on return.
const wake = () => {
if (!document.hidden && canvas.isConnected) run();
};
document.addEventListener('visibilitychange', wake);
if (typeof ResizeObserver === 'function') {
const observer = new ResizeObserver(() => {
if (!canvas.isConnected) {
observer.disconnect();
document.removeEventListener('visibilitychange', wake);
return;
}
resize();
if (still) run();
});
observer.observe(box);
}
canvas.addEventListener('webglcontextlost', (event) => {
event.preventDefault();
canvas.remove();
});
return {
flyTo(to: Camera) {
if (still) {
camera = [to[0], to[1]];
run();
return;
}
const distance = Math.hypot(to[0] - camera[0], to[1] - camera[1]);
flight = {
from: [camera[0], camera[1]],
to,
start: performance.now(),
duration: Math.min(1700, 700 + distance * 1.1),
};
run();
},
};
}
+1212 -1102
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -18,6 +18,7 @@
"store:graphic": "node scripts/generate-feature-graphic.mjs",
"store:check": "node scripts/check-store-metadata.mjs",
"build": "vite build",
"postbuild": "node scripts/precompress.mjs",
"build:analyze": "vite build --mode analyze",
"preview": "vite preview",
"typecheck": "tsc --noEmit",
+60
View File
@@ -0,0 +1,60 @@
/*
* The work behind scripts/precompress.mjs: a Brotli copy (<file>.br) beside every
* compressible build file under dist/assets.
*
* The server compresses a build file on every download otherwise, at the low level
* a request path can afford. A file under assets/ carries its content hash in its
* name and never changes, so it is compressed once here, at the level a build can
* afford, and the server hands that copy out as it is
* (server/src/nest/platform/precompressed-static.ts).
*/
import { readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { brotliCompressSync, constants } from 'node:zlib';
/** What the server's own compression would take; fonts, images and video are compressed formats already. */
const COMPRESSIBLE = /\.(?:m?js|css|svg|json|wasm|html|webmanifest)$/i;
/** The server leaves anything below 1 kB uncompressed too: the headers cost more than the saving. */
export const MIN_BYTES = 1024;
/** Quality 11 takes about ten times as long per byte as 9, so the largest chunks get 9. */
const BIG_BYTES = 1024 * 1024;
function* walk(dir) {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const full = join(dir, entry.name);
if (entry.isDirectory()) yield* walk(full);
else yield full;
}
}
/**
* Writes the .br copies under `dir` and returns what it did. A copy that would not be
* smaller than its file is not written, and a directory that does not exist is no work.
*/
export function precompress(dir) {
const result = { files: 0, before: 0, after: 0 };
let files;
try {
files = [...walk(dir)];
} catch (err) {
if (err.code === 'ENOENT') return result;
throw err;
}
for (const file of files) {
if (!COMPRESSIBLE.test(file)) continue;
const input = readFileSync(file);
if (input.length < MIN_BYTES) continue;
const output = brotliCompressSync(input, {
params: {
[constants.BROTLI_PARAM_QUALITY]: input.length > BIG_BYTES ? 9 : 11,
[constants.BROTLI_PARAM_SIZE_HINT]: input.length,
},
});
if (output.length >= input.length) continue;
writeFileSync(`${file}.br`, output);
result.files += 1;
result.before += input.length;
result.after += output.length;
}
return result;
}
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env node
/*
* postbuild: writes a Brotli copy beside every compressible file under dist/assets,
* which the server hands to a browser that accepts Brotli instead of compressing
* the file again on each download. scripts/lib/precompress.mjs holds the work.
*/
import { fileURLToPath } from 'node:url';
import { precompress } from './lib/precompress.mjs';
const { files, before, after } = precompress(fileURLToPath(new URL('../dist/assets', import.meta.url)));
const mb = (bytes) => (bytes / 1048576).toFixed(1);
console.log(`precompress: ${files} files, ${mb(before)} MB -> ${mb(after)} MB (brotli)`);
+1 -1
View File
@@ -10,7 +10,7 @@
"src/components/Map/MapViewGL.tsx": 2126,
"src/components/Planner/DayDetailPanel.test.tsx": 2333,
"src/components/Planner/DayPlanSidebar.test.tsx": 5349,
"src/components/Planner/DayPlanSidebar.tsx": 2929,
"src/components/Planner/DayPlanSidebar.tsx": 2910,
"src/components/Planner/PlaceFormModal.test.tsx": 2836,
"src/components/Planner/PlaceInspector.tsx": 1287,
"src/components/Studio/TravelElements.tsx": 1559,
+1 -2
View File
@@ -42,12 +42,11 @@
"src/components/Map/MapViewGL.tsx": 1,
"src/components/Map/ReservationOverlay.test.tsx": 1,
"src/components/Map/transitGeometry.ts": 1,
"src/components/Map/useDawarichTrailGL.test.ts": 4,
"src/components/Map/useMarkerThumbs.ts": 1,
"src/components/PDF/TripPDF.tsx": 40,
"src/components/Packing/PackingListPanelItemRow.test.tsx": 2,
"src/components/Planner/DayPlanSidebar.constants.ts": 1,
"src/components/Planner/DayPlanSidebar.tsx": 61,
"src/components/Planner/DayPlanSidebar.tsx": 52,
"src/components/Planner/DayPlanSidebarNoteModal.test.tsx": 1,
"src/components/Planner/PlaceFormModal.test.tsx": 3,
"src/components/Planner/PlaceFormModal.tsx": 1,
@@ -20,6 +20,7 @@
"components/Map/DawarichTrailLayer.tsx": 1,
"components/Map/dawarichTrail.ts": 10,
"components/Map/markerLook.ts": 1,
"components/Map/poiCategories.ts": 2,
"components/Map/useDawarichTrailGL.ts": 1,
"components/Packing/PackingBringersCard.tsx": 1,
"components/Planner/DayReorderPopup.tsx": 1,
@@ -3,10 +3,15 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useAdminUserActions } from './useAdminUserActions';
// FE-HOOK-ADMUSERACT-001 to FE-HOOK-ADMUSERACT-007
// FE-HOOK-ADMUSERACT-001 to FE-HOOK-ADMUSERACT-009
const api = vi.hoisted(() => ({ rotateJwtSecret: vi.fn(), resetUserPasskeys: vi.fn(), resetUserMfa: vi.fn() }));
vi.mock('../../api/client', () => ({ adminApi: api }));
const api = vi.hoisted(() => ({
rotateJwtSecret: vi.fn(),
resetUserPasskeys: vi.fn(),
resetUserMfa: vi.fn(),
}));
const http = vi.hoisted(() => ({ delete: vi.fn() }));
vi.mock('../../api/client', () => ({ adminApi: api, apiClient: http }));
const t = (key: string, params?: Record<string, unknown>) => (params ? `${key} ${JSON.stringify(params)}` : key);
@@ -28,6 +33,7 @@ beforeEach(() => {
api.rotateJwtSecret.mockReset().mockResolvedValue({});
api.resetUserPasskeys.mockReset().mockResolvedValue({ deleted: 2 });
api.resetUserMfa.mockReset().mockResolvedValue({ success: true });
http.delete.mockReset().mockResolvedValue({ data: { success: true, unlinked: true } });
});
describe('useAdminUserActions', () => {
@@ -101,4 +107,26 @@ describe('useAdminUserActions', () => {
expect(admin.toast.error).toHaveBeenCalledWith('common.error');
expect(ok).toBe(false);
});
it('FE-HOOK-ADMUSERACT-008: removing the SSO link calls the API, toasts and reports success', async () => {
const { admin, actions } = mount();
let ok: boolean | undefined;
await act(async () => {
ok = await actions.unlinkSso({ id: 11 });
});
expect(http.delete).toHaveBeenCalledWith('/admin/users/11/sso');
expect(admin.toast.success).toHaveBeenCalledWith('admin.sso.unlinkDone');
expect(ok).toBe(true);
});
it('FE-HOOK-ADMUSERACT-009: a failed SSO unlink toasts and reports failure', async () => {
http.delete.mockRejectedValue(new Error('x'));
const { admin, actions } = mount();
let ok: boolean | undefined;
await act(async () => {
ok = await actions.unlinkSso({ id: 11 });
});
expect(admin.toast.error).toHaveBeenCalledWith('common.error');
expect(ok).toBe(false);
});
});
@@ -1,4 +1,4 @@
import { adminApi } from '../../api/client';
import { adminApi, apiClient } from '../../api/client';
import type { TranslationFn } from '../../types';
interface UserActionsHost {
@@ -12,8 +12,8 @@ interface UserActionsHost {
/**
* The irreversible user actions behind the admin dialogs and their phone sheets:
* rotating the JWT secret, which signs everyone out including the admin, removing a
* user's passkeys and switching off a user's two-factor login. Each shell keeps its own
* confirm step and busy state around them.
* user's passkeys, switching off a user's two-factor login and removing a user's SSO
* link. Each shell keeps its own confirm step and busy state around them.
*/
export function useAdminUserActions(admin: UserActionsHost, t: TranslationFn) {
const { toast, setRotatingJwt, setShowRotateJwtModal, logout, navigate } = admin;
@@ -55,5 +55,17 @@ export function useAdminUserActions(admin: UserActionsHost, t: TranslationFn) {
}
};
return { rotateJwt, resetPasskeys, resetMfa };
/** Forgets the user's SSO identity so the next SSO sign-in links again (#3065); true when it worked. */
const unlinkSso = async (user: { id: number }): Promise<boolean> => {
try {
await apiClient.delete(`/admin/users/${user.id}/sso`);
toast.success(t('admin.sso.unlinkDone'));
return true;
} catch {
toast.error(t('common.error'));
return false;
}
};
return { rotateJwt, resetPasskeys, resetMfa, unlinkSso };
}
@@ -20,6 +20,7 @@ import { widgetCover, widgetWeather } from '../../native/widgetMedia';
import { atlasSummary, collabSummary, packingDetail, type WidgetAtlas } from '../../native/widgetOnline';
import {
buildSnapshot,
liveDayDue,
pickTrip,
publishWidgets,
todayOf,
@@ -207,9 +208,10 @@ export default function NativeWidgetsSync(): null {
});
}
if (cancelled) return;
const live = main.day
? tripDayState(main.day, now.getHours() * 60 + now.getMinutes(), t('native.widget.dayDone'))
: null;
// The Live Activity from three hours before the day's first timed stop, not all day long.
const minutes = now.getHours() * 60 + now.getMinutes();
const live =
main.day && liveDayDue(main.day, minutes) ? tripDayState(main.day, minutes, t('native.widget.dayDone')) : null;
await publishWidgets(main.snapshot, live, choices);
await publishToWatch(hero, main, today);
};
@@ -122,8 +122,8 @@ describe('DawarichTrailLayer', () => {
const [casing, line] = lines()
expect(casing.getAttribute('data-pane')).toBe('trek-track-casing')
expect(casing.getAttribute('data-weight')).toBe('6')
expect(casing.getAttribute('data-opacity')).toBe('0.55')
expect(casing.getAttribute('data-weight')).toBe('7')
expect(casing.getAttribute('data-opacity')).toBe('0.9')
// Only the casing takes the pane; the coloured line is left in Leaflet's
// default overlay pane. Pinned as the fact it is rather than as a rule:
@@ -131,8 +131,9 @@ describe('DawarichTrailLayer', () => {
// it, so the recorded line currently draws over the plan while the GL twin
// puts both of its layers under it.
expect(line.getAttribute('data-pane')).toBe('')
expect(line.getAttribute('data-weight')).toBe('3')
expect(line.getAttribute('data-dash')).toBe('6 5')
// Full colour, wide and long-dashed, so it reads on a busy street map.
expect(line.getAttribute('data-weight')).toBe('4')
expect(line.getAttribute('data-dash')).toBe('10 5')
expect(line.getAttribute('data-points')).toBe(JSON.stringify([[48.2, 16.37], [48.21, 16.38]]))
expect(lines().every(el => el.getAttribute('data-interactive') === 'false')).toBe(true)
@@ -5,6 +5,7 @@ import { frameLine } from '../../utils/lngFrame'
import type { DawarichTrack } from '@trek/shared'
import {
DAWARICH_TRAIL_CASING,
DAWARICH_TRAIL_STROKE,
trailSegments,
type DawarichTrailSegment,
} from './dawarichTrail'
@@ -55,8 +56,8 @@ export default function DawarichTrailLayer({
// theme-lint-disable — map paint
pathOptions={{
color: DAWARICH_TRAIL_CASING,
weight: 6,
opacity: 0.55,
weight: DAWARICH_TRAIL_STROKE.casingWidth,
opacity: DAWARICH_TRAIL_STROKE.casingOpacity,
lineCap: 'round',
lineJoin: 'round',
}}
@@ -72,9 +73,9 @@ export default function DawarichTrailLayer({
positions={segment.points}
pathOptions={{
color: segment.color,
weight: 3,
opacity: 0.85,
dashArray: '6 5',
weight: DAWARICH_TRAIL_STROKE.width,
opacity: DAWARICH_TRAIL_STROKE.opacity,
dashArray: DAWARICH_TRAIL_STROKE.dashLeaflet,
lineCap: 'round',
lineJoin: 'round',
}}
@@ -27,6 +27,22 @@ export const DAWARICH_TRAIL_COLOR = '#2563EB' // theme-lint-disable — map pain
/** The white casing under the line, so it stays visible over a satellite tile. */
export const DAWARICH_TRAIL_CASING = '#FFFFFF' // theme-lint-disable — map paint
/**
* How the recorded route is stroked, shared by the Leaflet and GL layers. A
* thin, translucent dash over a nearly opaque white casing read as a pale
* lavender trace on a busy street map and was barely visible (TestFlight
* feedback, 5.1.3). Full colour, a wider line and longer dashes keep it
* readable; the dash still tells it apart from the planned route.
*/
export const DAWARICH_TRAIL_STROKE = {
casingWidth: 7,
casingOpacity: 0.9,
width: 4,
opacity: 1,
dashLeaflet: '10 5',
dashGL: [2.5, 1.25] as [number, number],
} as const
/**
* Per-day hues, cycled.
*
+7 -1
View File
@@ -1,4 +1,4 @@
import { Utensils, Coffee, Wine, BedDouble, Camera, Landmark, Trees, Ticket, Fuel, Zap, ParkingSquare, Tent, Binoculars, Mountain, Warehouse, Droplet, Toilet, Sandwich, Anchor, Sailboat, Wrench, Store, BatteryCharging, type LucideIcon } from 'lucide-react'
import { Utensils, Coffee, Wine, BedDouble, Camera, Landmark, Trees, Ticket, Fuel, Zap, ParkingSquare, Tent, Binoculars, Mountain, Warehouse, Droplet, Toilet, Sandwich, Anchor, Sailboat, Wrench, Store, BatteryCharging, Croissant, ShoppingBasket, type LucideIcon } from 'lucide-react'
import type { TourPoiCategory } from '@trek/shared'
import { parsePluginPoiCategoryKey, type PluginPoiDetail } from '@trek/shared'
// The road-trip kinds take their colour from the one place that defines it, so the
@@ -29,6 +29,9 @@ export const POI_CATEGORIES: PoiCategory[] = [
{ key: 'museum', labelKey: 'poi.cat.museums', Icon: Landmark, color: '#6366F1' },
{ key: 'nature', labelKey: 'poi.cat.nature', Icon: Trees, color: '#16A34A' },
{ key: 'activity', labelKey: 'poi.cat.activities', Icon: Ticket, color: '#F59E0B' },
// Where to stock up: the bread for the day, and a supermarket or village shop.
{ key: 'bakery', labelKey: 'poi.cat.bakeries', Icon: Croissant, color: '#D97706' }, // theme-lint-disable: marker and pill paint, as the core pins above
{ key: 'supermarket', labelKey: 'poi.cat.groceries', Icon: ShoppingBasket, color: '#0D9488' }, // theme-lint-disable: marker and pill paint, as the core pins above
]
/**
@@ -70,6 +73,9 @@ export const TOUR_POI_LOOKS: Record<TourPoiCategory, PoiCategory> = {
market: { key: 'market', labelKey: 'tours.poi.cat.market', Icon: Store, color: coreColor('shopping') },
// BIK-07: the road trip's charging colour, so a charger reads as one on every map.
ebike_charging: { key: 'ebike_charging', labelKey: 'tours.poi.cat.ebike_charging', Icon: BatteryCharging, color: SERVICE_COLORS.charging },
// Resupply on a multi-day hike, in the explore pill's own looks.
bakery: { key: 'bakery', labelKey: 'tours.poi.cat.bakery', Icon: Croissant, color: coreColor('bakery') },
supermarket: { key: 'supermarket', labelKey: 'tours.poi.cat.supermarket', Icon: ShoppingBasket, color: coreColor('supermarket') },
}
// A Map rather than an object, so a category named after an Object.prototype member
@@ -180,16 +180,23 @@ describe('useDawarichTrailGL', () => {
expect(gl.spies.addSource).toHaveBeenCalledWith(SOURCE, expect.objectContaining({ type: 'geojson' }))
const [casingCall, lineCall] = gl.spies.addLayer.mock.calls
expect(casingCall[0].id).toBe(CASING_LAYER)
expect(casingCall[0].paint['line-color']).toBe(DAWARICH_TRAIL_CASING)
expect(casingCall[0].paint['line-width']).toBe(6)
expect(lineCall[0].id).toBe(LINE_LAYER)
if (!casingCall || !lineCall) throw new Error('expected the casing and the line layer')
type LayerSpec = { id: string; paint: Record<string, unknown> }
const casing = casingCall[0] as LayerSpec
const line = lineCall[0] as LayerSpec
expect(casing.id).toBe(CASING_LAYER)
expect(casing.paint['line-color']).toBe(DAWARICH_TRAIL_CASING)
expect(casing.paint['line-width']).toBe(7)
expect(casing.paint['line-opacity']).toBe(0.9)
expect(line.id).toBe(LINE_LAYER)
// Per-feature colour, with the casing white as the fallback a feature
// without one falls back to. The GPX layer uses the same shape.
expect(lineCall[0].paint['line-color']).toEqual(['coalesce', ['get', 'color'], DAWARICH_TRAIL_CASING])
expect(line.paint['line-color']).toEqual(['coalesce', ['get', 'color'], DAWARICH_TRAIL_CASING])
// Dashed, so the recording is distinguishable from the planned route for
// someone who cannot tell the two hues apart.
expect(lineCall[0].paint['line-dasharray']).toEqual([2, 1.6])
expect(line.paint['line-dasharray']).toEqual([2.5, 1.25])
expect(line.paint['line-width']).toBe(4)
expect(line.paint['line-opacity']).toBe(1)
// Both go beneath the planned route's casing. The line is inserted second
// and therefore ends up above its own casing and still below the plan.
@@ -2,7 +2,7 @@ import { useEffect } from 'react'
import type { Map } from 'mapbox-gl'
import type { GeoJSONSource } from 'mapbox-gl'
import type { DawarichTrack } from '@trek/shared'
import { DAWARICH_TRAIL_CASING, trailGeoJson, trailSegments } from './dawarichTrail'
import { DAWARICH_TRAIL_CASING, DAWARICH_TRAIL_STROKE, trailGeoJson, trailSegments } from './dawarichTrail'
/**
* The recorded route on the GL renderer — the imperative twin of
@@ -67,7 +67,11 @@ export function useDawarichTrailGL(
source: SOURCE,
layout: { 'line-cap': 'round', 'line-join': 'round' },
// theme-lint-disable — map paint
paint: { 'line-color': DAWARICH_TRAIL_CASING, 'line-width': 6, 'line-opacity': 0.55 },
paint: {
'line-color': DAWARICH_TRAIL_CASING,
'line-width': DAWARICH_TRAIL_STROKE.casingWidth,
'line-opacity': DAWARICH_TRAIL_STROKE.casingOpacity,
},
},
anchor,
)
@@ -81,11 +85,11 @@ export function useDawarichTrailGL(
// Per-day colour off the feature, with the same fallback the GPX
// layer uses when a feature somehow carries none.
'line-color': ['coalesce', ['get', 'color'], DAWARICH_TRAIL_CASING],
'line-width': 3,
'line-opacity': 0.85,
'line-width': DAWARICH_TRAIL_STROKE.width,
'line-opacity': DAWARICH_TRAIL_STROKE.opacity,
// Dashed, so the recording is distinguishable from the planned
// route without relying on colour alone.
'line-dasharray': [2, 1.6],
'line-dasharray': [...DAWARICH_TRAIL_STROKE.dashGL],
},
},
anchor,
@@ -5,7 +5,7 @@ import { fireEvent, render, screen, waitFor } from '../../../tests/helpers/rende
import { WeightInput } from './PackingListPanelWeightInput';
/** A row whose stored weight changes only once a save answers, as the store does. */
function SlowRow({ onSave }: { onSave: (grams: number | null) => void }) {
function SlowRow({ onSave, onStored }: { onSave: (grams: number | null) => void; onStored: () => void }) {
const [stored, setStored] = useState<number | null>(null);
return (
<WeightInput
@@ -13,7 +13,10 @@ function SlowRow({ onSave }: { onSave: (grams: number | null) => void }) {
width={36}
onSave={(grams) => {
onSave(grams);
setTimeout(() => setStored(grams), 300);
setTimeout(() => {
setStored(grams);
onStored();
}, 300);
}}
/>
);
@@ -22,7 +25,8 @@ function SlowRow({ onSave }: { onSave: (grams: number | null) => void }) {
describe('WeightInput', () => {
it('FE-COMP-PACKING-095: #3005 keeps every typed digit and saves the whole weight once', async () => {
const onSave = vi.fn();
render(<SlowRow onSave={onSave} />);
const onStored = vi.fn();
render(<SlowRow onSave={onSave} onStored={onStored} />);
const input = screen.getByRole('textbox') as HTMLInputElement;
fireEvent.focus(input);
@@ -35,7 +39,9 @@ describe('WeightInput', () => {
fireEvent.blur(input);
expect(onSave).toHaveBeenCalledTimes(1);
expect(onSave).toHaveBeenCalledWith(250);
await waitFor(() => expect(input.value).toBe('250'));
// Wait for the save to answer, so its update lands while the test still runs.
await waitFor(() => expect(onStored).toHaveBeenCalled());
expect(input.value).toBe('250');
});
it('FE-COMP-PACKING-096: saves on Enter and stores an empty field as no weight', () => {
@@ -254,3 +254,57 @@ describe('DayPlanSidebar timed booking drop', () => {
expect(onReorder).toHaveBeenCalledWith(10, [11, 12, 13, 14]);
});
});
// #3041: Firefox sends dragstart while it handles the mouse move that starts the
// drag, and delivers that move to the page right after. Taken as "the drag is over",
// it dropped the drag data at pick-up, so a stop could only be moved by its arrows,
// and the day list played its enter animation again.
describe('DayPlanSidebar drag in Firefox', () => {
const renderDay = () => {
const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' });
const stops = [buildPlace({ id: 1, name: 'Breakfast' }), buildPlace({ id: 2, name: 'Museum' })];
const assignments = {
'10': stops.map((place, i) => buildAssignment({ id: 11 + i, day_id: 10, order_index: i, place })),
};
const onReorder = vi.fn(async () => undefined);
const view = render(
<DayPlanSidebar {...makeDefaultProps({ days: [day], places: stops, assignments, onReorder })} />
);
const row = (text: string) => screen.getByText(text).closest('[draggable="true"]') as HTMLElement;
const list = view.container.querySelector('.scroll-container') as HTMLElement;
return { onReorder, row, list };
};
const dataTransfer = () => ({ setData: vi.fn(), effectAllowed: '', getData: vi.fn(() => '') });
it('FE-PLANNER-DAYPLAN-239: the mouse move that starts a drag, with the button still held, keeps the drag', async () => {
const { onReorder, row } = renderDay();
fireEvent.dragStart(row('Museum'), { dataTransfer: dataTransfer() });
// Firefox order: dragstart first, then the move that triggered it. The touch
// polyfill on hybrid laptops sends the same held-button moves throughout a drag.
fireEvent.mouseMove(document, { buttons: 1 });
expect(row('Museum').style.opacity).toBe('0.4');
fireEvent.dragOver(row('Breakfast'), { dataTransfer: dataTransfer() });
expect(row('Breakfast').style.borderTop).toContain('2px');
fireEvent.drop(row('Breakfast'), { dataTransfer: dataTransfer() });
await waitFor(() => expect(onReorder).toHaveBeenCalledWith(10, [12, 11]));
});
it('FE-PLANNER-DAYPLAN-240: a plain mouse move after a drag that never ended still clears it', () => {
const { row } = renderDay();
fireEvent.dragStart(row('Museum'), { dataTransfer: dataTransfer() });
fireEvent.dragOver(row('Breakfast'), { dataTransfer: dataTransfer() });
fireEvent.mouseMove(document, { buttons: 0 });
expect(row('Museum').style.opacity).toBe('1');
expect(row('Breakfast').style.borderTop).toBe('');
});
it('FE-PLANNER-DAYPLAN-241: the day list plays its enter animation once, not again when a drag ends', () => {
const { row, list } = renderDay();
expect(list.classList.contains('trek-stagger')).toBe(true);
fireEvent.dragStart(row('Museum'), { dataTransfer: dataTransfer() });
expect(list.classList.contains('trek-stagger')).toBe(false);
fireEvent.dragEnd(row('Museum'));
expect(row('Museum').style.opacity).toBe('1');
expect(list.classList.contains('trek-stagger')).toBe(false);
});
});
@@ -10,6 +10,7 @@ import { safeHttpUrl } from '../../utils/safeUrl'
import { ChevronDown, ChevronRight, ChevronUp, Compass, RotateCcw, ExternalLink, Pencil, GripVertical, Ticket, Plus, FileText, Trash2, Car, Lock, Hotel, Eraser, Route as RouteIcon, RouteOff, Bookmark, StickyNote, TramFront, Zap, MapPin, Globe } from 'lucide-react'
import type { PlannedTransitLeg } from './transitLeg'
import { useTransitLegPlanner } from './useTransitLegPlanner'
import { useDayPlanDragState } from './useDayPlanDragState'
import { WalkLateLine } from '../Tours/walk/WalkTransitNote'
import { TourOverrunLine } from '../Tours/TourDayTimeParts'
import { dayItemOverrun } from '../Tours/tourDayTime'
@@ -246,12 +247,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
// distances refresh instead of showing stale cached text (#1300).
const distanceUnit = useSettingsStore(s => s.settings.distance_unit)
const legsAbortRef = useRef<AbortController | null>(null)
const [draggingId, setDraggingId] = useState(null)
const [lockedIds, setLockedIds] = useState(new Set())
const [dropTargetKey, _setDropTargetKey] = useState(null)
const dropTargetRef = useRef(null)
const setDropTargetKey = (key) => { dropTargetRef.current = key; _setDropTargetKey(key) }
const [dragOverDayId, setDragOverDayId] = useState(null)
const [transportDetail, setTransportDetail] = useState(null)
const [transportPosVersion, setTransportPosVersion] = useState(0)
@@ -268,6 +264,9 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
fromType?: string; toType?: string; toId?: number; insertAfter?: boolean; toLegIndex?: number | null;
} | null>(null)
const dragDataRef = useRef(null)
const {
draggingId, setDraggingId, hasDragged, dropTargetKey, dropTargetRef, setDropTargetKey, dragOverDayId, setDragOverDayId,
} = useDayPlanDragState(dragDataRef)
const scrollContainerRef = useRef<HTMLDivElement | null>(null)
const dayRefs = useRef<Map<number, HTMLElement>>(new Map())
@@ -374,28 +373,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
}
document.addEventListener('dragend', cleanup)
return () => document.removeEventListener('dragend', cleanup)
}, [])
// A drag whose source row re-rendered away never sends its dragend to the
// document, and the drop line then stayed on a row until the next reload. The
// browser sends no mousemove during a drag, so the first plain mouse move or
// press after one means it is over.
useEffect(() => {
if (!draggingId && !dropTargetKey && !dragOverDayId) return
const settle = () => {
setDraggingId(null)
setDropTargetKey(null)
setDragOverDayId(null)
dragDataRef.current = null
window.__dragData = null
}
document.addEventListener('mousemove', settle)
document.addEventListener('pointerdown', settle, true)
return () => {
document.removeEventListener('mousemove', settle)
document.removeEventListener('pointerdown', settle, true)
}
}, [draggingId, dropTargetKey, dragOverDayId])
}, [setDraggingId, setDropTargetKey, setDragOverDayId])
// Initialize missing transport positions outside of render to avoid setState-during-render
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -1148,6 +1126,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
hotelLegs,
draggingId,
setDraggingId,
hasDragged,
lockedIds,
dropTargetKey,
dropTargetRef,
@@ -1316,6 +1295,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
hotelLegs,
draggingId,
setDraggingId,
hasDragged,
lockedIds,
dropTargetKey,
dropTargetRef,
@@ -1476,7 +1456,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
/>
{/* Tagesliste */}
<div className={`scroll-container flex flex-col gap-2 p-2${draggingId ? '' : ' trek-stagger'}`} style={{ flex: 1, overflowY: 'auto', minHeight: 0 }} ref={scrollContainerRef} onScroll={(e) => onScrollTopChange?.((e.currentTarget as HTMLElement).scrollTop)}>
<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
@@ -1,4 +1,4 @@
// FE-PLANNER-RESMODAL-001 to FE-PLANNER-RESMODAL-109
// FE-PLANNER-RESMODAL-001 to FE-PLANNER-RESMODAL-110
import { render, screen, waitFor, fireEvent, within, act } from '../../../tests/helpers/render';
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
@@ -1829,4 +1829,13 @@ describe('ReservationModal', () => {
expect(onSave.mock.calls[0][0].confirmation_number).toBe('PNR-NEW');
});
});
it('FE-PLANNER-RESMODAL-110: a refresh of the trip while the dialog is open keeps what the user typed (#3069)', async () => {
const { rerender } = render(<ReservationModal {...defaultProps} />);
const title = screen.getByPlaceholderText(/e\.g\. Lufthansa/i) as HTMLInputElement;
await userEvent.type(title, 'Le Jules Verne');
// A socket reconnect re-reads the trip: days, places and stays arrive as new arrays.
rerender(<ReservationModal {...defaultProps} days={[]} places={[]} accommodations={[]} />);
expect(title).toHaveValue('Le Jules Verne');
});
});
@@ -132,8 +132,12 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
setForm({ ...EMPTY_FORM, assignment_id: defaultAssignmentId ?? '' })
setPendingFiles([])
}
// Keyed only on what opens a different form. Days, places and stays are read
// when the form is seeded; a refresh of the trip while the dialog is open (a
// socket reconnect re-reads it) hands in new arrays of the same data and must
// not reseed it and wipe what the user is typing (#3069).
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [reservation, prefill, isOpen, selectedDayId, defaultAssignmentId, days, places, accommodations])
}, [reservation, prefill, isOpen, selectedDayId, defaultAssignmentId])
const handleSubmit = async (e?: { preventDefault?: () => void }) => {
e?.preventDefault?.()
@@ -1,4 +1,4 @@
// FE-PLANNER-TRANSMODAL-001 to FE-PLANNER-TRANSMODAL-083
// FE-PLANNER-TRANSMODAL-001 to FE-PLANNER-TRANSMODAL-085
import { render, screen, waitFor, fireEvent, within, act } from '../../../tests/helpers/render';
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
@@ -18,6 +18,7 @@ import {
buildAssignment,
buildReservation,
buildTripFile,
buildBudgetItem,
} from '../../../tests/helpers/factories';
import { TransportModal } from './TransportModal';
import type { Day, Reservation } from '../../types';
@@ -1725,4 +1726,22 @@ describe('TransportModal', () => {
const legs = onSave.mock.calls[0][0].metadata.legs as { confirmation_number?: string }[];
expect(legs.map(l => l.confirmation_number ?? null)).toEqual([null, 'SEG-TWO']);
});
it('FE-PLANNER-TRANSMODAL-084: a store refresh while the dialog is open keeps what the user typed (#3069)', async () => {
render(<TransportModal {...defaultProps} />);
const title = screen.getByPlaceholderText(/e\.g\. Lufthansa/i) as HTMLInputElement;
await userEvent.type(title, 'LH 400');
// A socket reconnect re-reads the trip: the costs arrive as a new array.
act(() => { useTripStore.setState({ budgetItems: [buildBudgetItem()] }); });
expect(title).toHaveValue('LH 400');
});
it('FE-PLANNER-TRANSMODAL-085: opening a different transport still fills the form with it', () => {
const first = buildReservation({ title: 'First flight', type: 'flight' });
const second = buildReservation({ title: 'Second flight', type: 'flight' });
const { rerender } = render(<TransportModal {...defaultProps} reservation={first} />);
expect(screen.getByDisplayValue('First flight')).toBeInTheDocument();
rerender(<TransportModal {...defaultProps} reservation={second} />);
expect(screen.getByDisplayValue('Second flight')).toBeInTheDocument();
});
});
@@ -135,7 +135,10 @@ export function TransportModal({ isOpen, onClose, onSave, reservation, days, sel
meta_seat: meta.seat || '',
}),
})
}, [isOpen, reservation, prefill, selectedDayId, budgetItems])
// Keyed only on what opens a different form. A store refresh while the dialog
// is open (a socket reconnect re-reads the trip, a fellow traveller's cost) must
// not reseed it and wipe what the user is typing (#3069).
}, [isOpen, reservation, prefill, selectedDayId])
const handleSubmit = async (e?: React.FormEvent) => {
e?.preventDefault()
@@ -1,4 +1,4 @@
// FE-PLANNER-TRANSPORTEP-001 to -021: the transport booking form both the desktop
// FE-PLANNER-TRANSPORTEP-001 to -022: the transport booking form both the desktop
// TransportModal and the phone's transport sheet save through.
import { describe, expect, it } from 'vitest';
@@ -499,6 +499,28 @@ describe('buildTransportPayload', () => {
expect(payload.reservation_time).toBeNull();
});
it('FE-PLANNER-TRANSPORTEP-022: a flight without airports keeps its day, times and flight details on save (#3070)', () => {
const payload = buildTransportPayload(
draft({
form: { ...EMPTY_TRANSPORT_FIELDS, title: 'Fly', type: 'flight', notes: 'only the notes changed' },
waypoints: [
{ ...emptyWaypoint(1), depTime: '09:40', airline: 'Lufthansa', flight_number: 'LH 400', seat: '12A' },
{ ...emptyWaypoint(2), arrTime: '11:30' },
],
}),
days,
DESKTOP_SAVE
);
expect(payload).toMatchObject({
day_id: 1,
end_day_id: 2,
reservation_time: '2026-05-01T09:40',
reservation_end_time: '2026-05-02T11:30',
endpoints: [],
});
expect(payload.metadata).toEqual({ airline: 'Lufthansa', flight_number: 'LH 400', seat: '12A' });
});
it('FE-PLANNER-TRANSPORTEP-017: the desktop anchors a train on its raw rows, the phone on the picked stations', () => {
const station = (name: string) => ({ name, lat: 1, lng: 1 });
const trainWaypoints = [
@@ -548,8 +548,12 @@ export function buildTransportPayload(
const dayDate = (id: string | number): string | null => days.find((d) => d.id === Number(id))?.date ?? null;
// Flight route as an ordered list of airports (origin .. stops .. destination).
const flightWps = form.type === 'flight' ? waypoints.filter((w) => w.airport) : [];
const firstWp = flightWps[0];
const lastWp = flightWps[flightWps.length - 1];
// A flight without a single airport (one created over MCP with a day and times
// but no endpoints) takes its day, times, airline and seat from the raw rows, as
// a train without stations does; otherwise a save wiped them (#3070).
const flightAnchors = flightWps.length > 0 || form.type !== 'flight' ? flightWps : waypoints;
const firstWp = flightAnchors[0];
const lastWp = flightAnchors[flightAnchors.length - 1];
// Only geocoded stations become map endpoints and legs.
const trainWps = stationRoute ? trainWaypoints : [];
const trainStations = trainWps.filter((w) => w.location);
@@ -0,0 +1,69 @@
import { useCallback, useEffect, useRef, useState, type MutableRefObject } from 'react';
/** A stop's or a day's id, as the day plan's drag handlers pass them around. */
type DragKey = string | number | null;
/**
* The drag state of the day plan (DayPlanSidebar): what is being dragged, which
* row the drop line stands on, which day the drag is over, and whether a drag
* happened yet.
*
* The day list fades in once, on mount. Switching its stagger back on when a
* drag ended played that entrance again on every drop, so the first drag turns
* it off for good (#3041).
*
* A drag whose source row re-rendered away never sends its dragend to the
* document, and the drop line then stayed on a row until the next reload. The
* browser sends no mousemove during a drag, so the first plain mouse move or
* press after one means it is over. Plain means no button held: Firefox fires
* dragstart while it handles the move that starts the drag and hands that move
* to the page afterwards, button still down. Read as the end, it threw the drag
* away at pick-up and left only the arrows to reorder a day (#3041).
*/
export function useDayPlanDragState(dragDataRef: MutableRefObject<unknown>) {
const [draggingId, setDraggingIdState] = useState<DragKey>(null);
const [hasDragged, setHasDragged] = useState(false);
const [dropTargetKey, setDropTargetKeyState] = useState<string | null>(null);
const dropTargetRef = useRef<string | null>(null);
const [dragOverDayId, setDragOverDayId] = useState<DragKey>(null);
// Stable, so the sidebar's listeners that call them are set up once.
const setDraggingId = useCallback((id: DragKey) => {
if (id != null) setHasDragged(true);
setDraggingIdState(id);
}, []);
const setDropTargetKey = useCallback((key: string | null) => {
dropTargetRef.current = key;
setDropTargetKeyState(key);
}, []);
useEffect(() => {
if (!draggingId && !dropTargetKey && !dragOverDayId) return;
const settle = (e: MouseEvent | PointerEvent) => {
if (e.type === 'mousemove' && e.buttons !== 0) return;
setDraggingIdState(null);
dropTargetRef.current = null;
setDropTargetKeyState(null);
setDragOverDayId(null);
dragDataRef.current = null;
window.__dragData = null;
};
document.addEventListener('mousemove', settle);
document.addEventListener('pointerdown', settle, true);
return () => {
document.removeEventListener('mousemove', settle);
document.removeEventListener('pointerdown', settle, true);
};
}, [draggingId, dropTargetKey, dragOverDayId, dragDataRef]);
return {
draggingId,
setDraggingId,
hasDragged,
dropTargetKey,
dropTargetRef,
setDropTargetKey,
dragOverDayId,
setDragOverDayId,
};
}
@@ -8,7 +8,7 @@ import {
Globe, Compass, Flag, Navigation, Map,
Church, Library, Store, Home, Cross,
Heart, Star, CreditCard, Wifi,
Luggage, Backpack, Zap,
Luggage, Backpack, Zap, Croissant, ShoppingBasket,
LucideIcon,
} from 'lucide-react'
@@ -22,7 +22,7 @@ export const CATEGORY_ICON_MAP: Record<string, LucideIcon> = {
Globe, Compass, Flag, Navigation, Map,
Church, Library, Store, Home, Cross,
Heart, Star, CreditCard, Wifi,
Luggage, Backpack, Zap,
Luggage, Backpack, Zap, Croissant, ShoppingBasket,
}
export const ICON_LABELS: Record<string, string> = {
@@ -37,6 +37,7 @@ export const ICON_LABELS: Record<string, string> = {
Church: 'Church', Library: 'Museum', Store: 'Market', Home: 'Accommodation', Cross: 'Medicine',
Heart: 'Favorite', Star: 'Top', CreditCard: 'Bank', Wifi: 'Internet',
Luggage: 'Luggage', Backpack: 'Backpack', Zap: 'Adventure',
Croissant: 'Bakery', ShoppingBasket: 'Groceries',
}
export function getCategoryIcon(iconName: string | null | undefined): LucideIcon {
@@ -8,6 +8,7 @@ import { pagesFor } from './dayPagerPages';
vi.mock('../../native/haptics', () => ({ tickHaptic: vi.fn() }));
const DAYS = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }, { id: 6 }] as unknown as Day[];
const LONG = Array.from({ length: 10 }, (_, k) => ({ id: k + 1 })) as unknown as Day[];
function setup(selectedDayId: number | null, over: Partial<Parameters<typeof MDayPager>[0]> = {}) {
const onSelectDay = vi.fn();
@@ -59,6 +60,19 @@ describe('pagesFor', () => {
).toEqual([4, 5, 6]);
});
it('also draws the days around the page a swipe heads for, so a run of swipes never meets blank pages', () => {
const drawn = (focusDayId: number | null) =>
pagesFor(LONG, 1, focusDayId)
.filter((p) => p.near)
.map((p) => p.dayId);
expect(drawn(6)).toEqual([1, 2, 3, 4, 5, 6, 7, 8]);
// Still only the selection's own window where nothing is previewed or the preview is gone.
expect(drawn(null)).toEqual([1, 2, 3]);
expect(drawn(99)).toEqual([1, 2, 3]);
// The focus never changes which page is current.
expect(pagesFor(LONG, 1, 6).find((p) => p.active)?.dayId).toBe(1);
});
it('keeps a page for a selection that points at no day, with the first day as the way back', () => {
expect(pagesFor(DAYS, null).map((p) => [p.key, p.dayId, p.active])).toEqual([
['none', null, true],
@@ -129,6 +143,19 @@ describe('MDayPager', () => {
expect(onPreview).toHaveBeenLastCalledWith(null);
});
it('draws the days ahead of a swipe while the strip still moves, before the selection lands', () => {
const { strip, onSelectDay } = setup(1);
expect(screen.queryByText('page 5')).not.toBeInTheDocument();
place(strip, 3, true);
fireEvent.scroll(strip);
expect(onSelectDay).not.toHaveBeenCalled();
expect(screen.getByText('page 1 live')).toBeInTheDocument();
expect(screen.getByText('page 5')).toBeInTheDocument();
expect(screen.queryByText('page 6')).not.toBeInTheDocument();
});
it('asks once, however many events report the same landing', () => {
const { strip, onSelectDay } = setup(2);
+13 -3
View File
@@ -16,7 +16,10 @@ import { pagesFor, type PagerItem } from './dayPagerPages';
* the swipe is decided, not once the snap has settled, which on iOS comes
* a good while later. The day only changes once the strip has come to rest on
* another page. Then
* the selection moves and the days around it draw their content.
* the selection moves and the days around it draw their content. The days
* around the page a swipe is heading for draw theirs as soon as it becomes the
* nearer one, so a run of quick swipes that never rests finds them drawn
* instead of blank until the snap lands (#3067).
* Keys follow the day ids, so the page that slid in keeps its state (scroll
* position, fetched route and weather) as it becomes the current one.
*
@@ -69,7 +72,10 @@ export default function MDayPager({
}: MDayPagerProps) {
const stripRef = useRef<HTMLDivElement>(null);
const [announcement, setAnnouncement] = useState('');
const pages = pagesFor(days, selectedDayId);
/** The page a swipe last headed for. It stays after the landing, so swiping
* back over the same days finds them drawn too. */
const [focusDayId, setFocusDayId] = useState<number | null>(null);
const pages = pagesFor(days, selectedDayId, focusDayId);
// Which page is current belongs in the key: on a trip of up to five days a
// chip tap can keep the same pages, and the strip then stayed on the old day
// while the rail already showed the new one.
@@ -135,7 +141,11 @@ export default function MDayPager({
const next = dayId != null && Number.isFinite(dayId) ? dayId : null;
if (next === previewed) return;
previewed = next;
if (next !== null) tickHaptic();
if (next !== null) {
// Draw ahead of the finger: the days around this one, before it lands.
setFocusDayId(next);
tickHaptic();
}
latest.current.onPreview?.(next);
};
+50 -9
View File
@@ -6,6 +6,11 @@ export interface MSection {
id: string;
label: string;
icon: LucideIcon;
/**
* The heading the section stands under. Consecutive sections with the same
* group share one heading; a screen whose sections name none shows none.
*/
group?: string;
}
interface MSectionRowProps {
@@ -33,6 +38,50 @@ export function MSectionRow({ section, active, current = false, onPick }: MSecti
);
}
/**
* The sections in order, each run of one group under its heading: the same list
* in the dropdown of a phone and in the list beside the page.
*/
export function MSectionList({
sections,
activeId,
markCurrent = false,
onPick,
}: {
sections: MSection[];
activeId: string;
/** Marks the active row as the page on show (the list beside the page). */
markCurrent?: boolean;
onPick: (id: string) => void;
}) {
return (
<>
{sections.map((section, i) => {
const heading = section.group && section.group !== sections[i - 1]?.group ? section.group : null;
return (
<div key={section.id} role="presentation">
{heading && (
<div
className={`px-[10px] pb-1 font-geist text-caption font-bold uppercase tracking-[.09em] text-m-faint ${
i === 0 ? 'pt-1' : 'pt-3'
}`}
>
{heading}
</div>
)}
<MSectionRow
section={section}
active={section.id === activeId}
current={markCurrent && section.id === activeId}
onPick={() => onPick(section.id)}
/>
</div>
);
})}
</>
);
}
/**
* The frame of a settings-like screen (settings, administration), one rule for
* both: the page column on a phone, a centred column on a wide window, and from
@@ -88,15 +137,7 @@ export default function MSectionNav({
<span className="min-w-0 flex-1 truncate text-subtitle font-bold text-m-ink">{title}</span>
</div>
{action && <div className="mb-1 px-[4px]">{action}</div>}
{sections.map((section) => (
<MSectionRow
key={section.id}
section={section}
active={section.id === activeId}
current={section.id === activeId}
onPick={() => onPick(section.id)}
/>
))}
<MSectionList sections={sections} activeId={activeId} markCurrent onPick={onPick} />
</nav>
);
}
+9 -1
View File
@@ -154,6 +154,9 @@ const SHORT_FORM_SHAPE = 'm-form-sheet short:flex-1 short:border-b-0 short:[--m-
// behind read through as sharp ghost text: the frosting it counted on is
// dropped whenever an ancestor animates its opacity (the scrim fading in),
// which WebKit and Chromium both do, so the fields floated over the list behind.
// For the same reason the dim fades on a layer of its own, beside the sheet and
// not around it: opacity multiplies down the tree, so a fading parent made even
// the opaque sheet see-through for its first frames.
const SURFACE = 'bg-[color:var(--m-sheetop)] border border-[color:var(--m-shbr)]'
// The docked sheet rises from below the screen edge like a native sheet; the
@@ -283,12 +286,17 @@ export default function MSheet({
// has to fall back to document.body (sheet mounted in the same commit as
// the shell).
<div
className={`m-root fixed inset-0 z-[60] ${dimTransparent ? 'bg-transparent short:bg-[color:var(--m-dim)]' : 'bg-[color:var(--m-dim)]'} ${open ? 'm-fade-in' : 'm-fade-out'}`}
className="m-root fixed inset-0 z-[60]"
role="presentation"
onClick={(e) => {
if (e.target === e.currentTarget) requestClose()
}}
>
<div
aria-hidden="true"
data-m-scrim=""
className={`pointer-events-none absolute inset-0 ${dimTransparent ? 'bg-transparent short:bg-[color:var(--m-dim)]' : 'bg-[color:var(--m-dim)]'} ${open ? 'm-fade-in' : 'm-fade-out'}`}
/>
<div className={regionClass(variant, wideAnchor, form)}>
<div className={boxClass(variant, wideWidth, form)}>
<PopoverArrow variant={variant} anchor={wideAnchor} />
+13 -4
View File
@@ -11,17 +11,24 @@ interface Page {
near: boolean;
}
/** Pages drawn with their content either side of the selection. */
/** Where a day stands in the strip, -1 for none. */
const indexOfDay = (days: PagerItem[], id: number | null): number =>
id == null ? -1 : days.findIndex((d) => d.id === id);
/** Pages drawn with their content either side of the selection, and of the page a swipe heads for. */
const REACH = 2;
/**
* A page for every day, so quick swipes in a row never run into the end of the
* strip before the first has settled (they used to spring back after two days).
* Only the selection and REACH days either side draw their content. A selection
* Only the selection and REACH days either side draw their content, and as
* many either side of `focusDayId`, the page a swipe is heading for: a run of
* quick swipes that has not landed yet then meets drawn pages instead of blank
* paper (#3067). Two windows at most, however long the trip. A selection
* that points at no day (the whole-trip view, or a day deleted remotely) still
* gets its page, with the first day next to it as a way back.
*/
export function pagesFor(days: PagerItem[], selectedDayId: number | null): Page[] {
export function pagesFor(days: PagerItem[], selectedDayId: number | null, focusDayId: number | null = null): Page[] {
const i = days.findIndex((d) => d.id === selectedDayId);
if (i < 0) {
const first = days[0];
@@ -30,5 +37,7 @@ export function pagesFor(days: PagerItem[], selectedDayId: number | null): Page[
...(first ? [{ key: `d${first.id}`, dayId: first.id, active: false, near: true }] : []),
];
}
return days.map((d, j) => ({ key: `d${d.id}`, dayId: d.id, active: j === i, near: Math.abs(j - i) <= REACH }));
const f = indexOfDay(days, focusDayId);
const near = (j: number) => Math.abs(j - i) <= REACH || (f >= 0 && Math.abs(j - f) <= REACH);
return days.map((d, j) => ({ key: `d${d.id}`, dayId: d.id, active: j === i, near: near(j) }));
}
+37 -8
View File
@@ -62,7 +62,14 @@
* 52px/26px offsets stand in for the phone status bar / home indicator, so
* real devices derive them from the safe-area insets. */
--bottom-nav-h: calc(84px + env(safe-area-inset-bottom, 0px));
--m-safe-top: calc(env(safe-area-inset-top, 0px) + 12px);
/* The safe area the iOS app measures (TrekBridgeViewController
* publishSafeArea) is a floor under env(): where a release lays the web view
* out below the status bar, WebKit reports 0 while a camera in a corner still
* reaches into the page. In a browser the variables are unset: env() alone. */
--m-safe-t: max(env(safe-area-inset-top, 0px), var(--trek-native-safe-top, 0px));
--m-safe-l: max(env(safe-area-inset-left, 0px), var(--trek-native-safe-left, 0px));
--m-safe-r: max(env(safe-area-inset-right, 0px), var(--trek-native-safe-right, 0px));
--m-safe-top: calc(var(--m-safe-t) + 12px);
/* The navigation rail's share of the leading edge (wide windows only), what
* every full-width fixed bar and the page column start after. */
--m-rail-w: 0px;
@@ -75,10 +82,10 @@
* reads the same values as the shell. */
html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-root {
--bottom-nav-h: env(safe-area-inset-bottom, 0px);
--m-rail-w: calc(env(safe-area-inset-left, 0px) + 100px);
--m-rail-w: calc(var(--m-safe-l) + 100px);
}
html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-root {
--m-rail-w: calc(env(safe-area-inset-right, 0px) + 100px);
--m-rail-w: calc(var(--m-safe-r) + 100px);
}
.dark .m-root {
@@ -123,9 +130,11 @@ html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-
/* ── Keyframes ──────────────────────────────────────────────────────────── */
/* The floating card pops in place, the way a native alert does. */
/* The floating card pops in place, the way a native alert does. It is opaque
halfway through the pop, so the page behind never reads through its fields. */
@keyframes m-sheet-in {
from { opacity: 0; transform: translateY(10px) scale(.96); }
45% { opacity: 1; }
to { opacity: 1; transform: translateY(0) scale(1); }
}
@keyframes m-sheet-out {
@@ -568,6 +577,17 @@ html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-
inset-inline-start: var(--m-rail-w, 0px);
inset-inline-end: 0;
}
/* Without the rail the floating bars keep clear of the sides' safe area too:
a camera in a corner can come as a side inset. The insets are the screen's,
not the text direction's, so right to left takes them the other way round.
On a wide window the rail takes the leading side and a bar may centre itself
(mx-auto). */
html:not(:has(.m-shell[data-size='wide'], .m-shell[data-size='split'])) :is(.m-bar-x, .m-span-x) {
margin-inline: var(--m-safe-l, 0px) var(--m-safe-r, 0px);
}
html[dir='rtl']:not(:has(.m-shell[data-size='wide'], .m-shell[data-size='split'])) :is(.m-bar-x, .m-span-x) {
margin-inline: var(--m-safe-r, 0px) var(--m-safe-l, 0px);
}
/* A screen whose background is a map reaches under the rail: the map runs to
the window's edge and the rail floats over it like the top controls do. Its
own bars then keep to the page column with m-bar-x / m-span-x. */
@@ -641,10 +661,10 @@ html:has(.m-shell) {
does; the fixed bars stay where they are. The rule above is for the browser,
where a pull at the top reloads an installed PWA, which the app cannot do.
Not on Android, whose stretch scales the bars too (MainActivity turns it
off), not sideways, and not on a screen with pull-to-refresh, whose pull
WebKit's bounce would race (mobile/usePullToRefresh.ts). */
html[data-native-ios]:not([data-pull-refresh]),
html[data-native-ios]:not([data-pull-refresh]):has(.m-shell) {
off), and not sideways. A screen with pull-to-refresh bounces too; its pull
holds only the move down from the top (mobile/usePullToRefresh.ts). */
html[data-native-ios],
html[data-native-ios]:has(.m-shell) {
overscroll-behavior-y: auto;
}
html:has(.m-shell) body {
@@ -664,6 +684,15 @@ html:has(.m-shell) {
html:has(.m-shell) [data-desktop-navbar] {
display: none;
}
/* A plugin's page inside the touch shell: below the status bar, above the dock,
after the rail, and exactly the visible height (100dvh), so the plugin's own
document is what scrolls instead of the app stretching past the screen. */
html:has(.m-shell) [data-plugin-page] {
--plugin-page-h: calc(100dvh - var(--bottom-nav-h, 0px));
box-sizing: border-box;
padding-top: env(safe-area-inset-top, 0px);
padding-inline-start: var(--m-rail-w, 0px);
}
html:has(.m-shell) .leaflet-control-zoom {
display: none !important;
}
@@ -12,6 +12,7 @@ import {
Puzzle,
Settings2,
SlidersHorizontal,
Smartphone,
User,
} from 'lucide-react'
import { useTranslation } from '../../../i18n'
@@ -26,8 +27,11 @@ import MSettingsIntegrations from './MSettingsIntegrations'
import MSettingsAccount from './MSettingsAccount'
import MSettingsAbout from './MSettingsAbout'
import MSettingsServer from './MSettingsServer'
import MAppLockCard from './MAppLockCard'
import MClientCertCard from './MClientCertCard'
import { isNativeApp } from '../../../native/platform'
import { useIsSplit } from '../../../hooks/sizeClass'
import MSectionNav, { MSectionRow, SECTION_SCREEN, type MSection } from '../../components/MSectionNav'
import MSectionNav, { MSectionList, SECTION_SCREEN, type MSection } from '../../components/MSectionNav'
/**
* Mobile settings screen: back + section-switcher pill on top, the section
@@ -44,21 +48,33 @@ export default function MSettings() {
// the page, the way Settings on an iPad does, instead of behind a dropdown.
const split = useIsSplit()
// Two groups, so it is clear what a setting reaches: the account's settings
// follow the user to every device; this device's stay on it (the server the
// app opens, the app lock, a client certificate, the offline copy).
const accountGroup = t('settings.groups.account')
const deviceGroup = t('settings.groups.device')
const app = isNativeApp()
const tabs: MSection[] = [
{ id: 'display', label: t('settings.tabs.display'), icon: SlidersHorizontal },
{ id: 'appearance', label: t('settings.tabs.appearance'), icon: Palette },
{ id: 'map', label: t('settings.tabs.map'), icon: Map },
{ id: 'notifications', label: t('settings.tabs.notifications'), icon: Bell },
...(hasIntegrations ? [{ id: 'integrations', label: t('settings.tabs.integrations'), icon: Plug }] : []),
...(hasPlugins && !managed ? [{ id: 'plugins', label: t('settings.tabs.plugins'), icon: Puzzle }] : []),
{ id: 'offline', label: t('settings.tabs.offline'), icon: CloudOff },
{ id: 'account', label: t('settings.tabs.account'), icon: User },
{ id: 'display', label: t('settings.tabs.display'), icon: SlidersHorizontal, group: accountGroup },
{ id: 'appearance', label: t('settings.tabs.appearance'), icon: Palette, group: accountGroup },
{ id: 'map', label: t('settings.tabs.map'), icon: Map, group: accountGroup },
{ id: 'notifications', label: t('settings.tabs.notifications'), icon: Bell, group: accountGroup },
...(hasIntegrations
? [{ id: 'integrations', label: t('settings.tabs.integrations'), icon: Plug, group: accountGroup }]
: []),
...(hasPlugins && !managed
? [{ id: 'plugins', label: t('settings.tabs.plugins'), icon: Puzzle, group: accountGroup }]
: []),
{ id: 'account', label: t('settings.tabs.account'), icon: User, group: accountGroup },
...(app ? [{ id: 'device', label: t('settings.tabs.device'), icon: Smartphone, group: deviceGroup }] : []),
{ id: 'offline', label: t('settings.tabs.offline'), icon: CloudOff, group: deviceGroup },
// Same call as the desktop page: About is about the project — what TREK is,
// where to file a bug, where to support it — and a customer of a hosted
// instance is the audience for none of it. The version and the source link
// move to the footer below, because AGPL §13 wants those offered wherever
// people reach the software over a network.
...(appVersion && !managed ? [{ id: 'about', label: t('settings.tabs.about'), icon: Info }] : []),
// people reach the software over a network. Under the product's name, not
// under either group.
...(appVersion && !managed ? [{ id: 'about', label: t('settings.tabs.about'), icon: Info, group: 'TREK' }] : []),
]
const active = tabs.find((tab) => tab.id === activeTab) || tabs[0]
@@ -105,17 +121,14 @@ export default function MSettings() {
{/* Section dropdown, in flow (pushes the content down like the demo) */}
{dropOpen && !split && (
<div className="m-pop-in -mt-[6px] mb-3 rounded-2xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheetop)] p-[6px] shadow-[0_16px_40px_-20px_rgba(0,0,0,.4)]">
{tabs.map((tab) => (
<MSectionRow
key={tab.id}
section={tab}
active={tab.id === active.id}
onPick={() => {
setActiveTab(tab.id)
setDropOpen(false)
}}
/>
))}
<MSectionList
sections={tabs}
activeId={active.id}
onPick={(id) => {
setActiveTab(id)
setDropOpen(false)
}}
/>
</div>
)}
@@ -126,8 +139,15 @@ export default function MSettings() {
{active.id === 'integrations' && hasIntegrations && <MSettingsIntegrations />}
{/* Per-plugin settings still reuse the existing responsive tab. */}
{active.id === 'plugins' && hasPlugins && !managed && <MSettingsPlugins />}
{/* Each card hides itself where it has nothing to offer; their own margins give way to one gap. */}
{active.id === 'device' && app && (
<div className="flex flex-col gap-3 [&>*]:m-0">
<MSettingsServer />
<MAppLockCard />
<MClientCertCard />
</div>
)}
{active.id === 'offline' && <MSettingsOffline />}
{active.id === 'account' && <MSettingsServer />}
{active.id === 'account' && <MSettingsAccount />}
{active.id === 'about' && appVersion && <MSettingsAbout appVersion={appVersion} />}
@@ -19,8 +19,6 @@ import {
import { useTranslation } from '../../../i18n'
import { MSetCard, MSetEyebrow, MSetInput, MSetButton, MSetHint } from './MSettingsUi'
import MConfirmSheet from './MConfirmSheet'
import MAppLockCard from './MAppLockCard'
import MClientCertCard from './MClientCertCard'
import PasswordChecklist from '../../../components/shared/PasswordChecklist'
import { fmtDate, usePasskeys } from '../../../components/Settings/usePasskeys'
import { stripTrailingSlashes, useAccountSettings } from '../../../components/Settings/useAccountSettings'
@@ -181,11 +179,7 @@ export default function MSettingsAccount() {
)}
{/* ── Two-factor authentication ───────────────────────────── */}
{/* The app lock, inside the app only (Face ID, Touch ID or the passcode). */}
<MAppLockCard />
{/* The client certificate for a server behind mutual TLS, once one is stored. */}
<MClientCertCard />
{/* The app lock and the client certificate belong to this device: MSettings, "This device". */}
<MSetCard title={t('settings.mfa.title')} icon={KeyRound} className="mt-3">
{mfaRequiredByPolicy && (
<div className="mb-3 flex gap-2 rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] p-3">
@@ -26,7 +26,7 @@ interface MVacaySettingsSheetProps {
/**
* Vacay settings sheet: weekend blocking (+ selectable weekend days), week
* start, carry-over, company holidays, public-holiday calendars (nager.at —
* start, carry-over, company holidays, public-holiday calendars (Nager.Holidays —
* label/color/country/region, several) and dissolving the Fusion.
*/
/** Each setting is a card on the inner surface, as the trip settings' sections. */
@@ -92,4 +92,23 @@ describe('usePullToRefresh', () => {
touch('touchend');
expect(onRefresh).not.toHaveBeenCalled();
});
it('holds a clearly downward move at the top from its first pixel, so the bounce does not start under the pull', () => {
setup();
touch('touchstart', 100, 100);
expect(touch('touchmove', 100, 103).defaultPrevented).toBe(true);
touch('touchend');
});
it('leaves the bounce everywhere else: a sideways start, and the page once it is scrolled', () => {
setup();
touch('touchstart', 100, 100);
expect(touch('touchmove', 104, 102).defaultPrevented).toBe(false);
touch('touchend');
Object.defineProperty(window, 'scrollY', { value: 300, configurable: true });
touch('touchstart', 100, 100);
expect(touch('touchmove', 100, 103).defaultPrevented).toBe(false);
touch('touchend');
expect(document.documentElement.hasAttribute('data-pull-refresh')).toBe(false);
});
});
+8 -13
View File
@@ -24,18 +24,13 @@ function refreshFailed(): void {}
* React render per frame; `state` only changes at the edges (armed, refreshing).
*/
/*
* The iOS app lets the page bounce at its ends (mobile.css). A pull is only told
* from a scroll after 8 px, and by then WebKit's own bounce has started and can no
* longer be stopped, so the two would pull at once. While a screen offers
* pull-to-refresh, <html> carries data-pull-refresh and the page does not bounce.
* The iOS app lets the page bounce at its ends (mobile.css), as every iOS list
* does. Only the pull down from the very top is this hook's: WebKit starts its
* own bounce on the first move, long before a pull is told from a scroll at 8 px,
* so a move that clearly heads down from the top is held from the first pixel.
* Everywhere else, the bottom of the page included, the bounce stays (TestFlight
* feedback: the screens with pull-to-refresh used not to bounce at all).
*/
let bounceHolds = 0;
function holdBounce(): void {
if (bounceHolds++ === 0) document.documentElement.setAttribute('data-pull-refresh', '');
}
function releaseBounce(): void {
if (--bounceHolds === 0) document.documentElement.removeAttribute('data-pull-refresh');
}
export function usePullToRefresh(
contentRef: RefObject<HTMLElement | null>,
@@ -77,6 +72,8 @@ export function usePullToRefresh(
const dx = e.touches[0].clientX - start.x;
const dy = e.touches[0].clientY - start.y;
if (!pulling) {
// Clearly downward at the top: WebKit's bounce must not start under the pull.
if (dy > 0 && dy >= 2 * Math.abs(dx) && scrolled() <= 0 && e.cancelable) e.preventDefault();
// Decide once: a sideways or upward start belongs to whatever is under the finger.
if (Math.abs(dy) < 8 && Math.abs(dx) < 8) return;
if (dy <= 0 || Math.abs(dx) > Math.abs(dy) || scrolled() > 0) {
@@ -127,7 +124,6 @@ export function usePullToRefresh(
});
};
holdBounce();
window.addEventListener('touchstart', onStart, { passive: true });
// Not passive: once a pull has started, the page must not also scroll or bounce.
window.addEventListener('touchmove', onMove, { passive: false });
@@ -139,7 +135,6 @@ export function usePullToRefresh(
window.removeEventListener('touchend', onEnd);
window.removeEventListener('touchcancel', onEnd);
place(0, false);
releaseBounce();
};
}, [contentRef, enabled, scrollerRef]);
+91 -1
View File
@@ -8,21 +8,28 @@ import {
BrowserSignInCancelled,
createHandoffSecret,
handoffUrl,
isHandoffReturn,
rememberHandoffReturn,
requestHandoffCode,
resumeBrowserSignIn,
signInThroughBrowser,
signInWithPasskey,
takeHandoffReturn,
} from './browserSignIn';
import { TrekShell } from './trekShell';
vi.mock('./trekShell', () => ({ APP_URL_SCHEME: 'com.liketrek.trek', TrekShell: { authenticate: vi.fn() } }));
vi.mock('./trekShell', () => ({
APP_URL_SCHEME: 'com.liketrek.trek',
TrekShell: { authenticate: vi.fn(), takeAuthCallback: vi.fn() },
}));
vi.mock('@simplewebauthn/browser', () => ({ startAuthentication: vi.fn() }));
vi.mock('../api/client', () => ({ authApi: { passkey: { loginOptions: vi.fn(), loginVerify: vi.fn() } } }));
vi.mock('../api/nativeAuth', () => ({ nativeAuthApi: { exchange: vi.fn(), handoff: vi.fn() } }));
beforeEach(() => {
vi.mocked(TrekShell.authenticate).mockReset();
vi.mocked(TrekShell.takeAuthCallback).mockReset().mockResolvedValue({ url: null });
localStorage.clear();
vi.mocked(nativeAuthApi.exchange).mockReset().mockResolvedValue();
});
@@ -89,6 +96,81 @@ describe('signInThroughBrowser', () => {
});
});
describe('resumeBrowserSignIn', () => {
// The app was ended while the browser was in front: the sign-in started, then
// the page that waited for it was gone. Only the stored verifier is left.
const startThenLoseThePage = async () => {
let finish: (value: { url: string }) => void = () => {};
vi.mocked(TrekShell.authenticate).mockReturnValue(new Promise((resolve) => (finish = resolve)));
void signInThroughBrowser('oidc');
await Promise.resolve();
const url = new URL(vi.mocked(TrekShell.authenticate).mock.calls[0][0].url);
return { challenge: url.searchParams.get('challenge') ?? '', finish };
};
it('redeems a return that reached an app started anew, with the verifier of that sign-in, once', async () => {
const { challenge } = await startThenLoseThePage();
vi.mocked(TrekShell.takeAuthCallback).mockResolvedValueOnce({ url: 'com.liketrek.trek://auth?code=c-9' });
await expect(resumeBrowserSignIn()).resolves.toBe(true);
const { code, verifier } = vi.mocked(nativeAuthApi.exchange).mock.calls[0][0];
expect(code).toBe('c-9');
expect(bytesToHex(sha256(new TextEncoder().encode(verifier)))).toBe(challenge);
vi.mocked(TrekShell.takeAuthCallback).mockResolvedValueOnce({ url: 'com.liketrek.trek://auth?code=c-9' });
await expect(resumeBrowserSignIn()).resolves.toBe(false);
expect(nativeAuthApi.exchange).toHaveBeenCalledTimes(1);
});
it('does nothing without a kept return, and keeps the verifier for one that may still come', async () => {
await startThenLoseThePage();
await expect(resumeBrowserSignIn()).resolves.toBe(false);
vi.mocked(TrekShell.takeAuthCallback).mockResolvedValueOnce({ url: 'com.liketrek.trek://auth?code=c-2' });
await expect(resumeBrowserSignIn()).resolves.toBe(true);
});
it('does nothing on a build without takeAuthCallback', async () => {
vi.mocked(TrekShell.takeAuthCallback).mockRejectedValueOnce({ code: 'UNIMPLEMENTED' });
await expect(resumeBrowserSignIn()).resolves.toBe(false);
expect(nativeAuthApi.exchange).not.toHaveBeenCalled();
});
it('drops a verifier older than the code it waits for', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
try {
await startThenLoseThePage();
vi.setSystemTime(Date.now() + 3 * 60 * 1000);
vi.mocked(TrekShell.takeAuthCallback).mockResolvedValueOnce({ url: 'com.liketrek.trek://auth?code=c-3' });
await expect(resumeBrowserSignIn()).resolves.toBe(false);
} finally {
vi.useRealTimers();
}
});
it('a sign-in that ends leaves the verifier of a newer one alone', async () => {
let rejectFirst: (err: unknown) => void = () => {};
vi.mocked(TrekShell.authenticate)
.mockReturnValueOnce(new Promise((_, reject) => (rejectFirst = reject)))
.mockReturnValueOnce(new Promise(() => {}));
const first = signInThroughBrowser('oidc').catch((err: unknown) => err);
void signInThroughBrowser('oidc');
await Promise.resolve();
const second = new URL(vi.mocked(TrekShell.authenticate).mock.calls[1][0].url).searchParams.get('challenge');
rejectFirst({ code: 'CANCELLED' });
await expect(first).resolves.toBeInstanceOf(BrowserSignInCancelled);
vi.mocked(TrekShell.takeAuthCallback).mockResolvedValueOnce({ url: 'com.liketrek.trek://auth?code=c-5' });
await expect(resumeBrowserSignIn()).resolves.toBe(true);
const { verifier } = vi.mocked(nativeAuthApi.exchange).mock.calls[0][0];
expect(bytesToHex(sha256(new TextEncoder().encode(verifier)))).toBe(second);
});
it('leaves nothing behind once the running app redeemed the return itself', async () => {
const { finish } = await startThenLoseThePage();
finish({ url: 'com.liketrek.trek://auth?code=c-4' });
await vi.waitFor(() => expect(nativeAuthApi.exchange).toHaveBeenCalledTimes(1));
vi.mocked(TrekShell.takeAuthCallback).mockResolvedValueOnce({ url: 'com.liketrek.trek://auth?code=c-4' });
await expect(resumeBrowserSignIn()).resolves.toBe(false);
});
});
describe('the remembered handoff return', () => {
const path = `/native-handoff?challenge=${'a'.repeat(64)}`;
@@ -118,6 +200,14 @@ describe('the remembered handoff return', () => {
localStorage.setItem('trek_native_handoff_return', 'not json');
expect(takeHandoffReturn()).toBeNull();
});
it('tells a way back to the handoff page from any other stored path', () => {
expect(isHandoffReturn(path)).toBe(true);
expect(isHandoffReturn('/native-handoff')).toBe(false);
expect(isHandoffReturn('/oauth/consent?client_id=foo')).toBe(false);
expect(isHandoffReturn(null)).toBe(false);
expect(isHandoffReturn(42)).toBe(false);
});
});
describe('signInWithPasskey', () => {
+79 -5
View File
@@ -12,9 +12,9 @@ import { APP_URL_SCHEME, TrekShell } from './trekShell';
* opens the server's /native-handoff page in the system browser, lets the user
* sign in there, and carries the session back with a one-time code.
*
* The verifier never leaves this function. Only its sha256 travels into the
* browser, and the code that comes back through the URL scheme is useless to
* anyone who does not also hold the verifier. The hash is computed in JS
* The verifier stays in the app. Only its sha256 travels into the browser, and
* the code that comes back through the URL scheme is useless to anyone who does
* not also hold the verifier. The hash is computed in JS
* because crypto.subtle is missing on a plain-http server, which is how many
* home networks reach theirs.
*/
@@ -50,6 +50,11 @@ export function rememberHandoffReturn(path: string): void {
}
}
/** A path back to the handoff page itself, and nothing else a stored value could point at. */
export function isHandoffReturn(path: unknown): path is string {
return typeof path === 'string' && path.startsWith(`${HANDOFF_PATH}?challenge=`);
}
/** The remembered handoff page, once: only a fresh path to the handoff page itself. */
export function takeHandoffReturn(): string | null {
try {
@@ -57,9 +62,9 @@ export function takeHandoffReturn(): string | null {
localStorage.removeItem(HANDOFF_RETURN_KEY);
if (!raw) return null;
const { path, at } = JSON.parse(raw) as { path?: unknown; at?: unknown };
if (typeof path !== 'string' || typeof at !== 'number') return null;
if (!isHandoffReturn(path) || typeof at !== 'number') return null;
if (Date.now() - at > HANDOFF_RETURN_TTL_MS) return null;
return path.startsWith(`${HANDOFF_PATH}?challenge=`) ? path : null;
return path;
} catch {
return null;
}
@@ -99,9 +104,76 @@ export class BrowserSignInCancelled extends Error {
}
}
const PENDING_SIGN_IN_KEY = 'trek_native_pending_sign_in';
// The server keeps the code a minute (NATIVE_HANDOFF_CODE_TTL_MS); two leave room for a slow start.
const PENDING_SIGN_IN_TTL_MS = 2 * 60 * 1000;
/**
* Android may end the app while the system browser is in front, a Samsung
* phone short of memory readily so. The browser's return then starts a new
* app, and the call that waited for it is gone with the verifier it held, so
* the user came back to the sign-in page, signed in to the server but not to
* the app. The verifier is kept in this server's storage in the app until the
* return is redeemed, or for two minutes at most.
*/
function keepPendingSignIn(verifier: string): void {
try {
localStorage.setItem(PENDING_SIGN_IN_KEY, JSON.stringify({ verifier, at: Date.now() }));
} catch {
/* storage blocked: only the return to a running app can be redeemed */
}
}
/** Drops the kept verifier, if it is still this sign-in's: a newer one may have taken its place. */
function dropPendingSignIn(verifier: string): void {
try {
const raw = localStorage.getItem(PENDING_SIGN_IN_KEY);
if (raw && (JSON.parse(raw) as { verifier?: unknown }).verifier === verifier) {
localStorage.removeItem(PENDING_SIGN_IN_KEY);
}
} catch {
/* storage blocked or the entry unreadable: nothing of ours to drop */
}
}
/** The verifier of a sign-in still open, once. */
function takePendingSignIn(): string | null {
try {
const raw = localStorage.getItem(PENDING_SIGN_IN_KEY);
localStorage.removeItem(PENDING_SIGN_IN_KEY);
if (!raw) return null;
const { verifier, at } = JSON.parse(raw) as { verifier?: unknown; at?: unknown };
if (typeof verifier !== 'string' || typeof at !== 'number') return null;
return Date.now() - at <= PENDING_SIGN_IN_TTL_MS ? verifier : null;
} catch {
return null;
}
}
/**
* Redeems a sign-in whose return reached an app started anew (see
* keepPendingSignIn). True when the WebView now holds a session; false when
* there was nothing to redeem, or the app is a build that cannot tell.
*/
export async function resumeBrowserSignIn(): Promise<boolean> {
let returned: string | null;
try {
({ url: returned } = await TrekShell.takeAuthCallback());
} catch {
return false; // a build without takeAuthCallback
}
if (!returned) return false;
const verifier = takePendingSignIn();
const code = new URL(returned).searchParams.get('code');
if (!verifier || !code) return false;
await nativeAuthApi.exchange({ code, verifier });
return true;
}
/** Resolves once the WebView holds a session cookie of its own. */
export async function signInThroughBrowser(start?: BrowserSignInStart, invite?: string): Promise<void> {
const { verifier, challenge } = createHandoffSecret();
keepPendingSignIn(verifier);
let returned: string;
try {
({ url: returned } = await TrekShell.authenticate({
@@ -109,9 +181,11 @@ export async function signInThroughBrowser(start?: BrowserSignInStart, invite?:
callbackScheme: APP_URL_SCHEME,
}));
} catch (err) {
dropPendingSignIn(verifier);
if ((err as { code?: string })?.code === 'CANCELLED') throw new BrowserSignInCancelled();
throw err;
}
dropPendingSignIn(verifier);
const code = new URL(returned).searchParams.get('code');
if (!code) throw new Error('The browser returned without a sign-in code');
await nativeAuthApi.exchange({ code, verifier });
+27
View File
@@ -8,6 +8,7 @@ const shell = vi.hoisted(() => ({
storeFinish: vi.fn(),
storeRestore: vi.fn(),
storeUnfinished: vi.fn(),
storeHeld: vi.fn(),
addListener: vi.fn(),
}));
@@ -34,6 +35,17 @@ describe('in-app purchase client', () => {
expect(productIdFor('pro', 'year')).toBe('cloud.pro.yearly');
});
it('the fake client can play a store account that already holds a subscription', async () => {
localStorage.setItem('trek-iap-fake-held', '1');
try {
expect(await fakeIapClient.held()).toBe(true);
expect(await fakeIapClient.purchase('cloud.plus.monthly')).toEqual({ kind: 'subscribed' });
} finally {
localStorage.removeItem('trek-iap-fake-held');
}
expect(await fakeIapClient.held()).toBe(false);
});
it('the fake client yields a receipt for the product asked for', async () => {
expect(await fakeIapClient.isAvailable()).toBe(true);
const outcome = await fakeIapClient.purchase('cloud.plus.monthly');
@@ -102,6 +114,21 @@ describe('native client', () => {
expect(await nativeIapClient.purchase('cloud.plus.monthly')).toEqual({ kind: 'failed' });
});
it('says when the store account already holds a subscription, and buys nothing then', async () => {
shell.storePurchase.mockResolvedValue({ kind: 'subscribed' });
expect(await nativeIapClient.purchase('cloud.plus.monthly')).toEqual({ kind: 'subscribed' });
shell.storeHeld.mockResolvedValue({ held: true });
expect(await nativeIapClient.held()).toBe(true);
expect(shell.storeHeld).toHaveBeenCalledWith({ prefix: 'cloud.' });
shell.storeHeld.mockResolvedValue({ held: false });
expect(await nativeIapClient.held()).toBe(false);
});
it('a build without storeHeld counts as holding nothing; the purchase still guards', async () => {
shell.storeHeld.mockRejectedValue(new Error('not implemented'));
expect(await nativeIapClient.held()).toBe(false);
});
it('finishes by transaction id and swallows a failure', async () => {
const purchase = { platform: 'apple' as const, productId: 'cloud.plus.monthly', receipt: 'x', transactionId: '7' };
shell.storeFinish.mockResolvedValue(undefined);
+34 -3
View File
@@ -29,10 +29,16 @@ export interface Purchase {
/**
* What a purchase attempt came to. `cancelled` is the customer backing out, not
* an error; `pending` is a purchase waiting on someone else (Ask to Buy, a bank),
* which a restore picks up once it goes through.
* which a restore picks up once it goes through. `subscribed` means the store
* account already holds a subscription: one per Apple ID or Google account, and
* a new one only once it has ended, so nothing was bought.
*/
type PurchaseOutcome =
{ kind: 'bought'; purchase: Purchase } | { kind: 'cancelled' } | { kind: 'pending' } | { kind: 'failed' };
| { kind: 'bought'; purchase: Purchase }
| { kind: 'cancelled' }
| { kind: 'pending' }
| { kind: 'failed' }
| { kind: 'subscribed' };
export interface IapClient {
/** Whether this build can take a payment. */
@@ -45,6 +51,12 @@ export interface IapClient {
prices(productIds: string[]): Promise<Map<string, string>>;
/** A test build (TestFlight, App Review), whose purchases cost nothing and may go ahead before the opening. */
isSandbox(): Promise<boolean>;
/**
* Whether the store account already holds a delivered subscription. While it
* does, nothing can be bought: on the App Store another plan would change that
* subscription, on Google Play it would run beside it.
*/
held(): Promise<boolean>;
/** Runs the platform's purchase sheet for a product and resolves with what became of it. */
purchase(productId: string): Promise<PurchaseOutcome>;
/** Tells the store a purchase was delivered, once its instance exists. */
@@ -88,7 +100,16 @@ export const fakeIapClient: IapClient = {
async isSandbox() {
return true;
},
async held() {
// `localStorage['trek-iap-fake-held'] = '1'` shows what a store account with a running subscription sees.
try {
return localStorage.getItem('trek-iap-fake-held') === '1';
} catch {
return false;
}
},
async purchase(productId) {
if (await this.held()) return { kind: 'subscribed' };
await new Promise((resolve) => setTimeout(resolve, 900));
const nonce = String(Date.now());
return {
@@ -160,12 +181,22 @@ export const nativeIapClient: IapClient = {
},
};
}
if (result.kind === 'cancelled' || result.kind === 'pending') return { kind: result.kind };
if (result.kind === 'cancelled' || result.kind === 'pending' || result.kind === 'subscribed') {
return { kind: result.kind };
}
return { kind: 'failed' };
} catch {
return { kind: 'failed' };
}
},
async held() {
try {
return (await TrekShell.storeHeld({ prefix: PRODUCT_PREFIX })).held === true;
} catch {
// A build without storeHeld: the purchase itself still refuses a second subscription.
return false;
}
},
async finish(purchase) {
try {
await TrekShell.storeFinish({ transactionId: purchase.transactionId });
+55 -1
View File
@@ -1,4 +1,4 @@
import { afterEach, describe, expect, it } from 'vitest';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { prepareField, prepareKeyboardFields } from './keyboardFields';
function field(html: string): HTMLInputElement {
@@ -89,3 +89,57 @@ describe('prepareKeyboardFields', () => {
expect(b.hasAttribute('enterkeyhint')).toBe(false);
});
});
describe('closeOnDone', () => {
// Wired the way the app wires it: on the document, in the capture phase,
// ahead of every handler the field has of its own.
const enter = (el: HTMLElement) =>
el.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }));
let stop: () => void = () => {};
afterEach(() => {
stop();
vi.useRealTimers();
});
it('closes the keyboard when nothing took the Enter of a "done" field', () => {
vi.useFakeTimers();
stop = prepareKeyboardFields(document);
const el = field('<input name="title" enterkeyhint="done">');
el.focus();
enter(el);
vi.runAllTimers();
expect(document.activeElement).not.toBe(el);
});
it('keeps the keyboard for a field that acted on the Enter and cleared itself', () => {
vi.useFakeTimers();
stop = prepareKeyboardFields(document);
const el = field('<input name="item" enterkeyhint="done">');
el.value = 'Socks';
el.focus();
el.addEventListener('keydown', () => {
el.value = '';
});
enter(el);
vi.runAllTimers();
expect(document.activeElement).toBe(el);
});
it('leaves "go" and "search" fields and handled Enters alone', () => {
vi.useFakeTimers();
stop = prepareKeyboardFields(document);
for (const hint of ['go', 'search']) {
const el = field(`<input enterkeyhint="${hint}">`);
el.focus();
enter(el);
vi.runAllTimers();
expect(document.activeElement).toBe(el);
}
const handled = field('<input enterkeyhint="done">');
handled.focus();
handled.addEventListener('keydown', (e) => e.preventDefault());
enter(handled);
vi.runAllTimers();
expect(document.activeElement).toBe(handled);
});
});
+26
View File
@@ -18,6 +18,12 @@
*
* An attribute the field sets itself always wins, and textareas, which take
* Enter as a new line, keep the return key. Only the app calls this.
*
* The "done" key also has to close the keyboard: a web view only sends Enter,
* and a field outside a form has nothing listening for it, so the key did
* nothing. When no handler took the Enter (the field still has focus and the
* same text a moment later) the field lets go of the focus. A field that acts
* on Enter and clears itself, such as a list that adds the next item, keeps it.
*/
const SKIP_TYPES = new Set([
@@ -104,14 +110,34 @@ export function prepareField(target: EventTarget | null): void {
}
}
/**
* Enter on a "done" field that nothing acted on closes the keyboard. Listens in
* the capture phase, so the field's text is read before any handler of the field
* runs; whether one took the Enter is read off the event once it has gone round.
*/
function closeOnDone(e: KeyboardEvent): void {
const el = e.target;
if (e.key !== 'Enter' || e.isComposing) return;
if (!(el instanceof HTMLInputElement) || el.getAttribute('enterkeyhint') !== 'done') return;
const before = el.value;
// After every handler of this Enter, including ones React schedules.
setTimeout(() => {
if (e.defaultPrevented) return;
if (el.ownerDocument.activeElement === el && el.value === before) el.blur();
}, 0);
}
export function prepareKeyboardFields(doc: Document = document): () => void {
// On the touch, before the focus: the keyboard is set up as the field takes it.
const onTouch = (e: Event) => prepareField(e.target instanceof Element ? e.target.closest('input') : null);
const onFocus = (e: FocusEvent) => prepareField(e.target);
doc.addEventListener('touchstart', onTouch, { capture: true, passive: true });
doc.addEventListener('focusin', onFocus, true);
// Capturing, so the text is read before the field's own handler can change it.
doc.addEventListener('keydown', closeOnDone, true);
return () => {
doc.removeEventListener('touchstart', onTouch, { capture: true });
doc.removeEventListener('focusin', onFocus, true);
doc.removeEventListener('keydown', closeOnDone, true);
};
}
+3 -3
View File
@@ -6,9 +6,6 @@
/** The privacy policy the store listings name too. */
export const PRIVACY_URL = 'https://liketrek.com/privacy?app=1';
/** What a TREK server is and how to run one, for someone who has none yet. */
export const SERVER_DOCS_URL = 'https://github.com/liketrek/TREK#readme';
/** Running the app with a sign-in proxy (Cloudflare Access, Pangolin and the like) in front of TREK. */
export const AUTH_PROXY_DOCS_URL = 'https://github.com/liketrek/TREK/wiki/Native-Apps#behind-a-sign-in-proxy';
@@ -27,5 +24,8 @@ export const CLOUD_URL = 'https://liketrek.com';
* store rules ask for it next to the purchase, together with the privacy policy.
*/
export const STORE_TERMS_URL = 'https://www.apple.com/legal/internet-services/itunes/dev/stdeula/';
/** Where the App Store and Google Play let someone manage or end a subscription. */
export const APP_STORE_SUBSCRIPTIONS_URL = 'https://apps.apple.com/account/subscriptions';
export const PLAY_SUBSCRIPTIONS_URL = 'https://play.google.com/store/account/subscriptions?package=com.liketrek.trek';
/** Our terms for TREK Cloud (§ 5a covers a purchase in the app), as the app opens them: without the site's sales header. */
export const CLOUD_TERMS_URL = 'https://liketrek.com/terms?app=1';
+26 -1
View File
@@ -11,9 +11,12 @@ import { prepareKeyboardFields } from './keyboardFields';
import { scrollToTop, startNativeApp } from './nativeApp';
import { keepOfflineShellFresh } from './offlineShell';
import { isNativeApp, isNativeIos } from './platform';
import { openPushTarget } from './push';
import { trackTouchInput } from './touchInput';
vi.mock('@capacitor/app', () => ({ App: { addListener: vi.fn(), minimizeApp: vi.fn() } }));
vi.mock('@capacitor/app', () => ({
App: { addListener: vi.fn(), minimizeApp: vi.fn(), getLaunchUrl: vi.fn(async () => undefined) },
}));
vi.mock('@capacitor/keyboard', () => ({
Keyboard: { setAccessoryBarVisible: vi.fn(), addListener: vi.fn(async () => ({ remove: vi.fn() })) },
}));
@@ -193,4 +196,26 @@ describe('startNativeApp', () => {
expect(report).not.toHaveBeenCalled();
vi.unstubAllGlobals();
});
it('follows the link a widget tap launched the app with, once per launch', async () => {
sessionStorage.clear();
vi.mocked(App.getLaunchUrl).mockResolvedValue({ url: 'com.liketrek.trek://navigate/trips/5?tab=listen' });
startNativeApp();
await vi.waitFor(() => expect(openPushTarget).toHaveBeenCalledWith('/trips/5?tab=listen'));
// A reload of the page in the same launch does not follow it again.
vi.mocked(openPushTarget).mockClear();
startNativeApp();
await Promise.resolve();
await Promise.resolve();
expect(openPushTarget).not.toHaveBeenCalled();
});
it('leaves the start page alone for a launch without a TREK link', async () => {
sessionStorage.clear();
vi.mocked(App.getLaunchUrl).mockResolvedValue({ url: 'https://example.com/elsewhere' });
startNativeApp();
await Promise.resolve();
await Promise.resolve();
expect(openPushTarget).not.toHaveBeenCalled();
});
});
+25
View File
@@ -59,6 +59,8 @@ export function startNativeApp(): void {
const prefix = `${APP_URL_SCHEME}://navigate`;
if (url.startsWith(prefix)) openPushTarget(url.slice(prefix.length) || '/');
});
// A tap that launched the app comes as the launch URL, not as appUrlOpen.
void openLaunchLink();
// A tap on the status bar scrolls the list under it back to the top, as in
// every iOS app (the status-bar plugin fires statusTap on iOS).
@@ -113,6 +115,29 @@ async function fetchServerFeatures(): Promise<{ minNativeShellApi?: unknown }> {
return (await res.json()) as { minNativeShellApi?: unknown };
}
/** The launch link this web view has already followed, so a reload does not follow it again. */
const LAUNCH_LINK_KEY = 'trek_launch_link_done';
/**
* A widget or Live Activity tap that starts the app from closed hands it
* com.liketrek.trek://navigate/<path> as the launch URL. appUrlOpen only fires
* for a running app, so the path was lost and the app opened its start page
* (a packing widget landed on the trip's plan, not its lists). Followed once
* per launch; the trip planner takes a ?tab= on a trip it already shows.
*/
async function openLaunchLink(): Promise<void> {
const prefix = `${APP_URL_SCHEME}://navigate`;
try {
const url = (await App.getLaunchUrl())?.url;
if (!url || !url.startsWith(prefix)) return;
if (sessionStorage.getItem(LAUNCH_LINK_KEY) === url) return;
sessionStorage.setItem(LAUNCH_LINK_KEY, url);
openPushTarget(url.slice(prefix.length) || '/');
} catch {
/* no launch URL here (an older app binary, or storage blocked): the start page stays */
}
}
/** The scrolled list in the middle of the screen, else the page, back to its top. */
export function scrollToTop(): void {
let el = document.elementFromPoint(window.innerWidth / 2, window.innerHeight / 2) as HTMLElement | null;
+20
View File
@@ -0,0 +1,20 @@
import { describe, expect, it } from 'vitest';
import { priceValue } from './priceValue';
describe('priceValue', () => {
it('reads the store price strings of the usual currencies, in hundredths', () => {
expect(priceValue('9,99 €')).toBe(999);
expect(priceValue('$9.99')).toBe(999);
expect(priceValue('59,99 €')).toBe(5999);
expect(priceValue('¥1,500')).toBe(150000);
expect(priceValue('1.234,50 €')).toBe(123450);
expect(priceValue('CHF 10')).toBe(1000);
});
it('has no value for nothing or for a string it cannot read with confidence', () => {
expect(priceValue(undefined)).toBeNull();
expect(priceValue('')).toBeNull();
expect(priceValue('free')).toBeNull();
expect(priceValue('1.2.3')).toBeNull();
});
});
+14
View File
@@ -0,0 +1,14 @@
/**
* The amount in a store price string such as "9,99 €", "$9.99" or "¥1,500", in
* hundredths; null when it cannot be read with confidence. Only ever compared
* with another price of the same store, never shown.
*/
export function priceValue(label: string | undefined): number | null {
if (!label) return null;
const digits = label.replace(/[^\d.,]/g, '');
const match = /^(\d{1,3}(?:[.,]\d{3})*|\d+)(?:[.,](\d{1,2}))?$/.exec(digits);
if (!match) return null;
const whole = Number(match[1].replace(/[.,]/g, ''));
const fraction = match[2] ? Number(match[2].padEnd(2, '0')) : 0;
return Number.isFinite(whole) ? whole * 100 + fraction : null;
}
+20 -5
View File
@@ -1,9 +1,9 @@
import { describe, expect, it, vi } from 'vitest';
import { candidateUrls, probeDemo, probeServer, type ProbeResponse } from './serverAddress';
import { candidateUrls, certificateTargetFor, probeDemo, probeServer, type ProbeResponse } from './serverAddress';
const features = (
url: string,
data: unknown = { bookingImport: false, aiParsing: false, nativeApp: true, nativeApi: 2 }
data: unknown = { bookingImport: false, aiParsing: false, nativeApp: true, nativeApi: 3 }
): ProbeResponse => ({ status: 200, data, url });
describe('candidateUrls', () => {
@@ -24,9 +24,24 @@ describe('candidateUrls', () => {
});
});
describe('certificateTargetFor', () => {
it('keeps a certificate for the https address the typed text stands for', () => {
expect(certificateTargetFor('Trek.Example.com')).toEqual({ host: 'trek.example.com', port: 443 });
expect(certificateTargetFor(' nas.local:8443/trek ')).toEqual({ host: 'nas.local', port: 8443 });
expect(certificateTargetFor('https://trek.example.com:443/')).toEqual({ host: 'trek.example.com', port: 443 });
});
it('has no target for a plain http address or nothing typed', () => {
expect(certificateTargetFor('http://nas.local:3001')).toBeNull();
expect(certificateTargetFor('')).toBeNull();
expect(certificateTargetFor(' ')).toBeNull();
expect(certificateTargetFor('ftp://trek.example.com')).toBeNull();
});
});
describe('probeServer', () => {
it('accepts a server at the minimum native API version or above', async () => {
for (const nativeApi of [2, 3]) {
for (const nativeApi of [3, 4]) {
const data = { bookingImport: false, nativeApp: true, nativeApi };
const get = vi.fn().mockResolvedValue(features('https://trek.example.com/api/health/features', data));
expect(await probeServer('https://trek.example.com', get)).toEqual({ ok: true, url: 'https://trek.example.com' });
@@ -34,7 +49,7 @@ describe('probeServer', () => {
});
it('calls a server below the minimum native API version too old', async () => {
const data = { bookingImport: false, nativeApp: true, nativeApi: 1 };
const data = { bookingImport: false, nativeApp: true, nativeApi: 2 };
const get = vi.fn().mockResolvedValue(features('https://trek.example.com/api/health/features', data));
expect(await probeServer('https://trek.example.com', get)).toEqual({ ok: false, reason: 'tooOld' });
});
@@ -181,7 +196,7 @@ describe('probeServer behind mutual TLS', () => {
});
it('connects where the proxy asked and TREK answered, with or without a certificate', async () => {
const trek = { bookingImport: false, nativeApp: true, nativeApi: 2 };
const trek = { bookingImport: false, nativeApp: true, nativeApi: 3 };
for (const sent of [true, false]) {
const get = vi.fn().mockResolvedValue(asked(200, sent, trek));
expect(await probeServer('https://trek.example.com', get)).toEqual({ ok: true, url: 'https://trek.example.com' });
+16 -3
View File
@@ -43,12 +43,13 @@ const FEATURES_PATH = '/api/health/features';
/**
* The oldest server API this app can work with (`nativeApi` in the features
* response). 2 is TREK 5.1.3, the first server whose sign-in from the app does
* not end in the browser. A server without the field is older still. Raising it
* response). 3 is TREK 5.1.4, whose UI follows a widget or Live Activity tap
* that starts the app; 2 was 5.1.3, the first server whose sign-in from the app
* does not end in the browser. A server without the field is older still. Raising it
* goes with SERVER_CHECK in TrekServerStore (iOS and Android), so a server the
* app remembers from before is checked against the new minimum once.
*/
const MIN_NATIVE_API = 2;
const MIN_NATIVE_API = 3;
function normalize(raw: string): string | null {
let parsed: URL;
@@ -74,6 +75,18 @@ export function candidateUrls(input: string): string[] {
return candidates.filter((url): url is string => url !== null);
}
/**
* The host and port a client certificate added on the address screen, before
* any check, is kept for: the https address the typed text stands for. Null
* for nothing typed or a plain http address, which never gets a certificate.
*/
export function certificateTargetFor(input: string): { host: string; port: number } | null {
const https = candidateUrls(input).find((url) => url.startsWith('https://'));
if (!https) return null;
const url = new URL(https);
return { host: url.hostname.toLowerCase(), port: url.port ? Number(url.port) : 443 };
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
+22 -4
View File
@@ -18,7 +18,12 @@ export interface TrekShellPlugin {
* newer one (SERVER_CHECK in TrekServerStore). Set only while no server is,
* so the address screen can check it again, pre-filled.
*/
getServer(): Promise<{ url: string | null; previousUrl?: string | null }>;
/**
* The server picked, the one before an update asked to check it again, and
* why its page did not load last time (taken once; builds before 5.1.4 leave
* it out).
*/
getServer(): Promise<{ url: string | null; previousUrl?: string | null; failure?: string | null }>;
/**
* Remembers the server and loads it. The current page is gone afterwards.
* `signInHosts` are the hosts of a proxy's sign-in page in front of it
@@ -27,13 +32,14 @@ export interface TrekShellPlugin {
* opens the server's welcome page with it, which signs the buyer in. A build
* without this option ignores it and opens the server as usual.
* `labels` are the words of the bar the app shows over a proxy's sign-in page,
* in the user's language: the server's UI is not there to say them.
* or over an error page in place of the server's (a proxy's block page), in the
* user's language: the server's UI is not there to say them.
*/
setServer(options: {
url: string;
signInHosts?: string[];
welcome?: string;
labels?: { signInHint: string; changeServer: string };
labels?: { signInHint: string; changeServer: string; errorPageHint?: string };
}): Promise<void>;
/** Forgets the server and returns to the address screen. */
resetServer(): Promise<void>;
@@ -45,6 +51,12 @@ export interface TrekShellPlugin {
* user closes the browser.
*/
authenticate(options: { url: string; callbackScheme: string }): Promise<{ url: string }>;
/**
* Android: a return to the sign-in scheme that found no authenticate() call
* waiting, because the app was started anew meanwhile. Handed out once, and
* only for two minutes, as long as the server keeps its code. Not in iOS builds, nor in Android builds before 5.1.4.
*/
takeAuthCallback(): Promise<{ url: string | null }>;
/** iOS: stores the server's start page for a cold start without network. */
refreshOfflineCopy(): Promise<{ saved: boolean }>;
/** iOS: loads that copy under the server's origin. False when there is none. */
@@ -105,7 +117,8 @@ export interface TrekShellPlugin {
* Android `purchaseToken`, which the control plane verifies with Google Play.
*/
storePurchase(options: { productId: string }): Promise<{
kind: 'bought' | 'cancelled' | 'pending' | 'failed';
/** `subscribed`: this store account already holds a delivered subscription, so nothing was bought. */
kind: 'bought' | 'cancelled' | 'pending' | 'failed' | 'subscribed';
jws?: string;
purchaseToken?: string;
productId?: string;
@@ -127,6 +140,11 @@ export interface TrekShellPlugin {
}): Promise<{ result: 'shown' | 'unsupported' }>;
/** iOS, feature storeKit: the newest active subscription under `prefix` on this Apple ID, if any. */
storeRestore(options: { prefix: string }): Promise<{ jws?: string; transactionId?: string }>;
/**
* Whether this Apple ID or Google account holds a delivered subscription under
* `prefix`, read without asking for a password. Not in builds before 5.1.4.
*/
storeHeld(options: { prefix: string }): Promise<{ held: boolean }>;
/** Feature watch: what the Apple Watch app shows (native/watch.ts), as JSON, sent on through WatchConnectivity. */
setWatchSnapshot(options: { json: string }): Promise<void>;
/** Feature watch: the ticks the watch sent since the last call, oldest first (parsed by parseWatchActions). */
+35
View File
@@ -15,6 +15,7 @@ vi.mock('./trekShell', () => ({
import { TrekShell } from './trekShell';
import {
buildSnapshot,
liveDayDue,
pickTrip,
publishWidgets,
todayOf,
@@ -151,6 +152,40 @@ describe('todayOf and tripDayState', () => {
});
});
describe('liveDayDue', () => {
const evening = {
tripTitle: 'T',
path: '/trips/1',
dayLabel: 'D',
stops: [
{ name: 'Walk', time: null, minutes: null },
{ name: 'Uber to the airport', time: '18:00', minutes: 18 * 60 },
{ name: 'Flight', time: '21:00', minutes: 21 * 60 },
],
};
it('keeps the lock screen free until three hours before the first timed stop', () => {
expect(liveDayDue(evening, 6 * 60 + 32)).toBe(false);
expect(liveDayDue(evening, 14 * 60 + 59)).toBe(false);
expect(liveDayDue(evening, 15 * 60)).toBe(true);
});
it('stays on through the day once it has started, until the day is done', () => {
expect(liveDayDue(evening, 19 * 60)).toBe(true);
expect(liveDayDue(evening, 23 * 60 + 30)).toBe(true);
});
it('starts from the earliest timed stop, wherever it stands in the list', () => {
const early = { ...evening, stops: [...evening.stops, { name: 'Breakfast', time: '08:00', minutes: 8 * 60 }] };
expect(liveDayDue(early, 5 * 60)).toBe(true);
expect(liveDayDue(early, 4 * 60 + 59)).toBe(false);
});
it('has nothing to show on a day without times', () => {
expect(liveDayDue({ ...evening, stops: [{ name: 'Walk', time: null, minutes: null }] }, 12 * 60)).toBe(false);
});
});
describe('publishWidgets', () => {
it('writes the snapshot without the internal minutes and ends the activity on a day without times', async () => {
const snapshot = buildSnapshot(
+17
View File
@@ -357,6 +357,23 @@ export function tripDayState(day: TripDay, nowMinutes: number, allDone: string):
};
}
/** How long before the day's first timed stop its Live Activity appears. */
const LIVE_LEAD_MINUTES = 3 * 60;
/**
* Whether the travel day's Live Activity belongs on the lock screen now: from
* three hours before the first stop with a time, then until the day is done. A
* day whose first stop is an evening flight does not hold the lock screen from
* the morning on.
*/
export function liveDayDue(day: TripDay, nowMinutes: number): boolean {
const first = day.stops.reduce<number | null>(
(min, s) => (s.minutes != null && (min === null || s.minutes < min) ? s.minutes : min),
null
);
return first !== null && nowMinutes >= first - LIVE_LEAD_MINUTES;
}
/** A trip a widget can be set to in Edit Widget, and its snapshot. */
export interface TripWidgetSnapshot {
id: number;
+2 -1
View File
@@ -28,7 +28,8 @@ export default function PluginPage(): React.ReactElement {
return (
<PageShell background="var(--bg-secondary)" navOffset="var(--nav-h, 56px)">
<HelpAnchor id="settings-plugins" />
<div style={{ height: 'calc(100vh - var(--nav-h, 56px))' }}>
{/* The phone shell sets --plugin-page-h and its own insets (mobile.css). */}
<div data-plugin-page style={{ height: 'var(--plugin-page-h, calc(100vh - var(--nav-h, 56px)))' }}>
<PluginFrame pluginId={pluginId} title={plugin?.name} fill surface="plugin-page" className="w-full h-full" />
</div>
</PageShell>
+61 -1
View File
@@ -8,6 +8,7 @@ import {
Fingerprint,
RefreshCw,
ShieldOff,
Unlink,
UserCog,
UserPlus,
} from 'lucide-react';
@@ -114,8 +115,9 @@ export default function AdminUserModals({ admin, t }: AdminUserModalsProps): Rea
rotatingJwt,
handleCreateUser,
handleSaveUser,
oidcConfigured,
} = admin;
const { rotateJwt, resetPasskeys, resetMfa } = useAdminUserActions(admin, t);
const { rotateJwt, resetPasskeys, resetMfa, unlinkSso } = useAdminUserActions(admin, t);
const [showCreatePw, setShowCreatePw] = React.useState(false);
const [showEditPw, setShowEditPw] = React.useState(false);
// The user whose passkeys wait for the admin's answer in the confirm dialog.
@@ -318,6 +320,13 @@ export default function AdminUserModals({ admin, t }: AdminUserModalsProps): Rea
</div>
</DialogSection>
)}
<SsoUnlinkSection
user={editingUser}
me={currentUser}
ssoSetUp={oidcConfigured}
onUnlink={unlinkSso}
t={t}
/>
</>
)}
</DialogShell>
@@ -480,6 +489,57 @@ docker run -d --name trek \\
confirmLabel={t('admin.mfa.reset')}
danger
/>
</>
);
}
/**
* Removing a user's SSO link (#3065): its section in the edit dialog and the
* question before it. Offered only while SSO is set up, and never for the
* admin's own account.
*/
function SsoUnlinkSection({
user,
me,
ssoSetUp,
onUnlink,
t,
}: {
user: { id: number; username: string } | null;
me: { id: number } | null | undefined;
ssoSetUp: boolean;
onUnlink: (user: { id: number }) => Promise<boolean>;
t: TranslationFn;
}): React.ReactElement | null {
const [asking, setAsking] = React.useState(false);
if (!ssoSetUp || !user || user.id === me?.id) return null;
return (
<>
<DialogSection label={t('admin.sso.unlink')}>
<div className="flex flex-wrap items-center gap-3 rounded-[12px] border border-edge-faint bg-surface-secondary px-3.5 py-3">
<p className="m-0 min-w-0 flex-1 basis-52 leading-snug text-content-muted" style={fs(12, 'body')}>
{t('admin.sso.unlinkHint')}
</p>
<button
type="button"
onClick={() => setAsking(true)}
className={`${SETTINGS_BUTTON_DANGER} flex-none`}
style={fs(12.5, 'body')}
>
<Unlink size={14} /> {t('admin.sso.unlink')}
</button>
</div>
</DialogSection>
<ConfirmDialog
isOpen={asking}
onClose={() => setAsking(false)}
onConfirm={() => void onUnlink(user)}
title={t('admin.sso.unlink')}
message={t('admin.sso.unlinkConfirm', { name: user.username })}
confirmLabel={t('admin.sso.unlink')}
danger
/>
</>
);
}
@@ -1,4 +1,4 @@
// FE-LOGIN-NATIVE-001 to FE-LOGIN-NATIVE-006: useLogin inside the iOS/Android app
// FE-LOGIN-NATIVE-001 to FE-LOGIN-NATIVE-008: useLogin inside the iOS/Android app
import { startAuthentication } from '@simplewebauthn/browser';
import { http, HttpResponse } from 'msw';
import React from 'react';
@@ -9,7 +9,7 @@ import { server } from '../../../tests/helpers/msw/server';
import { act, renderHook, waitFor } from '../../../tests/helpers/render';
import { resetAllStores } from '../../../tests/helpers/store';
import { TranslationProvider } from '../../i18n/TranslationContext';
import { BrowserSignInCancelled, signInThroughBrowser } from '../../native/browserSignIn';
import { BrowserSignInCancelled, resumeBrowserSignIn, signInThroughBrowser } from '../../native/browserSignIn';
import { useAuthStore } from '../../store/authStore';
import { markSignedOut, wasSignedOut } from '../../utils/signedOut';
import { useLogin } from './useLogin';
@@ -24,7 +24,7 @@ vi.mock('@simplewebauthn/browser', () => ({ startAuthentication: vi.fn() }));
vi.mock('../../native/platform', () => ({ isNativeApp: () => true }));
vi.mock('../../native/browserSignIn', async () => {
const actual = await vi.importActual<typeof import('../../native/browserSignIn')>('../../native/browserSignIn');
return { ...actual, signInThroughBrowser: vi.fn() };
return { ...actual, signInThroughBrowser: vi.fn(), resumeBrowserSignIn: vi.fn() };
});
const realLocation = window.location;
@@ -47,6 +47,7 @@ function clickEvent() {
beforeEach(() => {
resetAllStores();
vi.mocked(signInThroughBrowser).mockReset();
vi.mocked(resumeBrowserSignIn).mockReset().mockResolvedValue(false);
vi.mocked(startAuthentication).mockReset();
loadUser.mockClear();
useAuthStore.setState({ loadUser });
@@ -133,4 +134,21 @@ describe('useLogin in the native app', () => {
expect(result.current.error).toBe('Signing in did not work. Please try again.');
expect(result.current.isLoading).toBe(false);
});
it('FE-LOGIN-NATIVE-007: signs in with a browser return that reached an app Android started anew', async () => {
vi.mocked(resumeBrowserSignIn).mockResolvedValue(true);
const { result } = renderLogin();
await waitFor(() => expect(loadUser).toHaveBeenCalledWith({ silent: true }));
await waitFor(() => expect(result.current.showTakeoff).toBe(true));
expect(signInThroughBrowser).not.toHaveBeenCalled();
});
it('FE-LOGIN-NATIVE-008: explains a kept return that could not be redeemed, and stays on the page otherwise', async () => {
vi.mocked(resumeBrowserSignIn).mockRejectedValue(new Error('exchange failed'));
const { result } = renderLogin();
await waitFor(() => expect(result.current.error).toBe('Signing in did not work. Please try again.'));
expect(result.current.showTakeoff).toBe(false);
});
});
+31
View File
@@ -417,6 +417,37 @@ describe('useLogin — OIDC callback', () => {
const { result } = renderLogin();
await waitFor(() => expect(result.current.error).toBe('some_new_provider_code'));
});
it('FE-LOGIN-HOOK-213: a failed round trip the app started keeps the way back to the handoff page', async () => {
const handoff = `/native-handoff?challenge=${'a'.repeat(64)}`;
sessionStorage.setItem('oidc_redirect', handoff);
localStorage.removeItem('trek_native_handoff_return');
setSearch('?oidc_error=invalid_state');
const { result } = renderLogin();
await waitFor(() => expect(result.current.error).toBe('Invalid session. Please try again.'));
expect(sessionStorage.getItem('oidc_redirect')).toBe(handoff);
expect(JSON.parse(localStorage.getItem('trek_native_handoff_return') ?? '{}').path).toBe(handoff);
});
it('FE-LOGIN-HOOK-214: the SSO retry after that failure ends on the handoff page, not in the web app', async () => {
const handoff = `/native-handoff?challenge=${'b'.repeat(64)}`;
sessionStorage.setItem('oidc_redirect', handoff);
localStorage.removeItem('trek_native_handoff_return');
setSearch('?oidc_error=invalid_state');
const failed = renderLogin();
await waitFor(() => expect(failed.result.current.error).toBe('Invalid session. Please try again.'));
failed.unmount();
setSearch('?oidc_code=code-retry');
server.use(http.get('/api/auth/oidc/exchange', () => HttpResponse.json({ success: true })));
renderLogin();
await waitFor(() => expect(mockNavigate).toHaveBeenCalledWith(handoff, { replace: true }));
expect(sessionStorage.getItem('oidc_redirect')).toBeNull();
expect(localStorage.getItem('trek_native_handoff_return')).toBeNull();
});
});
describe('useLogin — language detection', () => {
+28 -1
View File
@@ -12,6 +12,9 @@ import { passwordErrorKey } from '../../utils/passwordError'
import { isNativeApp } from '../../native/platform'
import {
BrowserSignInCancelled,
isHandoffReturn,
rememberHandoffReturn,
resumeBrowserSignIn,
signInThroughBrowser,
takeHandoffReturn,
type BrowserSignInStart,
@@ -255,7 +258,14 @@ export function useLogin() {
email_link_blocked: t('login.oidc.emailLinkBlocked'),
}
setError(errorMessages[oidcError] || oidcError)
sessionStorage.removeItem('oidc_redirect')
// A round trip the app's sign-in started keeps its way back. The next SSO
// attempt from this page is a plain web login, and without the handoff page
// to return to it ends in the web app inside the app's browser sheet. The
// handoff page asks for a tap before it passes anything on, so keeping the
// path hands nothing over by itself; the copy is renewed for a slow retry.
const stashed = sessionStorage.getItem('oidc_redirect')
if (isHandoffReturn(stashed)) rememberHandoffReturn(stashed)
else sessionStorage.removeItem('oidc_redirect')
window.history.replaceState({}, '', '/login')
loadConfig(false)
return
@@ -303,6 +313,23 @@ export function useLogin() {
}
}
// In the app: a sign-in the system browser finished while Android started the
// app anew. Its return waited natively; redeemed here, it signs the app in.
useEffect(() => {
if (!nativeApp) return
resumeBrowserSignIn()
.then(async (signedIn) => {
if (!signedIn) return
await loadUser({ silent: true })
setShowTakeoff(true)
void loadSettings()
setTimeout(() => {
void navigate(redirectTarget)
}, 2600)
})
.catch(() => setError(t('native.login.failed')))
}, [nativeApp, loadUser, loadSettings, navigate, redirectTarget, t])
/** In the app: SSO and passkeys run in the system browser (native/browserSignIn.ts). */
const handleBrowserSignIn = async (start?: BrowserSignInStart): Promise<void> => {
setError('')
+25 -1
View File
@@ -538,11 +538,35 @@ describe('MSheet', () => {
<span>body</span>
</MSheet>,
);
const scrim = panel().closest('[role="presentation"]') as HTMLElement;
const root = panel().closest('[role="presentation"]') as HTMLElement;
const scrim = root.querySelector('[data-m-scrim]') as HTMLElement;
expect(scrim.className).toContain('bg-transparent');
expect(scrim.className).toContain('short:bg-[color:var(--m-dim)]');
});
it('FE-MOB-SHEET-036: the dim fades beside the sheet, never around it, so the opaque sheet is never see-through', () => {
const { rerender } = render(
<MSheet open onClose={() => {}} ariaLabel="Sheet">
<span>body</span>
</MSheet>,
);
const root = panel().closest('[role="presentation"]') as HTMLElement;
const scrim = root.querySelector('[data-m-scrim]') as HTMLElement;
expect(scrim.className).toContain('m-fade-in');
expect(scrim.className).toContain('pointer-events-none');
expect(scrim.contains(panel())).toBe(false);
// No ancestor of the sheet animates its opacity.
for (let el: HTMLElement | null = panel().parentElement; el; el = el.parentElement) {
expect(el.className || '').not.toMatch(/\bm-fade-(in|out)\b/);
}
rerender(
<MSheet open={false} onClose={() => {}} ariaLabel="Sheet">
<span>body</span>
</MSheet>,
);
expect(scrim.className).toContain('m-fade-out');
});
it('FE-MOB-SHEET-035: the region lets taps through to the scrim, the sheet itself takes them', () => {
render(
<MSheet open onClose={() => {}} ariaLabel="Sheet">
@@ -1,5 +1,5 @@
// FE-MOB-SET-NAV-001 onwards
import { describe, it, expect, beforeEach } from 'vitest';
import { describe, it, expect, beforeEach, vi } from 'vitest';
import userEvent from '@testing-library/user-event';
import { render, screen } from '../../../helpers/render';
import { resetAllStores, seedStore } from '../../../helpers/store';
@@ -7,6 +7,7 @@ import { buildSettings } from '../../../helpers/factories';
import { useSettingsStore } from '../../../../src/store/settingsStore';
import { usePluginStore } from '../../../../src/store/pluginStore';
import MSettings from '../../../../src/mobile/screens/settings/MSettings';
import * as platform from '../../../../src/native/platform';
describe('MSettings', () => {
beforeEach(() => {
@@ -35,4 +36,36 @@ describe('MSettings', () => {
expect(screen.getByRole('button', { name: /Notifications/ })).toBeInTheDocument();
expect(screen.queryByText('Language & region')).not.toBeInTheDocument();
});
it('FE-MOB-SET-NAV-003: the sections stand under "Your account" and "This device", with Offline on the device', async () => {
const user = userEvent.setup();
render(<MSettings />, { initialEntries: ['/settings'] });
await user.click(screen.getByRole('button', { name: /General/ }));
const account = screen.getByText('Your account');
const device = screen.getByText('This device');
const offline = screen.getByRole('button', { name: 'Offline' });
const accountRow = screen.getByRole('button', { name: 'Account' });
// Account settings first, then what stays on this device.
expect(account.compareDocumentPosition(accountRow) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(accountRow.compareDocumentPosition(device) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(device.compareDocumentPosition(offline) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
// The app's own section exists only in the app.
expect(screen.queryByRole('button', { name: 'App' })).not.toBeInTheDocument();
});
it('FE-MOB-SET-NAV-004: in the app, "App" joins This device', async () => {
const native = vi.spyOn(platform, 'isNativeApp').mockReturnValue(true);
try {
const user = userEvent.setup();
render(<MSettings />, { initialEntries: ['/settings'] });
await user.click(screen.getByRole('button', { name: /General/ }));
const device = screen.getByText('This device');
const app = screen.getByRole('button', { name: 'App' });
expect(device.compareDocumentPosition(app) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
} finally {
native.mockRestore();
}
});
});
@@ -48,3 +48,28 @@ describe('MGlassBar', () => {
expect(container.firstElementChild).toBe(screen.getByText('bar').parentElement);
});
});
describe('safe area in the touch shell', () => {
// jsdom applies no stylesheet and has no env(), so the rules are read from source.
const css = readFileSync(resolve(root, 'src/mobile/mobile.css'), 'utf8');
it('FE-MOB-CHROME-004: the top clearance takes env() with the measurement of the app as a floor, never in its place', () => {
expect(css).toContain('--m-safe-t: max(env(safe-area-inset-top, 0px), var(--trek-native-safe-top, 0px));');
expect(css).toContain('--m-safe-top: calc(var(--m-safe-t) + 12px);');
expect(css).toContain('--m-safe-l: max(env(safe-area-inset-left, 0px), var(--trek-native-safe-left, 0px));');
expect(css).toContain('--m-safe-r: max(env(safe-area-inset-right, 0px), var(--trek-native-safe-right, 0px));');
});
it('FE-MOB-CHROME-005: without the rail the floating bars keep clear of a side inset, such as a camera in a corner', () => {
const narrow = "html:not(:has(.m-shell[data-size='wide'], .m-shell[data-size='split'])) :is(.m-bar-x, .m-span-x) {";
const rule = css.split(narrow)[1]?.split('}')[0] ?? '';
expect(rule).toContain('margin-inline: var(--m-safe-l, 0px) var(--m-safe-r, 0px);');
// The insets are the screen's: right to left takes them the other way round.
const rtl = css.split(`html[dir='rtl']${narrow.slice('html'.length)}`)[1]?.split('}')[0] ?? '';
expect(rtl).toContain('margin-inline: var(--m-safe-r, 0px) var(--m-safe-l, 0px);');
// On a wide window the bars keep no side margin, so mx-auto still centres them.
for (const cls of ['m-bar-x', 'm-span-x']) {
expect(css.split(`\n.${cls} {`)[1]?.split('}')[0] ?? '').not.toContain('margin');
}
});
});
@@ -0,0 +1,41 @@
import { describe, expect, it } from 'vitest';
import { amountIn } from '../../../native-shell/amount';
// FE-NATIVE-AMOUNT-001 to FE-NATIVE-AMOUNT-005
//
// The amount inside a store price string (client/native-shell/amount.ts): read
// as a number, and written again in the same format, so the plan picker can
// count a price up and turn a yearly price into a monthly one in any currency.
describe('native shell price amounts', () => {
it('FE-NATIVE-AMOUNT-001: a euro price with a decimal comma reads and writes back the same way', () => {
const amount = amountIn('4,90 €');
expect(amount?.value).toBe(4.9);
expect(amount?.render(4.9)).toBe('4,90 €');
expect(amount?.render(79 / 12)).toBe('6,58 €');
});
it('FE-NATIVE-AMOUNT-002: a dollar price keeps its sign in front and its decimal point', () => {
const amount = amountIn('$199.00');
expect(amount?.value).toBe(199);
expect(amount?.render(199 / 12)).toBe('$16.58');
});
it('FE-NATIVE-AMOUNT-003: thousands keep their grouping mark', () => {
expect(amountIn('1.290 ₽')?.value).toBe(1290);
expect(amountIn('1.290 ₽')?.render(12345)).toBe('12.345 ₽');
expect(amountIn('CHF 1’290.50')?.value).toBe(1290.5);
expect(amountIn('CHF 1’290.50')?.render(2000)).toBe('CHF 2’000.00');
expect(amountIn("CHF 1'290.50")?.render(2000)).toBe("CHF 2'000.00");
});
it('FE-NATIVE-AMOUNT-004: a price without figures has no amount', () => {
expect(amountIn('')).toBeNull();
expect(amountIn('Free')).toBeNull();
});
it('FE-NATIVE-AMOUNT-005: a count never runs below zero', () => {
expect(amountIn('4,90 €')?.render(-3)).toBe('0,00 €');
});
});
+23 -19
View File
@@ -51,46 +51,50 @@ describe('native shell', () => {
it('FE-NATIVE-SHELL-002: the first screens speak without dashes as punctuation', () => {
for (const code of ['en', 'de']) {
const t = translator(code);
for (const key of ['native.welcome.sub', 'native.cloud.sub', 'native.cloud.f3']) {
for (const key of ['native.welcome.lead', 'native.plans.yearlyIs', 'native.provisioning.readySub']) {
expect(t(key)).not.toMatch(/[\u2013\u2014]| - /);
}
}
});
it("FE-NATIVE-SHELL-003: Russian keeps TREK's faces through Cyrillic stand-ins under the same family names", () => {
it("FE-NATIVE-SHELL-003: Russian keeps the shell's faces through Cyrillic stand-ins under the same family names", () => {
const faces = css.match(/@font-face\s*\{[^}]*\}/g) ?? [];
const cyrillic = faces.filter((f) => /unicode-range:\s*U\+0301, U\+0400-045F/.test(f));
expect(cyrillic.filter((f) => /font-family:\s*'Poppins'/.test(f))).toHaveLength(3);
expect(cyrillic.filter((f) => /font-family:\s*'MuseoModerno'/.test(f))).toHaveLength(1);
for (const face of cyrillic) {
expect(cyrillic.filter((f) => /font-family:\s*'Plus Jakarta Sans'/.test(f))).toHaveLength(3);
for (const face of faces) {
const file = /url\('\.\/fonts\/([^']+)'\)/.exec(face)?.[1];
expect(file).toBeTruthy();
expect(() => readFileSync(resolve(process.cwd(), 'native-shell/fonts', file as string))).not.toThrow();
}
});
it('FE-NATIVE-SHELL-004: a short screen on its side puts the two halves of a screen side by side', () => {
const compact = /orientation: landscape\) and \(max-height: 500px\)/;
expect(find('.screen:has(> .col)', compact)[0]?.body).toMatch(
/grid-template-columns:\s*minmax\(0, 1fr\) minmax\(0, 1fr\)/
);
expect(find('.col-about', compact)[0]?.body).toMatch(/position:\s*sticky/);
// Everywhere else the halves are no boxes of their own: one column, as before.
expect(find('.col')[0]?.body).toMatch(/display:\s*contents/);
it('FE-NATIVE-SHELL-004: a wide screen or a phone on its side puts the landscape beside a column of its own', () => {
const wide = /min-width: 900px\), \(orientation: landscape\) and \(max-height: 500px\)/;
expect(find('.scr', wide)[0]?.body).toMatch(/flex-direction:\s*row/);
expect(find('.body', wide)[0]?.body).toMatch(/overflow-y:\s*auto/);
// On a phone the content is no box of its own: it flows in the screen's column.
expect(find('.body')[0]?.body).toMatch(/display:\s*contents/);
// Two screens with a hinge: the landscape on one, the content on the other.
expect(find('.body', /horizontal-viewport-segments: 2/)[0]?.body).toMatch(/env\(viewport-segment-width 1 0\)/);
});
it('FE-NATIVE-SHELL-005: a screen taller than the window scrolls instead of overflowing both edges', () => {
expect(find('.screen')[0]?.body).toMatch(/margin-block:\s*auto/);
expect(find('.scr')[0]?.body).toMatch(/overflow-y:\s*auto/);
const shell = find('.shell')[0]?.body ?? '';
expect(shell).toMatch(/overflow-x:\s*clip/);
expect(shell).not.toMatch(/justify-content:\s*center/);
// The button at the foot stays in reach while the screen scrolls under it.
expect(find('.dock')[0]?.body).toMatch(/position:\s*sticky/);
});
it('FE-NATIVE-SHELL-006: in Arabic the chevrons sit at the far edge and point along the reading direction, the price stands apart', () => {
expect(find('.btn .chev')[0]?.body).toMatch(/margin-inline-start:\s*auto/);
expect(find(":root[dir='rtl'] .chev")[0]?.body).toMatch(/transform:\s*scaleX\(-1\)/);
expect(find('.plan-price small')[0]?.body).toMatch(/margin-inline-start:\s*7px/);
expect(find('.btn-row')[0]?.body).toMatch(/text-align:\s*start/);
expect(css).not.toMatch(/margin-left|margin-right|padding-left|padding-right|text-align:\s*left/);
it('FE-NATIVE-SHELL-006: in Arabic and Hebrew the layout mirrors through logical sides only', () => {
expect(find(":root[dir='rtl'] .back svg")[0]?.body).toMatch(/transform:\s*scaleX\(-1\)/);
expect(find(":root[dir='rtl'] .cycle[data-year='true'] .thumb")[0]?.body).toMatch(/translateX\(-100%\)/);
expect(find('.fld .edge')[0]?.body).toMatch(/inset-inline-end:\s*14px/);
expect(find('.card')[0]?.body).toMatch(/inset-inline:/);
expect(css).not.toMatch(
/margin-left|margin-right|padding-left|padding-right|text-align:\s*left|[^-]left:\s|[^-]right:\s/
);
});
});
+33
View File
@@ -0,0 +1,33 @@
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
import { ICON_CHUNK } from '../../../iconChunk.js';
describe('ICON_CHUNK', () => {
it('FE-ICON-CHUNK-001: takes every lucide module, on either path separator', () => {
expect(ICON_CHUNK.test.test('/app/node_modules/lucide-react/dist/esm/icons/chevron-down.js')).toBe(true);
expect(ICON_CHUNK.test.test('/app/node_modules/lucide-react/dist/esm/createLucideIcon.js')).toBe(true);
expect(ICON_CHUNK.test.test('C:\\app\\node_modules\\lucide-react\\dist\\esm\\icons\\map.js')).toBe(true);
});
it('FE-ICON-CHUNK-002: takes nothing else', () => {
expect(ICON_CHUNK.test.test('/app/node_modules/react/index.js')).toBe(false);
expect(ICON_CHUNK.test.test('/app/node_modules/lucide-react-native/dist/esm/icons/map.js')).toBe(false);
expect(ICON_CHUNK.test.test('/app/client/src/components/shared/PluginIcon.tsx')).toBe(false);
expect(ICON_CHUNK.test.test('/app/client/src/lucide-react/own.ts')).toBe(false);
});
it('FE-ICON-CHUNK-003: holds only what the first load already needs', () => {
// Without the tag the group would also collect icons that sit behind a lazy route
// and make them part of the first load (see the note on the groups in vite.config.js).
expect(ICON_CHUNK.tags).toEqual(['$initial']);
expect(ICON_CHUNK.name).toBe('vendor-icons');
});
it('FE-ICON-CHUNK-004: vite.config.js lists it among the chunk groups', () => {
const config = readFileSync(resolve(process.cwd(), 'vite.config.js'), 'utf8');
const groups = config.slice(config.indexOf('groups: ['));
expect(config).toContain("import { ICON_CHUNK } from './iconChunk.js'");
expect(groups).toMatch(/groups: \[[\s\S]*?\n {12}ICON_CHUNK,\n/);
});
});
@@ -0,0 +1,61 @@
import { randomBytes } from 'node:crypto';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { brotliDecompressSync } from 'node:zlib';
import { afterEach, describe, expect, it } from 'vitest';
import { MIN_BYTES, precompress } from '../../../scripts/lib/precompress.mjs';
let dir: string;
afterEach(() => rmSync(dir, { recursive: true, force: true }));
function tree(files: Record<string, string | Buffer>) {
dir = mkdtempSync(join(tmpdir(), 'trek-precompress-'));
for (const [name, content] of Object.entries(files)) {
mkdirSync(join(dir, name, '..'), { recursive: true });
writeFileSync(join(dir, name), content);
}
return dir;
}
const script = 'export const answer = 42;\n'.repeat(200);
describe('precompress', () => {
it('writes a Brotli copy that unpacks to the file, and counts what it saved', () => {
const result = precompress(tree({ 'index-AbCd1234.js': script, 'nested/Map-AbCd1234.css': script }));
expect(brotliDecompressSync(readFileSync(join(dir, 'index-AbCd1234.js.br'))).toString()).toBe(script);
expect(existsSync(join(dir, 'nested/Map-AbCd1234.css.br'))).toBe(true);
expect(result.files).toBe(2);
expect(result.before).toBe(script.length * 2);
expect(result.after).toBeLessThan(result.before);
});
it('leaves compressed formats and files under the size floor alone', () => {
const result = precompress(
tree({
'font-AbCd1234.woff2': script,
'clip-AbCd1234.mp4': script,
'tiny-AbCd1234.js': 'x'.repeat(MIN_BYTES - 1),
})
);
expect(result.files).toBe(0);
expect(existsSync(join(dir, 'font-AbCd1234.woff2.br'))).toBe(false);
expect(existsSync(join(dir, 'clip-AbCd1234.mp4.br'))).toBe(false);
expect(existsSync(join(dir, 'tiny-AbCd1234.js.br'))).toBe(false);
});
it('writes no copy that would not be smaller than its file', () => {
// Random bytes have nothing for a compressor to find.
const result = precompress(tree({ 'noise-AbCd1234.json': randomBytes(4096) }));
expect(result.files).toBe(0);
expect(existsSync(join(dir, 'noise-AbCd1234.json.br'))).toBe(false);
});
it('does nothing for a build directory that is not there', () => {
dir = join(tmpdir(), 'trek-precompress-missing');
expect(precompress(dir)).toEqual({ files: 0, before: 0, after: 0 });
});
});
+4 -1
View File
@@ -4,6 +4,7 @@ import { VitePWA } from 'vite-plugin-pwa';
import { visualizer } from 'rollup-plugin-visualizer';
import { rtlTextAlias, plyrSpriteAlias } from './rtlTextAlias.js';
import { withoutRuntimeFonts } from './bookFontPrecache.js';
import { ICON_CHUNK } from './iconChunk.js';
import { readFileSync } from 'node:fs';
// The version this bundle is built as, baked in at build time. The Docker build
@@ -70,7 +71,8 @@ export default defineConfig(({ mode }) => ({
// offline-first travel planner a route the user never opened before losing
// signal still has to work. The trade is that splitting buys first paint and
// not install size: 107 entries / 17,795 KiB before any of it, 463 /
// 23,292 KiB now (measured, not estimated).
// 23,292 KiB after it, and 460 / 59,426 KiB as of 5.1.2 with the icons in
// one chunk (iconChunk.js; 652 entries without it). All measured, not estimated.
//
// Keep this figure honest. #2228 traced PWA boot failures to the browser
// evicting this origin's whole bucket, precached shell included, and this
@@ -350,6 +352,7 @@ export default defineConfig(({ mode }) => ({
tags: ['$initial'],
test: /[\\/]node_modules[\\/](zustand|dexie|axios|zod|dompurify|isomorphic-dompurify)[\\/]/,
},
ICON_CHUNK,
],
},
},
Binary file not shown.
Binary file not shown.
+147 -14
View File
@@ -14,7 +14,13 @@
// FeatureCollections that the server serves at runtime (no network at boot): one for
// every country's borders, and one per country for its regions.
//
// A few countries take their regions from another source instead (REGION_SOURCES below:
// Ireland's counties from Tailte Éireann).
//
// geoBoundaries: CC BY 4.0 — https://www.geoboundaries.org/ (attribution required).
// Tailte Éireann: CC BY 4.0 — https://data-osi.opendata.arcgis.com/ (attribution required).
import { simplifySharedBorders } from './lib/shared-border-simplify.mjs';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -317,13 +323,86 @@ const A3_TO_A2 = {
*/
const ADM_LEVEL = { GBR: 'ADM2' };
/**
* The 26 counties of Ireland, keyed by the COUNTY field of Tailte Éireann's layer, with
* their ISO 3166-2:IE codes (the source carries none).
*/
const IE_COUNTIES = {
CARLOW: ['IE-CW', 'Carlow'],
CAVAN: ['IE-CN', 'Cavan'],
CLARE: ['IE-CE', 'Clare'],
CORK: ['IE-CO', 'Cork'],
DONEGAL: ['IE-DL', 'Donegal'],
DUBLIN: ['IE-D', 'Dublin'],
GALWAY: ['IE-G', 'Galway'],
KERRY: ['IE-KY', 'Kerry'],
KILDARE: ['IE-KE', 'Kildare'],
KILKENNY: ['IE-KK', 'Kilkenny'],
LAOIS: ['IE-LS', 'Laois'],
LEITRIM: ['IE-LM', 'Leitrim'],
LIMERICK: ['IE-LK', 'Limerick'],
LONGFORD: ['IE-LD', 'Longford'],
LOUTH: ['IE-LH', 'Louth'],
MAYO: ['IE-MO', 'Mayo'],
MEATH: ['IE-MH', 'Meath'],
MONAGHAN: ['IE-MN', 'Monaghan'],
OFFALY: ['IE-OY', 'Offaly'],
ROSCOMMON: ['IE-RN', 'Roscommon'],
SLIGO: ['IE-SO', 'Sligo'],
TIPPERARY: ['IE-TA', 'Tipperary'],
WATERFORD: ['IE-WD', 'Waterford'],
WESTMEATH: ['IE-WH', 'Westmeath'],
WEXFORD: ['IE-WX', 'Wexford'],
WICKLOW: ['IE-WW', 'Wicklow'],
};
/**
* Countries whose regions come from somewhere other than geoBoundaries, because no
* geoBoundaries level is the one people think in.
*
* IRL: ADM1 is the four provinces and ADM2 the 166 local electoral areas; there is no
* county layer at all (#2922). Tailte Éireann (CC BY 4.0) publishes the 26 counties,
* with Dublin, Cork, Galway and Limerick each one county (city and county together),
* which is what ISO 3166-2:IE lists.
*
* Each entry names the download, the file it is cached under, how many features it must
* yield, the tolerance its full-detail outlines are simplified with (see
* lib/shared-border-simplify.mjs) and how one feature's properties become the
* geoBoundaries `shapeName`/`shapeISO` that normalizeAdm1 reads, so everything after the
* download treats it like any other country. A feature it cannot place fails the build.
*/
const REGION_SOURCES = {
IRL: {
url:
'https://services-eu1.arcgis.com/FH5XCsx8rYXqnjF5/arcgis/rest/services/' +
'Counties___OSi_National_Statutory_Boundaries___Generalised_20m/FeatureServer/0/query' +
'?where=1%3D1&outFields=COUNTY&outSR=4326&f=geojson',
cacheFile: 'tailte-eireann-counties-2019-generalised-20m.geojson',
count: 26,
tolerance: 0.002,
toShape: ({ COUNTY }) => {
const county = IE_COUNTIES[COUNTY];
return county && { shapeISO: county[0], shapeName: county[1] };
},
},
};
const COUNTRIES = Object.keys(A3_TO_A2); // every ISO alpha-3 code (ADM1 fetch list)
// ATLAS_ONLY=IRL[,GBR…] rebuilds just those countries' regions: their admin1/<A2> files
// are rewritten and their features swapped into admin1.geojson.gz in place, while admin0
// and every other country stay as they are. Saves fetching the whole world for one fix.
const ONLY = (process.env.ATLAS_ONLY || '')
.split(',')
.map((s) => s.trim().toUpperCase())
.filter(Boolean);
for (const a3 of ONLY) if (!A3_TO_A2[a3]) throw new Error(`ATLAS_ONLY: unknown alpha-3 code ${a3}`);
// Cache raw downloads so re-runs (e.g. to tune simplification) don't re-fetch ~360 files.
const CACHE_DIR = path.join(__dirname, '..', '.atlas-geo-cache', GB_REF);
async function fetchGeo(url) {
const cacheFile = path.join(CACHE_DIR, url.split('/').slice(-1)[0]);
async function fetchGeo(url, cacheName = url.split('/').slice(-1)[0]) {
const cacheFile = path.join(CACHE_DIR, cacheName);
if (fs.existsSync(cacheFile)) {
const cached = fs.readFileSync(cacheFile, 'utf8');
return cached === '' ? null : JSON.parse(cached);
@@ -422,6 +501,30 @@ function normalizeAdm0Feature(f) {
};
}
// A country's raw region layer: from its REGION_SOURCES entry when it has one, else the
// geoBoundaries level ADM_LEVEL names (ADM1 by default).
async function fetchRegions(a3) {
const source = REGION_SOURCES[a3];
if (!source) return fetchGeo(MEDIA(a3, ADM_LEVEL[a3] || 'ADM1'));
const geo = await fetchGeo(source.url, source.cacheFile);
if (!geo?.features) throw new Error(`${a3}: region source could not be downloaded`);
const features = geo.features.map((f) => {
const shape = source.toShape(f.properties || {});
if (!shape) throw new Error(`${a3}: region source has a feature it cannot place: ${JSON.stringify(f.properties)}`);
return { type: 'Feature', properties: shape, geometry: quantizeGeometry(f.geometry, ADM1_DECIMALS) };
});
const codes = new Set(features.map((f) => f.properties.shapeISO));
if (features.length !== source.count || codes.size !== source.count) {
throw new Error(
`${a3}: expected ${source.count} distinct regions, the source has ${features.length} (${codes.size} distinct)`,
);
}
// By code, so the output does not depend on the order the service happens to answer in.
features.sort((a, b) => (a.properties.shapeISO < b.properties.shapeISO ? -1 : 1));
return { features: simplifySharedBorders(features, source.tolerance) };
}
function normalizeAdm1(geo, a3, countryName) {
if (!geo?.features) return [];
const a2 = A3_TO_A2[a3] || null;
@@ -477,7 +580,46 @@ function normalizeAdm1(geo, a3, countryName) {
.filter(Boolean);
}
const write = (name, features) => {
const fc = { type: 'FeatureCollection', features };
const gz = zlib.gzipSync(Buffer.from(JSON.stringify(fc)), { level: 9 });
const file = path.join(OUT_DIR, `${name}.geojson.gz`);
fs.writeFileSync(file, gz);
console.log(
`[atlas-geo] wrote ${path.relative(path.join(__dirname, '..'), file)} — ${features.length} features, ${(gz.length / 1e6).toFixed(1)} MB gz`,
);
};
const readShipped = (name) =>
JSON.parse(zlib.gunzipSync(fs.readFileSync(path.join(OUT_DIR, `${name}.geojson.gz`))).toString('utf8')).features;
// The ATLAS_ONLY path. A full build writes the countries in COUNTRIES order, each one's
// features in a single run, so a rebuilt country goes back where its run was, or where
// it would have been, and admin1.geojson.gz ends up as a full build would leave it.
async function rebuildOnly(countries) {
console.log(`[atlas-geo] rebuilding the regions of ${countries.join(', ')} only`);
fs.mkdirSync(CACHE_DIR, { recursive: true });
const a3ToName = Object.fromEntries(readShipped('admin0').map((f) => [f.properties.ADM0_A3, f.properties.NAME]));
const order = new Map(COUNTRIES.map((a3, i) => [A3_TO_A2[a3], i]));
let bundle = readShipped('admin1');
for (const a3 of countries) {
const a2 = A3_TO_A2[a3];
const features = normalizeAdm1(await fetchRegions(a3), a3, a3ToName[a3] || a3);
if (!features.length) throw new Error(`${a3}: no regions to write`);
const first = bundle.findIndex((f) => f.properties.iso_a2 === a2);
const at = first !== -1 ? first : bundle.findIndex((f) => order.get(f.properties.iso_a2) > order.get(a2));
const rest = bundle.filter((f) => f.properties.iso_a2 !== a2);
const cut = at === -1 ? rest.length : at;
bundle = [...rest.slice(0, cut), ...features, ...rest.slice(cut)];
write(`admin1/${a2}`, features);
}
write('admin1', bundle);
}
async function main() {
if (ONLY.length) return rebuildOnly(ONLY);
console.log(`[atlas-geo] geoBoundaries ref ${GB_REF}; ${COUNTRIES.length} countries`);
fs.mkdirSync(OUT_DIR, { recursive: true });
fs.mkdirSync(CACHE_DIR, { recursive: true });
@@ -496,9 +638,10 @@ async function main() {
}
}
// ADM1 (sub-national regions) — per-country gbOpen (carries ISO 3166-2 `shapeISO`).
// ADM1 (sub-national regions) — per-country gbOpen (carries ISO 3166-2 `shapeISO`),
// or the country's own source (REGION_SOURCES).
console.log('[atlas-geo] downloading ADM1 (regions)…');
const adm1Raw = await pool(COUNTRIES, (a3) => fetchGeo(MEDIA(a3, ADM_LEVEL[a3] || 'ADM1')));
const adm1Raw = await pool(COUNTRIES, fetchRegions);
const adm1Features = [];
let withCodes = 0;
COUNTRIES.forEach((a3, idx) => {
@@ -507,16 +650,6 @@ async function main() {
adm1Features.push(...feats);
});
const write = (name, features) => {
const fc = { type: 'FeatureCollection', features };
const gz = zlib.gzipSync(Buffer.from(JSON.stringify(fc)), { level: 9 });
const file = path.join(OUT_DIR, `${name}.geojson.gz`);
fs.writeFileSync(file, gz);
console.log(
`[atlas-geo] wrote ${path.relative(path.join(__dirname, '..'), file)} — ${features.length} features, ${(gz.length / 1e6).toFixed(1)} MB gz`,
);
};
write('admin0', adm0Features);
// Read only by two shipped migrations (Migration20200101021500/…031500), whose bodies
// never change; the server itself reads the per-country files below.

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