Compare commits

...

212 Commits

Author SHA1 Message Date
Maurice ec7f5e0585 test(atlas): cache the test places' regions in one go rather than an awaited loop 2026-11-19 22:11:29 +01:00
Maurice 8e38749bc3 fix(transit): show every stop name and each ride's arrival in the folded-out itinerary
The same gap as on the phone (#3139) in the desktop day plan's folded-out
transit row and the assistant's transit card: each ride cut its stop names
to one line and showed only its departure, and a walk cut its target. The
names and the walk target now wrap, and each ride shows its arrival under
its departure. The phone's booking sheet lets the route line under its
title wrap too.
2026-11-19 21:57:28 +01:00
Maurice 2c17edd74c docs(docker): the entrypoint drops to node with setpriv, say so beside its copy 2026-11-19 21:57:28 +01:00
Maurice c5e2afc21b fix(atlas): count places and cities the same way on the Atlas page and in the stats API
The Atlas page showed 100 cities and 169 places where GET /api/v1/stats
and the dashboard's passport card showed 66 and 164 for the same account.
The two sides counted with their own code. The Atlas page took the address
part right before the country as the city, which is often the region
(Bavaria for Munich, Nuremberg and Regensburg alike), and counted a bare
place name with no comma as a city. The stats side read its places with a
DISTINCT over address, coordinates and region only, so two places that
looked alike (the same hotel on two trips, places with neither address nor
coordinates) counted once, and its city reader skipped every address part
with a digit, so "10178 Berlin" never counted as Berlin.

Both now take places and cities from one method: every place counts once,
a city is read with cityFromAddress, which skips the region (#1115) and now
reads a city written beside its postcode (German, French, US, Japanese,
Dutch, British and Canadian forms) while a street with its house number
still does not count, and two spellings that differ only in case are one
city. The Atlas page, the passport card, /api/v1/stats and the MCP atlas
tool follow it. The response shapes are unchanged.

Closes #3137
2026-11-19 21:57:28 +01:00
Maurice 502e6916d9 fix(docker): start under rootful Podman on hosts that block gosu's signals
Started as root, the entrypoint dropped to the node user with gosu. gosu is
a Go program, and Go changes a process's ids by sending every runtime thread
a realtime signal and spinning until each one has answered, with no limit.
On a host whose security module drops that signal inside the container
(AppArmor on recent Ubuntu, under rootful Podman) gosu spun at full CPU
forever, before Node printed a line: no logs, no database, port 3000 never
served. Running as uid 1000 worked only because that path skips gosu.

The entrypoint now drops privileges with setpriv from util-linux, which is
already in the image: single-threaded C that makes the same id changes
without any signal. Node still runs as uid and gid 1000 with no
capabilities and HOME=/home/node. gosu stays in the image for anyone who
calls it by hand.

Closes #3135
2026-11-19 21:57:28 +01:00
Maurice 61674cf918 fix(transit): show every stop name and each ride's arrival in the journey details
The expanded transit card on the phone cut a ride's "from -> to" line to
one line, so a long first stop pushed the destination out of sight, and
it showed only the departure of each ride. The phone's booking sheet and
the desktop leg list (booking dialog, booking card, journey modal) cut
the stop names and the sheet title the same way.

The detail views now let stop names, walk targets and the booking title
wrap instead of truncating, and the expanded card shows each ride's
arrival time under its departure. The collapsed card still shortens its
headline, since expanding it shows everything.

Closes #3139
2026-11-19 21:57:28 +01:00
Maurice ac01925be7 fix(mobile): show a place's full name in its details sheet
The details sheet cut the place name to one line, and nothing in the
sheet showed the rest; only the edit form did. The sheet is where a
place is read in full, so the name now wraps onto as many lines as it
needs, as the desktop inspector already does. The address under it
wrapped before and still does.

Closes #3140
2026-11-19 21:57:28 +01:00
Maurice 99465d04de fix(mobile): the add-place button of the stay sheet takes the caption size
It uses the planner's add-place label, which no view named before, so the
unused-key baseline of planner.ts drops by one.
2026-11-19 21:41:54 +01:00
Maurice 73a7c4843b fix(mobile): a stay can be added to a trip that has no place yet
A stay belongs to one of the trip's places, so on a new trip the
accommodation sheet only said "Add places to your trip first", and the
booking could not be saved without leaving the sheet (TestFlight feedback,
5.1.3). The hint now carries the "Add place/activity" button for anyone
allowed to add places: the place form opens over the sheet, and the place
is listed to pick once it is saved.
2026-11-19 21:31:46 +01:00
Maurice 6e919696bb fix(native): a tap beside a field closes the keyboard
The app hides the keyboard's bar with its "done" button, and a textarea
keeps its return key for new lines, so after typing a note in the place
editor nothing closed the keyboard and it covered the rest of the sheet,
times and Save included (TestFlight feedback, 5.1.3). A tap away from the
focused field now lets go of the focus. A scroll keeps the keyboard open,
and a tap on another field moves the focus there.
2026-11-19 21:27:54 +01:00
Maurice d32cfb3635 fix(native): give the Apple Watch app icon a light background
watchOS crops the icon to a circle on a black face, so the black icon did
not read as a circle at all (App Review, guideline 4). The mark now sits
dark on a light grey ground, drawn from the same master silhouette.
2026-11-19 21:26:38 +01:00
Maurice 31c9f40550 fix(native): App Review builds can buy TREK Cloud while orders are closed
While TREK Cloud's orders are closed, the plan picker on iOS offers the
subscriptions only to builds that buy in the App Store sandbox (TestFlight,
App Review, Xcode). That was read from the receipt's file name alone, which
App Review's build did not carry: the reviewer saw "TREK Cloud opens soon"
and no way to buy, and the app was rejected under 2.1(b) because its
in-app purchases could not be found.

The environment now comes from the signed app transaction (StoreKit 2, iOS
16 and later), with the receipt's file name as the fallback on iOS 15 or
when the app transaction cannot be read. A production build still sees the
plans without a buy button until orders open, and the cloud refuses a
production purchase before the opening as before.
2026-11-19 21:26:38 +01:00
Maurice 7ae4dcba51 fix(db): sort the Postgres move's names with an explicit code-unit compare
Five sorts in the Postgres bootstrap and the move from SQLite relied on the
default sort, which SonarCloud reports as a bug because it compares by code
unit implicitly. They order migration names, table names and JSON keys for a
checksum, where locale-aware ordering would change the result, so each now
names the code-unit compare the default already used. Nothing changes.
2026-11-18 23:58:20 +01:00
Maurice daa4e1dfcf test(planner): an older place lookup that answers last does not replace the newer results 2026-11-18 23:30:37 +01:00
Raz Erlich 9a7bce6fd8 fix(planner): scope transit picks by day and rank other stays by date 2026-11-18 23:30:36 +01:00
Maurice 0834d4f8fe docs(airtrail): name the API key scopes AirTrail 3.13 checks 2026-11-18 23:17:47 +01:00
Maurice d8c28c9998 fix(airtrail): read the v1 answers at the boundary and refuse an arrival before the departure
The v1 bodies were cast to their types unchecked, so a flight page whose data
was not a list, or a passenger list of another shape, failed deeper down as a
TypeError instead of an AirTrail request error. Each v1 answer (a flight, a
page of flights, a created flight, a reference lookup, the key owner) is now
read through a small schema that keeps the fields TREK does not need lenient.

The legacy save refuses an arrival before the departure; the v1 body passed
it on, so an overnight arrival time without its date would have been stored
before the departure. The v1 write-back now refuses it with the same message.
2026-11-18 23:17:27 +01:00
aaronspruit 76ff6e15b1 feat(airtrail): use the AirTrail /api/v1 routes, and keep the legacy routes
AirTrail 3.13 adds /api/v1 and marks the /api/flight/* routes as
deprecated. TREK now asks the public discovery document GET /api/v1
and uses v1 when the instance has it. It uses the legacy routes for
an older instance. The client methods keep their signatures, and the
sync hash stays the same, so a linked flight does not sync again
when an instance changes to v1.

The probe cache holds only a clear answer: 200 with the discovery
document gives v1, and 404 gives legacy. The cache is per AirTrail
URL, for 10 minutes. A timeout, a 5xx or a network error fails that
call only. A 401, a 403 or a page that is not the discovery document
uses legacy for that call only. A 404 for one flight makes the client
ask the probe again before it reports the flight as deleted.

A missing scope gives AirtrailScopeError, which names the scope. It
does not unlink a flight. The API key hint and the help step list
the scopes for read and for write-back, in all languages.

Each new request goes through safeFetch, with the SSRF guard, the
timeout and the size cap. The flight list reads pages of 100 and
fails above 50 pages. A failed list unlinks nothing.

airtrail-v1.ts translates between the v1 shapes and the legacy
shapes. A write-back looks up the airport, airline and aircraft ids,
and changes each local time to a UTC instant in the zone of its own
airport. It writes each instant in the +00:00 form of the legacy
save, because AirTrail stores the string as it gets it and the sync
hash reads that string.

The tests cover both APIs over HTTP, the probe cache rules, the sync
hash on a switch and on a save, the page limit, the scope error, and
the UTC conversion across midnight, the date line and daylight-saving
changes.
2026-11-18 23:07:35 +01:00
Maurice 3e0a2ef8ed fix(native): widgets turn to the next trip day by themselves
TestFlight feedback: during a trip the widgets stayed on day 1 until the app
was opened again. The app wrote only today's day into the widget snapshot,
and only while it ran, so every timeline entry after midnight still showed
the day it last ran, with its stops all ahead again.

The snapshot now also carries the trip's days from today on (a month at
most, sixteen stops a day), each with its date. On iOS every timeline entry
takes the day of its own date, so the quarter-hour entry at midnight turns
the widget to the next day, and the bookings list drops the days behind; the
Android widgets do the same on each update. A snapshot from an app without
the days reads as it was written, and an older app binary ignores them.
2026-11-18 22:21:26 +01:00
Maurice fd35f79c36 fix(mobile): keep every screen clear of an iPhone Duo's status capsule
TestFlight feedback: on an iPhone Duo the status capsule in the top right
corner covered the trip's controls, its day chips, the map's category bar and
the first cards of every trip tab, upright and on its side. The app has
measured the capsule since 0f42b8b8a, but only the shell's own bars and page
used it, and the trip, its map and the sheets place their own controls.

- Upright, a control row in the capsule's height stands beside it and the
  content starts below it: the trip's top row and day chips, the map's
  category bar, the road trip's stage bar, every trip tab's first row, the
  places browser, the plan timeline, docked and card sheets, the assistant,
  the account menu, the image viewer's close button, the atlas search,
  vacay's header and a journey's content and map controls.
- On a wide window the page gives up the capsule's side over the whole
  height instead, as an iPhone on its side does for its camera: lifting each
  page below the capsule cost a quarter of the height of an unfolded Duo.
  The list tabs, the assistant panel and the form sheets end before it too.
- Screens whose first row is part of the page (settings, administration,
  collections) are lifted until that row is below the capsule; screens that
  keep clear of it by themselves (atlas, vacay, a journey) are not lifted.
- Right to left the rail stands on the capsule's side and takes it.

All of it reads the corner variables the app publishes, which are 0 on every
other device and before iOS 26, so nothing else moves. The rules for the
screens that place their own controls live in mobile/corner.css.
2026-11-18 21:23:14 +01:00
Maurice 294a386d23 fix(planner): take a ?tab=, ?day= or ?assistant= link once per URL
React Router lands the URL without the link as a transition. Until it does,
every render still read the link, and the tab link took it again on each of
them: selectTab is a new function per render and onLinked sets state, so a
notification's ?tab= link rendered the planner into React's update limit and
the route's error page replaced the trip on an iPad or an unfolded foldable.
Both link hooks now take a link once per URL and wait for the cleaned one;
the same link in a new URL is taken again.
2026-11-18 21:23:03 +01:00
Maurice ee79413653 fix(mobile): keep the navigation rail's list ref stable
The rail's list ref was an inline function that set state. React 19 detaches
and re-attaches a ref whose function changed, so every commit set the list to
null and back and asked for one more render of the rail. The ref is one
function for the rail's lifetime now.
2026-11-18 21:23:03 +01:00
Maurice ec08915a16 fix(trips): a day added before the start leaves the plan on its dates
Adding a day before a trip's start with "Keep bookings on their dates"
moved almost everything a day earlier and emptied the last day. The day
grid was always rebuilt by position: the n-th day row took the n-th date
of the new range. With bookings kept on their dates, only timed bookings
and stays were re-anchored afterwards. Places, day notes, bookings with no
time and a booking's place in a day's order stayed on their re-dated rows
and slid to the day before. Days added at both ends had the same problem.

planDayGrid now takes keepDates. When the new range still holds every
dated day, each of them keeps its date and the new days go around them.
The server passes it unless the traveller chose to shift everything, and
the trip dialog's warning check uses the same rule. A moved or shorter
range still follows the positional rule the dialog describes, and "Shift
everything" still moves the whole plan with the new start.

Two things keyed outside the day rows followed the old rule. Road trip day
boundaries are keyed by day number, so a new first day left each one on
the day before its own. They now follow their days to their new numbers
and go out to every screen. The owner's leave days moved by the change of
start even when days were only added. They now move by as far as the
trip's first day moved, which is nothing when days are only added. The
help text of the option and the MCP description say what happens when
days are added.

Closes #3119
2026-11-18 17:14:38 +01:00
Maurice 40f9c020bb fix(bookings): show the calendar date beside transport times
Tapping a transport in the compact Transports or Bookings list on the phone
opens the transport sheet, and its time boxes showed only the clock time. The
sheet named a date only in its subline, and only for a booking with no route
and no airline or number, so a flight or ferry could not be placed on a day
without unfolding the whole list. A transport holding only times (its date
lives on the linked trip day) had no date at all, and the desktop transport
detail dialog had the same gap: it read the date off reservation_time alone
and never named the arrival day of an overnight trip.

The dates now come from one helper, bookingDates(), which reads the booking's
own date, then the stop's local date, then the linked day's date, the rule
bookingFacts already used and now shares. The phone sheet prints the date
above each time (a leg opened from its row uses its own days); when no time
box carries a date, because no time is entered yet or the live flight card
stands in their place, the subline names the day instead. The desktop dialog
names the day, or both days of an overnight trip in reading order, in the
user's locale.

Closes #3122
2026-11-18 16:52:18 +01:00
Maurice 684a3bf5f5 fix(roadtrip): draw the drive between connected days in the arrival day's colour
With "Connect the days" and "A colour per day" on, the drive from one day's
last stop to the next day's first stop was coloured as the day it left. A stop
reached after midnight was handled the same way: the line into it kept the
colour of the day it came from. The road trip panel counts both drives toward
the arriving day (its distance includes them, and the setting's hint says
connecting drives count toward the arrival day). So the map showed the drive
under one day while the panel counted it under the other. This also happened
with daily travel times set to end the day at the last place, whenever the
schedule could not be kept (a drive longer than the window) and the days were
drawn as stored.

assembleRoadtrip now puts every line drawn into a day under that day's
number, the day whose figures count it, and still marks it as a join, so the
one-day stage view still leaves it off. Every map takes its day colours
from this list: desktop Leaflet and Mapbox GL, the phone map and its stage
view. The client tests that pinned the old colouring and the old join order
now expect the new ones.

Closes #3123
2026-11-18 16:52:17 +01:00
Maurice 26122a4208 ci(test): mirror the dev push run on the release pull request
Every push to dev started test.yml twice for the same commit: the push
run on dev and the pull_request run of the open release PR into main.
Together about 72 long jobs exceeded the 60 organisation slots, so jobs
queued and ci-ok landed minutes later.

On a pull request from dev into main (head in this repository) the
changes job now sets mirror and turns every area off
(scripts/ci/changed-areas.mjs), so no gate, test, coverage or scan job
runs. ci-ok keeps its needs verdict and then runs
scripts/ci/mirror-push-run.mjs, which waits for the ci-ok of the push
run of test.yml on dev for exactly the PR head commit and passes or
fails with it. A missing push run, one that ended without a verdict,
an API that keeps failing or a wait past 17 minutes fails with a
re-run hint. ci-ok reads with actions, checks and contents only, and
its timeout rises to 20 minutes.

A push to dev now lists its changes against the merge base with main
instead of the previous push, so the run the mirror copies covers
every area the release pull request brings in, also when an earlier
push's run was cancelled or red.

The release workflows keep reading the newest ci-ok on a commit. A
green mirror implies a green push ci-ok before it; a mirror that fails
on its own blocks a release until it is re-run.
2026-11-18 16:18:46 +01:00
Maurice 9dc80760f7 feat(server): name the database in the start banner
The move guide tells the operator to check that the log reports the Postgres engine, but the start banner never said which database the process runs on. It now carries a Database line with the engine's own description: the SQLite file, or the Postgres URL with its password masked. The guide's check and the manual checklist point at that line.
2026-11-18 15:43:26 +01:00
Maurice 090db8519d docs(postgres): document the volume path per major and what the move carries over
The compose pages name postgres:18, list the volume path for 18 and for 14
to 17, and say that changing a database's major needs pg_upgrade or a
backup and restore. The move steps say to carry the install's own
environment variables, container name and port over, and to append the
passwords and COMPOSE_FILE to the existing .env instead of replacing it,
so later plain docker compose commands, the ones in Updating included, keep
using the Postgres file instead of starting TREK on the old travel.db. The
pages also say which data is lost to an anonymous volume, which compose
service waits for the database, what tables that differ from the Postgres
schema mean, and how to recover from a first start without a password.
2026-11-18 15:22:52 +01:00
Maurice efc55ac700 fix(deploy): run the Postgres compose on postgres:18 without the Swarm-only config mode
The postgres image refuses a volume at /var/lib/postgresql/data from 18 on,
so the db service now mounts /var/lib/postgresql, and the file says that 14
to 17 need the old path and that an existing database keeps its image tag
and path. Compose ignores a config's mode outside Swarm and warned about it
on every command, while the image sourced the init script anyway. The mode
is gone and the script runs its work in a subshell, so set -eu and exit stay
inside it and a failure still fails the first start whether the script is
sourced or executed.
2026-11-18 15:22:52 +01:00
Maurice 85b773420c fix(db): say what a schema difference means when the move to Postgres refuses it
The refusal listed the differences and nothing else. A table or column
only one side has now comes with what that means: the file is at this
version's level, the start that brought it there added every column it
could, the start log names the rest, and the operator keeps running on
SQLite and reports it. A column of TREK's own schema the move cannot copy
is listed apart and named a bug in TREK, since the file is not at fault.
The server guide describes the gap, the repair, the check and the refusal.
2026-11-18 15:22:51 +01:00
Maurice 771dab7c35 feat(db): name the tables and columns the database lacks on every start
After the migrations, both engines compare the declared entities with the
live schema in one catalog statement and log a warning naming each table or
column that is missing, what fails because of it, and that it should be
reported. It never refuses a start, not even when the check itself fails,
and says nothing on a database the migrations built; a Postgres lane suite
holds that on a real server.
2026-11-18 15:22:38 +01:00
Maurice ca7cdcebcc fix(db): add every column an upgraded pre-ORM install can lack
The legacy baseline records the positional runner's steps up to
schema_version as executed without running them, so a column that runner
never added stays missing for good. Two things in its history left such
gaps: a step inserted below a version a build had already shipped (step 53,
users.mfa_backup_codes, so turning on MFA failed there) and a column added
to createTables() with no step (users.immich_access_token).

Migration20200101046460 adds, where missing, every column the schema held
at legacy step 258 that head still holds and ALTER TABLE ADD COLUMN can
add, declared as head declares it; on Postgres every one of them is in the
baseline, so nothing is added there. The list is derived again from the
migrations in tests/unit/db/legacy-column-repair.test.ts, which also adds
all of them to a database lacking them and upgrades a v244 install shaped
like the one whose move to Postgres was refused.
2026-11-18 15:22:38 +01:00
Maurice 6bc27a259b ci(test): give the e2e container a compiler on a node_modules cache miss
better-sqlite3 compiles on install, and the Playwright container has no make or g++, so the first e2e run of a lockfile failed in npm ci. The setup action now installs both when they are missing, before npm ci; a cache hit skips the step.
2026-11-18 14:52:59 +01:00
Maurice a2d9c2416d ci(native): drop the watch-bridge job and the lockfile trigger
watch-bridge repeated the client typecheck and three client test files
that test.yml already runs on every change under client/, inside ci-ok.
The shells link only @capacitor/* packages, all declared in
client/package.json, which stays a trigger, so a native dependency bump
still builds iOS and Android while lockfile-only bumps no longer queue a
Mac build.
2026-11-18 14:48:44 +01:00
Maurice fd1942afab ci(test): restructure test.yml for a ten-minute ci-ok
Rename the workflow to CI and name every job "<Area> <what>[ i/n]" with
ids in kebab-case, in area order. Fold i18n parity, shared coverage and
the plugin SDK into Shared tests, split the client gates into Client
types and Client checks (with the bundle), and merge the image and chart
jobs into Docker and Helm with per-area step conditions. Server and
client tests run in ten slices, the Postgres lane in three per major,
and e2e in two slices inside the digest-pinned Playwright container.

A local setup action restores node_modules and shared/dist from exact
cache keys and falls back to npm ci and the shared build. The
node_modules key covers the lockfile and every workspace package.json,
so npm ci still refuses a package.json out of step with the lockfile.
Only pushes to dev and main save, the npm download cache included, and
only a full install saves that one. The plugin SDK installs and runs
before the root install so it resolves only its own dependencies.
Timeouts drop to 15/10/5 minutes. The workflow tests now check the name
form, the Playwright tag against the lockfile, scan's needs, timeouts,
the cache keys and saves, and that installs go through the setup action;
.github/actions/ counts like test.yml in changed-areas.
2026-11-18 14:48:43 +01:00
Maurice 23eabe1499 style(server): format the doc-sync controller test 2026-11-18 13:44:54 +01:00
Maurice bcc82db7bd test(server): pass numeric row ids to controllers and seed addons with booleans
Controllers read their path ids through the rowId pipe now, so unit tests that call a handler directly pass the number the pipe hands it. The e2e suites enable addons with true, the type of the entity's field. The realtime gateway test builds its book sockets through one helper instead of a second hand-built TripAccessService.
2026-11-18 13:36:37 +01:00
Maurice 26b220470a fix(shared): parse an id param's digits with Number before the integer check
The union of an integer and a digit string fed z.coerce.number() through pipe(), which Zod 4 types with an unknown input and tsc refuses. The digits are now turned into a number with Number and checked by z.number().int().positive(), the same rule as before.
2026-11-18 13:24:09 +01:00
Maurice cdc31967b2 docs(db): describe the final Postgres, plugin data and deployment behaviour
wiki/Database-Postgres.md, server/CLAUDE.md and the plugin SDK docs now
describe what plugin SQL may name on Postgres, the pinned output
settings, the shared contract (NUL and transaction control refused on
every engine), the move's refusals, the Postgres lane in two slices per
major on 14 and 18, and that TREK runs as one instance on either engine.
server/.env.example names the version 18 client tools the image ships,
and the troubleshooting entry and the Helm values name the full set of
roles a restore refuses. A doc-paths baseline entry that no longer
applies is removed.
2026-11-18 13:20:10 +01:00
Maurice 4a435df6e4 fix(plugin-sdk): apply TREK's plugin data contract under trek-plugin dev and the mock host
trek-plugin dev and createMockHost copied the db:own checks by hand and
let through what TREK refuses (NUL, transaction control outside tx()), so
a plugin worked locally and failed in TREK. Both now read the contract
from src/plugin-data-contract.ts, a byte-identical copy of the server's
file that the parity test compares, and check in the server's order.
Tests compare every refusal of the dev database and the mock host with
the contract's text.
2026-11-18 13:20:09 +01:00
Maurice 21f4f7d5de docs(server): plain wording in the comments and test titles this change added
Comments and test titles added on this branch cited review labels and
planning documents that do not exist in the repository, and some used
dashes as separators. They now say what the code does and why in plain
sentences, and the Postgres lane's suites share one header format. Test
ids stay as they were.
2026-11-18 13:20:09 +01:00
Maurice e3d195896c ci(postgres): run the lane in two slices per major with fsync off
Before Postgres 15, every CREATE DATABASE ... TEMPLATE the lane runs per
file is two checkpoints waiting for fsync, and the lane took 20 to 23
minutes on 14 against about 12 on 18. The service now runs with fsync
off, set through ALTER SYSTEM and a reload and checked afterwards. A test
database has nothing to keep through a crash.

Two slices per major replace three, so four long jobs replace six. The
job-count note in test.yml now states the real count: up to 30 jobs, 24
of them long, for 20 organisation-wide slots. At least four long jobs
start only after another has ended. A run with six slices started nine
long jobs four to five minutes late and ended its client coverage eight
minutes after the on-time shards. The job comment says what was measured
on CI and what only locally. The lane docs say two slices, and the root
guide describes the slice gate.
2026-11-18 13:20:09 +01:00
Maurice 911bd825c1 test(ci): fail every sliced job whose slice count the gate cannot hold to one
A sliced job states its slice count three times: the matrix shard axis,
the i/n in its name and the --shard=i/n it hands vitest. Changing one and
not the others still passes and leaves part of the suite in no slice or
reports the wrong count. workflow-jobs.test.mjs now treats every job that
names matrix.shard or runs --shard as sliced and fails, naming the exact
fix, until the three agree. A job whose axis is not the one-line
"shard: [1, ..., n]" form fails too, instead of going unchecked, and so
does a fixed --shard. Tests on small inline workflows hold the reader
itself to these cases.
2026-11-18 13:20:08 +01:00
Maurice 81628d78ee fix(db): name the Postgres compose file in the move command hint
The boot refusal beside a SQLite install told the operator to run the move
with plain `docker compose run`, which uses the SQLite compose file. It now
gives the command the wiki gives, and PGBOOT-037 holds both to the page.
2026-11-18 13:20:08 +01:00
Maurice 69e791206e fix(db): trace a broken key in the move without blaming the wrong row
The move read unique indexes by joining indkey to pg_attribute. An expression key such as lower(email) has attnum 0 there, so idx_users_email_lower was missing from the plan. The catalog query now reads each index's key as Postgres prints it, whether any part of it is an expression, and the columns it reads: the plain key columns and the Var nodes of indexprs, without INCLUDE columns or the predicate.

A broken unique key no longer names --drop-nul as its cause. The refusal names the key and the shared value from Postgres's detail. It explains that the SQLite file held the two rows apart, and the hint about SQLite's lower() appears only for an expression key. Values --drop-nul changed in the key's columns are listed as rows to check first, and only when the duplicate value holds their text. An unrelated value that lost a NUL is no longer named. A plain key over a quoted column is named by its column, not as an expression.

A row that breaks a constraint (SQLSTATE class 23) is now a MoveRefusal that says what to correct, in the SQLite file or in a plugin's plugin.db. Before, it was a bare error with a stack. A value Postgres refuses by its type (class 22) stays a failure: it names no row, and values.ts should have refused it first, so the message asks for a bug report. MoveRefusal and the remedy text move to refusal.ts so copy.ts can use them without an import cycle. The usage text of --drop-nul and the wiki's move section describe NUL in JSON, the key listing and these refusals.
2026-11-18 13:20:08 +01:00
Maurice e66330e226 fix(db): treat a raw NUL in JSON like any NUL in the move
A raw U+0000 in TREK's JSON text, which an old or hand-edited travel.db can hold, was refused as "not valid JSON" without naming the NUL or the remedy. It is now refused with the NUL reason, so the refusal names --drop-nul. With --drop-nul, raw and escaped NULs are removed and nothing else, the way TREK's own writes drop them, and each change is listed. Text that is not valid JSON even without its NULs is refused as that, and the checksum's source side follows the same rule.

A \u escape of half a surrogate pair parses in JavaScript but jsonb refuses it. Before, that failed the insert without naming a row. It is now refused by table, row and column.
2026-11-18 13:20:07 +01:00
Maurice c970245e0d fix(plugins): hold plugin data on Postgres to its own schema and to one contract on both engines
The plugin SQL guard now refuses what still reached outside a plugin's
schema or depended on the server:
- reads of the system columns (xmin, xmax, cmin, cmax, ctid, tableoid),
  which show transaction ids and storage layout and do not exist on
  SQLite; a value of the plugin's own may still be named xmin with AS
- the xid and xid8 types wherever the word stands for the type, since
  age() of an xid is the cluster's transaction counter
- the text search functions that coerce a text argument to regconfig, a
  catalog lookup by name, which leave the allowlist
- collations and access methods outside the set every server has, which
  could tell whether a locale or an extension exists

Every plugin transaction pins, with SET LOCAL, the settings that decide
how values print and parse (TimeZone UTC, DateStyle, the C locales, float,
bytea and xml output, the text search configuration), so a plugin's output
neither depends on nor reveals the server's configuration.

Both stores now keep one contract. Its texts and caps live once, in
plugin-data-contract.ts, and both stores throw only those: NUL in SQL,
an argument or a migration id is refused on SQLite as on Postgres,
transaction control is refused in every call on both engines (tx() is
how a batch becomes atomic), a closed store refuses every call, and the
Postgres store answers the cases better-sqlite3 names with its words.
The SQLite store moves beside the Postgres one as SqlitePluginDataStore
in db/engine/sqlite, takes its file from the backend so src/db never
imports src/nest, and no longer needs the driver exemption. A contract
test runs every violation on both stores and fails when they answer
differently. The Postgres lane holds the allowlist, the pinned settings
and the SQL plugins commonly write against a real database.
2026-11-18 13:20:07 +01:00
Maurice cc0fe6ce2b test(api): hold every request row id to toRowId on paths, bodies, queries, MCP URIs and plugin RPC
ROUTEID walks every route the app registers.
- ROUTEID-001 sends 'abc' and the non-canonical spellings of a seeded row's id to each path param named like an id, and requires no 5xx and the answer 'abc' gets. It then sends the spellings of an id no row has and records what the database drivers are handed (tests/helpers/sql-capture.ts, below MikroORM and Kysely). It fails when a spelling, or the number Number() makes of it, reaches SQL, so a route over a table the suite seeds nothing in is held too. Stale NOT_ROW_IDS entries fail, and the walk runs on one listening keep-alive server.
- ROUTEID-002 walks every @trek/shared request, body and query schema and every route's body and query DTO, and fails on a field named like a row id that accepts such a spelling. String ids are listed with their reason; open fields name the handler test that holds them.

Three more suites cover the other entry points:
- MCPROWID does the same for every MCP resource template.
- RPCROWID refuses a plugin RPC id param read past rowIdParam.
- BODYID, JRNID and QUERYID cover the open accommodation update body, the collab reply, the journey fields a handler parses itself and the notifications limit and offset.

All suites that boot the app run in the SQLite suite and in the Postgres lane on 14 and 18. server/CLAUDE.md states the rule and the four gates.
2026-11-18 13:20:07 +01:00
Maurice 39346ceca7 fix(mcp,rpc): parse resource URI, websocket and plugin RPC ids with toRowId
Eleven MCP tool files carried their own parseId, which used Number() and so took '0x1' and '1e20'; they now share uriRowId. The websocket join and book:join read the id with toRowId instead of Number().

Plugin RPC ids go through rowIdParam instead of num(), and a param that may be left out goes through the new optionalRowIdParam. num() let '0x5', 1.5 and 1e20 through, which Postgres refuses or reads its own way while SQLite matches nothing.

accommodations.create read its refs with Math.trunc(Number()), and accommodations.update bound its open input's refs as sent. collab.createMessage took replyTo only when typeof was 'number', which let 1.5 and 1e20 through. All three now read their ids as row ids. A canonical numeric string still passes, as the published contract says, and the refusal keeps num()'s message.
2026-11-18 13:20:06 +01:00
Maurice 6dfba51f21 fix(api): read body, query and handler-parsed ids with toRowId instead of Number() and parseInt
The services and controllers that took an id from a request with Number(), parseInt() or not at all now use toRowId. That covers admin users, notifications (and their limit and offset), trip members and guests, day notes, assignments, memories (photo owner, album link, body photo_id), photos, mail-ingest, the assistant id parsers, dawarich, registration invites, the plugin contribution routes and the collab reply.

The accommodation update body is open, so AccommodationsService reads the place and day refs of every stay write with toRowId and answers a refused one with the create schema's 400.

AdminService.deleteUser checked the caller with parseInt and deleted with Number(), so an admin could delete their own account by spelling its id in hex; both now use one parse.

The OAuth session revoke called Number(id) first and so revoked session 5 for '0x5'; the service now reads the id as sent.
2026-11-18 13:20:06 +01:00
Maurice 3973741509 fix(shared): refuse a malformed row id in every request schema
Request fields that hold a row id took z.union([z.number(), z.string()]), a bare z.string() or z.array(z.number()), so '0x5', '5e0', 1.5 and 1e20 reached the handler and from there SQL, where SQLite matches nothing, Postgres 14 and 15 refuse the cast and 16 and later read hex and underscores as a number. Two primitives join idParamSchema: rowIdInputSchema takes a safe integer or its digits and keeps the value as sent, so field types do not change; rowIdStringSchema takes digits only, for multipart fields. Both refuse with 'Invalid id'. The accommodation, assignment, reservation position, admin invite, collab reply, vacay, file and memories photo ids now use them, and every list of ids is z.array(z.number().int()). idParamSchema takes only the decimal spelling or a whole number, and the trip-journal-link and tour library ids use it. A body id spelled '0x5' is now a 400 on SQLite too.
2026-11-18 13:20:05 +01:00
Maurice 3eac508baf fix(api): parse path ids with a rowId pipe that answers like an unknown id
RowIdPipe (src/nest/common/row-id.pipe.ts) parses a path param with toRowId. It answers a refused spelling with the route's own not-found answer, so '0x5', '5e0' and 'abc' get what an id that names no row gets. ParseRowIdPipe replaces Nest's ParseIntPipe with the same 400 and message: ParseIntPipe let '-1' and numbers past 2^53 through, and Postgres refuses the latter as out of range. Journey, journey recordings, day import, book design, map, public photo, collections, doc-sync, vacay, atlas and the plugin user-data export declare their ids through it. The upload routes parse in the handler with withRowId, so a refused id takes the existing cleanup path, or carry SpoolCleanupInterceptor (collections).
2026-11-18 13:20:05 +01:00
Maurice 7f6f2eb97c fix(db): read every request row id through toRowId, at the trip guards and the repository lookups
toRowId moves to src/db/row-id.ts so repositories can use it (src/db sits below src/nest), together with a new withRowId helper; src/nest/common/row-id.ts re-exports both. Its docstring is rewritten to state the rule plainly. TripsRepository read its number | string trip ids raw: SQLite matched '0x1' against nothing, Postgres 14 and 15 refused the cast with a 500, and 16 and later read it as trip 1. Its access reads, DaysRepository.existsInTrip and the packing template lookups now parse the id first, so an id toRowId refuses is no row on every engine. TripAccessGuard, TripOwnerGuard and JourneyAssistantGuard used Number(), which read '0x1' and '1e0' as row 1; they now use toRowId.
2026-11-18 13:20:05 +01:00
Maurice f2cfbc4041 fix(db): close the move's remaining silent changes
An attack on the move to Postgres with real SQLite files found five values
that changed without a refusal or a listing, or a valid file that failed:

- Negative zero in a plugin column became 0: pg sends the number -0 as "0",
  and the checksum printed both as "0". It is sent as text and kept apart in
  the checksum on both sides.
- Text whose bytes are not valid UTF-8 was read with each bad sequence
  replaced by U+FFFD, and the checksum was built from the replaced text.
  Text is now read as its bytes and decoded strictly in the file's encoding
  (UTF-8, or UTF-16 for a file created so); such a value is refused in
  TREK's and in plugin data, with --drop-nul too, and listed with its bytes.
- --drop-nul serialized a JSON value again, so a large number lost digits
  and 1.0 became 1. Only the \u0000 escapes are removed now.
- A plugin default Postgres refuses for the column (DEFAULT 0 on a BLOB
  column) failed the move, and DEFAULT 1.5 on an integer column would have
  been rounded. Such a default is left off and listed as not carried over.
- A plugin index or primary key SQLite compared with COLLATE NOCASE or RTRIM
  became one that compares exactly. It is still created, and the summary
  lists the collation it lost.

Each case has a regression test that fails without its fix, on SQLite and
on the Postgres lane.
2026-11-17 23:30:35 +00:00
Maurice 636fc7d0a6 fix(db): refuse the column notation without parentheses and aclitem in plugin SQL
Postgres reads x.f as the call f(x) when x has no column f. The guard counted
that spelling only after ")." or "].", so over a function in FROM that
returns a single value, or a parameter, the allowlist was bypassed:
"select g.obj_description from generate_series(...) g" returned the comments
on every object of the database, and g.current_schemas, g.txid_status and
$1.ts_token_type passed as well. A refused catalog function after a dot is
now refused too, except the names in COLUMN_NAMES (money, name, oid, version,
xid, xml), which take no argument or only convert it to their type, so t.name
keeps working. PGPLUG-021 holds that list to pg_proc on the lane's server.

The type aclitem names roles: '=r'::aclitem printed the cluster's first
superuser and 'x=r/x'::aclitem told whether a role exists. It is refused in
every spelling like the reg* types.

The allowlist itself moves to assets/postgres/plugin-functions.txt, beside
the catalog list it is checked against. As TypeScript it spelled 'like' and
'json_each', names of Postgres functions that the SQLite dialect gate reads
as SQLite SQL.
2026-11-17 23:30:29 +00:00
Maurice adcda60f7d ci(postgres): run the Postgres lane in three slices per major
Since the lane runs every suite that boots the app it takes about ten
minutes on Postgres 18 and about 25 on 14, past the job's 20 minute timeout.
Each major now runs it in three slices (--shard=i/3), each on its own runner
and service with its own template; the probe and its artifact stay once per
major, in the first slice. ci-ok still needs server-postgres, whose result is
failure when any slice fails or is cancelled, so every slice is required.
2026-11-17 22:50:02 +00:00
Maurice e8f808b67f fix(reservations): parse every referenced id in a booking body with toRowId
The booking body is not schema-checked, so day_id, end_day_id, place_id,
assignment_id, accommodation_id and the create_accommodation ids can arrive
as any string. The reference guards passed them to SQL as they came. SQLite
compares '0x5', '5e0' or 'abc' against an integer id and matches nothing
(or, for '5e0', the row), so the guard answered "Unknown reference". Postgres
refuses the cast on 14 and 15 and reads hex as a number from 16 on, so the
same body answered a 500 on one major and reached a real row on another;
the Postgres 14 lane caught it in L2.

Both guards now read each id through toRowId, the rule every other untrusted
row id follows: an id it refuses resolves to nothing, so referencesOutsideTrip
does not name it and unresolvedReferences does, and the answer is the same
400 on every engine. create() reads the payload's accommodation_id through
toRowId as update() already did, instead of storing '0x5.0', which the
reads' join could not cast back on Postgres.

ReservationRow and ReservationTraveler move to reservation-rows.ts, the way
reservation-inputs.ts holds the input shapes, so the service stays within
its size baseline; the service exports them on and it is lowered to 1166.
2026-11-17 22:49:55 +00:00
Maurice 70108e5694 test(memories): type the Synology fakes' request init as RequestInit
The fakes that answer safeFetch by API took their init as any; safeFetch
declares it as RequestInit, which is what they read (the body as
URLSearchParams or text). The SSRF album case had gained one more of them,
which put the tests' no-explicit-any count one over its baseline. All five
are typed now, and the baseline is lowered to the 1545 the tests hold.
2026-11-17 22:49:55 +00:00
Maurice c75fb22289 docs(db): describe the move's refusals and --drop-nul
The wiki's move section, the server guide and the nul-free header said
the move drops NUL as every write does. They now say what it does: a
plugin's data moves unchanged or the move is refused with the values
listed, TREK's own NUL is refused unless --drop-nul is given, which lists
every value it changed, and the checksum comes from the SQLite values.
2026-11-17 23:28:42 +01:00
Maurice 621b2f17df test(db): run the move's NUL and plugin type rules on a real Postgres
The plugin in the move suite gains a BLOB column holding text and an
untyped column holding numbers, and the plugin store must read both back
as they were stored. A new suite moves a file whose plugin and own rows
hold NUL: the plugin's refuses before anything is written, TREK's
refuses until --drop-nul, a username that dropping the NUL makes
duplicate is named with users_username_unique, and a move without a
collision lists the value it changed and stores it without the NUL.
2026-11-17 23:28:41 +01:00
Maurice bc6728678b fix(db): let the move to Postgres change nothing silently
The move stripped NUL from a plugin's own text, merging keys that were
distinct, and turned a plugin's values into another type (text in a BLOB
column into bytea, numbers in an untyped column into text). Its checksum
was built from the converted values, so both passed as verified.

A plugin's data now moves exactly as the Postgres plugin store would
hand it back, or not at all: a NUL, a value of another storage class
than its column, or an integer past 2^53 refuses the move before
anything is written, listing plugin, table, row and column. A column
left open by SQLite's affinity takes the kind its values need, so text
in a BLOB column stays text.

TREK's own text holding a NUL from an older install is refused by
default too. --drop-nul drops it, lists every changed value in the
summary, and names a unique key that dropping a NUL broke.

Every table's checksum is now built from the values read from SQLite,
so a conversion that changes a value fails the verification.
2026-11-17 23:28:41 +01:00
Maurice 6040b60e86 fix(db): keep NUL only in the password fields TREK hashes, not every key naming a password
nulFreeInput left a string as sent under any key containing "password".
That covered the admin settings password_login and password_registration,
which are flags: 'true\u0000' failed the lockout check as a disabled
password login while the database stored 'true'. It also tested the raw
key, so 'pass\u0000word' lost the NUL of the password it carried.

The exemption is now HASHED_PASSWORD_KEYS, the fields TREK only ever hashes
with bcrypt (password, current_password, new_password), matched exactly on
the key without its NUL. A unit test reads every field of the shared
schemas and the instance settings named like a password, passphrase or
secret and fails until each is either in that list or decided against with
its reason.
2026-11-17 23:22:59 +01:00
Maurice 2edf5f807a fix(db): let a plugin call only an allowlist of Postgres's catalog functions
The plugin SQL guard refused functions by name, so every function that reads
the catalogs or the server and was not listed passed: obj_description,
col_description and shobj_description returned the comments on TREK's
tables, columns, database and roles by OID, format_type named a type by its
OID, and version(), current_database(), inet_server_addr() and the session
keywords described the server.

A call to a pg_catalog function is now refused unless the function is on
PLUGIN_FUNCTIONS (string, number, date and time, JSON, array, aggregate,
window, UUID, range, geometry, network and text search functions), in
either spelling of a call, f(...) and the column notation (x).f. The
catalog's function names of Postgres 14 to 18 are kept in
assets/postgres/catalog-functions.txt, and PGPLUG-021 fails on the lane
when the server has a function that list does not name, so a new major
cannot widen what a plugin may call. The session keywords current_user,
session_user, current_role, user, system_user, current_catalog and
current_schema are refused unquoted.
2026-11-17 23:22:59 +01:00
Maurice fd864cc441 chore(lint): read the rule test's parser from typescript-eslint and drop a stale knip entry 2026-11-17 23:04:13 +01:00
Maurice b004d3b88e test(journey): a NUL inside a share token is dropped before the lookup 2026-11-17 23:04:13 +01:00
Maurice 9b1bd6e435 test(memories): answer the SSRF album case by API, not by call order 2026-11-17 23:04:12 +01:00
Maurice 73f3aa8309 test(db): give the stand-in migration storage the master transaction calls 2026-11-17 23:04:12 +01:00
Maurice 82195c7418 fix(db): type the cleaned cookies for the strict compiler 2026-11-17 23:04:12 +01:00
Maurice 9fd77b04fa docs(db): describe the layers that hold plugin SQL on Postgres and the NUL rule for plugin data
The plugin-sdk README, the Postgres wiki page and server/CLAUDE.md now name
the layers as the code enforces them: the refusal on a privileged role and
the boot log line, the guard (the reg* types, INTO after the statement's
own INSERT or MERGE only, TEMP only where it makes a temporary object), the
targets Postgres resolves before an ALTER, DROP, REFRESH, TRUNCATE or
CREATE INDEX, one statement per round trip, pg_temp last, and the quota over
every relation with the object cap. They also say that a plugin argument
holding NUL is refused on Postgres and bound exactly on SQLite.
2026-11-17 23:04:12 +01:00
Maurice f1ea716305 fix(db): hold plugin SQL on Postgres in layers the database enforces
The token guard kept leaking: on a superuser connection an unqualified
`alter type int4 rename to int4x` renamed pg_catalog's type for the whole
server, sequences and catalog-only objects grew the database past the quota,
regtype/regconfig/regdictionary looked TREK's objects up by name, and a
column alias named insert or merge in front of INTO made a table. Instead
of a longer word list, the store now asks the database:

- No plugin SQL while TREK's role is privileged in the sense of the restore
  check (PRIVILEGED_ROLE_SQL, imported from server-checks.ts): every db:own
  call fails with PRIVILEGED_ROLE_PLUGIN_REFUSAL, read once per pool
  connection, and the boot log says why.
- The objects an ALTER, DROP, REFRESH, TRUNCATE or CREATE INDEX ... ON
  changes, and the tables a CREATE or ALTER TABLE ties to its own, are
  resolved with to_regclass/to_regtype in the transaction right before the
  statement, and it is refused unless each one found lies in the plugin's
  schema. An unqualified int4, text or box is pg_catalog's and refused even
  with the role check off.
- The quota counts every relation of the schema with its TOAST table, and a
  schema holds at most PLUGIN_SCHEMA_MAX_OBJECTS catalog objects (relations,
  types, constraints, enum labels).
- The guard refuses every reg* type and its array in every spelling, the
  has_*_privilege functions, currtid2 and the BRIN/GIN maintenance
  functions; INTO only after the INSERT or MERGE that is the statement's
  verb or a WITH body's; TEMP only where it makes a temporary object
  (CREATE TEMP/TEMPORARY, SELECT ... INTO TEMP), so a column named temp
  works again; a base type; and a NUL anywhere in the SQL text.
- A bound value or a migration id holding NUL is refused with the reason
  instead of being stripped, so the plugin's keys never change meaning.

Every bypass from the re-review is a test on the real database, on the
role the plugin data is meant to run as and on a superuser connection with
the role check off.
2026-11-17 23:04:12 +01:00
Maurice da1a02e7a8 fix(plugins): bind a plugin's own SQLite arguments exactly again, NUL included
5ff5e7660 stripped U+0000 from every argument a plugin bound to its own
SQLite file, but left the rows it had stored alone. A key written with a
NUL (through a bound arg or char(0) in the plugin's SQL) could no longer be
found by the same key, upserts added duplicates, and keys that differ only
in where a NUL sits ('a\0bc', 'ab\0c') collapsed into one and collided.

A plugin's data is the plugin's, so its file binds the arguments exactly as
sent again, as before that commit. TREK's own data still holds no NUL; the
Postgres store, whose text cannot hold the character, refuses it instead.
2026-11-17 23:04:11 +01:00
Maurice 9808e113e4 fix(db): refuse restores for CREATEROLE members, server file grants and parameter grants
The privileged-role check missed three ways a role can reach the database
host from SQL. Before PostgreSQL 16 a member of a CREATEROLE role sets its
role to it and grants itself pg_execute_server_program, since role
attributes are not inherited but the grant checks the role in effect. A role
granted EXECUTE on lo_export, lo_import, pg_read_file, pg_ls_dir and their
siblings reads or writes server files, and lo_export keeps the file after the
transaction rolls back. From PostgreSQL 15 on a role can be granted ALTER
SYSTEM on a setting or SET on a superuser-only one.

PRIVILEGED_ROLE_SQL now counts all three. The parameter grants are read
through query_to_xml inside a CASE taken only on 15 or later, because a
statement naming pg_parameter_acl does not parse on 14. A SET grant on a
setting every role may change anyway, and pg_monitor, stay ordinary. The
lane test creates each kind of role and shows the escalation the check is
for on the server it runs against.
2026-11-17 23:04:11 +01:00
Maurice 13e81c04ab fix(db): drop NUL from every request value before any logic runs
The database stores no NUL on either engine, but the application still held
the value a client sent. A key or a check made from it was then a different
value from the one the database compared: `victim@x.test` followed by NUL
was a fresh key for the per-email password-reset throttle while the lookup
found the victim's row, so every spelling mailed a new link and voided the
last one.

Every input now loses its NUL where it enters TREK: the nulFreeRequest
middleware after the body parsers (path, query string, body, cookies), the
first global pipe for what a route parses itself (a multipart body), the
websocket adapter for every frame, and the MCP registry through a new
host-supplied input mapper, since /mcp keeps its raw body. Headers need
nothing: Node refuses a NUL in one with a 400. A string under a key naming a
password stays as sent: it is only ever hashed, and stripping it would lock
out an account whose password was set with one. The stripping in the
database layer stays as the backstop for what does not come from a request.
2026-11-17 23:04:11 +01:00
Maurice fd42d06d55 docs(db): drop the pg_restore rollback that fails and name the client tool directories the code searches
Updating offered a second way to roll back a Postgres update: drop the
database, create it again and pg_restore the pre-migrate copy into it. TREK's
copy is a dump of its schema by name, so pg_restore creates public again,
stops at "schema public already exists" and rolls the load back, leaving an
empty database in the middle of a rollback. The page now says so and keeps the
steps that clear the schema instead.

Environment-Variables listed /usr/lib/postgresql/17 to 14 as the default
search path for the client tools; the code and the image start at 18.
2026-11-17 23:04:11 +01:00
Maurice e6f4f7a5f3 fix(db): leave nothing behind when a first Postgres boot fails, so RESTORE_FROM_BACKUP still runs
createFromBaseline created the migration history's table through MikroORM's
storage before, and outside, the transaction that runs the baseline. Without a
master transaction MikroORM commits that table on its own, so a first boot that
failed in the baseline (a server without ICU, a timeout, a dropped connection)
left an empty mikro_orm_migrations behind. The next start with
RESTORE_FROM_BACKUP took that for a database in use, skipped the restore with a
warning and brought up an empty instance, after which the restore never ran.

The table is now created on the baseline's own transaction, so a failed first
boot leaves the database empty. The boot restore also treats a lone migration
history that records nothing as no database, which a restore clears anyway; any
other answer keeps it, so the check fails closed. Database-Postgres says both.
2026-11-17 23:04:11 +01:00
Maurice 9497b586b7 test(db): read the raw-SQL exemptions without awaiting in a loop
The two checks over every file under src/ awaited ESLint's config file by
file, which lint:warnings counts as no-await-in-loop. They read the configs
with Promise.all instead.
2026-11-17 23:04:10 +01:00
Maurice 77d90be4f8 docs(db): describe plugin SQL on its own pool client instead of the marker hook
The guard's header, server/CLAUDE.md and the Postgres wiki page named
extended-query.ts and a hook on every pool connection. They now say that the
store sends each plugin statement over the extended protocol on a client it
checks out per call, and drops that client's temporary tables and session
state before handing it back.
2026-11-17 23:04:10 +01:00
Maurice a884539a2b fix(db): run plugin SQL on a pool client of its own instead of patching the pool
Plugin statements on Postgres went over the extended query protocol through a
marker parameter and a hook that replaced query() on every client of TREK's
pool. That kept a plugin to one statement per round trip, but it changed
TREK's own hot path for a concern only plugin data has.

The plugin data store now checks a pg client out of the ORM's pool for each
transaction, through MikroORM's getNativeClient, and runs the transaction on
it directly. Every plugin write goes as a query with queryMode 'extended' and
every read through a pg-cursor on that client, so Postgres parses exactly one
statement either way. The settings the transaction makes are local, and
before the client goes back to the pool the store drops temporary tables,
cursors, listeners, session advisory locks and sequence state, or closes a
client it cannot bring back to that state. The row cap, quota, time budget,
untimed migrate, per-plugin queue, pool share and script commits are as
before, and plugin args are still sent without NUL.

The marker, the hook and its install in the Postgres driver are gone.
2026-11-17 23:04:10 +01:00
Maurice 633df91bd6 fix(db): refuse raw SQL everywhere under src/, not only in the repositories
The ESLint walls against raw(), the sql tag and SQL text handed to
execute/run/all/get applied to src/db/repositories and src/db/seeders only. A
service, job, guard or MCP tool could send its own SQLite-only SQL through
em.getConnection().execute(...), which the Postgres probe never runs, since it
only calls the repositories. The walls now cover all of src/. The dialect layer,
the engines and the migrations stay the homes of raw SQL, and the four boot-time
lifecycle files that hold SQL text today are named and pinned to their count.
2026-11-17 23:04:10 +01:00
Maurice dd98469a02 fix(db): pass the chunk size and the abort options through the NUL-free connection
The wrapper took the chunk size of a stream as optional, which lint:strict refuses, and dropped the abort options Kysely hands executeQuery and streamQuery, so a cancelled query kept running.
2026-11-17 23:04:10 +01:00
Maurice 223a7605ed test: import vi in the trip members suite and type the move's SQLite ORM options 2026-11-17 23:04:10 +01:00
Maurice 0e04eeaf9a test: send the reset and seeding steps one by one or together, not awaited in a loop
resetDatabase empties tables and puts back the default categories one after another through the repo's oneByOne helper, where the order can matter, and the default addons and photo providers together; the MCP suites switch their addons on together and create ordered stops through oneByOne. The warnings this brings below the baseline, and the no-explicit-any and no-unused-vars counts earlier commits lowered, are lowered in scripts/eslint-baseline.json.
2026-11-17 23:04:09 +01:00
Maurice aa77e21d4b fix(db): refuse to regenerate a frozen Postgres baseline and check its trigger ports once frozen
gen:pg-baseline rewrote the baseline with its cut at the newest migration on
disk, so after a migration landed after the cut, running it moved the cut over
that migration while Postgres installs created from the old baseline would
still run it through the migrator. It now refuses while a migration follows the
committed cut, names those migrations and the routine, and moves the cut only
with --move-cut (lint:dialect keeps such a migration under the post-cut rules
either way).

check:pg-baseline stopped comparing SQLite triggers with POSTGRES_TRIGGERS once
the baseline was frozen, so a trigger a later migration created on SQLite went
unnoticed. The comparison now runs in both states, with advice that points at
the migration when the baseline is frozen.
2026-11-17 23:04:09 +01:00
Maurice 8c8cfb5d5d fix(db): hold SQLite-only functions, LIKE and the sqlite member of a post-cut migration in lint:dialect
lint:dialect missed several classes of SQL that SQLite reads and Postgres does
not, or reads differently:

- group_concat, ifnull, instr, iif, printf, typeof, total(), changes() and
  json_object/json_array/json_valid/json_type/json_quote, as calls in SQL text
  and as the bare name handed to eb.fn.
- LIKE in SQL text, Kysely's 'like' operator and MikroORM's $like, which ignore
  case on SQLite only. A LIKE that is exact on purpose now says so in a
  like-exact comment; the six existing ones (setting keys, storage paths, the
  lowercased reference search, sqlite_master) carry it.
- The sqlite member of engineDdl was not read at all, so a trigger or a data
  backfill put there never reached Postgres. It may now hold only the schema
  change and a rebuild's copy and sqlite_sequence bookkeeping, and SQLite
  statements with an empty postgres member need a sqlite-only reason.
- execBestEffort, bestEffort and execUnlessTableMissing in a post-cut
  migration: on Postgres a swallowed failure aborts the migration transaction.
- The post-cut rules follow POSTGRES_FIRST_CUT as well as the manifest, so
  regenerating the baseline over a new migration no longer releases it.

src/db/engine/sqlite/ is SQLite's own code and is no longer scanned.
2026-11-17 23:04:09 +01:00
Maurice 9eeb59997e fix(db): count every spelling of an engine check in lint:engine-dispatch
The gate matched only isSqlite(/isPostgres(, instanceof on a platform class
and a comparison on a property named engine or id. A destructured engine name,
the literal on the left, a switch over the engine, instanceof on a driver class
and a comparison with a driver class all passed with an empty baseline, and
standalone-orm.ts already held one such check. The regex now matches every one
of them, the guard in standalone-orm.ts moves into the engine port as
assertSqliteOrmConfig, and the advice names where a check belongs.
2026-11-17 23:04:09 +01:00
Maurice 8179d7d707 test(db): list the carry-over migration among the ones without a legacy step 2026-11-17 23:04:09 +01:00
Maurice f211a1c614 docs(db): describe the NUL, whole-number and calendar-date rules
server/CLAUDE.md names where NUL is dropped, INTCOL and the .int() rule
for integer columns, and the calendar-date check for a bound date, and no
longer lists the places NUL suite as SQLite-only. The Postgres wiki says
the move drops a NUL instead of refusing it.
2026-11-17 23:04:09 +01:00
Maurice f42ef5246c fix(db): store no NUL character on either engine
Postgres text cannot hold U+0000, so any write or filter carrying one (a
request body, a query string, an import, a feed, a forwarded mail, a
plugin's own SQL) answered a 500 on Postgres while SQLite stored it. Both
engines now drop the character where every value leaves for the database
(src/db/nul-free.ts): the MikroORM platforms when they inline a string or
serialize a JSON value, the Kysely dialects for every parameter, a
plugin's own SQLite file for its arguments, and the move from SQLite,
which used to refuse such text. The same request now answers the same
status and leaves the same row on both engines, so the places NUL suite
runs on Postgres as well and leaves SQLITE_ONLY.
2026-11-17 23:04:08 +01:00
Maurice e1a5864406 fix(storage): find a stored reference in any case on Postgres too
The release queue narrows each owner's rows with LIKE '%run%' before it
parses them, and relied on SQLite's LIKE ignoring ASCII case. On Postgres
LIKE is exact, so a row naming an object in uppercase was not found and
the release deleted an object that row still names. likeAny now matches
LOWER(column) against the lowercase run, which reads alike on both
engines. RELI-010 fails on Postgres without it.
2026-11-17 23:04:08 +01:00
Maurice 62c03d71bf fix(db): find no nearest day for a date the calendar does not have
The nearest-day fallback of a booking's time cast the bound date to a
timestamp on Postgres, which refuses 2024-02-30 with a 500, while SQLite's
JULIANDAY rolled it over into March and placed the booking there.
dayDistance now refuses anything but a calendar date on both engines
(isCalendarDate), so a caller that forgets the check fails on SQLite too,
and findNearestDayId answers no day for such a date. The size baseline of
Reservations.repository.ts drops by one line.
2026-11-17 23:04:08 +01:00
Maurice f4ce2c2bd0 fix(db): keep a carried-over half day as a half on both engines
A vacation day can be taken as a half day, so what a year carries into
the next can end in a half. vacay_user_years.carried_over was an INTEGER
column: SQLite stored 29.5 as a REAL, Postgres (bigint) rounded it to 30,
and the move refused such a SQLite value. The column becomes REAL on
SQLite (a table rebuild that keeps every id and the AUTOINCREMENT counter)
and double precision on Postgres, through the first migration after the
Postgres baseline's cut. VACAY-046 books a half day and reads the
carry-over on both engines.
2026-11-17 23:04:08 +01:00
Maurice d643f8c329 test(memories): answer the session retry cases by API, not by call order
The album list asks three sources at once; which call reaches the fake first
depends on how database reads interleave, which differs between the engines.
The fake now answers by API and category and the cases assert the retry with
a fresh session itself.
2026-11-17 23:04:08 +01:00
Maurice 1b270806a1 test(share): write the place photo cache through the app's own ORM
The suite built the cache over a second SQLite ORM, so on Postgres its rows
went to a database the app never reads.
2026-11-17 23:04:07 +01:00
Maurice 2d7392c4c0 fix(db): refuse a fraction for an integer column at the request boundary
Every integer column is bigint on Postgres. SQLite stored a fraction sent
to one (a packing quantity of 1.5, a budget item for 2.5 days, an id of
3.5) as a REAL, while Postgres rounded it in a statement MikroORM renders
and refused it with a 500 in a Kysely statement, so the engines held
different data for the same request.

The request schemas of those fields now take whole numbers only, and
INTCOL (tests/unit/contracts/integer-columns.test.ts) holds the class: it
reads the integer columns from the entities and fails on any DTO field or
inline MCP tool field of that name that takes any number.
2026-11-17 23:04:07 +01:00
Maurice a9cdb2f91c docs(db): describe the plugin SQL layers and the refused restore roles
The Postgres wiki page and the plugin author guide list what the plugin
SQL guard now refuses and the two layers behind it, and the wiki and
server/CLAUDE.md name every kind of role a restore refuses, including
CREATEROLE on PostgreSQL 14 and 15, which the managed postgres role on
such a server holds.
2026-11-17 23:04:07 +01:00
Maurice 2983971c8b fix(db): refuse restores for every role that can reach the database host
The privileged-role check looked only at the role's own rolsuper and at
pg_execute_server_program and pg_write_server_files. A role that is no
superuser itself but a member of one passed it and could SET ROLE to the
superuser from a crafted archive; on PostgreSQL 14 and 15 a role with
CREATEROLE could grant itself pg_execute_server_program; and
pg_read_server_files let COPY read the server's files into TREK's tables.

The check now counts membership in any superuser role, the three
predefined server roles, and CREATEROLE before 16. The boot warning and
the restore refusal describe the same list from one constant. A Postgres
lane suite creates each kind of role and evaluates the check as it, and
shows on the server it runs against whether CREATEROLE can grant itself
pg_execute_server_program.
2026-11-17 23:04:07 +01:00
Maurice e6a0a39a51 fix(db): read plugin SQL the way the Postgres lexer does and refuse INTO and TEMP anywhere
The guard ended a -- comment at LF only, while Postgres ends it at CR as
well, so "select 1 --\rfrom public.users" hid a qualified name from the
guard that Postgres then read, and with no args a second statement after
the CR ran as TREK's role. It also only looked for INTO at the top level
of a SELECT, so "(select ... into temp users)" made a temporary table that
shadowed TREK's own users table on the pooled connection.

The tokenizer now skips exactly what Postgres skips as whitespace, ends a
line comment at CR or LF, and refuses any character the two read
differently (other control characters, non-ASCII whitespace such as
U+00A0, U+FEFF and U+2028, and the non-decimal and underscored numbers
Postgres before 16 reads another way) instead of guessing. INTO is refused
anywhere but after INSERT or MERGE, at any depth, and the words TEMP and
TEMPORARY anywhere outside a string or quoted name.

The guard tests carry both payloads and their variants; the Postgres lane
runs them against the real database, proves a second statement in one
text is refused by Postgres over the extended protocol, and that a
temporary table never shadows TREK's or a plugin's tables.
2026-11-17 23:04:07 +01:00
Maurice 87612c0c79 fix(db): run plugin SQL one statement at a time and search pg_temp last
The plugin SQL guard was the only thing between a plugin and TREK's tables
on Postgres, and two gaps in it were enough to leave the plugin schema.
Two layers now hold even when the guard is fooled.

A plugin write with no bound args went over the simple query protocol,
which runs every statement in its text. Plugin statements now go through
extendedQuery, which pg sends over the extended protocol whatever the
args, so a second statement is a syntax error instead of a statement that
runs. A marker parameter carries the request to the pool's clients, and a
client without the hook binds one value too many, so it fails closed.

pg_temp is searched before the search_path unless the path names it, and
a temporary table lives as long as its pooled connection, so one left
behind would stand in for users, sessions and every other table for the
next caller. Every connection of TREK's pool now puts pg_temp last on the
search_path the role configured, and a plugin transaction sets its schema
with pg_temp last.
2026-11-17 23:04:07 +01:00
Maurice ff57883e3d test(db): run the notifications and advanced packing MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well. The tag notification case waits for the fire-and-forget row with
vi.waitFor instead of one turn of the event loop: on SQLite the insert
lands within that turn, on Postgres it needs a few round trips more.
2026-11-17 23:04:06 +01:00
Maurice cd1a3fd433 test(realtime): run the websocket wire envelope suite on the real database module
It takes the ORM from the app buildApp boots, seeds through the factories
and resets through resetDatabase instead of the SQLite snapshot mock, so
it runs in the Postgres lane as well.
2026-11-17 23:04:06 +01:00
Maurice 377f22972b test(db): run the trips and vacay MCP suites and the route inventory on the real database module
The MCP suites seed through the booted container's ORM instead of the
SQLite snapshot mock and reset through resetDatabase. The route inventory
never touched the database and only mocked it; without the mock it
compiles AppModule over the real module, so it runs in the Postgres lane
as well.
2026-11-17 23:04:06 +01:00
Maurice fff7d123f6 test(db): run the transports, trip members and trip warnings MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well. The trip warnings suite seeded through the factories but only closed
the snapshot handle; it now boots the container to reach the ORM the reset
needs.
2026-11-17 23:04:06 +01:00
Maurice bedb70c479 test(db): run the share, tags, maps and weather, and transit MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well. The transit suite saves its permission levels through the
container's PermissionsService in a request context instead of one built
by hand over the SQLite handle.
2026-11-17 23:04:06 +01:00
Maurice 3b8270edc3 test(db): run the reservations, road trip and settings MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well. The road trip suite saves its permission levels through the
container's PermissionsService in a request context instead of one built
by hand over the SQLite handle.
2026-11-17 23:04:05 +01:00
Maurice 6137aaf716 test(db): run the packing, places and plugin MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well. The plugin search suite seeded nothing through the snapshot handle
and only closed it; it now boots the container to reach the ORM the reset
needs.
2026-11-17 23:04:05 +01:00
Maurice 97a3389409 test(db): run the feeds and invite, journey, leg transport mode, memories and notes MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well.
2026-11-17 23:04:05 +01:00
Maurice 95ade9cbb2 test(db): run the days, accommodations, files and help MCP suites on the real database module
They seed through the booted container's ORM instead of the SQLite snapshot
mock and reset through resetDatabase, so they run in the Postgres lane as
well. The collab sub-feature case in the help suite toggles through the
container's AddonsService in a request context instead of one built by
hand over the SQLite handle.
2026-11-17 23:04:05 +01:00
Maurice c4c278d2f3 test(db): run the budget and collections MCP suites on the real database module
They seed through the booted container's ORM instead of a second ORM over
the SQLite snapshot mock, and reset through resetDatabase, so they run in
the Postgres lane as well. The settlement parity cases call the
container's BudgetController in a request context instead of one built by
hand over the SQLite handle, and the collections suite drops its raw
per-table DELETE for the same reset.
2026-11-17 23:04:05 +01:00
Maurice 2cb1964863 test(db): run the AirTrail, atlas expanded, collab and categories MCP suites on the real database module
They seed through the booted container's ORM instead of a second ORM over
the SQLite snapshot mock, and reset through resetDatabase, so they run in
the Postgres lane as well. The PermissionsService the AirTrail cases save
through and the CategoriesMcp and DemoService the categories write
harness attaches are the container's own, called in a request context,
instead of instances built by hand over the SQLite handle.

include_coords compares the coordinates as a set: getTravelStats reads
them through a SELECT DISTINCT without an order, and Postgres returns
them in hash order.
2026-11-17 23:04:05 +01:00
Maurice 876cc5e0f0 test(db): run the demo tool gate, addon gating, atlas and assignments MCP suites on the real database module
They seed through the booted container's ORM instead of a second ORM over
the SQLite snapshot mock, and reset through resetDatabase, so they run in
the Postgres lane as well. The tour the assignment cases put on a day is
made with makeTour instead of a raw insert.
2026-11-17 23:04:04 +01:00
Maurice caae538056 test(db): merge the factory imports of the newly ported integration suites
One import per module, and the resetTestDb import that no longer has a
caller dropped.
2026-11-17 23:04:04 +01:00
Maurice 1cebddac0e test(db): run the trips and vacay suites on the real database module
They reset through resetDatabase and seed through the ORM factories on the
booted app's ORM instead of the SQLite snapshot mock, so they run in the
Postgres lane as well.
2026-11-17 23:04:04 +01:00
Maurice 78bfa8183a test(db): run the share, system notices and trip access primitives suites on the real database module
They reset through resetDatabase and seed through the ORM factories on the
booted app's ORM instead of the SQLite snapshot mock, so they run in the
Postgres lane as well.
2026-11-17 23:04:04 +01:00
Maurice 43af349391 test(db): run the security, settings, tags and todo suites on the real database module
They reset through resetDatabase and seed through the ORM factories on the
booted app's ORM instead of the SQLite snapshot mock, so they run in the
Postgres lane as well.
2026-11-17 23:04:04 +01:00
Maurice 9c35343d9d test(db): run the scheduler gate, storage health context and uploads suites on the real database module
They drop the SQLite snapshot mock and, where they seed, reset through
resetDatabase and seed through the ORM factories, so they run in the
Postgres lane as well.
2026-11-17 23:04:03 +01:00
Maurice b0b1986377 test(db): keep the legacy upgrade suites on SQLite by name
They boot on a SQLite file the retired positional runner built, which no
Postgres database ever came from, so they belong in SQLITE_ONLY rather
than in the snapshot baseline. The lane scan now tells such a suite apart
from the snapshot mock: it mocks src/db/database onto a database of its
own, never names createSnapshotTestDb, and is named in SQLITE_ONLY with
its reason. A snapshot suite added to SQLITE_ONLY stays in the baseline.
2026-11-17 23:04:03 +01:00
Maurice f11f021e15 test(db): run the Immich, Synology and unified memories suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.

IMMICH-057 and SYNO-035 need a shared photo row whose trip is gone, which
the foreign key's cascade rules out on a database that enforces it; they
write it with SQLite's foreign keys off as before and are skipped on
Postgres, which has no such switch.
2026-11-17 23:04:03 +01:00
Maurice 6e7336b8d7 test(db): run the MCP and OAuth suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well. The OAuth service they drove by hand over a second ORM on the
SQLite handle is now the container's own, called in a request context.

The MCP audit cases wait for the mcp.tool_call row: the transport writes
it without awaiting it, so on Postgres it can land after the response.
2026-11-17 23:04:03 +01:00
Maurice 927fcab67f test(db): run the places and incoming leg mode suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.

The two cases about a NUL byte in a place name move to
places-nul-sqlite.test.ts, listed in SQLITE_ONLY: they pin SQLite's value
quoting, and Postgres text cannot hold U+0000. The control characters
0x01 to 0x1F stay in places.test.ts and run on both engines.
2026-11-17 23:04:03 +01:00
Maurice c51f4f78bb test(db): run the packing, reservations and journey suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.
2026-11-17 23:04:02 +01:00
Maurice 12f4a40d7c test(db): run the OIDC, passkey, profile, notifications and ORM request context seam suites on the real database module
They reset through resetDatabase (the seam suite needs no reset) and seed
through the ORM factories instead of the SQLite snapshot mock, so they run
in the Postgres lane as well.
2026-11-17 23:04:02 +01:00
Maurice 3a6e91e26b test(db): run the journey place order, maps, misc and local OIDC provider suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.
2026-11-17 23:04:02 +01:00
Maurice 680ce7324a test(db): run the admin and auth suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well, the user erasure cases included.
2026-11-17 23:04:02 +01:00
Maurice f5fbd60b5e test(db): run the files and collab suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.
2026-11-17 23:04:02 +01:00
Maurice 8c1395c8f1 test(db): run the atlas and backup suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.
2026-11-17 23:04:02 +01:00
Maurice 19bfa77ace test(db): run the assignments, day notes and async closure guard suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.
2026-11-17 23:04:01 +01:00
Maurice 2fb041a428 test(db): run the feeds, atlas geocode, collections and Immich suites on the real database module
They reset through resetDatabase and seed through the ORM factories
instead of the SQLite snapshot mock, so they run in the Postgres lane as
well.
2026-11-17 23:04:01 +01:00
Maurice be1983c9a4 test(db): run the boot, boot sweep, demo seed, AirTrail and doc sync context suites on the real database module
They boot the app without the SQLite snapshot mock, so they run in the
Postgres lane as well. The demo seed suite spies on the real runDemoSeed
export instead of replacing the database module to wrap it.
2026-11-17 23:04:01 +01:00
Maurice 2288487fe1 fix(oauth): narrow the refused registration for the strict compiler 2026-11-17 23:04:01 +01:00
Maurice b2384892a8 test(db): run the session revocation, api docs, app config and help suites on the real database module
They boot the app without the SQLite snapshot mock, so they run in the
Postgres lane as well. sessionRowsOf reads a user's session rows through
a booted app's ORM, next to sessionRows for the suites that still hand in
a better-sqlite3 handle.
2026-11-17 23:04:01 +01:00
Maurice 43e30ca28e test(realtime): run the websocket connection suite on the real database module
Seeds through the ORM factories, resets through resetDatabase and mints
ws-tokens through the container's TokenService instead of one built by hand
over the SQLite snapshot mock, so it runs in the Postgres lane as well.
2026-11-17 23:04:01 +01:00
Maurice 42f0705f07 test(todo): run the todo MCP tool suite on the real database module
Seeds through the booted container's ORM instead of a second ORM over the
SQLite snapshot mock, and resets through resetDatabase, so it runs in the
Postgres lane as well.
2026-11-17 23:04:00 +01:00
Maurice e97dbc89c9 fix(db): keep the stay filter inside src/db and cover the flag type's missing read
src/db may not import src/nest, so the '<id>.0' shape is spelled where the
filter is. The flag type's undefined read had no test, which left the types
folder below its branch threshold.
2026-11-17 23:04:00 +01:00
Maurice 76dfbe0a00 test(days): run the days suite on the real database module
Seeds through the ORM factories and resets through resetDatabase instead of
the SQLite snapshot mock, so it runs in the Postgres lane as well.
2026-11-17 23:04:00 +01:00
Maurice 424fa538e0 test(budget): run the budget suite on the real database module
Seeds through the ORM factories and resets through resetDatabase instead of
the SQLite snapshot mock, so it runs in the Postgres lane as well.
2026-11-17 23:04:00 +01:00
Maurice 863ff62b6c test(categories): run the categories suite on the real database module
It resets through resetDatabase instead of the SQLite snapshot mock, so it
runs in the Postgres lane as well.
2026-11-17 23:04:00 +01:00
Maurice e2b0910e28 test(db): reset a suite's database between tests on either engine
resetTestDb needs the SQLite snapshot mock's better-sqlite3 handle, so a
suite resetting with it can only run on SQLite. resetDatabase takes the
booted app's ORM and leaves the same state on SQLite and Postgres: every
table but the kept ones emptied (read from the live schema), sequences left
counting, seedDefaults' rows back through the ORM, and on the first call the
users sequence restarted as the snapshot mock normalises it.
2026-11-17 23:03:59 +01:00
Maurice cf9172f9e7 fix(db): type the move's value conversion and client for the server's compiler
Formats the two files the format gate listed.
2026-11-17 23:03:59 +01:00
Maurice 0e911608af fix(db): match a stay's bookings by the stored '<id>.0' text, as SQLite did
Reading the TEXT column as an integer also matched '14', ' 14' and '14abc',
which the legacy REAL-bound compare never did (AC37/AC40). Comparing with the
'<id>.0' text the services store keeps that contract on both engines.
2026-11-17 23:03:59 +01:00
Maurice 95d067ad6d test(auth): a plugin table missing from the schema fails the user erasure
The erasure no longer skips a missing plugin table in a savepoint of its own (61ea6b648); USER-CLEANUP-005 still expected the skip.
2026-11-17 23:03:59 +01:00
Maurice ba043cb1c0 style(plugins): keep the runtime and the SDK within their size baselines
The plugin data engine added three lines to each; six comments that wrapped past 120 columns now fit in one.
2026-11-17 23:03:59 +01:00
Maurice 3a4c523509 test(db): the move command's own output and target ORM 2026-11-17 23:03:58 +01:00
Maurice 057748c47a fix(db): set no deferred references once the move refused a value
Nothing is inserted after the first refused value, so the self-references held back had no rows to land on, and the move failed on them instead of listing the values (MOVE-006).
2026-11-17 23:03:58 +01:00
Maurice e4457ed9eb style(db): format postgresTarget as Prettier does 2026-11-17 23:03:58 +01:00
Maurice f430cbe59e chore(lint): lower the server's no-console baseline to 231
AuthService no longer warns through console when an invite's last use was taken: the registration now refuses it inside its transaction.
2026-11-17 23:03:58 +01:00
Maurice 5316362e9e fix(db): open the move's SQLite source through openDatabase, keep the drop failure as the cause
ESLint refused both: better-sqlite3 is imported only in src/db/connection.ts and its named neighbours, and an error thrown in a catch carries what that catch caught.
2026-11-17 23:03:58 +01:00
Maurice 900f2bfc30 test(realtime): read each parity case after its notification sends have settled
On Postgres a fire-and-forget notification still ran when the case read its recording, so it landed in the next case. The harness now waits for NotificationsService.settled() after each write and each exemption; a late send of any other kind still fails the next case.
2026-11-17 23:03:58 +01:00
Maurice b7c8f0629c feat(notifications): know when the sends a write left running have finished
Most writes start their notification without waiting for it. NotificationsService now tracks each send until it settles, and settled() resolves once every send started before it has finished. The channel check moves to channel-gate.ts, which keeps the service under the size limit.
2026-11-17 23:03:57 +01:00
Maurice 45fef1077a test(demo): read the baseline refusal from the logger 2026-11-17 23:03:57 +01:00
Maurice ddb42ecf0a test(db): name the restore's plugin schemas as plugin ids allow 2026-11-17 23:03:57 +01:00
Maurice 09295781f4 test(integrations): give the AirTrail suites' UnitOfWork its engine 2026-11-17 23:03:57 +01:00
Maurice 5938609f69 test(db): no await inside a loop in the Postgres tests 2026-11-17 23:03:57 +01:00
Maurice d3cd484519 test(db): stand-in pg tools write --file=- to their own stdout
The CI runner gives a child process a socket for stdout, which /dev/stdout cannot open, so every case whose pg_restore streams its script failed there. The COPY terminators in PGTOOLS-020 are spelled as a dump spells them.
2026-11-17 23:03:56 +01:00
Maurice 410d2393e0 fix(db): log the demo baseline refusal through the logger, read the tool versions at once 2026-11-17 23:03:56 +01:00
Maurice 44b6340be5 docs(db): every transaction goes through UnitOfWork, checks read inside it 2026-11-17 23:03:56 +01:00
Maurice 2f3dc4ea79 feat(lint): refuse a transaction outside UnitOfWork under src/
trek/transactions-through-unit-of-work reads the receiver's type and reports
transactional() on anything but a UnitOfWork (an untyped receiver
included), and begin() or transaction() on an EntityManager, a connection
or Kysely. src/db/engine/ and the two boot-time schema files are left out.
It runs with the rest of the server's ESLint, so lint:warnings fails on a
new one, and its message names UnitOfWork, writeTransaction and the rule in
server/CLAUDE.md.
2026-11-17 23:03:56 +01:00
Maurice af861e5816 fix(db): read the checks a write relies on in the transaction that writes
On Postgres a check read before a transaction, or outside one, no longer
holds at the write that follows: the pool runs other requests' writes in
between. Moved into the unit of work that writes:

- the last-admin guard of an admin's role edit and of an account deletion
  (deleteUserCompletely takes a precondition run in its transaction)
- the login lockout guards of the auth settings save and the SSO settings
  save
- the first-account check of an SSO sign-up, which starts over as an
  ordinary sign-up when another account won
- the OAuth client caps, the token cap and the mail intake limits
- the year check before a vacay year is opened, and the label name check of
  a rename

A password sign-up that loses the last use of an invite is now refused, as
the SSO sign-up already was, and a reset link is burned by one conditional
update, so two resets with one link cannot both change the password.
2026-11-17 23:03:56 +01:00
Maurice c1bbe27ac6 fix(db): take the write lock in every transaction that writes
UnitOfWork took the engine's write lock, but four repositories opened
transactions of their own: the demo addon set, the plugin user erasure's
savepoints, and the plugin metadata and scheduler cap checks. On Postgres
those ran beside the others on the pool.

writeTransaction (src/db/engine/write-transaction.ts) is now the one
transaction that writes: UnitOfWork wraps it, and the demo seed and reset,
which run outside the container, call it with the engine the environment
names. The capped plugin writes run in their caller's unit of work instead
of a transaction of their own, and the plugin erasure runs in the erasure's
transaction without savepoints, since its three tables come with the
migrations on both engines. lint:tx counts writeTransaction as a
transaction.
2026-11-17 23:03:56 +01:00
Maurice 11f4373076 docs(db): rotating the encryption key on Postgres 2026-11-17 23:03:55 +01:00
Maurice f57fb7f9de test(db): the key rotation on Postgres, and its refusals before a key is asked 2026-11-17 23:03:55 +01:00
Maurice 96f2427518 fix(db): rotate the encryption key on Postgres through the server's engine
The rotation ran on the SQLite file only and refused when TREK_DB_URL was
set. Its statements now go through a small store per engine: better-sqlite3
for the file, unchanged, and on Postgres the server's own MikroORM
connection, in one transaction that takes the engine's write lock first. The
Postgres path checks that it reaches a database holding TREK's tables and
that the data directory is writable before it asks for a key, writes a
pg_dump copy before it changes anything, refuses DB_PATH or TREK_DB_FILE
beside the URL, and reads the jsonb addon config the driver hands back
parsed. The SQLite transaction is now BEGIN IMMEDIATE, since better-sqlite3
takes no async function.
2026-11-17 23:03:55 +01:00
Maurice 3f51153dcc docs(db): moving an existing install to Postgres, and the refusal of an empty database beside one 2026-11-17 23:03:55 +01:00
Maurice fc37eb95d1 test(db): move a factory-seeded SQLite install into Postgres and read it back through the app 2026-11-17 23:03:55 +01:00
Maurice 55607ff2f9 feat(db): move a SQLite install into an empty Postgres database
npm run db:move-to-postgres (dist/move-to-postgres.js in the image) copies
a SQLite file at this build's migration level into an empty Postgres
database. It refuses a file at another level, rows whose references point
at nothing and a target holding any table or plugin schema, creates the
schema with the engine's own bootstrap, then in one transaction copies every
table in foreign key order (setting a self-reference once its rows are in),
converts each value to its column's type and refuses one Postgres cannot
hold exactly, copies each plugin's plugin.db into its schema, moves the
sequences past the copied ids and compares every table's row count and an
order-free checksum over all rows before it commits. A failure drops the
schema again. The SQLite files and the uploads are never written.
2026-11-17 23:03:54 +01:00
Maurice 1ea08dcf0a fix(db): refuse a Postgres boot that would leave a SQLite install behind
Setting TREK_DB_URL on an existing SQLite install booted a new, empty
instance beside its data. The Postgres bootstrap now refuses an empty
database, or a migrated one without a single account, while the data
directory's travel.db holds accounts, and names the move command. A file
that cannot be read counts as holding them. TREK_DB_IGNORE_SQLITE_FILE=true
starts anyway, with a warning; the file is opened read-only and only when
the database holds no TREK data.
2026-11-17 23:03:54 +01:00
Maurice c6f6dd2d57 fix(db): find a stay's bookings on Postgres
reservations.accommodation_id is TEXT and holds '14.0'. Compared with a bare
number, Postgres binds the number as the text '14' and finds nothing, so
deleting a stay, a day or a place left its bookings behind with no error. The
three filters read the column as an integer, as the joins already do.
2026-11-17 23:03:54 +01:00
Maurice 579df97bba fix(db): type the integer flag and the owner literal for the server's compiler
The server compiles without strictNullChecks, where a narrowed value returned
as is keeps its full type, and two literal arms of one UNION column must share
a type.
2026-11-17 23:03:54 +01:00
Maurice aa2f7ca8b4 test(db): the Postgres plugin data store against a stand-in client
Covers what every call sets up, the schema check before plugin SQL runs, the
row cap, the time budget between chunks and at statement_timeout, the quota,
a script committed statement by statement, the tx and migrate shapes and one
call at a time per plugin, without a database. The Postgres lane runs the
same store on a real one.
2026-11-17 23:03:54 +01:00
Maurice 17c9c0758f docs(db): plugin data on Postgres, its SQL rules and one TREK per database
The plugin-sdk README says what dialect a plugin writes when TREK runs on
Postgres, what the guard refuses and how the limits hold there. The wiki's
Postgres page describes the plugin schemas, their backup and restore and
the one-instance-per-database limit, and its key rotation path now names
the file where it is.
2026-11-17 23:03:54 +01:00
Maurice 7340087353 fix(db): carry the plugin data schemas in Postgres backups and restores
pg_dump now names the trek_plugin_ schemas TREK's role owns beside its own
schema. A restore reads the dump's plugin schemas from its table of
contents, drops the plugin schemas the role owns, creates the dump's and
loads them with TREK's schema, all in the one psql transaction. Schemas of
another role and every other schema of the database are never read or
dropped.

The dump's migration history is read from TREK's mikro_orm_migrations only,
so a plugin table of that name cannot pass for it.
2026-11-17 23:03:53 +01:00
Maurice 910c98b971 feat(plugins): store plugin data on the engine TREK runs on
PLUGIN_DATA binds the plugin data backend to the engine (the same
{ sqlite, postgres }[engine.id] binding the backup port uses): the SQLite
file per plugin, unchanged, or the Postgres schema per plugin. The host
opens a plugin's store through it and an uninstall that deletes data erases
through it, which drops the schema on Postgres. Nothing outside db/engine
asks which engine runs.

A plugin's SQL is passed through as written, so a plugin needs to know the
dialect: db.engine (db:own) answers 'sqlite' or 'postgres', and the SDK
exposes it as ctx.db.engine(), in the mock host (dbEngine option) and in
dev. The plugin facts are regenerated and the SDK goes to 1.10.0.

The Postgres lane's PGPLUG suite installs, uses and erases plugin data on
Postgres and shows that a plugin reaches neither TREK's users table nor
another plugin's schema.
2026-11-17 23:03:53 +01:00
Maurice b144781e9f feat(db): keep a plugin's own data in a Postgres schema of its own
A plugin with db:own got a SQLite WAL file in the data volume whatever the
engine, so a Postgres install still needed a local disk (discussion #386).
This adds the plugin data port (db/engine/plugin-data.ts) and its Postgres
side: one schema per plugin, trek_plugin_<id>, reached through TREK's pool.

Every call runs in a transaction that creates the schema if missing, puts
only it on the search_path and sets statement_timeout to the call's budget.
Reads stream through a cursor and stop at the row cap, a write that grows
the schema past the quota rolls back, and the calls of one plugin run one at
a time on at most half of the pool.

TREK's role may read every table, and a role per plugin would need
CREATEROLE, so plugin-sql-guard.ts checks each statement first: it lexes the
SQL as Postgres does and refuses another schema as a qualifier, the pg_
catalogs and functions, functions that run SQL from a string or reach an
object by a name in one, temporary tables, and every statement but DML and
DDL on tables, indexes, views, sequences and types.
2026-11-17 23:03:53 +01:00
Maurice a26db47cb6 refactor(db): keep the touched files within their size baselines
The users identity guard moves to repositories/_shared/user-identity.ts
(Users.repository.ts re-exports UserIdentityTakenError), the flag text pass
of the entity generator to scripts/generate-entities-flags.ts, and the
Wallet pass query takes the repository's EntityManager. The size baseline
of Users.repository.ts is lowered to what it holds now (1445 to 1421); a
few exports only their own file used are no longer exported.
2026-11-17 23:03:53 +01:00
Maurice 9e5379d092 fix(demo): keep a demo baseline per engine and check it before every reset
The baseline was travel-baseline.db on both engines and went straight into
the swap, so a SQLite baseline left in the data directory made every hourly
reset of a Postgres demo fail inside pg_restore, and never got replaced. It
is now named after the engine's archive entry (travel-baseline.db on
SQLite, travel-baseline.pgdump on Postgres), and the backup port's new
checkCopy refuses one the engine cannot restore before the swap; the reset
then saves a fresh baseline and logs the reason instead of failing hourly.
2026-11-17 23:03:53 +01:00
Maurice 693acd5580 fix(db): reset the admin on Postgres and keep the key rotation off it
reset-admin.js opened data/travel.db with better-sqlite3 whatever the
engine, so on a Postgres install it created a stray SQLite file or reset
the admin in a leftover one. With TREK_DB_URL set it now resets the account
in Postgres through the built server's engine (its pool, SSL and write
lock, in one transaction), and refuses a TREK_DB_FILE beside the URL; the
SQLite branch is unchanged. migrate-encryption.ts cannot re-encrypt the
secrets in Postgres yet, so it now stops before it opens or writes any file
when TREK_DB_URL is set. The wiki says what each does on Postgres.
2026-11-17 23:03:52 +01:00
Maurice c3f6177be1 fix(db): sort NULLs where SQLite sorts them on Postgres
SQLite takes NULL as the smallest value and Postgres as the largest, so any
list ordered by a nullable column (bookings without a time, trips without
dates) came back in another order on Postgres. Instead of every ORDER BY
spelling its NULL position, the Postgres engine renders SQLite's wherever a
statement names none: a Kysely query compiler for this.kysely() statements
and a MikroORM platform for find() and the query builder. An explicit
position is kept.

A new Postgres-lane suite checks the answers the probe cannot see: the NULL
order, a stay linked as '14.0' in the public reads, the traveller owner
flag, the identity errors for a lost race, and the plugin caps under a race
on the pool.
2026-11-17 23:03:52 +01:00
Maurice 60642cc18b fix(plugins): hold the write lock for the plugin cap checks on Postgres
meta.set and scheduler.set checked their caps in a transaction of the
repository's own, which keeps check and write together on SQLite's single
writer but not on Postgres, where two pool connections both read the same
count. Both RPCs now run the capped write inside UnitOfWork.transactional,
which takes the engine's write lock; the repository's transaction becomes a
savepoint of it.
2026-11-17 23:03:52 +01:00
Maurice 54b843ae29 fix(db): store addons.enabled as the integer flag on Postgres too
addons.enabled was the one flag MikroORM's boolean type declared as a
Postgres boolean, while SQLite and every other flag hold 0/1, so an addon
migration's usual SET enabled = 1 would fail there and a Kysely read would
answer true instead of 1. The column now uses IntegerFlagType: the entity
still reads a boolean, both engines store 0/1, and the regenerated Postgres
baseline declares it bigint default 0. The entity generator renders the
type for the columns in BOOLEAN_COLUMNS.
2026-11-17 23:03:52 +01:00
Maurice 633e9bcdc1 docs(db): Postgres 14 to 18, the database role, restore limits and the manual rollback
- Database-Postgres: supported versions, the version 18 client and the tool
  search order, sslrootcert with a client before 16, how to create a role
  that is not a superuser and move an older compose install to one, a
  current schema other than public, and the space a restore needs.
- Updating: the manual rollback clears the whole schema and loads the copy
  in one transaction, as TREK's restore does; dropping only the tables left
  the collation, the trigger functions and the sequences behind. A unit
  test keeps the printed statement equal to CLEAR_SCHEMA_SQL, and the boot's
  rollback hint points at that section.
- Troubleshooting, Install-Docker-Compose, Environment-Variables, README
  and server/CLAUDE.md follow.
2026-11-17 23:03:52 +01:00
Maurice eab501925f fix(deploy): run TREK as a role that is not a superuser in the Postgres compose file
The compose file let the postgres image create TREK's role as the
superuser, so a crafted backup restored by TREK could run commands in the
database container. The superuser is now postgres, with a password of its
own, and an init script creates the role trek that owns TREK's database and
nothing more. The Helm values say the same about the role in the URL.
2026-11-17 23:03:51 +01:00
Maurice 2630d7e8ec build(docker): ship the PostgreSQL 18 client tools from the PGDG repository
A client handles every server up to its own major and refuses a newer one,
so the image needs the newest supported major, 18, which Debian 13 does not
ship. The PGDG repository is added with its signing key kept in the
repository and its component pinned to 18.
2026-11-17 23:03:51 +01:00
Maurice 116ba52fbb fix(db): check the Postgres server and tools before a dump or a restore
- The client tools are looked for newest first, from 18 down: a client
  handles every server up to its own major and refuses a newer one. A dump
  or a restore now refuses a client older than the server up front, naming
  both versions, and the boot refuses a server outside PostgreSQL 14 to 18.
- sslrootcert=system is used only by a client from libpq 16 on; an older
  client is refused with a message that names sslrootcert and the bin dir.
- The restore's CVE-2025-8714 table covers 18.
- A restore refuses a role that is a superuser or may run programs or write
  files on the database host, since the archive's SQL runs as that role;
  the boot warns about such a role.
- pg_restore's script is streamed to its work file and stopped once it
  passes BACKUP_MAX_DECOMPRESSED_MB, so a small dump can no longer expand
  without limit on the data volume.
- A failed tool's error keeps only the summarized stderr; its cause names
  the exit code and signal instead of carrying the process error, whose
  message and stderr quoted row data into the log.
- The migration history is looked for in the current schema, where the
  tables and the backups are, so a role whose search_path is not public
  boots a second time.
2026-11-17 23:03:51 +01:00
Maurice e5fb6d9107 fix(db): read unique violations and missing tables the same way on both engines
guardIdentity matched only SQLite's message text, so on Postgres a lost
race for an email or a username escaped as a 500 instead of a 409. The new
dialect module driver-errors.ts reads a unique violation by Postgres's
SQLSTATE 23505 and constraint name, or by SQLite's message, and the users
repository maps the key names of both engines. isMissingTableError moves
there too and also knows Postgres's 42P01 for an unconverted error.
2026-11-17 23:03:51 +01:00
Maurice 98529bc84c fix(db): return the traveller owner flag as a number on Postgres
The owner and member branches of listTravellerUsernames selected bound
values, which Postgres resolves to text in a UNION column, so the public
API reported every traveller as owner: false. The literals are written into
the statement as integers now.
2026-11-17 23:03:51 +01:00
Maurice 4a3ad562a7 fix(db): match a stay-linked booking on Postgres in the public stay check
publicStayExists cast reservations.accommodation_id straight to integer,
which Postgres refuses for the stored '14.0', so the calendar feed and the
share links failed for every trip once any booking was linked to a stay.
The correlation now goes through accommodationIdMatches, which compares
through the new dialect helper integerTextEqualsKysely, and the Wallet pass
context uses the same helper instead of its own numeric cast.
2026-11-17 23:03:50 +01:00
Maurice 518287ff12 docs(db): describe the discovered Postgres lane and the 14/18 job 2026-11-17 23:03:50 +01:00
Maurice 0cdfb9eb42 ci(db): run the Postgres probe and lane on Postgres 14 and 18
TREK supports Postgres 14 to 18, and CI tested 17 only. One server-postgres
job per major now runs the probe and then the lane against the same service,
so the change keeps the job count of the two jobs it replaces. The lane's
global setup refuses a service whose major is not TREK_TEST_PG_MAJOR, and
the image's Postgres boot moves to 18, the major its client tools target.

scripts/ci/workflow-jobs.test.mjs fails when a job other than the scan is
missing from ci-ok's needs, and changed-areas pins that migrations,
repositories, the engine and the lane's files always run the job.
2026-11-17 23:03:50 +01:00
Maurice 4d0067a455 test(db): find the Postgres lane's suites instead of listing them
The lane ran a hand-kept list of 26 suites that had already missed
trip-tags-mcp and the broadcast-parity suites, and listed two that never
touch a database. tests/postgres/lane.ts now takes every test file that
reaches src/bootstrap.ts or src/nest/app.module.ts through its imports and
does not vi.mock src/db/database, minus a named SQLITE_ONLY map with the
reason for each.

tests/unit/postgres-lane.test.ts (PGLANE, in the SQLite lane) fails on a
suite that names a boot entry point the discovery does not see, on a stale
exclusion, and on a new suite that boots the app over the SQLite snapshot
mock; the 105 that still do are held in snapshot-suites-baseline.json,
which only shrinks.
2026-11-17 23:03:50 +01:00
Maurice 66d4431d26 docs(db): the routine for a migration after the Postgres cut 2026-11-17 23:03:50 +01:00
Maurice 293a48c26a fix(db): keep check:pg-baseline speaking once the baseline is frozen
A frozen baseline still has its manifest verified, and the check now lists the
migrations that run on Postgres after the cut and what holds them. Every
problem it reports says what to do about it.
2026-11-17 23:03:50 +01:00
Maurice 80fca10784 feat(db): hold migrations after the Postgres cut to engineDdl in lint:dialect
A migration newer than the baseline's through (read from
assets/postgres/baseline.json) fails on a schema statement outside engineDdl,
a plain string column for addColumnIfMissing or a SQLite-only helper, and on a
SQLite spelling in an engineDdl postgres member. The advice names the two
steps, and the baseline cannot hold an allowance for these rules.
2026-11-17 23:03:49 +01:00
Maurice 830cd6e3b5 feat(db): print the Postgres side of a new migration with gen:pg-migration
The script builds a scratch database the way a boot does (the baseline, then
the migrations after its cut) up to the target migration, compares it with the
entities by PARITY-PG's rules and prints the remaining statements as the
postgres member of engineDdl. The scratch database is always dropped.
2026-11-17 23:03:49 +01:00
Maurice 0f338d5484 refactor(db): move PARITY-PG's schema comparison into the Postgres engine
Which comparator statements change nothing (drop not null on a live primary
key, spelling-only defaults and checks proven by a rolled-back fingerprint, the
hand-ported triggers) is now one module the parity test and the migration
generator share, with unit tests for the sorting and the rollback.
2026-11-17 23:03:49 +01:00
Maurice a99cd40f4d feat(db): write a migration's schema change once per engine
A migration after the Postgres baseline's cut runs on both engines, but its DDL
is not one language. engineDdl(this, { sqlite, postgres }) queues the statements
of the engine the migration runs on, like addSql, and addColumnIfMissing takes a
column definition per engine, both picked in the dialect layer so a migration
never branches on the engine itself.
2026-11-17 23:03:49 +01:00
Maurice f3ea50b17b fix(db): cut the Postgres baseline at the newest migration again
The merge with dev brought eight migrations written for SQLite (DATETIME,
INTEGER PRIMARY KEY without identity); run verbatim on Postgres they stop the
first boot. No Postgres install has been released, so the baseline moves to
the newest migration and those tables come from the entities.
2026-11-17 23:03:49 +01:00
Isaias Tavares 2e3762afe1 feat(db): run TREK on PostgreSQL
TREK runs on PostgreSQL when TREK_DB_URL is set, and on SQLite as before
otherwise: an engine port under src/db/engine, the dialect helpers under
src/db/dialect, a Postgres baseline for the migrations up to the cut,
pg_dump/pg_restore backups, a probe of every repository method against a
real server and a Postgres test lane in CI.
2026-11-17 23:03:33 +01:00
Maurice 17b47b38b9 test(places): wait for the new tag's tick, not only the tag
The tag reaches the trip's list before the form ticks it, so the button
could be found in the moment between and read as not pressed.
2026-11-17 10:12:33 +01:00
Maurice 494c848ec9 chore(i18n): drop the place form's old text placeholders
The texts card explains each text in a line of its own and the phone sheet
follows it, so the description, notes and day note placeholders are no
longer read anywhere.
2026-11-17 09:41:30 +01:00
Maurice c203b0a597 test(places): look for the hidden tab's formatting buttons too 2026-11-17 09:27:49 +01:00
Maurice b36fefdf5d test(places): keep the place form's test file at its size
The tab changes had grown it past its line budget; the labels of the texts
are covered by PlaceFormTexts' own tests.
2026-11-17 09:20:46 +01:00
Maurice 8611359f7c chore(lint): lower the tests' non-null count to what they hold 2026-11-17 09:18:50 +01:00
Maurice c8e48460b6 fix(places): settle the gates for the place form rework
The text tabs name their field type for the switch, so it type-checks. The
colour field's sliders run left to right in every language and say so with
dir=ltr and a logical inset. The new phone fields take their sizes from the
type tiers or fs() instead of rem literals, the category field builds its
icon as an element, and the ESLint and theme baselines come down to what the
tree now holds. The tests follow the tabs (only the open tab's field and
formatting bar are shown), the category list and the files row, whose link
button keeps its place before attach.
2026-11-17 09:08:41 +01:00
Maurice 5ecf3001af fix(places): keep the hooks' helper types to their files
knip counts an exported type nothing imports; the tabs' row type and the
hours' field type are only used where they are declared.
2026-11-17 08:57:18 +01:00
Maurice 2c5beee849 fix(deps): hold jsdom at 29 and isomorphic-dompurify at 3, and settle the gates
jsdom 31 failed 56 client test files: it simplifies calc() and reads an
unset border as none in computed styles, and its File no longer carries
what the upload tests hand it. It moves back to 29 with isomorphic-dompurify
3, which needs it; the lockfile is resolved from the one before the bump, so
both sit at the root as they did. jsdom stays a root devDependency, so npm
keeps the copy vitest resolves at the root.

knip 6.45 reports tsconfig-paths, which test.yml loads from the server, as
unlisted rather than unresolved; it is the server's dependency. The removed
RTL text plugin took one swallowed catch with it, so that ESLint count is
lowered to what the tree holds.
2026-11-17 08:49:37 +01:00
Maurice a3f6635633 feat(places): colour tags, tabs for the texts and opening hours on the phone
Tags on the place form are pills in their own colour, with a palette under
the dot that recolours a tag for the whole trip (PUT /trips/:id/tags/:id was
there already, the client now reaches it through repo and store) and a
custom colour field of its own instead of the system picker. A new tag is
made in a colour picked the same way.

Description, notes and the note for one day's visit sit in one card under a
switch, each with a line on where the text shows up; the day tab is named
after its day and is only there with one visit in context. Nothing about the
three fields changes underneath.

Opening hours get a switch for open around the clock next to closed. Google
writes a place open all week as one period on Sunday that never closes; it
read as Sunday open and every other day closed, and now opens every day.

The phone form follows the desktop: category as one field with a list, tags
in one field, the texts switch, and phone, e-mail and opening hours, which it
did not have. The hours and the text tabs are shared hooks (usePlaceHours,
usePlaceTextTabs). Files and costs on the phone sheets are drawn as fields
like the rest, and the paste hint, a keyboard shortcut a phone has no use
for, is gone with its key.
2026-11-17 08:44:46 +01:00
Mariano 33d074c786 feat(places): tags on places, owned by the trip
A place keeps its one category, which decides its marker, and can now carry
any number of tags as extra labels to filter by.

- Tags belong to the trip (tags.trip_id): every member sees the same list and
  whoever may edit the trip's places adds, renames and deletes. Personal tags
  stay what they were.
- The place form picks them on desktop and mobile through one shared hook,
  usePlaceTags, and can add a new tag to the trip on the spot.
- The existing category filter of the places list lists the tags as well.
- Tags show on the place (inspector pills, phone place sheet); the marker is
  untouched.
- MCP: create_place, create_and_assign_place and update_place take `tags`,
  and list/create/update/delete_trip_tag manage a trip's tags.
- /api/trips/:tripId/tags and the tripTags:changed event keep every client
  of the trip in step.
2026-11-17 08:44:10 +01:00
Maurice e952586f60 chore(deps): keep the rollup musl pins on the installed rollup
The minor and patch group raised the Alpine pins to 4.68.3 while rollup
itself stayed on 4.62.0, so npm nested a second 4.62.0 copy under rollup
and the hoisted pins went unused. The pins follow rollup again.
2026-11-17 07:56:26 +01:00
Maurice 35c0cd35ef ci(dependabot): leave TypeScript majors to be moved by hand
TypeScript 7 is the native compiler without a JavaScript API, which
typescript-eslint, the coverage instrumenter and the Postgres probe need.
2026-11-16 21:20:33 +01:00
Maurice a1d753a975 style(i18n): format Arabic and Thai locales for Prettier 3.10
Prettier 3.10 measures the width of Arabic and Thai text differently, so
strings that fit the line now stay on it.
2026-11-16 21:20:33 +01:00
Maurice 35dbcc2103 chore(deps): bump npm dependencies, jsdom 31, isomorphic-dompurify 4 and dotenv 18
The minor and patch group of #3108 without MikroORM: 7.2.9 refuses to set
the OAuth client reference from its client_id (the Postgres probe fails on
OauthTokens.insertToken and OauthConsents.upsertGrant), so MikroORM stays on
7.2.8 and with it better-sqlite3 and kysely, which it pins exactly.

mapbox-gl 3.33 shapes right-to-left text itself and removed setRTLTextPlugin,
so the engine registers nothing any more and @mapbox/mapbox-gl-rtl-text, its
Vite alias and the registration guard go. The WebAssembly module it loads
instead comes from api.mapbox.com, which the CSP already allows.

jsdom 31 and isomorphic-dompurify 4 move together, since the sanitizer needs
jsdom 31. jsdom is also a root devDependency now: listed only in the client,
npm nests it under client/ where vitest's built-in jsdom environment does not
find it.

dotenv 18 is loaded through `import 'dotenv/config'` only, which stays quiet.

Closes #3108, closes #3109, closes #3110, closes #3112
2026-11-16 21:20:33 +01:00
Maurice 3c054fffa0 chore(plugin-sdk): bump @clack/prompts from 1.8.1 to 1.9.0
Closes #3106
2026-11-16 21:20:32 +01:00
Maurice c1bad1204c ci: bump SonarSource/sonarqube-scan-action from 8.4.1 to 8.5.0
Closes #3107
2026-11-16 21:20:32 +01:00
1034 changed files with 54675 additions and 15211 deletions
+156
View File
@@ -0,0 +1,156 @@
name: Set up Node and the workspaces
description: >-
Node from .nvmrc, the workspace dependencies from an exact cache or npm ci,
and optionally shared/dist from a cache or a build. Runs after checkout.
# A local action, so it is versioned with the workflow that calls it and needs
# no SHA pin. scripts/ci/changed-areas.mjs counts .github/actions/ like
# test.yml: a change here runs everything.
#
# node_modules is restored only on an exact key: the runner image, the scope,
# the Node ABI, the lockfile and every workspace package.json. There are no
# restore-keys, so a hit is the tree npm ci would build and a miss is a plain
# npm ci. The package.json files are in the key because npm ci is also the
# check that they agree with the lockfile: an edited range without a fresh
# lockfile misses the cache and fails the install, as it did when every job
# ran npm ci. Only pushes to dev and main save, the npm download cache
# included, so pull requests read what their base left and cannot evict it or
# fill the repository's cache quota with entries of their own.
inputs:
scope:
description: >-
Which workspaces to install: full (npm ci), client (shared and client)
or shared (shared alone).
required: true
build-shared:
description: "'true' to restore shared/dist, or build it on a miss."
required: false
default: 'false'
runs:
using: composite
steps:
- uses: actions/setup-node@v6
with:
node-version-file: .nvmrc
# ImageOS and ImageVersion name the runner image, whose system libraries
# the native modules were built against. They live in the runner's
# environment, not in the env context, so the key is put together here. A
# job in a container has neither; the container's OS release stands in,
# and that job's tree is kept apart from the runner's.
- name: Work out the cache keys
id: keys
shell: bash
env:
SCOPE: ${{ inputs.scope }}
DEPS: ${{ hashFiles('.nvmrc', 'package-lock.json', 'package.json', 'client/package.json', 'server/package.json', 'shared/package.json') }}
SHARED: ${{ hashFiles('shared/src/**', 'shared/package.json', 'shared/tsconfig*.json', 'shared/tsdown.config.ts', 'package-lock.json') }}
run: |
set -euo pipefail
case "$SCOPE" in
full | client | shared) ;;
*) echo "::error::scope must be full, client or shared, not '$SCOPE'"; exit 1 ;;
esac
if [ -n "${ImageOS:-}" ]; then
image="$ImageOS-${ImageVersion:-unknown}"
else
image="container-$(. /etc/os-release && echo "$ID$VERSION_ID")"
fi
abi="$(node -p process.versions.modules)"
echo "nm=nm-$RUNNER_OS-$image-$SCOPE-node$abi-$DEPS" >> "$GITHUB_OUTPUT"
echo "sd=sd-$RUNNER_OS-$SHARED" >> "$GITHUB_OUTPUT"
echo "save=${{ github.event_name == 'push' && (github.ref == 'refs/heads/dev' || github.ref == 'refs/heads/main') }}" >> "$GITHUB_OUTPUT"
- name: Restore node_modules
id: nm
uses: actions/cache/restore@v6
with:
path: |
node_modules
server/node_modules
client/node_modules
shared/node_modules
key: ${{ steps.keys.outputs.nm }}
# The npm download cache only matters when npm ci runs, so it is restored
# only then. It may fall back to an older lockfile's cache: npm ci checks
# every tarball against the lockfile's integrity hash and fetches what is
# missing, so a stale entry only costs downloads.
- name: Restore the npm download cache
id: npm
if: steps.nm.outputs.cache-hit != 'true'
uses: actions/cache/restore@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
restore-keys: npm-${{ runner.os }}-
- name: Install dependencies
if: steps.nm.outputs.cache-hit != 'true'
shell: bash
env:
SCOPE: ${{ inputs.scope }}
run: |
set -euo pipefail
# better-sqlite3 ships no prebuilt binary and compiles on install. The
# hosted runners carry a compiler; the Playwright container of the e2e
# jobs does not, so on a cache miss there it gets one first. A hit,
# the usual case once a push to dev has saved the container's key,
# never reaches this step.
if ! command -v make >/dev/null || ! command -v g++ >/dev/null; then
export DEBIAN_FRONTEND=noninteractive
timeout 300 apt-get update -qq
timeout 300 apt-get install -y -qq --no-install-recommends make g++
fi
case "$SCOPE" in
full) npm ci ;;
# The scoped install keeps @testing-library/dom (a peer of
# @testing-library/react) in the tree.
client) npm ci --workspace shared --workspace client ;;
shared) npm ci --workspace shared ;;
esac
- name: Save node_modules
if: steps.nm.outputs.cache-hit != 'true' && steps.keys.outputs.save == 'true'
uses: actions/cache/save@v6
with:
path: |
node_modules
server/node_modules
client/node_modules
shared/node_modules
key: ${{ steps.keys.outputs.nm }}
# Only a full install saves the download cache, so the entry holds every
# tarball; a scoped job that finished first would otherwise claim the key
# with part of the tree and no later run would fill it.
- name: Save the npm download cache
if: steps.nm.outputs.cache-hit != 'true' && steps.keys.outputs.save == 'true' && steps.npm.outputs.cache-hit != 'true' && inputs.scope == 'full'
uses: actions/cache/save@v6
with:
path: ~/.npm
key: npm-${{ runner.os }}-${{ hashFiles('package-lock.json') }}
# The key holds every input of the build: the sources, the package and
# build configs, and the lockfile that pins tsdown and zod.
- name: Restore shared/dist
id: sd
if: inputs.build-shared == 'true'
uses: actions/cache/restore@v6
with:
path: shared/dist
key: ${{ steps.keys.outputs.sd }}
- name: Build shared
if: inputs.build-shared == 'true' && steps.sd.outputs.cache-hit != 'true'
shell: bash
run: npm run build --workspace=shared
- name: Save shared/dist
if: inputs.build-shared == 'true' && steps.sd.outputs.cache-hit != 'true' && steps.keys.outputs.save == 'true'
uses: actions/cache/save@v6
with:
path: shared/dist
key: ${{ steps.keys.outputs.sd }}
+11 -1
View File
@@ -7,8 +7,11 @@
# enforce-target-branch.yml moves those onto dev.
#
# Every PR runs test.yml like any other, so ci-ok decides whether it can
# merge. Dependabot runs get no Actions secrets, so s3-contract and the Sonar
# merge. Dependabot runs get no Actions secrets, so server-s3 and the Sonar
# scan skip themselves on these PRs and ci-ok counts the skip as passed.
# A bump of @playwright/test also needs the Playwright container tag and
# digest in test.yml's client-e2e moved by hand; workflow-jobs.test.mjs
# fails the PR until they match.
version: 2
updates:
# The root lockfile covers the client, server and shared workspaces.
@@ -25,6 +28,13 @@ updates:
groups:
npm-minor-and-patch:
update-types: [minor, patch]
ignore:
# TypeScript 7 is the native compiler and has no JavaScript API yet:
# typescript-eslint, the coverage instrumenter and the Postgres probe all
# call into it (readConfigFile, ScriptTarget). It moves by hand once the
# tooling supports it.
- dependency-name: typescript
update-types: [version-update:semver-major]
# plugin-sdk is standalone with a lockfile of its own and ships to npm.
- package-ecosystem: npm
+8 -1
View File
@@ -18,9 +18,16 @@ jobs:
- uses: actions/setup-node@v6
with:
node-version-file: .nvmrc
cache: npm
cache-dependency-path: package-lock.json
# shared's ESLint and Prettier plugins are its own devDependencies, and
# the format ratchet in scripts/lib/ resolves prettier from the root, so
# shared plus the root is the whole tree these checks read. npm ci
# installs exactly what the lockfile says, where npm install could
# resolve anew.
- name: Install dependencies
run: npm install
run: npm ci --workspace shared --include-workspace-root
- name: Run lint & format check
# Both are check-only: lint used to run eslint --fix, which rewrote the
+7 -29
View File
@@ -10,6 +10,13 @@ permissions:
#
# Unsigned on purpose: signing and store uploads need secrets that fork PRs do
# not get, and belong in a release workflow of their own.
#
# package-lock.json is not a trigger: every dependency bump touches it, and a
# Mac build per bump only held the queue. The shells link nothing but the
# @capacitor/* packages, all declared in client/package.json, and a Dependabot
# bump of one of them raises the range there too, so it still runs. The client
# typecheck and the watch and widget snapshot tests run in test.yml on every
# change under client/.
on:
pull_request:
paths:
@@ -24,7 +31,6 @@ on:
- 'client/scripts/check-store-metadata.mjs'
- 'client/fastlane/**'
- 'client/package.json'
- 'package-lock.json'
- 'shared/src/i18n/*/native.ts'
- '.github/workflows/native.yml'
workflow_dispatch:
@@ -182,34 +188,6 @@ jobs:
path: client/ios/WidgetPreviews/out
retention-days: 14
# The watch's half in the UI (client/src/native/watch.ts): the snapshot it
# builds and the ticks it takes back, typechecked and tested here as well,
# so a change to the bridge is checked next to the Swift that reads it.
watch-bridge:
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v6
with:
node-version-file: .nvmrc
cache: npm
- name: Install
run: npm ci --workspace=shared --workspace=client
- name: Build shared
run: npm run build --workspace=shared
- name: Typecheck the client
working-directory: client
run: npm run typecheck
- name: Test the widget and watch snapshots
working-directory: client
run: npx vitest run src/native/watch.test.ts src/native/widgets.test.ts src/native/widgetExtras.test.ts
# The watch app on watchOS simulators in its screenshot mode (DemoMode.swift):
# every screen on the largest and the smallest watch, the main ones in every
# language, and the complications, as PNGs to look at without a watch.
+1 -1
View File
@@ -13,7 +13,7 @@ name: Security Scan
# - scout scans the built image, base image packages included. It needs
# the Docker Hub login, so it runs on PRs and pushes into main only and
# skips fork PRs. Whether the image builds at all is test.yml's
# docker-image job, which a red scan cannot hide.
# docker job, which a red scan cannot hide.
on:
pull_request:
branches: [main, dev]
+895 -718
View File
File diff suppressed because it is too large Load Diff
+13 -5
View File
@@ -31,6 +31,7 @@ Tests:
npm run test # all workspaces
npm run test --workspace=server # vitest run (server); also test:unit / test:integration / test:ws
npm run test:e2e # server e2e (boots Nest against a temp SQLite)
npm run test:pg --workspace=server # the Postgres lane (vitest.pg.config.ts; needs TREK_TEST_DB_URL, e.g. postgres://postgres:trek@127.0.0.1:55432/postgres)
npm run test:cov # coverage (lcov) for all four packages incl. plugin-sdk
cd client && npm run test # client vitest run
cd client && npm run e2e # Playwright (CI runs the public and app projects; the screenshot and help-media ones are local)
@@ -51,7 +52,9 @@ cd client && npm run lint:skips # no .only; skipped tests may
cd client && npm run lint:i18n-keys # every key the client names exists in en; unused en keys may only shrink (CI gate)
cd server && npm run lint:boundaries # no new import cycles or cross-domain reach-ins (CI gate)
cd server && npm run lint:dialect # SQLite-only SQL spellings may only shrink (CI gate; rules in server/CLAUDE.md)
cd server && npm run lint:engine-dispatch # engine checks outside src/db/dialect/ and src/db/engine/ may only shrink (CI gate)
cd server && npm run probe:pg # dialect helpers + the repository statements it reaches against Postgres (CI job; needs TREK_PG_PROBE_URL)
cd server && npm run check:pg-baseline # the Postgres baseline in server/assets/postgres/ matches the entities and the migrations (CI gate)
cd server && npm run lint:tx # no new method writing twice outside one transaction (CI gate)
cd server && npm run lint:test-sql # raw SQL fixtures in tests/ may only shrink; seed through tests/helpers/factories (CI gate)
cd server && npm run lint:test-mocks # vi.mock of config, realtime and db modules in tests/ may only shrink (CI gate)
@@ -134,13 +137,18 @@ These principles come out of a full-repo audit and shape all new code:
## Quality gates in CI
`.github/workflows/test.yml` runs, per package: typecheck (server also `typecheck:tests`, client also the strict-mode ratchet `lint:strict`), lint (client and server through `lint:warnings`, which also holds the warning count per rule), `lint:pages`, `lint:rtl`, `lint:size` (client and server), the server's `lint:strict`, `lint:boundaries`, `lint:tx`, `lint:dialect`, `lint:test-sql`, `lint:test-mocks`, `lint:test-new-service`, `lint:query-api`, `lint:mcp-zod`, `lint:service-http` and `lint:response-contracts`, the client's and server's `lint:format`, `lint:layers`, `lint:offline`, `lint:dup`, `lint:pairs`, `lint:skips`, `lint:i18n-keys` and `theme:lint`, shared's `contracts:open`, the repo-wide `lint:knip` (in server-lint-checks), `check:plugin-facts`, `i18n:parity:strict` (with the untranslated-strings ratchet), the S3 contract suite, the Postgres probe (`postgres-probe`: every dialect helper on SQLite and Postgres, and the statements every repository method reaches with sample arguments against a Postgres service; the SQL errors per method and the list of methods it cannot measure are held to a baseline that only shrinks and fails while it is still unmeasured; see `server/CLAUDE.md`), the browser end-to-end flows (Chromium and WebKit), a client build with `check:gl-split`, coverage for all four packages, then a SonarCloud scan. It also builds the Docker image and boots it until `/api/health/ready` answers (`docker-image`), and lints and renders the Helm chart against the Kubernetes schemas and runs `docker compose config` on every compose file (`deploy-manifests`). `lint-prettier.yml` additionally runs `lint` + `lint:format` on `shared/`, both check-only. `plugin-sdk` has no lint script and is outside the eslint gates. **Not in CI**: the screenshot and help-media Playwright projects; run them locally. There are no git hooks; nothing runs before a commit except you. Other workflows build Docker images, scan them, and publish `trek-plugin-sdk` on `plugin-sdk-v*` tags.
`.github/workflows/test.yml` runs, per package: typecheck (server also `typecheck:tests`, client also the strict-mode ratchet `lint:strict`), lint (client and server through `lint:warnings`, which also holds the warning count per rule), `lint:pages`, `lint:rtl`, `lint:size` (client and server), the server's `lint:strict`, `lint:boundaries`, `lint:tx`, `lint:dialect`, `lint:engine-dispatch`, `lint:test-sql`, `lint:test-mocks`, `lint:test-new-service`, `lint:query-api`, `lint:mcp-zod`, `lint:service-http` and `lint:response-contracts`, the client's and server's `lint:format`, `lint:layers`, `lint:offline`, `lint:dup`, `lint:pairs`, `lint:skips`, `lint:i18n-keys` and `theme:lint`, shared's `contracts:open`, the repo-wide `lint:knip` (in `server-lint`), `check:plugin-facts`, `i18n:parity:strict` (with the untranslated-strings ratchet), the S3 contract suite, TREK on Postgres (`server-postgres`, once per supported major, 14 and 18, each in three slices: first the Postgres probe (in the first slice), every dialect helper on SQLite and Postgres and the statements every repository method reaches with sample arguments, its SQL errors per method and the methods it cannot measure held to a baseline that only shrinks and fails while it is still unmeasured; then the Postgres lane, every suite that boots the app on the real database module, found by `server/tests/postgres/lane.ts` rather than listed, plus PARITY-PG and the write lock; see `server/CLAUDE.md`), the browser end-to-end flows (Chromium and WebKit, in the Playwright container, in two slices), a client build with `check:gl-split`, coverage for all four packages, then a SonarCloud scan. It also builds the Docker image and boots it until `/api/health/ready` answers, on SQLite and on Postgres 18, and lints and renders the Helm chart against the Kubernetes schemas and runs `docker compose config` on every compose file (both in `docker`, each part when its area changed). `lint-prettier.yml` additionally runs `lint` + `lint:format` on `shared/`, both check-only. `plugin-sdk` has no lint script and is outside the eslint gates. **Not in CI**: the screenshot and help-media Playwright projects; run them locally. There are no git hooks; nothing runs before a commit except you. Other workflows build Docker images, scan them, and publish `trek-plugin-sdk` on `plugin-sdk-v*` tags.
- **Job names read "package: what"** (`Server: Types`, `Client: Tests 3/7`), and the list at the top of `test.yml` says what each job holds. A new job follows the scheme and joins that list, and the job-count note there says when a long job needs a slot freed first.
- **Tests run beside the gates, in shards.** The client and server suites run in slices on parallel runners (`client-tests`, `server-tests`, through each package's `vitest.shard.config.ts`), and `client-coverage`/`server-coverage` merge their blob reports and check the thresholds against the whole. A red slice is usually a failing test, a red merge job usually a threshold.
- **`ci-ok` is the required check.** The branch ruleset requires `ci-ok` (plus `lint` and `check-target` from their own workflows), and `ci-ok` needs every job above except the scan. It fails if any of them failed or was cancelled and passes if they passed or were skipped. A new gate job counts only once it is listed in `ci-ok`'s `needs:`.
- **Job names read "<Area> <what>[ <variant>][ i/n]"** (`Server tests 3/10`, `Server Postgres 14 2/3`, `Docker and Helm`): the area first, one of Changes, Shared, Server, Client, Docker or Sonar, then lower case, with no colon, no parentheses and no middle dot, and a slice only at the end, so the checks list sorts by area. The workflow is named `CI`, so a check reads `CI / Server tests 3/10`. Job ids are the names in kebab-case (`server-tests`), the jobs stand in `test.yml` in area order, and the list at the top of `test.yml` says what each job holds. A new job follows the scheme and joins that list; `scripts/ci/workflow-jobs.test.mjs` fails on a name outside it. `ci-ok`, `lint` and `check-target` keep their names: the ruleset requires them by name.
- **What the folded jobs hold.** `Shared tests` is the plugin SDK's typecheck and coverage, run before the root install so the SDK resolves only its own dependencies, then i18n parity and shared's coverage. `Client types` is the typecheck and the strict ratchet; `Client checks` the source ratchets, then the production build with `check:gl-split`. `Docker and Helm` builds and boots the image when the image area changed and checks the chart and compose files when the deploy area changed. Inside a folded job each group of steps runs after a failure in another, so one red check shows every gate that failed; the step names say which.
- **Tests run beside the gates, in shards.** The client and server suites run in ten slices each on parallel runners (`client-tests`, `server-tests`, through each package's `vitest.shard.config.ts`), the Postgres lane in three per major, and the end-to-end flows in two, and `client-coverage`/`server-coverage` merge their blob reports and check the thresholds against the whole. A red slice is usually a failing test, a red merge job usually a threshold. A sliced job states its slice count in its matrix's shard axis, the `i/n` in its name and its `--shard=i/n`; `scripts/ci/workflow-jobs.test.mjs` fails until all three agree, and on any job naming `matrix.shard` or `--shard` whose axis is not the one-line `shard: [1, ..., n]` it reads.
- **`ci-ok` is the required check.** The branch ruleset requires `ci-ok` (plus `lint` and `check-target` from their own workflows), and `ci-ok` needs every job above except the scan. It fails if any of them failed or was cancelled and passes if they passed or were skipped. A new gate job counts only once it is listed in `ci-ok`'s `needs:`, and `scripts/ci/workflow-jobs.test.mjs` (in `test:ci-scripts`) fails while a job other than the scan is missing there.
- **The release pull request mirrors the push run.** On the pull request from `dev` into `main` (head branch in this repository), `changes` sets `mirror` and turns every area off (`scripts/ci/changed-areas.mjs`), so no test, gate or scan job runs, and `ci-ok` runs `scripts/ci/mirror-push-run.mjs`: it waits for the `ci-ok` of the push run of `test.yml` on `dev` for exactly the PR's head commit and passes or fails with it. No such push run, one that ended without a verdict, or a wait past 17 minutes fails with a re-run hint, never passes. A push to `dev` lists its changes against the merge base with `main`, not against the previous push, so the run it mirrors covers every area the pull request brings in, even when an earlier push's run was cancelled or red. Testing that commit twice doubled the jobs past the 60 slots.
- **Guides name paths that exist**: the `changes` job runs `scripts/ci/doc-paths.mjs`, which resolves every backtick path in the CLAUDE.md files, `README.md`, `server/src/nest/README.md` and the wiki against the tracked files; the missing ones are listed in `scripts/ci/doc-paths-baseline.json`, which only shrinks (`--update` after a fix).
- **What runs is decided by `changes`, not by `on.paths`**: `scripts/ci/changed-areas.mjs` maps the changed files to the `code`, `image` and `deploy` areas (tests: `npm run test:ci-scripts`). A path filter on the workflow would leave `ci-ok` unreported on a docs-only PR and block it. Add a new top-level file the build reads to the right area there.
- **What runs is decided by `changes`, not by `on.paths`**: `scripts/ci/changed-areas.mjs` maps the changed files to the `code`, `image` and `deploy` areas (tests: `npm run test:ci-scripts`). A path filter on the workflow would leave `ci-ok` unreported on a docs-only PR and block it. Add a new top-level file the build reads to the right area there. A change to `test.yml`, to `scripts/ci/` or to a local action under `.github/actions/` runs everything.
- **Setup goes through one local action.** Every job that installs dependencies uses `.github/actions/setup/action.yml` (`scope` full, client or shared; `build-shared`) instead of its own `npm ci`; `workflow-jobs.test.mjs` fails on a job that installs on its own (plugin-sdk's own install in its directory excepted). The action restores node_modules on an exact key (runner image, scope, Node ABI, `.nvmrc`, the lockfile and every workspace `package.json`, so npm ci still refuses a `package.json` out of step with the lockfile; no restore-keys) and shared/dist on a key over shared's sources and build config, and runs `npm ci` or the shared build on a miss. Only pushes to dev and main save, the npm download cache included; pull requests only read.
- **End-to-end runs in the Playwright container**, `mcr.microsoft.com/playwright:v<version>-noble` pinned by digest, so no step installs browsers or system libraries. Dependabot bumps only the lockfile: on every Playwright PR move the tag and its digest in `client-e2e` by hand (`docker buildx imagetools inspect mcr.microsoft.com/playwright:v<version>-noble`); `workflow-jobs.test.mjs` fails until the tag names the lockfile's `@playwright/test` version.
- **Budget: `ci-ok` within ten minutes.** One code run starts at most about 35 long jobs (gates, slices, Postgres, e2e, Docker), so two PR runs fit in the organisation's 60 concurrent jobs. Every job sets `timeout-minutes` of at most 20 (15 for the long ones, 10 for the short ones), which `workflow-jobs.test.mjs` holds. A new long job, slice or shard needs a reason that outweighs its slot; the job-count note at the top of `test.yml` has the numbers.
- **Runners and Node**: jobs run on `ubuntu-24.04`, not `ubuntu-latest`, and every `setup-node` reads `.nvmrc`. Third-party actions (anything outside `actions/*`) are pinned by commit SHA with the tag in a comment; Dependabot keeps both current.
- **Security scans are advisory.** `security.yml` runs `npm audit` (what the image installs, plus `plugin-sdk`) on every PR and push into dev and main, and Docker Scout on the built image for main. Neither is required: a newly published advisory would turn every open PR red at once. Fixes are held as floors in the root `package.json` `overrides`; npm ignores an `overrides` block in a workspace `package.json`, so never put one there.
- **Releases** are dispatched by hand and refuse a commit whose `ci-ok` is not green. `docker-dev.yml` (any branch, usually dev) is the canary: it builds the dispatched commit as the next minor or major `-pre.N` and moves only `:latest-pre` and `:<major>-pre`. `docker.yml` (main only) bumps the version, commits and tags it, builds both platforms from exactly that commit and moves `:latest`, `:<major>`, `:<major>.<minor>` and `:<version>`. Its `bump=auto` only finalizes a prerelease in flight; without one it stops and asks for patch, minor or major. Ship a release that migrates or changes a lot as a prerelease first, and as a minor, so installs pinned to `:<major>.<minor>` can wait it out.
+24 -10
View File
@@ -72,17 +72,30 @@ COPY server/package.json ./server/
# package, and a telemetry ping.
# The upgrade takes the Debian security fixes the base image was built before
# (zlib, 11/2026, failed the image scan until node:24-trixie-slim caught up).
RUN apt-get update && \
#
# postgresql-client-18 brings pg_dump, pg_restore and psql to
# /usr/lib/postgresql/18/bin, which back up and restore an install on Postgres
# (TREK_DB_URL). A client handles every server up to its own major and refuses
# a newer one, so the image carries the newest major TREK supports (14 to 18).
# Debian 13 ships 17 only, so it comes from the PostgreSQL project's apt
# repository (PGDG): the `18` component lists that major's packages and no
# other, and the repository's signing key (fingerprint B97B 0AFC AA1A 47F0 44F2
# 44A0 7FCC 7D46 ACCC 4CF8) is kept beside the entrypoint instead of fetched at
# build time. Raise both together when TREK supports a newer major.
COPY server/scripts/pgdg-apt-key.asc /etc/apt/keyrings/pgdg.asc
RUN echo 'deb [signed-by=/etc/apt/keyrings/pgdg.asc] http://apt.postgresql.org/pub/repos/apt trixie-pgdg main 18' \
> /etc/apt/sources.list.d/pgdg.list && \
apt-get update && \
apt-get upgrade -y --no-install-recommends && \
apt-get install -y --no-install-recommends tzdata dumb-init wget ca-certificates \
libkitinerary-bin libsqlite3-0 && \
libkitinerary-bin libsqlite3-0 postgresql-client-18 && \
npm ci --workspace=server --omit=dev --ignore-scripts && \
{ ln -sf "$(find /usr/lib -name kitinerary-extractor -type f | head -1)" /usr/local/bin/kitinerary-extractor || true; } && \
rm -rf /var/lib/apt/lists/* /usr/local/lib/node_modules/npm /usr/local/bin/npm /usr/local/bin/npx && \
chown -R node:node /app
# gosu rebuilt with a current Go toolchain (stage 0) — the entrypoint script uses
# it to drop to node.
# gosu rebuilt with a current Go toolchain (stage 0). The entrypoint drops to node
# with setpriv since #3135; gosu stays in the image for anyone who calls it by hand.
COPY --from=gosu-build /out/gosu /usr/local/bin/gosu
ENV XDG_CACHE_HOME=/tmp/kf6-cache
@@ -94,8 +107,9 @@ ENV KITINERARY_EXTRACTOR_PATH=/usr/local/bin/kitinerary-extractor
COPY --chown=node:node --from=server-builder /app/server/dist ./server/dist
# Runtime data assets read from server/assets at runtime: airports.json (flight
# transport search) and atlas/*.geojson.gz + atlas/admin1/*.geojson.gz (Atlas
# country/region map). The build
# transport search), atlas/*.geojson.gz + atlas/admin1/*.geojson.gz (Atlas
# country/region map) and postgres/baseline.* (the schema a fresh Postgres
# database starts from). The build
# only emits dist, so these must be copied explicitly or the features silently
# degrade to empty in the image.
COPY --chown=node:node --from=server-builder /app/server/assets ./server/assets
@@ -106,9 +120,9 @@ COPY --chown=node:node wiki ./wiki
# tsconfig-paths/register reads this at runtime to resolve MCP SDK paths.
COPY --chown=node:node server/tsconfig.json ./server/
# Encryption-key rotation is run on demand via tsx (a prod dep) straight from the
# raw .ts source — it never enters dist, so it must be copied in explicitly or
# raw .ts source (the command and its stores module). They never enter dist, so they must be copied in explicitly or
# `node --import tsx scripts/migrate-encryption.ts` fails with module-not-found.
COPY --chown=node:node server/scripts/migrate-encryption.ts ./server/scripts/migrate-encryption.ts
COPY --chown=node:node server/scripts/migrate-encryption.ts server/scripts/migrate-encryption-stores.ts ./server/scripts/
# Admin recovery script (node server/reset-admin.js) for locked-out installs.
COPY --chown=node:node server/reset-admin.js ./server/reset-admin.js
COPY --chown=node:node --from=shared-builder /app/shared/dist ./shared/dist
@@ -159,8 +173,8 @@ HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \
# carrying quotes does not survive that round-trip (the container then dies with
# a shell syntax error before Node starts). A CMD of one bare token does.
COPY server/scripts/entrypoint.sh /usr/local/bin/trek-entrypoint
# Root-owned on purpose — this is what calls gosu, so it runs before the drop to
# node. chmod is explicit because a checkout on Windows carries no exec bit.
# Root-owned on purpose: it runs as root and drops to node itself, with setpriv.
# chmod is explicit because a checkout on Windows carries no exec bit.
RUN chmod 0755 /usr/local/bin/trek-entrypoint
ENTRYPOINT ["dumb-init", "--"]
+5
View File
@@ -321,6 +321,11 @@ docker compose up -d
See [Install with Docker Compose](https://github.com/liketrek/TREK/wiki/Install-Docker-Compose)
for the full walkthrough.
TREK stores its data in SQLite by default. Set `TREK_DB_URL` to run it on a PostgreSQL 14 to 18 database instead. The
[`docker-compose.postgres.yml`](docker-compose.postgres.yml) example starts one beside TREK, and the
[Postgres guide](https://github.com/liketrek/TREK/wiki/Database-Postgres) covers the requirements, the backups and
how to move an existing SQLite install to Postgres with the command TREK ships for it.
<br />
<h2 id="helm-kubernetes">Helm (Kubernetes)</h2>
+1
View File
@@ -46,6 +46,7 @@ See `values.yaml` for more options.
- Both PVCs are `ReadWriteOnce`. Set `persistence.data.accessModes` and/or `persistence.uploads.accessModes` to override, for example `[ReadWriteMany]` so a backup pod can mount the volume. On the data volume such a pod may only read: SQLite corrupts `travel.db` when a second process writes it over a network filesystem.
- To use your own PVCs, set `persistence.data.existingClaim` and/or `persistence.uploads.existingClaim`. The other values for that volume (size, storageClassName, accessModes, annotations) are then ignored.
- With `persistence.enabled: false`, the data and uploads volumes use an `emptyDir` — storage is ephemeral and lost on pod restart. Intended for testing only.
- `database.url` runs TREK on a PostgreSQL database instead of the SQLite file. The chart writes it into its Secret as `TREK_DB_URL`; `database.existingSecret` and `database.existingSecretKey` read it from a Secret you manage. Leave both empty for SQLite. Keep `replicas: 1` either way. See the wiki page `Database-Postgres`.
- `JWT_SECRET` is managed entirely by the server — auto-generated into the data PVC on first start and rotatable via the admin panel (Settings → Danger Zone). No Helm configuration needed.
- `ENCRYPTION_KEY` encrypts stored secrets (API keys, MFA, SMTP, OIDC) at rest. Recommended: set via `secretEnv.ENCRYPTION_KEY` or `existingSecret`. If left empty, the server falls back automatically: existing installs use `data/.jwt_secret` (no action needed on upgrade); fresh installs auto-generate a key persisted to the data PVC.
- Liveness and readiness probes are configurable under `probes`. Overrides are merged over the defaults, so `--set probes.liveness.initialDelaySeconds=60` keeps the `httpGet` handler. When switching to `exec` or `tcpSocket`, clear `httpGet` in the same override. Set `probes.liveness: null` to remove a probe.
+17 -4
View File
@@ -1,3 +1,6 @@
{{- if and .Values.database.url (not .Values.database.existingSecret) .Values.existingSecret }}
{{- fail "database.url is written into the chart's own Secret, which existingSecret replaces. Put TREK_DB_URL in your Secret and set database.existingSecret instead." }}
{{- end }}
apiVersion: apps/v1
kind: Deployment
metadata:
@@ -5,11 +8,13 @@ metadata:
labels:
app: {{ include "trek.name" . }}
spec:
# One replica. Its rate limits, pending codes, permission cache and WebSocket
# connections live in the process's memory, so a second pod would not share them. That
# holds with database.url (PostgreSQL) too; see updateStrategy in values.yaml.
replicas: 1
# TREK is a single-writer SQLite app on a ReadWriteOnce PVC, so the default
# RollingUpdate would start a second pod holding the same volume before the old one
# exits — a Multi-Attach deadlock, or two processes on one travel.db. Recreate tears
# the old pod down first. Keep it, see updateStrategy in values.yaml.
# The default RollingUpdate would start a second pod on the same ReadWriteOnce PVC
# before the old one exits: a Multi-Attach deadlock, or two processes on one travel.db.
# Recreate tears the old pod down first. Keep it, see updateStrategy in values.yaml.
strategy:
type: {{ .Values.updateStrategy | default "Recreate" }}
selector:
@@ -61,6 +66,14 @@ spec:
name: {{ default (printf "%s-secret" (include "trek.fullname" .)) .Values.existingSecret }}
key: {{ .Values.existingSecretKey | default "ENCRYPTION_KEY" }}
optional: true
{{- if or .Values.database.url .Values.database.existingSecret }}
# Required when set: a missing key stops the pod rather than starting it on SQLite.
- name: TREK_DB_URL
valueFrom:
secretKeyRef:
name: {{ default (printf "%s-secret" (include "trek.fullname" .)) .Values.database.existingSecret }}
key: {{ if .Values.database.existingSecret }}{{ .Values.database.existingSecretKey | default "TREK_DB_URL" }}{{ else }}TREK_DB_URL{{ end }}
{{- end }}
- name: ADMIN_EMAIL
valueFrom:
secretKeyRef:
+6
View File
@@ -8,6 +8,9 @@ metadata:
type: Opaque
data:
{{ .Values.existingSecretKey | default "ENCRYPTION_KEY" }}: {{ .Values.secretEnv.ENCRYPTION_KEY | b64enc | quote }}
{{- if .Values.database.url }}
TREK_DB_URL: {{ .Values.database.url | b64enc | quote }}
{{- end }}
{{- if .Values.secretEnv.ADMIN_EMAIL }}
ADMIN_EMAIL: {{ .Values.secretEnv.ADMIN_EMAIL | b64enc | quote }}
{{- end }}
@@ -65,6 +68,9 @@ stringData:
{{- else }}
{{ .Values.existingSecretKey | default "ENCRYPTION_KEY" }}: {{ randAlphaNum 32 | quote }}
{{- end }}
{{- if .Values.database.url }}
TREK_DB_URL: {{ .Values.database.url | quote }}
{{- end }}
{{- if .Values.secretEnv.ADMIN_EMAIL }}
ADMIN_EMAIL: {{ .Values.secretEnv.ADMIN_EMAIL | quote }}
{{- end }}
+23 -4
View File
@@ -4,10 +4,13 @@ image:
# tag: latest
pullPolicy: IfNotPresent
# Deployment update strategy. Keep Recreate: TREK is a single-writer SQLite app, and
# during a RollingUpdate the new pod migrates the database while the old one still
# writes to it. A ReadWriteMany volume does not make that safe; SQLite's WAL needs both
# processes on one host, which network filesystems do not provide.
# Deployment update strategy. Keep Recreate. The new pod migrates the database when it
# starts, and during a RollingUpdate it would do that while the old pod still writes to
# it. Recreate stops the old pod first. On SQLite two processes on one travel.db are
# unsafe, and a ReadWriteOnce volume cannot be attached to both pods at once.
# With database.url the database is PostgreSQL, but the reason for one replica stays: TREK
# keeps rate limits, pending codes, the permission cache and WebSocket connections in
# memory, so a second pod would not share them. Postgres does not make more replicas safe.
updateStrategy: Recreate
# Pod-level security context. fsGroup gives the node user (uid/gid 1000) group access
@@ -178,6 +181,22 @@ env:
# address is sent unless you set one here.
# Database. Empty (the default) keeps TREK on its SQLite file in the data volume. Set url to
# run TREK on a PostgreSQL database instead (see the wiki page Database-Postgres). The URL
# carries the password, so it is never a plain env value: with url, the chart writes it into
# its own Secret as TREK_DB_URL; with existingSecret, TREK reads TREK_DB_URL from that Secret
# under existingSecretKey and the chart writes nothing. existingSecret wins over url. The
# variable is required when either is set: a missing Secret key stops the pod instead of
# starting it on SQLite. The role in the URL owns TREK's database and must not be a superuser
# (nor a member of one, nor hold a right that reaches the server's files or programs): a
# restore runs the backup's SQL as that role and refuses one that could reach the database host. The wiki page shows the
# SQL that creates such a role. PostgreSQL 14 to 18 is supported.
# url: "postgres://trek:<password>@postgres.example.internal:5432/trek?sslmode=require"
database:
url: ""
existingSecret: ""
existingSecretKey: TREK_DB_URL
# Secret environment variables stored in a Kubernetes Secret.
# JWT_SECRET is managed entirely by the server (auto-generated into the data PVC,
# rotatable via the admin panel) — it is not configured here.
@@ -82,10 +82,12 @@ abstract class TrekWidget : GlanceAppWidget() {
// Read inside the composition: a session outlives one update, and every
// write (the dashboard's, then each trip's) must reach it.
val version by WidgetStore.version.collectAsState()
val snapshot = remember(version) {
val stored = remember(version) {
val tripId = if (perTrip && appWidgetId >= 0) WidgetStore.tripFor(context, appWidgetId) else WidgetStore.AUTO
WidgetStore.load(context, tripId)
}
// The day of the trip is today's on every update, not the one the app last wrote.
val snapshot = stored?.on(LocalDate.now())
TrekWidgetTheme.Themed { Content(snapshot) }
}
}
@@ -27,7 +27,28 @@ data class WidgetSnapshot(
val labels: Labels,
/** The trip's next flight or the one in the air; last and defaulted, so older callers keep compiling. */
val flight: Flight? = null,
/**
* The trip's days from the day the app wrote this on, each with its date, so
* the widget turns to the next day itself (see [on]); empty from an app
* that predates them.
*/
val days: List<Today> = emptyList(),
) {
/**
* The snapshot as it reads on [date]: that date's trip day out of [days],
* none before or after the trip, and only the bookings from that date on.
* The app writes its snapshot only while it runs, so without this a widget
* showed the day it last ran. A snapshot without [days] reads as written.
*/
fun on(date: LocalDate): WidgetSnapshot {
if (days.isEmpty()) return this
val key = date.toString()
return copy(
today = days.firstOrNull { it.date == key },
bookings = bookings.filter { (it.date ?: key) >= key },
)
}
data class Trip(
val title: String,
val start: String,
@@ -52,7 +73,8 @@ data class WidgetSnapshot(
val symbol: String?,
)
data class Today(val dayLabel: String, val stops: List<Stop>, val index: Int?, val total: Int?)
/** A trip day; [date] (yyyy-MM-dd) is absent from an app that predates the days ahead. */
data class Today(val dayLabel: String, val stops: List<Stop>, val index: Int?, val total: Int?, val date: String? = null)
data class Weather(
val temp: Int,
@@ -212,6 +234,16 @@ data class WidgetSnapshot(
null
}
private fun dayOf(t: JSONObject): Today = Today(
dayLabel = t.optString("dayLabel"),
stops = t.optJSONArray("stops").objects().map {
Stop(it.str("time"), it.optString("name"), it.int("minutes"), it.str("color"), it.str("symbol"))
},
index = t.int("index"),
total = t.int("total"),
date = t.str("date"),
)
fun fromJson(o: JSONObject): WidgetSnapshot = WidgetSnapshot(
trip = o.optJSONObject("trip")?.let {
Trip(
@@ -226,16 +258,8 @@ data class WidgetSnapshot(
memberCount = it.int("memberCount"),
)
},
today = o.optJSONObject("today")?.let { t ->
Today(
dayLabel = t.optString("dayLabel"),
stops = t.optJSONArray("stops").objects().map {
Stop(it.str("time"), it.optString("name"), it.int("minutes"), it.str("color"), it.str("symbol"))
},
index = t.int("index"),
total = t.int("total"),
)
},
today = o.optJSONObject("today")?.let(::dayOf),
days = o.optJSONArray("days").objects().map(::dayOf),
weather = o.optJSONObject("weather")?.let {
Weather(it.optInt("temp"), it.int("high"), it.int("low"), it.optString("main"), it.optString("label"), it.str("place"), it.int("rain"))
},
@@ -99,4 +99,34 @@ class WidgetSnapshotTest {
assertEquals("ferry.fill", TrekIcons.booking("cruise").first)
assertEquals("bookmark.fill", TrekIcons.booking("something").first)
}
@Test
fun turnsToTheDayOfTheDateItIsReadOn() {
val json = """{"trip":{"title":"T","start":"2026-11-06","end":"2026-11-08","path":"/trips/1"},
"today":{"date":"2026-11-06","dayLabel":"Day 1 of 3","stops":[{"time":"09:00","name":"Museum","minutes":540}]},
"days":[
{"date":"2026-11-06","dayLabel":"Day 1 of 3","stops":[{"time":"09:00","name":"Museum","minutes":540}]},
{"date":"2026-11-07","dayLabel":"Day 2 of 3","stops":[{"time":"10:00","name":"Harbour","minutes":600}]}
],
"bookings":[
{"title":"Hotel","kind":"hotel","date":"2026-11-06","confirmed":true,"path":"/trips/1"},
{"title":"Train","kind":"train","date":"2026-11-07","confirmed":true,"path":"/trips/1"}
],
"labels":{}}"""
val snapshot = WidgetSnapshot.parse(json)!!
assertEquals("Day 1 of 3", snapshot.on(LocalDate.of(2026, 11, 6)).today!!.dayLabel)
val second = snapshot.on(LocalDate.of(2026, 11, 7))
assertEquals("Day 2 of 3", second.today!!.dayLabel)
assertEquals("Harbour", second.today!!.stops.single().name)
assertEquals(listOf("Train"), second.bookings.map { it.title })
// A day the app wrote nothing for (the trip is over) shows no day.
assertNull(snapshot.on(LocalDate.of(2026, 11, 9)).today)
}
@Test
fun aSnapshotWithoutDaysReadsAsWritten() {
val snapshot = WidgetSnapshot.parse(WidgetSamples.json(running = true, now = today))!!
assertTrue(snapshot.days.isEmpty())
assertEquals(snapshot, snapshot.on(today.plusDays(3)))
}
}
+21 -2
View File
@@ -686,9 +686,8 @@ extension TrekShellPlugin {
/// know are left out, so the shell offers only what can really be bought.
@objc func storeProducts(_ call: CAPPluginCall) {
let ids = call.getArray("ids", String.self) ?? []
// TestFlight, App Review and Xcode builds buy in the sandbox; their receipt says so.
let sandbox = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt"
Task {
let sandbox = await Self.buysInSandbox()
guard AppStore.canMakePayments, let products = try? await Product.products(for: ids) else {
call.resolve(["products": [], "sandbox": sandbox])
return
@@ -697,6 +696,26 @@ extension TrekShellPlugin {
}
}
/// Whether this build buys in the App Store sandbox: TestFlight, App Review and
/// Xcode builds do, and while TREK Cloud's orders are closed only they may buy.
/// The signed app transaction names its environment; the receipt's file name,
/// which App Review builds do not always carry, is only the fallback where the
/// app transaction is missing (iOS 15) or cannot be read.
static func buysInSandbox() async -> Bool {
let receiptSaysSandbox = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt"
guard #available(iOS 16.0, *), let result = try? await AppTransaction.shared else {
return receiptSaysSandbox
}
// An unverified transaction still names the environment it was signed in;
// it only decides whether the button shows, the cloud checks every purchase itself.
let transaction: AppTransaction
switch result {
case .verified(let signed), .unverified(let signed, _):
transaction = signed
}
return transaction.environment != .production || receiptSaysSandbox
}
/// Feature storeKit: runs the App Store purchase sheet. Resolves with `kind`
/// bought (with the signed transaction the control plane verifies), cancelled,
/// pending (Ask to Buy, a payment the bank still has to approve) or failed.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 104 KiB

After

Width:  |  Height:  |  Size: 49 KiB

@@ -21,12 +21,14 @@ struct TrekProvider: TimelineProvider {
func getSnapshot(in context: Context, completion: @escaping (TrekEntry) -> Void) {
let stored = WidgetSnapshot.load()
let snapshot: WidgetSnapshot? = (stored?.trip != nil || !context.isPreview) ? stored : WidgetSnapshot.sample(running: false)
completion(TrekEntry(date: Date(), snapshot: snapshot))
let now = Date()
completion(TrekEntry(date: now, snapshot: snapshot?.on(now)))
}
/// An entry every quarter hour for the next six hours, so the now line and
/// the next stop move on without the app; the app reloads the timeline
/// whenever it writes a new snapshot.
/// the next stop move on without the app, each with the trip day of its own
/// date: the one at midnight turns to the next day. The app reloads the
/// timeline whenever it writes a new snapshot, WidgetKit when it runs out.
func getTimeline(in context: Context, completion: @escaping (Timeline<TrekEntry>) -> Void) {
completion(TrekProvider.timeline(WidgetSnapshot.load()))
}
@@ -36,10 +38,11 @@ struct TrekProvider: TimelineProvider {
let calendar = Calendar.current
let minute = calendar.component(.minute, from: now)
let firstStep = calendar.date(byAdding: .minute, value: 15 - minute % 15, to: now) ?? now
var entries = [TrekEntry(date: now, snapshot: snapshot)]
var entries = [TrekEntry(date: now, snapshot: snapshot?.on(now))]
for step in 0..<24 {
if let date = calendar.date(byAdding: .minute, value: step * 15, to: firstStep) {
entries.append(TrekEntry(date: calendar.date(bySetting: .second, value: 0, of: date) ?? date, snapshot: snapshot))
let at = calendar.date(bySetting: .second, value: 0, of: date) ?? date
entries.append(TrekEntry(date: at, snapshot: snapshot?.on(at)))
}
}
return Timeline(entries: entries, policy: .atEnd)
+2 -1
View File
@@ -63,7 +63,8 @@ struct TrekTripProvider: AppIntentTimelineProvider {
func snapshot(for configuration: SelectTripIntent, in context: Context) async -> TrekEntry {
let stored = WidgetSnapshot.load(trip: configuration.trip?.id)
let snapshot: WidgetSnapshot? = (stored?.trip != nil || !context.isPreview) ? stored : WidgetSnapshot.sample(running: false)
return TrekEntry(date: Date(), snapshot: snapshot)
let now = Date()
return TrekEntry(date: now, snapshot: snapshot?.on(now))
}
func timeline(for configuration: SelectTripIntent, in context: Context) async -> Timeline<TrekEntry> {
@@ -35,6 +35,8 @@ struct WidgetSnapshot: Codable {
}
struct Today: Codable {
/// The calendar day it is, yyyy-MM-dd (absent from an app that predates `days`).
var date: String?
var dayLabel: String
var stops: [Stop]
/// 1-based position of today in the trip.
@@ -245,6 +247,9 @@ struct WidgetSnapshot: Codable {
var trip: Trip?
var today: Today?
/// The trip's days from the day the app wrote this on, each with its date,
/// so the widget turns to the next day itself (see `on(_:)`).
var days: [Today]?
var weather: Weather?
var bookings: [Booking]?
var todos: Todos?
@@ -306,6 +311,26 @@ struct WidgetSnapshot: Codable {
return days + 1
}
/// The snapshot as it reads on `date`: that date's trip day out of `days`,
/// none before or after the trip, and only the bookings from that date on.
/// The app writes its snapshot only while it runs, so without this a widget
/// showed the day it last ran (TestFlight feedback: "stuck on day 1"). A
/// snapshot from an app without `days` reads as it was written.
func on(_ date: Date) -> WidgetSnapshot {
guard let days, !days.isEmpty else { return self }
let key = WidgetSnapshot.key(date)
var snapshot = self
snapshot.today = days.first { $0.date == key }
snapshot.bookings = bookings?.filter { ($0.date ?? key) >= key }
return snapshot
}
/// A date as the app writes one, yyyy-MM-dd in the device's calendar day.
static func key(_ date: Date) -> String {
let parts = Calendar.current.dateComponents([.year, .month, .day], from: date)
return String(format: "%04d-%02d-%02d", parts.year ?? 0, parts.month ?? 0, parts.day ?? 0)
}
static func daysBetween(_ from: Date, _ to: Date) -> Int? {
let calendar = Calendar.current
return calendar.dateComponents([.day], from: calendar.startOfDay(for: from), to: calendar.startOfDay(for: to)).day
+10 -11
View File
@@ -53,15 +53,15 @@
"format:check": "prettier --check \"src/**/*.tsx\" \"src/**/*.css\""
},
"dependencies": {
"@assistant-ui/react": "0.15.32",
"@assistant-ui/react": "0.15.36",
"@capacitor/action-sheet": "^8.1.1",
"@capacitor/android": "^8.6.0",
"@capacitor/android": "^8.6.2",
"@capacitor/app": "^8.1.1",
"@capacitor/core": "^8.5.0",
"@capacitor/core": "^8.6.2",
"@capacitor/dialog": "^8.0.1",
"@capacitor/filesystem": "^8.1.3",
"@capacitor/haptics": "^8.0.2",
"@capacitor/ios": "^8.6.0",
"@capacitor/ios": "^8.6.2",
"@capacitor/keyboard": "^8.0.5",
"@capacitor/share": "^8.0.1",
"@capacitor/splash-screen": "^8.0.2",
@@ -101,7 +101,6 @@
"@fontsource/satisfy": "^5.3.0",
"@fontsource/shrikhand": "^5.3.0",
"@fontsource/yellowtail": "^5.3.0",
"@mapbox/mapbox-gl-rtl-text": "^0.4.0",
"@maplibre/maplibre-gl-leaflet": "0.1.4",
"@noble/hashes": "^1.8.0",
"@simplewebauthn/browser": "^13.3.0",
@@ -113,8 +112,8 @@
"iso-3166-2": "^1.0.0",
"leaflet": "^1.9.4",
"lucide-react": "^0.577.0",
"mapbox-gl": "^3.31.0",
"maplibre-gl": "6.16.0",
"mapbox-gl": "^3.35.0",
"maplibre-gl": "6.18.0",
"modern-screenshot": "4.7.0",
"plyr": "^3.8.5",
"react": "^19.3.1",
@@ -132,14 +131,14 @@
"zustand": "^5.0.15"
},
"devDependencies": {
"@capacitor/cli": "^8.6.0",
"@capacitor/cli": "^8.6.2",
"@eslint/js": "^10.0.1",
"@jscpd/core": "^4.2.5",
"@jscpd/tokenizer": "^4.2.6",
"@playwright/test": "^1.65.0",
"@testing-library/jest-dom": "^6.10.0",
"@testing-library/react": "^16.3.3",
"@testing-library/user-event": "^14.6.8",
"@testing-library/user-event": "^14.6.10",
"@trivago/prettier-plugin-sort-imports": "^6.0.2",
"@types/leaflet": "^1.9.22",
"@types/node": "^25.9.8",
@@ -157,7 +156,7 @@
"jsdom": "^29.1.1",
"msw": "^2.15.0",
"postcss": "^8.5.28",
"prettier": "^3.9.10",
"prettier": "^3.10.1",
"prettier-plugin-organize-imports": "^4.3.0",
"prettier-plugin-tailwindcss": "^0.8.1",
"rollup-plugin-visualizer": "^7.1.2",
@@ -165,7 +164,7 @@
"tailwindcss": "^3.4.19",
"typescript": "^6.0.3",
"typescript-eslint": "^8.72.1",
"vite": "8.3.6",
"vite": "8.3.8",
"vite-plugin-pwa": "^2.0.0",
"vitest": "^4.1.12"
}
+21
View File
@@ -0,0 +1,21 @@
import { createRequire } from 'node:module';
import path from 'node:path';
/**
* Plyr's icon sprite. The package publishes its JS and CSS entries and nothing
* else, so `plyr/dist/plyr.svg` is refused by the resolver although the file is
* right there. Resolving the entry it does publish and stepping across keeps this
* working wherever npm hoists the package.
*
* Shared by vite.config.js and vitest.config.ts: the build needs it to emit the
* asset, and the test run needs it because a component reaches the same
* specifier. The pattern is a regex so a `?url` suffix survives the rewrite. The player has to point at a copy on this origin
* (#2341): its default is the sprite on cdn.plyr.io, which the CSP refuses.
*/
export const plyrSpriteAlias = {
find: /^plyr\/dist\/plyr\.svg/,
replacement: path.join(
path.dirname(createRequire(import.meta.url).resolve('plyr')),
'plyr.svg',
),
};
-39
View File
@@ -1,39 +0,0 @@
import { createRequire } from 'node:module';
import path from 'node:path';
/**
* setRTLTextPlugin() takes the URL of a classic script that the GL worker pulls in
* with importScripts. mapbox-gl-rtl-text ships exactly that as
* dist/mapbox-gl-rtl-text.js, but its "exports" field publishes only the ESM/WASM
* entry, so the resolver refuses the subpath. Resolving the entry it does publish
* and stepping across to dist keeps this working wherever npm hoists the package.
*
* Shared by vite.config.js and vitest.config.ts: the build needs it to emit the
* asset, and the test run needs it because a lazily imported engine module reaches
* the same specifier.
*
* The pattern is a regex, not a string key: the import carries a `?url` suffix,
* which a string alias will not match. It is left unanchored on purpose so the
* query survives the rewrite and Vite still emits an asset URL.
*/
export const rtlTextAlias = {
find: /^@mapbox\/mapbox-gl-rtl-text\/dist\/mapbox-gl-rtl-text\.js/,
replacement: path.join(
path.dirname(createRequire(import.meta.url).resolve('@mapbox/mapbox-gl-rtl-text')),
'../dist/mapbox-gl-rtl-text.js',
),
};
/**
* Same shape for Plyr's icon sprite. The package publishes its JS and CSS entries
* and nothing else, so `plyr/dist/plyr.svg` is refused by the resolver although
* the file is right there. The player has to point at a copy on this origin
* (#2341): its default is the sprite on cdn.plyr.io, which the CSP refuses.
*/
export const plyrSpriteAlias = {
find: /^plyr\/dist\/plyr\.svg/,
replacement: path.join(
path.dirname(createRequire(import.meta.url).resolve('plyr')),
'plyr.svg',
),
};
+4 -4
View File
@@ -1,18 +1,18 @@
{
"src": {
"@typescript-eslint/no-non-null-assertion": 368,
"@typescript-eslint/no-non-null-assertion": 367,
"@typescript-eslint/no-misused-promises": 820,
"no-console": 88,
"complexity": 217,
"@typescript-eslint/no-explicit-any": 143,
"trek/no-swallowed-catch": 128,
"trek/no-swallowed-catch": 127,
"max-params": 31,
"trek/store-without-selector": 66,
"react-hooks/refs": 534,
"react-hooks/set-state-in-effect": 189,
"@typescript-eslint/no-floating-promises": 162,
"react-hooks/exhaustive-deps": 113,
"@typescript-eslint/no-unused-vars": 122,
"@typescript-eslint/no-unused-vars": 121,
"react-hooks/immutability": 28,
"max-lines-per-function": 127,
"react-hooks/static-components": 50,
@@ -35,7 +35,7 @@
},
"tests": {
"@typescript-eslint/no-explicit-any": 489,
"@typescript-eslint/no-non-null-assertion": 1876,
"@typescript-eslint/no-non-null-assertion": 1875,
"@typescript-eslint/no-misused-promises": 22,
"@typescript-eslint/no-unused-vars": 51,
"@typescript-eslint/no-floating-promises": 33,
+19
View File
@@ -698,6 +698,24 @@
"desktop": ["src/components/Planner/PlaceFormModal.tsx"],
"mobile": ["src/mobile/screens/trip/sheets/PlPlaceSearch.tsx"]
},
{
"feature": "Place add/edit form: tags",
"hooks": ["src/components/Planner/usePlaceTags.ts"],
"desktop": ["src/components/Planner/PlaceFormModal.tsx"],
"mobile": ["src/mobile/screens/trip/sheets/MPlaceEditSheet.tsx"]
},
{
"feature": "Place add/edit form: description, notes and the day note as tabs",
"hooks": ["src/components/Planner/usePlaceTextTabs.ts"],
"desktop": ["src/components/Planner/PlaceFormTexts.tsx"],
"mobile": ["src/mobile/screens/trip/sheets/PlPlaceTexts.tsx"]
},
{
"feature": "Place add/edit form: phone, e-mail and opening hours",
"hooks": ["src/components/Planner/usePlaceHours.ts"],
"desktop": ["src/components/Planner/PlaceContactFields.tsx"],
"mobile": ["src/mobile/screens/trip/sheets/PlContactFields.tsx"]
},
{
"feature": "Place detail actions",
"hooks": ["src/components/Planner/usePlaceActions.ts"],
@@ -1172,6 +1190,7 @@
"src/mobile/screens/trip/sheets/MTripSheetUi.tsx": "Phone sheet UI primitives (eyebrow, headers, stat boxes, action circles) and a time display helper.",
"src/mobile/screens/trip/sheets/PlFileAttach.tsx": "Markup only; pending files and link actions come through props from the phone form sheets.",
"src/mobile/screens/trip/sheets/PlSheetChrome.tsx": "Phone form sheet chrome primitives (header, footer, field classes).",
"src/mobile/screens/trip/sheets/PlTags.tsx": "Markup only; the tag picker's state comes through props from MPlaceEditSheet, which runs usePlaceTags, and the chips of the place sheet draw the tags the place carries.",
"src/mobile/screens/trip/sheets/PlTimeFields.tsx": "Phone time fields that already share timeCollisions with the desktop PlaceFormModal.",
"src/mobile/screens/trip/sheets/tourSheetOpen.ts": "Phone only context for MTourDetailShell: whether the tour sheet is open and the name it carries.",
"src/mobile/screens/trip/tabs/MCollabTab.tsx": "Phone collab sub tab router that reuses the desktop CollabLinks component.",
-2
View File
@@ -519,8 +519,6 @@
"src/components/Map/reservationsMapbox.ts",
"src/components/Map/routeUsageCounter.test.ts",
"src/components/Map/routeUsageCounter.ts",
"src/components/Map/rtlText.test.ts",
"src/components/Map/rtlText.ts",
"src/components/Map/selectedPlaceTarget.test.ts",
"src/components/Map/selectedPlaceTarget.ts",
"src/components/Map/trackColors.ts",
+1 -1
View File
@@ -27,7 +27,7 @@
"pdf.ts": 1,
"perm.ts": 4,
"places.ts": 9,
"planner.ts": 53,
"planner.ts": 52,
"reservations.ts": 21,
"roadtrip.ts": 36,
"settings.ts": 37,
+3 -3
View File
@@ -241,7 +241,7 @@
"mobile/screens/trip/sheets/MDaysSheet.tsx": 4,
"mobile/screens/trip/sheets/MExportSheet.tsx": 2,
"mobile/screens/trip/sheets/MImportSheet.tsx": 2,
"mobile/screens/trip/sheets/MLinkedCosts.tsx": 9,
"mobile/screens/trip/sheets/MLinkedCosts.tsx": 8,
"mobile/screens/trip/sheets/MMehrSheet.tsx": 3,
"mobile/screens/trip/sheets/MNoteSheet.tsx": 1,
"mobile/screens/trip/sheets/MPlaceEditSheet.tsx": 2,
@@ -250,8 +250,8 @@
"mobile/screens/trip/sheets/MTransportFormSheet.tsx": 9,
"mobile/screens/trip/sheets/MTransportSheet.tsx": 9,
"mobile/screens/trip/sheets/MTripSheetUi.tsx": 5,
"mobile/screens/trip/sheets/PlCategoryPicker.tsx": 2,
"mobile/screens/trip/sheets/PlFileAttach.tsx": 7,
"mobile/screens/trip/sheets/PlCategoryPicker.tsx": 1,
"mobile/screens/trip/sheets/PlFileAttach.tsx": 3,
"mobile/screens/trip/sheets/PlPlaceSearch.tsx": 6,
"mobile/screens/trip/sheets/PlSheetChrome.tsx": 5,
"mobile/screens/trip/sheets/PlTimeFields.tsx": 3,
+14
View File
@@ -0,0 +1,14 @@
import type { TripTagCreateRequest, TripTagListResponse, TripTagResponse, TripTagUpdateRequest } from '@trek/shared';
import apiClient from './client';
/** The tags a trip owns: every member reads them, and whoever may edit its places adds one. */
export const tripTagsApi = {
list: (tripId: number | string): Promise<TripTagListResponse> =>
apiClient.get(`/trips/${tripId}/tags`).then((r) => r.data),
/** Answers the trip's existing tag when it already has one of that name. */
create: (tripId: number | string, body: TripTagCreateRequest): Promise<TripTagResponse> =>
apiClient.post(`/trips/${tripId}/tags`, body).then((r) => r.data),
/** A new name or colour for one of the trip's tags; every place carrying it shows the change. */
update: (tripId: number | string, tagId: number, body: TripTagUpdateRequest): Promise<TripTagResponse> =>
apiClient.put(`/trips/${tripId}/tags/${tagId}`, body).then((r) => r.data),
};
@@ -0,0 +1,87 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { render, waitFor } from '../../../tests/helpers/render';
import { offlineDb } from '../../db/offlineDb';
import type { Day, Trip } from '../../types';
const published = vi.hoisted(() => ({ calls: [] as unknown[][] }));
vi.mock('@capacitor/app', () => ({ App: { addListener: vi.fn(async () => ({ remove: vi.fn() })) } }));
vi.mock('../../native/capabilities', () => ({ useNativeCapabilities: () => ({ caps: {} }) }));
vi.mock('../../native/watch', () => ({
applyWatchActions: vi.fn(async () => []),
buildWatchSnapshot: vi.fn(),
publishWatch: vi.fn(async () => {}),
takeWatchActions: vi.fn(async () => []),
watchActive: () => false,
}));
vi.mock('../../native/widgetMedia', () => ({
widgetCover: vi.fn(async () => null),
widgetWeather: vi.fn(async () => null),
}));
vi.mock('../../native/widgetOnline', () => ({
atlasSummary: vi.fn(async () => null),
collabSummary: vi.fn(async () => null),
packingDetail: vi.fn(async () => null),
}));
vi.mock('../../native/widgets', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../native/widgets')>();
return {
...actual,
widgetsActive: () => true,
publishWidgets: vi.fn(async (...args: unknown[]) => {
published.calls.push(args);
}),
};
});
import NativeWidgetsSync from './NativeWidgetsSync';
const trip = {
id: 7,
title: 'Lisbon',
start_date: '2026-11-06',
end_date: '2026-11-08',
is_archived: 0,
} as unknown as Trip;
const day = (id: number, n: number, date: string, name: string) =>
({
id,
trip_id: 7,
day_number: n,
date,
assignments: [{ id: id * 10, order_index: 0, place: { name, place_time: '10:00' } }],
}) as unknown as Day;
describe('NativeWidgetsSync', () => {
beforeEach(async () => {
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(new Date(2026, 10, 7, 9, 0));
published.calls = [];
await offlineDb.trips.put(trip as never);
await offlineDb.days.bulkPut([
day(1, 1, '2026-11-06', 'Castle'),
day(2, 2, '2026-11-07', 'Harbour'),
day(3, 3, '2026-11-08', 'Market'),
] as never);
});
afterEach(async () => {
vi.useRealTimers();
await offlineDb.trips.clear();
await offlineDb.days.clear();
});
it('FE-NATIVE-WSYNC-001: writes today and every day ahead, so the widgets turn the day without the app', async () => {
render(<NativeWidgetsSync />);
await waitFor(() => expect(published.calls.length).toBeGreaterThan(0));
const snapshot = published.calls[0][0] as {
today: { date: string; stops: { name: string }[] } | null;
days: { date: string; stops: { name: string }[] }[];
};
expect(snapshot.today).toMatchObject({ date: '2026-11-07', stops: [{ name: 'Harbour' }] });
expect(snapshot.days.map((d) => [d.date, d.stops[0]?.name])).toEqual([
['2026-11-07', 'Harbour'],
['2026-11-08', 'Market'],
]);
});
});
@@ -25,11 +25,10 @@ import {
liveFlightOf,
pickTrip,
publishWidgets,
todayOf,
snapshotDays,
tripDayState,
widgetTripChoices,
widgetsActive,
withBookings,
type TripWidgetSnapshot,
type WidgetLabels,
} from '../../native/widgets';
@@ -191,11 +190,15 @@ export default function NativeWidgetsSync(): null {
const tripSnapshot = async (trip: Trip | null, context: SyncContext, atlas: WidgetAtlas | null) => {
const days = trip ? await offlineDb.days.where('trip_id').equals(trip.id).toArray() : [];
const extra = trip ? await tripExtras(trip, days, context) : null;
const plain = trip
? todayOf(trip, days, context.today, (n, m) => t('native.widget.dayOf', { n, m }), context.time)
: null;
const day = plain ? withBookings(plain, extra?.reservations ?? [], context.today, context.time) : null;
return { day, days, extra, snapshot: buildSnapshot(trip, day, labels(t), { ...extra?.extras, atlas }) };
// Today and the days after it: the widgets turn to the next day at midnight by themselves.
const { today: day, ahead } = snapshotDays(trip, days, {
reservations: extra?.reservations ?? [],
from: context.today,
dayLabel: (n, m) => t('native.widget.dayOf', { n, m }),
formatTime: context.time,
});
const snapshot = buildSnapshot(trip, day, labels(t), { ...extra?.extras, atlas, days: ahead });
return { day, days, extra, snapshot };
};
/** The hero trip in full for the watch, with the ticks from it applied so far. */
+3 -5
View File
@@ -1,7 +1,5 @@
import mapboxgl from 'mapbox-gl'
import 'mapbox-gl/dist/mapbox-gl.css'
import rtlTextPluginUrl from '@mapbox/mapbox-gl-rtl-text/dist/mapbox-gl-rtl-text.js?url'
import { registerRtlTextPlugin } from '../rtlText'
/**
* The only module in the client that pulls mapbox-gl in at runtime.
@@ -10,8 +8,8 @@ import { registerRtlTextPlugin } from '../rtlText'
* a static import from anywhere in the tree drags 1.8 MB into the parent chunk and
* quietly undoes the split. `npm run check:gl-split` fails on that.
*/
// Arabic/Hebrew/Persian labels come out unjoined and reversed without this.
// Mapbox's signature is (url, callback, deferred) — see rtlText.ts.
registerRtlTextPlugin(() => mapboxgl.setRTLTextPlugin(rtlTextPluginUrl, null, true))
// No RTL text plugin to register: since 3.33 Mapbox GL shapes Arabic and orders
// bidirectional text itself, loading a small WebAssembly module from
// api.mapbox.com the first time such a label appears (#2235).
export default mapboxgl
@@ -25,7 +25,7 @@ import { installOfflineProtocol } from '../../../native/offlineTiles'
// together with this module.
maplibregl.setWorkerUrl(workerUrl)
// No RTL text plugin here, unlike mapbox. MapLibre 6.9 shapes Arabic and orders
// No RTL text plugin here, as with mapbox. MapLibre 6.9 shapes Arabic and orders
// bidirectional text itself; the old plugin would replace that implementation, and
// a v6 worker can only load the plugin's UMD build through eval.
@@ -1,14 +1,13 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
/**
* What each engine module does on import. Everything else is a helper: the guard
* in rtlText.ts has its own tests, but a guard nobody calls looks exactly like a
* working fix from the outside. Deleting the mapbox registration, swapping an
* argument or dropping the deferred flag left the whole suite green, and so would
* a maplibre engine that forgot its worker URL.
* What each engine module does on import. Both GL engines shape right-to-left
* text themselves now (MapLibre since 6.9, Mapbox since 3.33), so neither may
* register the old plugin, and a maplibre engine that forgot its worker URL
* would draw no tile at all.
*
* The engines are mocked because importing them for real builds a worker pool
* under jsdom, and the plugin URL is mocked so the 133 KB payload never loads.
* under jsdom.
*/
const { mapboxSet, maplibreSet, maplibreWorker } = vi.hoisted(() => ({
mapboxSet: vi.fn(),
@@ -21,7 +20,6 @@ vi.mock('maplibre-gl', () => ({ setRTLTextPlugin: maplibreSet, setWorkerUrl: map
vi.mock('mapbox-gl/dist/mapbox-gl.css', () => ({}));
vi.mock('maplibre-gl/dist/maplibre-gl.css', () => ({}));
vi.mock('maplibre-gl/dist/maplibre-gl-worker.mjs?worker&url', () => ({ default: '/assets/maplibre-worker.js' }));
vi.mock('@mapbox/mapbox-gl-rtl-text/dist/mapbox-gl-rtl-text.js?url', () => ({ default: '/assets/rtl-plugin.js' }));
beforeEach(() => {
vi.resetModules();
@@ -30,15 +28,14 @@ beforeEach(() => {
maplibreWorker.mockReset();
});
describe('the GL engines register the RTL text plugin (#2235)', () => {
it('FE-MAP-RTL-001: importing the mapbox engine registers it deferred, with a null callback', async () => {
await import('./mapbox');
describe('the GL engines on import (#2235)', () => {
it('FE-MAP-RTL-001: importing the mapbox engine registers no plugin', async () => {
const engine = await import('./mapbox');
expect(mapboxSet).toHaveBeenCalledTimes(1);
// Mapbox GL 3 takes (url, callback, deferred). The third argument is what
// keeps the payload off the wire until a map paints RTL text; dropping it
// would fetch 133 KB for every user on every map.
expect(mapboxSet).toHaveBeenCalledWith(expect.stringContaining('rtl'), null, true);
// Mapbox GL 3.33 shapes right-to-left text itself and dropped the plugin API;
// calling it would throw on the real engine.
expect(mapboxSet).not.toHaveBeenCalled();
expect(engine.default).toBeDefined();
});
it('FE-MAP-RTL-002: importing the maplibre engine registers no plugin', async () => {
@@ -49,14 +46,6 @@ describe('the GL engines register the RTL text plugin (#2235)', () => {
expect(maplibreSet).not.toHaveBeenCalled();
});
it('FE-MAP-RTL-003: an engine still loads when its registration throws', async () => {
mapboxSet.mockImplementation(() => { throw new Error('already registered'); });
const engine = await import('./mapbox');
expect(engine.default).toBeDefined();
});
it('FE-MAP-RTL-004: importing the maplibre engine points it at the bundled worker', async () => {
const engine = await import('./maplibre');
-38
View File
@@ -1,38 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { registerRtlTextPlugin } from './rtlText'
describe('registerRtlTextPlugin', () => {
it('runs the engine-supplied registration', () => {
const register = vi.fn()
expect(registerRtlTextPlugin(register)).toBe(true)
expect(register).toHaveBeenCalledTimes(1)
})
// Registering twice is how the engines report it: Mapbox throws.
it('never lets a refused registration break map creation', () => {
const register = vi.fn(() => {
throw new Error('setRTLTextPlugin cannot be called multiple times.')
})
expect(() => registerRtlTextPlugin(register)).not.toThrow()
expect(registerRtlTextPlugin(register)).toBe(false)
})
// MapLibre reports the same by rejecting, and an unhandled rejection would
// reach the console for something the user cannot act on.
it('swallows a rejected registration promise', async () => {
const onUnhandled = vi.fn()
process.on('unhandledRejection', onUnhandled)
expect(registerRtlTextPlugin(() => Promise.reject(new Error('404')))).toBe(true)
await new Promise(resolve => setTimeout(resolve, 0))
process.off('unhandledRejection', onUnhandled)
expect(onUnhandled).not.toHaveBeenCalled()
})
it('leaves a resolved promise alone', async () => {
expect(registerRtlTextPlugin(() => Promise.resolve())).toBe(true)
})
})
-50
View File
@@ -1,50 +0,0 @@
/**
* Arabic, Hebrew, Persian and Urdu labels need two things a GL engine does not do
* on its own: the bidirectional algorithm, and Arabic contextual shaping (a letter
* is drawn differently depending on its neighbours). Without them the engine lays
* the codepoints out one by one, left to right, in isolated forms — so القاهرة
* comes out as ة ر ه ا ق ل ا, unjoined and reversed. Raster basemaps never showed
* this because their labels are drawn server-side, which is why it only surfaced
* once the default basemap became a vector style.
*
* Mapbox GL exposes the fix as an optional plugin and does not load it by
* default. Registering is global to the engine, so it happens once in the engine
* module rather than at each map's construction site. MapLibre needed the same
* plugin up to version 5; since 6.9 it shapes and reorders the text itself, and
* its engine module registers nothing.
*
* The call itself stays with the caller: Mapbox GL 3 takes
* `(url, callback, deferred)` and returns nothing, while MapLibre took
* `(url, lazy)` and returned a promise, so the guard below accepts either rather
* than guessing an arity.
*
* Deliberately no getRTLTextPluginStatus() pre-check: reading it made MapLibre
* build its worker pool, which is an eager side effect for a module that is
* imported for its default export, and throws outright under jsdom. Registering
* twice is reported — by a throw or a rejected promise depending on the engine —
* and both are handled below, so the probe bought nothing.
*/
/**
* Runs a GL engine's RTL-plugin registration, swallowing the ways it can fail.
*
* Callers register lazily, so the payload is only fetched once a map actually
* paints RTL text and a user who never leaves Latin script downloads nothing.
*
* @returns whether the registration call completed without throwing.
*/
export function registerRtlTextPlugin(register: () => void | Promise<unknown>): boolean {
try {
const pending = register()
// MapLibre reports a failed or duplicate registration by rejecting; Mapbox
// routes the same through its callback. Neither is worth surfacing: a map
// with unshaped labels still renders, and an unhandled rejection would not
// give the user anything to act on.
if (pending instanceof Promise) pending.catch(() => {})
return true
} catch {
// Already registered, or the engine refused outright. Registering the plugin
// must never be able to break map creation.
return false
}
}
@@ -1,4 +1,4 @@
// FE-PLANNER-DPTRANSPORT-001 to FE-PLANNER-DPTRANSPORT-021
// FE-PLANNER-DPTRANSPORT-001 to FE-PLANNER-DPTRANSPORT-024
import { render, screen, fireEvent, within } from '../../../tests/helpers/render'
import userEvent from '@testing-library/user-event'
import { resetAllStores, seedStore } from '../../../tests/helpers/store'
@@ -329,4 +329,29 @@ describe('DayPlanSidebarTransportDetailModal', () => {
await user.click(screen.getByRole('button', { name: 'Close' }))
expect(setTransportDetail).toHaveBeenCalledWith(null)
})
// #3122: a transport holding only times showed them without the day they fall on.
it('FE-PLANNER-DPTRANSPORT-022: a booking holding only times names the date of its linked day', () => {
seedStore(useTripStore, { days: [{ id: 4, trip_id: 1, day_number: 2, date: '2025-06-16' }] as never })
const res = { ...flight(), day_id: 4, reservation_time: '09:15', reservation_end_time: '11:00', endpoints: [] } as Reservation
render(<DayPlanSidebarTransportDetailModal {...makeProps({ transportDetail: res })} />)
expect(screen.getByText('09:15 → 11:00').parentElement).toHaveTextContent(/Mon, Jun 16/)
})
it('FE-PLANNER-DPTRANSPORT-023: an overnight booking names the arrival date too', () => {
const res = { ...flight(), reservation_time: '2025-06-15T22:30:00', reservation_end_time: '2025-06-16T06:05:00' } as Reservation
render(<DayPlanSidebarTransportDetailModal {...makeProps({ transportDetail: res })} />)
expect(screen.getByText('22:30 → 06:05').parentElement).toHaveTextContent(/Sun, Jun 15 → Mon, Jun 16/)
})
it('FE-PLANNER-DPTRANSPORT-024: in a right-to-left UI the overnight days read in order', () => {
document.documentElement.dir = 'rtl'
try {
const res = { ...flight(), reservation_time: '2025-06-15T22:30:00', reservation_end_time: '2025-06-16T06:05:00' } as Reservation
render(<DayPlanSidebarTransportDetailModal {...makeProps({ transportDetail: res })} />)
expect(screen.getByText('22:30 → 06:05').parentElement).toHaveTextContent('⁨Sun, Jun 15⁩ ← ⁨Mon, Jun 16⁩')
} finally {
document.documentElement.dir = ''
}
})
})
@@ -14,7 +14,9 @@ import { BOX, Eyebrow, Field, fs, toneColor, toneOf } from './bookings/bookingPa
import { filesFor } from '../../utils/reservationFiles'
import { bookingDayLabel, segmentCodeLabel } from './transportDetailModel'
import { TransitLegs, transitSummary } from './bookings/transitParts'
import type { Reservation } from '../../types'
import { bookingDates } from './bookings/bookingsModel'
import { flowText } from '../../utils/flowText'
import type { Day, Reservation } from '../../types'
type Translate = (key: string, params?: Record<string, string | number>) => string
@@ -50,11 +52,12 @@ export function DayPlanSidebarTransportDetailModal({ transportDetail, ...rest }:
function TransportDetailDialog({ res, setTransportDetail, onNavigateToFiles, onEdit, t, locale, timeFormat }: Omit<DayPlanSidebarTransportDetailModalProps, 'transportDetail'> & { res: Reservation }) {
const titleId = useId()
const allFiles = useTripStore(s => s.files)
const days = useTripStore(s => s.days)
const close = () => setTransportDetail(null)
const meta = parseReservationMetadata(res)
const transit = transitSummary(meta)
const files = filesFor(res, allFiles || [])
const when = whenOf(res, locale, timeFormat)
const when = whenOf(res, days, locale, timeFormat)
const cells = detailCells(res, meta, t)
const confirmed = res.status === 'confirmed'
@@ -192,11 +195,18 @@ function detailCells(res: Reservation, meta: Record<string, unknown>, t: Transla
return cells
}
/** The booking's day and its time or time range, each empty when the booking has none. */
function whenOf(res: Reservation, locale: string, timeFormat: string): { day: string; time: string } {
const { date, time } = splitReservationDateTime(res.reservation_time)
/**
* The booking's calendar day (both, when it arrives on a later one) and its time or
* time range, each empty when the booking has none. A booking holding only times
* takes the date of the day it is linked to (#3122).
*/
function whenOf(res: Reservation, days: Day[], locale: string, timeFormat: string): { day: string; time: string } {
const { time } = splitReservationDateTime(res.reservation_time)
const { time: endTime } = splitReservationDateTime(res.reservation_end_time)
const day = date ? bookingDayLabel(date, locale) : ''
const dates = bookingDates(res, days || [])
// An arrival date alone would read as the departure, so it only joins a start date.
const span = dates.start ? [dates.start, dates.end !== dates.start ? dates.end : null].filter((d): d is string => !!d) : []
const day = span.length > 0 ? flowText(span.map(d => bookingDayLabel(d, locale))) : ''
const start = time ? formatTime(time, locale, timeFormat) : ''
const end = endTime ? formatTime(endTime, locale, timeFormat) : ''
return { day, time: start && end ? `${start} → ${end}` : start }
@@ -1,4 +1,4 @@
// FE-PLANNER-CONTACT-001 to FE-PLANNER-CONTACT-002
// FE-PLANNER-CONTACT-001 to FE-PLANNER-CONTACT-004
import { describe, expect, it, vi } from 'vitest'
import { useState } from 'react'
import userEvent from '@testing-library/user-event'
@@ -54,7 +54,7 @@ describe('PlaceContactFields (#2472)', () => {
const opens = screen.getAllByRole('textbox', { name: /Monday opens/ })
await user.type(opens[0], '0930')
expect(opens[0]).toHaveValue('09:30')
expect(JSON.parse(onChange.mock.lastCall![1])[0]).toEqual({ closed: false, open: '09:30' })
expect(JSON.parse(onChange.mock.lastCall?.[1])[0]).toEqual({ closed: false, open: '09:30' })
})
it('FE-PLANNER-CONTACT-004: looked-up hours fill an empty place, and an edited one offers to take them over', async () => {
@@ -87,5 +87,33 @@ describe('PlaceContactFields (#2472)', () => {
// Still an e-mail field, so the keyboard and the browser's check stay.
expect(screen.getByLabelText('E-mail')).toHaveAttribute('type', 'email')
})
})
it('FE-PLANNER-CONTACT-003: a day opens around the clock with one switch, and an all-day lookup shows it on', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
render(<Harness onChange={onChange} />)
await user.click(screen.getByRole('button', { name: 'Add opening hours' }))
const allDay = screen.getByRole('switch', { name: 'Monday: Open 24 hours' })
expect(allDay).toHaveAttribute('aria-checked', 'false')
await user.click(allDay)
expect(JSON.parse(onChange.mock.lastCall?.[1])[0]).toEqual({ closed: false, open: '00:00', close: '23:59' })
expect(allDay).toHaveAttribute('aria-checked', 'true')
// The two time fields give way to the word.
expect(screen.queryByRole('textbox', { name: /Monday opens/ })).not.toBeInTheDocument()
expect(screen.getByText('Open 24 hours', { selector: 'span' })).toBeInTheDocument()
// Closing the day turns the all-day switch off.
await user.click(screen.getByRole('switch', { name: 'Monday: Closed' }))
expect(JSON.parse(onChange.mock.lastCall?.[1])[0]).toEqual({ closed: true })
expect(allDay).toHaveAttribute('aria-checked', 'false')
})
it('FE-PLANNER-CONTACT-004: looked-up hours open around the clock arrive with the all-day switch on', () => {
const suggested = Array.from({ length: 7 }, () => ({ closed: false, open: '00:00', close: '23:59' }))
render(<Harness onChange={vi.fn()} suggested={suggested} />)
for (const day of ['Monday', 'Sunday']) {
expect(screen.getByRole('switch', { name: `${day}: Open 24 hours` })).toHaveAttribute('aria-checked', 'true')
}
})
})
@@ -1,14 +1,22 @@
import { useEffect, useId, useRef, useState } from 'react'
import { Copy, Mail, Phone, RotateCcw, X } from 'lucide-react'
import { useId } from 'react'
import { Copy, DoorClosed, Mail, Phone, RotateCcw, X } from 'lucide-react'
import type { PlaceClientOrigin, PlaceOpeningHours } from '@trek/shared'
import CustomTimePicker from '../shared/CustomTimePicker'
import { Tooltip } from '../shared/Tooltip'
import { DialogSection, fs } from '../shared/DialogShell'
import { AddRowButton, EditorField, GRID_2, INPUT } from '../shared/dialogParts'
import { cleanWeek, readWeek, weekdayNames, writeWeek } from './placeHours'
import { isAllDay, weekdayNames } from './placeHours'
import { usePlaceHours } from './usePlaceHours'
import { useTranslation } from '../../i18n'
import { NO_AUTOFILL } from '../../utils/noAutofill'
/** A closed or all-day row says so in place of the two times, in a box of their height. */
const DAY_STATE = 'flex h-[38px] min-w-0 items-center rounded-[10px] border border-edge-faint bg-surface-tertiary px-3.5 font-medium text-content-muted'
/** The two switches after the times: square, as tall as a time field. */
const DAY_BUTTON = 'grid h-[38px] w-[38px] flex-none place-items-center rounded-[10px] border font-semibold transition-colors'
const DAY_BUTTON_OFF = 'border-edge bg-surface-input text-content-faint hover:border-content-faint hover:text-content'
const DAY_BUTTON_ON = 'border-transparent bg-accent text-accent-text shadow-sm'
interface Props {
/** Anchor for the "add by hand" jump from an empty search. */
id?: string
@@ -36,45 +44,11 @@ interface Props {
export function PlaceContactFields({ id: anchorId, phone, email, openingHours, onChange, suggestedHours }: Props) {
const { t, locale } = useTranslation()
const id = useId()
// The editor's own draft, so a half-typed time ("09:3") stays on screen while
// only finished times reach the place.
const [week, setDraft] = useState(() => readWeek(openingHours))
const written = useRef(openingHours)
const [editing, setEditing] = useState(() => openingHours !== '')
const hours = usePlaceHours({ openingHours, suggestedHours, onChange: (value, origin) => onChange('opening_hours', value, origin) })
const { week, editing } = hours
const names = weekdayNames(locale, 'short')
const longNames = weekdayNames(locale, 'long')
// A value from outside (a picked search result, a reopened place) replaces the draft.
useEffect(() => {
if (openingHours === written.current) return
written.current = openingHours
setDraft(readWeek(openingHours))
if (openingHours) setEditing(true)
}, [openingHours])
const setWeek = (next: PlaceOpeningHours, origin?: PlaceClientOrigin) => {
setDraft(next)
const text = writeWeek(cleanWeek(next))
written.current = text
onChange('opening_hours', text, origin)
}
const setDay = (i: number, patch: Partial<PlaceOpeningHours[number]>) =>
setWeek(week.map((day, d) => (d === i ? { ...day, ...patch } : day)))
const copyFirstToAll = () => setWeek(week.map(() => ({ ...week[0] })))
const clearHours = () => { setWeek(readWeek('')); setEditing(false) }
// Looked-up hours are taken over by a place that has none yet, once per lookup.
const adopted = useRef<PlaceOpeningHours | null>(null)
useEffect(() => {
if (!suggestedHours || adopted.current === suggestedHours) return
adopted.current = suggestedHours
if (written.current) return
setWeek(suggestedHours, 'enrichment')
setEditing(true)
// setWeek only reads refs and setters; the lookup is the trigger.
}, [suggestedHours])
const canTakeOver = !!suggestedHours && writeWeek(suggestedHours) !== writeWeek(cleanWeek(week))
return (
<div id={anchorId} className="flex flex-col gap-4">
<div className={GRID_2}>
@@ -98,22 +72,22 @@ export function PlaceContactFields({ id: anchorId, phone, email, openingHours, o
label={t('inspector.openingHours')}
action={editing ? (
<div className="flex items-center gap-1">
{canTakeOver && (
{hours.canTakeOver && (
<Tooltip label={t('places.hoursFromDetails')}>
<button type="button" onClick={() => setWeek(suggestedHours!, 'enrichment')} aria-label={t('places.hoursFromDetails')}
<button type="button" onClick={hours.takeOver} aria-label={t('places.hoursFromDetails')}
className="grid h-7 w-7 place-items-center rounded-full text-content-faint hover:bg-surface-hover hover:text-content">
<RotateCcw size={13} strokeWidth={2} />
</button>
</Tooltip>
)}
<Tooltip label={t('places.hoursCopyFirst', { day: longNames[0] })}>
<button type="button" onClick={copyFirstToAll} aria-label={t('places.hoursCopyFirst', { day: longNames[0] })}
<button type="button" onClick={hours.copyFirstToAll} aria-label={t('places.hoursCopyFirst', { day: longNames[0] })}
className="grid h-7 w-7 place-items-center rounded-full text-content-faint hover:bg-surface-hover hover:text-content">
<Copy size={13} strokeWidth={2} />
</button>
</Tooltip>
<Tooltip label={t('places.hoursRemove')}>
<button type="button" onClick={clearHours} aria-label={t('places.hoursRemove')}
<button type="button" onClick={hours.clearHours} aria-label={t('places.hoursRemove')}
className="grid h-7 w-7 place-items-center rounded-full text-content-faint hover:bg-surface-hover hover:text-danger">
<X size={14} strokeWidth={2.2} />
</button>
@@ -126,32 +100,45 @@ export function PlaceContactFields({ id: anchorId, phone, email, openingHours, o
{week.map((day, i) => (
<div key={i} className="grid min-h-[46px] grid-cols-[44px_minmax(0,1fr)_auto] items-center gap-2.5 px-3 py-1.5">
<span className="font-semibold text-content-secondary" style={fs(12.5, 'body')} title={longNames[i]}>{names[i]}</span>
{day.closed ? (
<span className="text-content-faint" style={fs(12.5, 'body')}>{t('places.hoursClosed')}</span>
{day.closed || isAllDay(day) ? (
<span className={DAY_STATE} style={fs(12.5, 'body')}>
{day.closed ? t('places.hoursClosed') : t('places.hoursAllDay')}
</span>
) : (
<div className="flex min-w-0 items-center gap-1.5">
<div className="min-w-0 flex-1">
<CustomTimePicker value={day.open ?? ''} onChange={v => setDay(i, { open: v || undefined })}
<div className='flex min-w-0 items-center gap-1.5'>
<div className='min-w-0 flex-1'>
<CustomTimePicker value={day.open ?? ''} onChange={v => hours.setDay(i, { open: v || undefined })}
aria-label={`${longNames[i]} ${t('places.hoursOpens')}`} />
</div>
<span className="flex-none text-content-faint">–</span>
<div className="min-w-0 flex-1">
<CustomTimePicker value={day.close ?? ''} onChange={v => setDay(i, { close: v || undefined })}
<span className='flex-none text-content-faint'>–</span>
<div className='min-w-0 flex-1'>
<CustomTimePicker value={day.close ?? ''} onChange={v => hours.setDay(i, { close: v || undefined })}
aria-label={`${longNames[i]} ${t('places.hoursCloses')}`} />
</div>
</div>
)}
<button type="button" role="switch" aria-checked={day.closed} aria-label={`${longNames[i]}: ${t('places.hoursClosed')}`}
onClick={() => setDay(i, day.closed ? { closed: false } : { closed: true, open: undefined, close: undefined })}
className={`rounded-full border px-2.5 py-[3px] font-semibold transition-colors ${day.closed ? 'border-[color:var(--text-primary)] bg-surface-tertiary text-content' : 'border-edge text-content-faint hover:text-content'}`}
style={fs(11)}>
{t('places.hoursClosed')}
</button>
<div className='flex items-center gap-1.5'>
<Tooltip label={t('places.hoursAllDay')}>
<button type='button' role='switch' aria-checked={isAllDay(day)} aria-label={`${longNames[i]}: ${t('places.hoursAllDay')}`}
onClick={() => hours.toggleAllDay(i)}
className={`${DAY_BUTTON} ${isAllDay(day) ? DAY_BUTTON_ON : DAY_BUTTON_OFF}`}
style={fs(11.5, 'body')}>
24h
</button>
</Tooltip>
<Tooltip label={t('places.hoursClosed')}>
<button type='button' role='switch' aria-checked={day.closed} aria-label={`${longNames[i]}: ${t('places.hoursClosed')}`}
onClick={() => hours.toggleClosed(i)}
className={`${DAY_BUTTON} ${day.closed ? DAY_BUTTON_ON : DAY_BUTTON_OFF}`}>
<DoorClosed size={15} strokeWidth={2} />
</button>
</Tooltip>
</div>
</div>
))}
</div>
) : (
<AddRowButton onClick={() => setEditing(true)}>{t('places.hoursAdd')}</AddRowButton>
<AddRowButton raised onClick={() => hours.setEditing(true)}>{t('places.hoursAdd')}</AddRowButton>
)}
</DialogSection>
</div>
@@ -238,7 +238,7 @@ export default function PlaceDetailsColumn({
// tiles, which is too small to tell a facade from a foyer. The column is
// stretched to the form's height by the row it sits in, so the extra room
// costs nothing that was being used.
<aside className={dialog ? `${SIDE_COLUMN} ${fluid ? '' : 'sm:w-80'}` : `w-full ${fluid ? '' : 'sm:w-80'} shrink-0 flex flex-col rounded-[18px] border border-[color:var(--m-cbr)] bg-[color:var(--m-card)] overflow-hidden self-stretch`}>
<aside className={dialog ? `${SIDE_COLUMN} ${fluid ? '' : 'sm:w-80'}` : `w-full ${fluid ? '' : 'sm:w-80'} shrink-0 flex flex-col self-stretch`}>
{dialog ? (
<ColumnHead icon={<Landmark size={13} strokeWidth={2.2} />}>{t('places.details.title')}</ColumnHead>
) : (
@@ -247,16 +247,15 @@ export default function PlaceDetailsColumn({
aria-expanded={open}
aria-controls={bodyId}
onClick={() => setOpen(o => !o)}
className={`flex w-full shrink-0 items-center gap-2.5 px-3 py-2.5 text-start ${open ? 'border-b border-[color:var(--m-rowbr)]' : ''}`}
// A badge over the column's blocks: what they are, and the fold.
className="flex h-[36px] w-full shrink-0 items-center gap-2 rounded-full border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] pe-3 ps-3.5 text-start"
>
<span className="flex h-8 w-8 flex-none items-center justify-center rounded-full bg-[color:var(--m-ic)] text-m-ink">
<Landmark size={15} strokeWidth={2} />
</span>
<span className="min-w-0 flex-1 text-body font-semibold text-m-ink">{t('places.details.title')}</span>
<Landmark size={13} strokeWidth={2.2} className="flex-none text-m-muted" />
<span className="min-w-0 flex-1 truncate font-geist text-caption font-semibold text-m-ink">{t('places.details.title')}</span>
<ChevronDown
size={16}
size={13}
strokeWidth={2.2}
className={`flex-none text-m-muted transition-transform duration-200 ${open ? 'rotate-180' : ''}`}
className={`flex-none text-m-faint transition-transform duration-200 ${open ? 'rotate-180' : ''}`}
/>
</button>
)}
@@ -267,7 +266,7 @@ export default function PlaceDetailsColumn({
className={dialog ? 'contents' : `grid transition-[grid-template-rows] duration-300 ease-out ${open ? 'grid-rows-[1fr]' : 'grid-rows-[0fr]'}`}
>
<div className={dialog ? 'flex min-h-0 flex-1 flex-col gap-3.5 overflow-y-auto px-3 pb-3' : `min-h-0 overflow-hidden ${open ? '' : 'invisible'}`}>
<div className={dialog ? 'contents' : 'p-3 space-y-3'}>
<div className={dialog ? 'contents' : 'space-y-3 pt-3'}>
{/* The place's picture first: its own ones are there whatever the sources answer. */}
<PictureBlock
photos={state === 'ready' && !data?.disabled ? (data?.photos ?? []) : []}
@@ -47,6 +47,11 @@ export interface PlaceFormData {
// Which shareable fields the user typed and which a pick or the details column filled
// (placeFieldOrigins.ts). Rides along to the save as `fieldOrigins`; never shown.
fieldOrigins?: PlaceFieldOrigins
// The ids of the place's tags, always the whole set, as the save takes them. Absent
// until one is ticked or unticked in the form (usePlaceTags): a missing key writes
// nothing, so a save that never touched the tags cannot undo a tag put on the place
// elsewhere in the meantime.
tags?: number[]
}
export function isGoogleMapsUrl(input: string): boolean {
@@ -0,0 +1,97 @@
// FE-PLANNER-PLACEFORM-TAGS-001 to FE-PLANNER-PLACEFORM-TAGS-004: the place's tags in the
// desktop dialog. The logic is usePlaceTags', tested on its own; this is the form around it.
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { buildPlace, buildTag } from '../../../tests/helpers/factories';
import { server } from '../../../tests/helpers/msw/server';
import { placeFormProps, seedPlaceFormStores } from '../../../tests/helpers/placeFormSetup';
import { render, screen, waitFor, within } from '../../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { useTripStore } from '../../store/tripStore';
import PlaceFormModal from './PlaceFormModal';
vi.mock('../shared/CustomTimePicker', async () => ({
default: (await import('../../../tests/helpers/placeForm')).TimePickerStub,
}));
const monument = buildTag({ id: 7, trip_id: 1, name: 'Monument', color: '#6366f1' });
const zone = buildTag({ id: 8, trip_id: 1, name: 'Zone', color: '#10b981' });
const tagGroup = () => screen.getByRole('group', { name: 'Tags' });
const tagSwitch = (name: string) => within(tagGroup()).getByRole('button', { name });
beforeEach(() => {
resetAllStores();
seedPlaceFormStores();
seedStore(useTripStore, { tripTags: [monument, zone] });
});
describe('PlaceFormModal, the tags', () => {
it('FE-PLANNER-PLACEFORM-TAGS-001: a new place is saved with the tags ticked in the form', async () => {
const user = userEvent.setup();
const onSave = vi.fn().mockResolvedValue(undefined);
render(<PlaceFormModal {...placeFormProps} onSave={onSave} />);
expect(tagSwitch('Monument')).toHaveAttribute('aria-pressed', 'false');
await user.type(screen.getByPlaceholderText(/e\.g\. Eiffel Tower/i), 'Belem Tower');
await user.click(tagSwitch('Monument'));
expect(tagSwitch('Monument')).toHaveAttribute('aria-pressed', 'true');
await user.click(screen.getByRole('button', { name: /^Add$/i }));
await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ name: 'Belem Tower', tags: [7] }));
});
it('FE-PLANNER-PLACEFORM-TAGS-002: an edit starts from the tags the place carries and saves the whole set', async () => {
const user = userEvent.setup();
const onSave = vi.fn().mockResolvedValue(undefined);
const place = buildPlace({ name: 'Belem Tower', tags: [{ id: 8, name: 'Zone' }] });
render(<PlaceFormModal {...placeFormProps} place={place} onSave={onSave} />);
expect(tagSwitch('Zone')).toHaveAttribute('aria-pressed', 'true');
await user.click(tagSwitch('Monument'));
await user.click(tagSwitch('Zone'));
await user.click(screen.getByRole('button', { name: /^Update$/i }));
await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
expect(onSave).toHaveBeenCalledWith(expect.objectContaining({ tags: [7] }));
});
it('FE-PLANNER-PLACEFORM-TAGS-003: an edit that never touched the tags leaves them out of the save', async () => {
const user = userEvent.setup();
const onSave = vi.fn().mockResolvedValue(undefined);
const place = buildPlace({ name: 'Belem Tower', tags: [{ id: 8, name: 'Zone' }] });
render(<PlaceFormModal {...placeFormProps} place={place} onSave={onSave} />);
await user.click(screen.getByRole('button', { name: /^Update$/i }));
await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
expect(onSave.mock.calls[0][0]).not.toHaveProperty('tags');
});
it('FE-PLANNER-PLACEFORM-TAGS-004: a name typed into the tag field becomes a tag of the trip, ticked, without saving the place', async () => {
const user = userEvent.setup();
const onSave = vi.fn().mockResolvedValue(undefined);
let sent: unknown;
server.use(
http.post('/api/trips/1/tags', async ({ request }) => {
sent = await request.json();
return HttpResponse.json({ tag: buildTag({ id: 9, trip_id: 1, name: 'Viewpoint' }) }, { status: 201 });
})
);
render(<PlaceFormModal {...placeFormProps} onSave={onSave} />);
const field = screen.getByRole('textbox', { name: 'New tag' });
expect(screen.getByRole('button', { name: 'Add tag' })).toBeDisabled();
await user.type(field, 'Viewpoint{Enter}');
// The tag reaches the trip first and is ticked a beat later, so wait for the tick itself.
await waitFor(() => expect(tagSwitch('Viewpoint')).toHaveAttribute('aria-pressed', 'true'));
expect(sent).toMatchObject({ name: 'Viewpoint' });
expect(field).toHaveValue('');
expect(useTripStore.getState().tripTags.map((tag) => tag.name)).toEqual(['Monument', 'Viewpoint', 'Zone']);
expect(onSave).not.toHaveBeenCalled();
});
});
@@ -66,7 +66,7 @@ describe('PlaceFormModal', () => {
it('FE-COMP-PLACEFORM-005: shows Description field', () => {
render(<PlaceFormModal {...defaultProps} />);
expect(screen.getByPlaceholderText(/Short description/i)).toBeInTheDocument();
expect(screen.getByLabelText('Description')).toBeInTheDocument();
});
it('FE-COMP-PLACEFORM-006: shows Address field', () => {
@@ -1486,8 +1486,9 @@ describe('PlaceFormModal', () => {
render(<PlaceFormModal {...defaultProps} onSave={onSave} categories={[cat]} />);
await user.type(screen.getByPlaceholderText(/e\.g\. Eiffel Tower/i), 'Louvre');
await user.type(screen.getByPlaceholderText(/Short description/i), 'Glass pyramid');
await user.type(screen.getByPlaceholderText(/Personal notes/i), 'Book ahead');
await user.type(screen.getByLabelText('Description'), 'Glass pyramid');
await user.click(within(screen.getByRole('group', { name: 'Text to edit' })).getByRole('button', { name: 'Notes' }));
await user.type(screen.getByLabelText('Notes'), 'Book ahead');
await user.type(screen.getByPlaceholderText(/Street, City, Country/i), 'Rue de Rivoli');
await user.type(screen.getByPlaceholderText(/Longitude/i), '2.3376');
await user.type(screen.getByPlaceholderText('https://...'), 'https://louvre.fr');
@@ -2438,16 +2439,13 @@ describe('PlaceFormModal on the dialog frame', () => {
// The icon button beside it carries the same name.
expect(within(screen.getByPlaceholderText('Search places...').closest('.flex') as HTMLElement).getByRole('button', { name: 'Search' })).toBeInTheDocument();
expect(screen.getByLabelText('Name *')).toHaveValue('Louvre');
expect(screen.getByLabelText('Description')).toBe(screen.getByPlaceholderText(/Short description/i));
expect(screen.getByLabelText('Notes')).toBe(screen.getByPlaceholderText(/Personal notes/i));
expect(screen.getByLabelText('Address')).toBe(screen.getByPlaceholderText(/Street, City, Country/i));
expect(screen.getByLabelText('Notes for this day')).toBeInTheDocument();
expect(screen.getByLabelText('Website')).toBe(screen.getByPlaceholderText('https://...'));
const coords = screen.getByRole('group', { name: 'Coordinates' });
expect(within(coords).getByPlaceholderText(/Latitude/i)).toBeInTheDocument();
expect(within(coords).getByPlaceholderText(/Longitude/i)).toBeInTheDocument();
// Each Markdown field keeps its own formatting bar.
expect(screen.getAllByRole('toolbar')).toHaveLength(2);
expect(screen.getAllByRole('toolbar', { hidden: true })).toHaveLength(2);
});
it('FE-PLANNER-PLACEFORM-105: the new category field takes the focus when it opens', async () => {
@@ -2683,10 +2681,10 @@ describe('PlaceFormModal in the look of the booking editors', () => {
it('FE-PLANNER-PLACEFORM-120: the formatting bars show their names in the shared tooltip, never the native one', async () => {
const user = userEvent.setup();
render(<PlaceFormModal {...defaultProps} />);
const bars = screen.getAllByRole('toolbar');
const bars = screen.getAllByRole('toolbar', { hidden: true });
expect(bars).toHaveLength(2);
for (const bar of bars) {
for (const button of within(bar).getAllByRole('button')) expect(button).not.toHaveAttribute('title');
for (const b of within(bar).getAllByRole('button', { hidden: true })) expect(b).not.toHaveAttribute('title');
}
await user.hover(within(bars[0]).getByRole('button', { name: 'Bold' }));
expect(await screen.findByRole('tooltip')).toHaveTextContent('Bold');
@@ -2746,6 +2744,7 @@ describe('PlaceFormModal and the columns beside it', () => {
const assignment = buildAssignment({ id: 123, day_id: 5, place, notes: 'Old note' });
render(<PlaceFormModal {...defaultProps} onSave={onSave} place={place} assignmentId={123} dayAssignments={[assignment]} />);
await user.click(within(screen.getByRole('group', { name: 'Text to edit' })).getByRole('button', { name: /day/i }));
const notes = screen.getByRole('textbox', { name: 'Notes for this day' });
expect(notes).toHaveValue('Old note');
await user.clear(notes);
@@ -1,6 +1,5 @@
import { useState, useEffect, useRef, useMemo, useCallback, useId, type ReactNode } from 'react'
import type { PlaceClientOrigin, RoadtripStopType, TourListItem } from '@trek/shared'
import NoteFormatToolbar from '../shared/NoteFormatToolbar'
import { useAuthStore } from '../../store/authStore'
import { useAddonStore } from '../../store/addonStore'
import { useCanDo } from '../../store/permissionsStore'
@@ -23,6 +22,9 @@ import {
prefillForm, savedCategoryId, type PlaceFormData, type PlacePrefill,
} from './PlaceFormModal.helpers'
import { useNewCategory, usePlaceForm } from './usePlaceForm'
import { usePlaceTags } from './usePlaceTags'
import { PlaceFormTags } from './PlaceFormTags'
import { PlaceFormTexts } from './PlaceFormTexts'
import { usePlaceSearch } from './usePlaceSearch'
import { guessCategoryId } from '@trek/shared'
import { offersGoogleRetry } from '../../utils/placeSource'
@@ -37,9 +39,9 @@ import { DEFAULT_SERVICE_KIND, serviceStopChoice, type ServiceStopMode } from '.
import { STOP_KIND_BY_KEY } from '../Roadtrip/stopKinds'
import { getCategoryIcon } from '../shared/categoryIcons'
import {
DialogShell, DialogHeader, DialogTile, DialogSection, DialogFooter, FooterSpacer, DialogButton, NEUTRAL_TINT, fs,
DialogShell, DialogHeader, DialogTile, DialogFooter, FooterSpacer, DialogButton, NEUTRAL_TINT, fs,
} from '../shared/DialogShell'
import { EditorField, GRID_2, INPUT, LABEL, PANEL, TEXTAREA } from '../shared/dialogParts'
import { EditorField, GRID_2, INPUT, LABEL, PANEL } from '../shared/dialogParts'
import { SoftPill, tintOf } from './planParts'
import { TimeSection } from './PlaceFormTimeSection'
import { HeaderPills } from './PlaceFormHeaderPills'
@@ -128,6 +130,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
const image = usePlaceImageField({
place, imageUrl: form.image_url, pendingImage, canUploadFiles, stageUpload, stageAttached, removeImage,
})
const tagField = usePlaceTags({ tripId, place, tags: form.tags, setForm, t, toast })
// The index the picked place came from, as its row named it, shown as a pill
// in the head band. Null for a place typed by hand or taken from the saved list.
const [pickedSource, setPickedSource] = useState<string | null>(null)
@@ -220,6 +223,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
}, [place, prefillCoords, isOpen, assignmentId])
const places = useTripStore((s) => s.places)
const tripDays = useTripStore((s) => s.days)
// Where the trip is happening — the hint that tells the search which of a
// thousand identically named places is meant. Autocomplete wants a box, the
// search wants a point; both are derived from the same places.
@@ -403,6 +407,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
categories,
assignmentId,
dayAssignments,
dayNumber: dayNumberOf(assignmentId, dayAssignments, tripDays),
isMobile,
collectionsEnabled,
form,
@@ -451,6 +456,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
handlePaste,
pickImage,
image,
tagField,
adoptDescription,
hasTimeError,
handleSubmit,
@@ -792,13 +798,15 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
</div>
)}
{/* Extra labels next to the one category, to filter the places by. Not for a
stop on a drive, which is not an activity anyone looks up by its tags. */}
{!serviceStop && <PlaceFormTags tags={S.tagField} t={t} />}
{/* The day in context: its times and its own note. Both live on the
day-assignment, not on the pool place (#2163), so they are only shown
when a single assignment is in context (itinerary edit, or a
single-assignment pool edit). Hidden when creating, and for unassigned
or multi-day pool edits where a single time is ambiguous and would not
persist. */}
{/* The day in context: its times. They live on the day-assignment, not on
the pool place (#2163), so they are only shown when a single assignment
is in context (itinerary edit, or a single-assignment pool edit). Hidden
when creating, and for unassigned or multi-day pool edits where a single
time is ambiguous and would not persist. */}
{!!(place && S.assignmentId) && (
<div className={PANEL}>
<TimeSection
@@ -811,39 +819,25 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
tour={props.tour}
t={t}
/>
<EditorField label={t('places.assignmentNotes')} htmlFor={`${fieldId}-day-notes`}>
<textarea
id={`${fieldId}-day-notes`}
value={form.assignment_notes ?? ''}
onChange={e => handleChange('assignment_notes', e.target.value)}
rows={2}
placeholder={t('places.assignmentNotesPlaceholder')}
className={`${TEXTAREA} resize-y`}
/>
</EditorField>
</div>
)}
<MarkdownField
id={`${fieldId}-description`}
label={t('places.formDescription')}
value={form.description}
onChange={v => handleChange('description', v)}
placeholder={t('places.formDescriptionPlaceholder')}
{/* Description, notes and the note for this day, one at a time. The day
note follows the times: only with a single assignment in context. */}
<PlaceFormTexts
fieldId={fieldId}
description={form.description}
notes={form.notes}
dayNotes={place && S.assignmentId ? (form.assignment_notes ?? "") : null}
dayNumber={S.dayNumber}
onChange={(field, value) => handleChange(field, value)}
t={t}
/>
{/* Notes — Markdown, same as the description, and rendered as such in the
inspector. The bar is how anyone finds that out. */}
<MarkdownField
id={`${fieldId}-notes`}
label={t('places.formNotes')}
value={form.notes}
onChange={v => handleChange('notes', v)}
placeholder={t('places.formNotesPlaceholder')}
maxLength={2000}
/>
{!showDetails && <div className={PANEL}><PlaceImageSection image={S.image} onPickUrl={S.pickImage} t={t} /></div>}
{!showDetails && <PlaceImageSection image={S.image} onPickUrl={S.pickImage} t={t} />}
{/* Link, files and how to reach the place, in one card. */}
<div className={PANEL}>
{/* The link and the files side by side, as on a booking. */}
<div className={canUploadFiles ? GRID_2 : ''}>
<EditorField label={t('places.formWebsite')} htmlFor={`${fieldId}-website`}>
@@ -877,6 +871,7 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
suggestedHours={S.detailsHours}
onChange={(field, value, origin) => handleChange(field, value, origin)}
/>
</div>
{/* Costs — create / view the expense linked to this place (#1298).
Same block, same flow as a booking: save first, then the editor.
@@ -884,6 +879,7 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
Never for a stop on a drive: a petrol stop is not an activity with a budget
line, and the fuel it buys is an expense of the trip rather than of a place. */}
{S.isBudgetEnabled && !serviceStop && (
<div className={PANEL}>
<BookingCostsSection
placeId={place?.id ?? null}
reservationId={null}
@@ -895,6 +891,7 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
customTooltips
whiteButtons
/>
</div>
)}
</form>
{twoColumn && (
@@ -905,32 +902,9 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
)
}
/** A Markdown field: its label, the formatting bar on the same line, the text under both. */
function MarkdownField({ id, label, value, onChange, placeholder, maxLength }: {
id: string
label: string
value: string
onChange: (value: string) => void
placeholder: string
maxLength?: number
}) {
const ref = useRef<HTMLTextAreaElement | null>(null)
return (
<DialogSection
className="min-w-0"
label={<label htmlFor={id}>{label}</label>}
action={<NoteFormatToolbar textareaRef={ref} onChange={onChange} compact customTooltips />}
>
<textarea
id={id}
ref={ref}
value={value}
onChange={e => onChange(e.target.value)}
rows={3}
maxLength={maxLength}
placeholder={placeholder}
className={`${TEXTAREA} resize-y`}
/>
</DialogSection>
)
/** The number of the day the edited visit is on, for the day note's tab; null when it is not known. */
function dayNumberOf(assignmentId: number | null, visits: Assignment[], days: { id: number; day_number?: number | null }[]): number | null {
if (!assignmentId) return null
const dayId = visits.find(visit => visit.id === assignmentId)?.day_id
return days.find(day => day.id === dayId)?.day_number ?? null
}
@@ -0,0 +1,115 @@
// FE-PLANNER-PLFORMTAGS-001 to FE-PLANNER-PLFORMTAGS-007: the markup of the place form's tags
// on the desktop. The state behind it is usePlaceTags', tested on its own.
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, within } from '../../../tests/helpers/render';
import { PlaceFormTags } from './PlaceFormTags';
import type { PlaceTagsField } from './usePlaceTags';
const t = (key: string) => key;
function field(overrides: Partial<PlaceTagsField> = {}): PlaceTagsField {
return {
options: [
{ id: 7, name: 'Monument', color: '#6366f1', on: true },
{ id: 8, name: 'Zone', on: false },
],
toggle: vi.fn(),
name: '',
setName: vi.fn(),
newColor: '#ec4899',
setNewColor: vi.fn(),
recolor: vi.fn(() => Promise.resolve()),
saving: false,
canAdd: false,
addNew: vi.fn(() => Promise.resolve()),
handleNameKey: vi.fn(),
...overrides,
};
}
describe('PlaceFormTags', () => {
it('FE-PLANNER-PLFORMTAGS-001: shows every tag on offer as a switch that says whether it is on', () => {
render(<PlaceFormTags tags={field()} t={t} />);
const group = screen.getByRole('group', { name: 'places.tags' });
expect(within(group).getByRole('button', { name: 'Monument' })).toHaveAttribute('aria-pressed', 'true');
expect(within(group).getByRole('button', { name: 'Zone' })).toHaveAttribute('aria-pressed', 'false');
});
it('FE-PLANNER-PLFORMTAGS-002: a click on a tag switches that tag', () => {
const tags = field();
render(<PlaceFormTags tags={tags} t={t} />);
fireEvent.click(screen.getByRole('button', { name: 'Zone' }));
expect(tags.toggle).toHaveBeenCalledTimes(1);
expect(tags.toggle).toHaveBeenCalledWith(8);
});
it('FE-PLANNER-PLFORMTAGS-003: the name of a new tag is typed into the field, whose keys go to the hook', () => {
const tags = field({ name: 'View' });
render(<PlaceFormTags tags={tags} t={t} />);
const input = screen.getByRole('textbox', { name: 'places.newTag' });
expect(input).toHaveValue('View');
expect(input).toHaveAttribute('maxlength', '50');
fireEvent.change(input, { target: { value: 'Viewpoint' } });
expect(tags.setName).toHaveBeenCalledWith('Viewpoint');
fireEvent.keyDown(input, { key: 'Enter' });
expect(tags.handleNameKey).toHaveBeenCalledTimes(1);
});
it('FE-PLANNER-PLFORMTAGS-004: the add button waits for a name, then adds the tag; a trip without tags shows the field alone', () => {
const idle = field({ options: [] });
const { unmount } = render(<PlaceFormTags tags={idle} t={t} />);
expect(screen.getByRole('button', { name: 'places.addTag' })).toBeDisabled();
expect(within(screen.getByRole('group', { name: 'places.tags' })).getAllByRole('button')).toHaveLength(2);
unmount();
const ready = field({ name: 'Viewpoint', canAdd: true });
render(<PlaceFormTags tags={ready} t={t} />);
fireEvent.click(screen.getByRole('button', { name: 'places.addTag' }));
expect(ready.addNew).toHaveBeenCalledTimes(1);
});
it("FE-PLANNER-PLFORMTAGS-005: a tag's dot opens the palette, and a swatch recolours the tag and closes it", () => {
const tags = field();
render(<PlaceFormTags tags={tags} t={t} />);
// The mock t ignores the name, so the first dot is Monument's.
const dot = screen.getAllByRole('button', { name: 'places.tagColor' })[0];
expect(screen.queryByRole('button', { name: '#10b981' })).not.toBeInTheDocument();
fireEvent.click(dot);
expect(dot).toHaveAttribute('aria-expanded', 'true');
// The tag's own colour is the one marked.
expect(screen.getByRole('button', { name: '#6366f1' })).toHaveAttribute('aria-pressed', 'true');
fireEvent.click(screen.getByRole('button', { name: '#10b981' }));
expect(tags.recolor).toHaveBeenCalledWith(7, '#10b981');
expect(screen.queryByRole('button', { name: '#10b981' })).not.toBeInTheDocument();
});
it("FE-PLANNER-PLFORMTAGS-006: the new tag's colour is picked the same way and tints the field once a name is typed", () => {
const tags = field({ name: 'Food' });
render(<PlaceFormTags tags={tags} t={t} />);
fireEvent.click(screen.getByRole('button', { name: 'places.newTagColor' }));
fireEvent.click(screen.getByRole('button', { name: '#f97316' }));
expect(tags.setNewColor).toHaveBeenCalledWith('#f97316');
expect(tags.recolor).not.toHaveBeenCalled();
const pill = screen.getByRole('textbox', { name: 'places.newTag' }).parentElement as HTMLElement;
expect(pill.style.background).toContain('#ec4899');
});
it('FE-PLANNER-PLFORMTAGS-007: Escape and a click outside close the palette without a pick', () => {
const tags = field();
render(<PlaceFormTags tags={tags} t={t} />);
const onDialogKey = vi.fn();
document.addEventListener('keydown', onDialogKey);
fireEvent.click(screen.getByRole('button', { name: 'places.newTagColor' }));
fireEvent.keyDown(screen.getByRole('button', { name: '#f97316' }), { key: 'Escape' });
expect(screen.queryByRole('button', { name: '#f97316' })).not.toBeInTheDocument();
// Escape stays in the palette and does not reach the dialog around it.
expect(onDialogKey).not.toHaveBeenCalled();
document.removeEventListener('keydown', onDialogKey);
fireEvent.click(screen.getByRole('button', { name: 'places.newTagColor' }));
fireEvent.pointerDown(document.body);
expect(screen.queryByRole('button', { name: '#f97316' })).not.toBeInTheDocument();
expect(tags.setNewColor).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,151 @@
import { TRIP_TAG_NAME_MAX } from '@trek/shared';
import { Check, Plus } from 'lucide-react';
import { useState } from 'react';
import { DialogSection, fs } from '../shared/DialogShell';
import { PANEL } from '../shared/dialogParts';
import { TagColorPopover } from './TagColorPopover';
import type { PlaceTagsField } from './usePlaceTags';
type Translate = (key: string, params?: Record<string, string | number>) => string;
const ROW = 'flex flex-wrap items-center gap-2';
/** One tag: the colour dot and the name, two buttons in one pill. */
const PILL =
'relative inline-flex h-8 min-w-0 max-w-full items-center rounded-full border shadow-sm transition-[background-color,border-color,box-shadow] duration-150';
const PILL_OFF = 'border-edge bg-surface-input hover:border-content-faint';
const DOT_BUTTON =
'ms-1 grid h-6 w-6 flex-none place-items-center rounded-full transition-transform duration-150 hover:scale-110 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--text-primary)]';
const DOT = 'h-3.5 w-3.5 rounded-full ring-1 ring-inset ring-edge';
const NAME_BUTTON = 'inline-flex h-full min-w-0 items-center gap-1.5 rounded-e-full ps-1.5 font-medium';
/** The tick of a picked tag, in a round white badge. */
const TICK = 'me-1 grid h-5 w-5 flex-none place-items-center rounded-full bg-surface-card shadow-sm';
const NEW_TAG =
'relative inline-flex h-8 min-w-0 items-center rounded-full border pe-1 transition-[background-color,border-color,box-shadow] duration-150 focus-within:shadow-sm';
const NEW_TAG_INPUT = 'w-32 min-w-0 bg-transparent ps-1.5 text-content outline-none placeholder:text-content-faint';
const ADD_BUTTON =
'grid h-6 w-6 flex-none place-items-center rounded-full shadow-sm transition-[background-color,color,transform] duration-150 enabled:hover:scale-110 disabled:cursor-default disabled:bg-surface-tertiary disabled:text-content-faint disabled:shadow-none';
const FALLBACK_COLOR = 'var(--text-muted)';
const tint = (color: string, percent: number) => `color-mix(in srgb, ${color} ${percent}%, var(--bg-input))`;
/**
* The tags of the place form on the desktop, as a card like the search and the
* address. Every tag on offer is a pill in its own colour: the name ticks it for
* the place, the dot opens a palette that recolours it for the whole trip. The
* field after them adds a new tag, in a colour picked the same way and shown on
* the field as it is typed. The state is usePlaceTags'; this is its markup.
*/
export function PlaceFormTags({ tags, t }: { tags: PlaceTagsField; t: Translate }) {
// Which palette is open: a tag's id, 'new' for the new tag's colour, or none.
const [palette, setPalette] = useState<number | 'new' | null>(null);
// The colour a tag shows while its custom colour is being dragged, before it is kept.
const [preview, setPreview] = useState<{ id: number; color: string } | null>(null);
const typing = !!tags.name.trim();
const closePalette = () => {
setPalette(null);
setPreview(null);
};
return (
<div className={PANEL}>
<DialogSection label={t('places.tags')}>
<div role="group" aria-label={t('places.tags')} className={ROW}>
{tags.options.map((tag) => {
const color = (preview?.id === tag.id ? preview.color : tag.color) ?? FALLBACK_COLOR;
return (
<span
key={tag.id}
className={`${PILL} ${tag.on ? '' : PILL_OFF}`}
style={tag.on ? { background: tint(color, 18), borderColor: tint(color, 55) } : undefined}
>
<button
type="button"
aria-label={t('places.tagColor', { name: tag.name })}
aria-expanded={palette === tag.id}
onClick={() => (palette === tag.id ? closePalette() : setPalette(tag.id))}
className={DOT_BUTTON}
>
<span aria-hidden="true" className={DOT} style={{ background: color }} />
</button>
<button
type="button"
aria-pressed={tag.on}
onClick={() => tags.toggle(tag.id)}
className={`${NAME_BUTTON} ${tag.on ? 'pe-0 text-content' : 'pe-3 text-content-secondary hover:text-content'}`}
style={fs(12, 'body')}
>
<span className="truncate">{tag.name}</span>
{tag.on && (
<span aria-hidden="true" className={TICK}>
<Check size={11} strokeWidth={3.2} style={{ color }} />
</span>
)}
</button>
{palette === tag.id && (
<TagColorPopover
label={t('places.tagColor', { name: tag.name })}
value={tag.color ?? null}
onPick={(next) => void tags.recolor(tag.id, next)}
onPreview={(next) => setPreview({ id: tag.id, color: next })}
onClose={closePalette}
t={t}
/>
)}
</span>
);
})}
<span
className={NEW_TAG}
style={{
background: tint(tags.newColor, typing ? 14 : 6),
borderColor: tint(tags.newColor, typing ? 60 : 35),
borderStyle: typing ? 'solid' : 'dashed',
}}
>
<button
type="button"
aria-label={t('places.newTagColor')}
aria-expanded={palette === 'new'}
onClick={() => (palette === 'new' ? closePalette() : setPalette('new'))}
className={DOT_BUTTON}
>
<span aria-hidden="true" className={DOT} style={{ background: tags.newColor }} />
</button>
<input
type="text"
value={tags.name}
onChange={(e) => tags.setName(e.target.value)}
onKeyDown={tags.handleNameKey}
maxLength={TRIP_TAG_NAME_MAX}
aria-label={t('places.newTag')}
placeholder={t('places.newTag')}
className={NEW_TAG_INPUT}
style={fs(12, 'body')}
/>
<button
type="button"
onClick={() => void tags.addNew()}
disabled={!tags.canAdd}
aria-label={t('places.addTag')}
className={ADD_BUTTON}
style={tags.canAdd ? { background: tags.newColor, color: 'var(--bg-card)' } : undefined}
>
<Plus size={13} strokeWidth={2.8} />
</button>
{palette === 'new' && (
<TagColorPopover
label={t('places.newTagColor')}
value={tags.newColor}
onPick={tags.setNewColor}
onPreview={tags.setNewColor}
onClose={closePalette}
t={t}
/>
)}
</span>
</div>
</DialogSection>
</div>
);
}
@@ -0,0 +1,66 @@
// FE-PLANNER-PLFORMTEXTS-001 to FE-PLANNER-PLFORMTEXTS-004: the place form's three texts in one card.
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, within } from '../../../tests/helpers/render';
import { PlaceFormTexts } from './PlaceFormTexts';
const t = (key: string, params?: Record<string, string | number>) =>
params ? `${key}:${Object.values(params).join(',')}` : key;
function renderTexts(overrides: Partial<Parameters<typeof PlaceFormTexts>[0]> = {}) {
const onChange = vi.fn();
render(
<PlaceFormTexts
fieldId="f"
description="A tower"
notes=""
dayNotes={null}
onChange={onChange}
t={t}
{...overrides}
/>
);
return onChange;
}
const tabs = () => within(screen.getByRole('group', { name: 'places.notesKind' }));
describe('PlaceFormTexts', () => {
it('FE-PLANNER-PLFORMTEXTS-001: shows one text at a time, with the line on where it appears', () => {
renderTexts();
expect(tabs().getByRole('button', { name: 'places.notesTabAbout' })).toHaveAttribute('aria-pressed', 'true');
expect(screen.getByLabelText('places.formDescription')).toBeVisible();
expect(screen.getByLabelText('places.formNotes')).not.toBeVisible();
expect(screen.getByLabelText('places.formDescription')).toHaveAccessibleDescription('places.notesHintDescription');
fireEvent.click(tabs().getByRole('button', { name: 'places.formNotes' }));
expect(screen.getByLabelText('places.formNotes')).toBeVisible();
expect(screen.getByLabelText('places.formDescription')).not.toBeVisible();
});
it('FE-PLANNER-PLFORMTEXTS-002: each text writes its own field, and both keep their text while hidden', () => {
const onChange = renderTexts({ notes: 'Book ahead' });
fireEvent.change(screen.getByLabelText('places.formDescription'), { target: { value: 'A tall tower' } });
expect(onChange).toHaveBeenLastCalledWith('description', 'A tall tower');
expect(screen.getByLabelText('places.formNotes')).toHaveValue('Book ahead');
fireEvent.change(screen.getByLabelText('places.formNotes'), { target: { value: 'Book early' } });
expect(onChange).toHaveBeenLastCalledWith('notes', 'Book early');
});
it('FE-PLANNER-PLFORMTEXTS-003: the day tab is there only with a visit in context, named after its day', () => {
renderTexts();
expect(tabs().getAllByRole('button')).toHaveLength(2);
expect(screen.queryByLabelText('places.assignmentNotes')).not.toBeInTheDocument();
});
it('FE-PLANNER-PLFORMTEXTS-004: the day note is plain text under the tab of its day', () => {
const onChange = renderTexts({ dayNotes: 'Meet at 9', dayNumber: 3 });
const day = tabs().getByRole('button', { name: 'places.notesTabDayN:3' });
fireEvent.click(day);
const field = screen.getByLabelText('places.assignmentNotes');
expect(field).toBeVisible();
expect(field).toHaveValue('Meet at 9');
fireEvent.change(field, { target: { value: 'Meet at 10' } });
expect(onChange).toHaveBeenLastCalledWith('assignment_notes', 'Meet at 10');
});
});
@@ -0,0 +1,122 @@
import { CalendarDays, Info, StickyNote } from 'lucide-react';
import { useRef, type ReactNode } from 'react';
import { fs } from '../shared/DialogShell';
import NoteFormatToolbar from '../shared/NoteFormatToolbar';
import { PANEL, Segmented } from '../shared/dialogParts';
import { usePlaceTextTabs, type PlaceTextField } from './usePlaceTextTabs';
type Translate = (key: string, params?: Record<string, string | number>) => string;
/** The desktop draws each tab with an icon; the phone keeps to the words. */
const ICONS: Record<PlaceTextField, ReactNode> = {
description: <Info size={13} strokeWidth={2} />,
notes: <StickyNote size={13} strokeWidth={2} />,
assignment_notes: <CalendarDays size={13} strokeWidth={2} />,
};
const DOT = 'h-1.5 w-1.5 flex-none rounded-full bg-current opacity-60';
/** The field's frame, holding the text and, under it, the formatting bar, like a message composer. */
const FIELD_BOX =
'overflow-hidden rounded-[10px] border border-edge bg-surface-input focus-within:ring-2 focus-within:ring-[color:var(--text-primary)]';
const BARE_TEXTAREA =
'block w-full min-w-0 resize-y border-0 bg-transparent px-3 py-2 text-[length:calc(13px*var(--fs-scale-body,1))] leading-normal text-content outline-none placeholder:text-content-faint';
const FIELD_BAR = 'flex items-center justify-end border-t border-edge-faint px-1.5 py-0.5';
/**
* The place's three texts in one card: what the place is, notes on it, and the
* note for this day's visit. A switch on top picks the one to write; the others
* stay mounted and only hidden, so each keeps its caret and undo history, and a
* dot marks a tab that already holds text. The day tab is there only when the
* form edits one day-assignment.
*/
export function PlaceFormTexts({
fieldId,
description,
notes,
dayNotes,
dayNumber = null,
onChange,
t,
}: {
fieldId: string;
description: string;
notes: string;
/** null when no single day-assignment is in context. */
dayNotes: string | null;
/** The day that visit is on, to name the tab after it ("Only day 3"). */
dayNumber?: number | null;
onChange: (field: PlaceTextField, value: string) => void;
t: Translate;
}) {
const { tabs, shown, setActive } = usePlaceTextTabs({ description, notes, dayNotes, dayNumber, t });
const refs = {
description: useRef<HTMLTextAreaElement | null>(null),
notes: useRef<HTMLTextAreaElement | null>(null),
assignment_notes: useRef<HTMLTextAreaElement | null>(null),
};
return (
<div className={PANEL}>
<Segmented<PlaceTextField>
fill
value={shown.field}
onChange={setActive}
label={t('places.notesKind')}
options={tabs.map((tab) => ({
value: tab.field,
label: tab.value.trim() ? (
<>
{tab.label}
<span aria-hidden="true" className={DOT} />
</>
) : (
tab.label
),
icon: (
<span aria-hidden="true" className="flex">
{ICONS[tab.field]}
</span>
),
}))}
/>
{tabs.map((tab) => (
<p
key={tab.field}
id={`${fieldId}-${tab.field}-hint`}
hidden={tab.field !== shown.field}
className="m-0 -mb-1 leading-snug text-content-muted"
style={fs(11)}
>
{tab.hint}
</p>
))}
{/* The box hides, not the field: the field's own `block` class would win over `hidden`. */}
{tabs.map((tab) => (
<div key={tab.field} hidden={tab.field !== shown.field} className={FIELD_BOX}>
<textarea
id={`${fieldId}-${tab.field}`}
ref={refs[tab.field]}
aria-label={tab.aria}
aria-describedby={`${fieldId}-${tab.field}-hint`}
value={tab.value}
onChange={(e) => onChange(tab.field, e.target.value)}
rows={3}
maxLength={tab.maxLength}
className={BARE_TEXTAREA}
/>
{tab.markdown && (
<div className={FIELD_BAR}>
<NoteFormatToolbar
textareaRef={refs[tab.field]}
onChange={(v) => onChange(tab.field, v)}
compact
customTooltips
/>
</div>
)}
</div>
))}
</div>
);
}
@@ -169,7 +169,7 @@ function UploadTile({
disabled={reading}
aria-pressed={selected}
aria-label={t('places.uploadImage')}
className={`${TILE} ${ring(selected, dialog)} ${preview ? '' : 'border border-dashed border-edge bg-surface-card'}`}
className={`${TILE} ${ring(selected, dialog)} ${preview ? '' : dialog ? 'border border-edge-faint bg-surface-secondary hover:bg-surface-tertiary' : 'border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)]'}`}
onMouseEnter={() => onHover(!!preview)}
onMouseLeave={() => onHover(false)}
>
@@ -179,13 +179,15 @@ function UploadTile({
{selected && <Picked />}
</>
) : (
<span className="flex h-full w-full flex-col items-center justify-center gap-1 px-1 text-center text-caption leading-tight text-content-muted group-hover:text-content">
{reading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<ImagePlus className="h-4 w-4" strokeWidth={2} />
)}
{t('places.uploadImage')}
// Icon only: the tooltip and the button's name say what it does.
<span className="flex h-full w-full items-center justify-center">
<span className="grid h-11 w-11 place-items-center rounded-full bg-surface-card text-content-muted shadow-sm transition-transform duration-150 group-hover:scale-105 group-hover:text-content">
{reading ? (
<Loader2 className="h-5 w-5 animate-spin" />
) : (
<ImagePlus className="h-5 w-5" strokeWidth={1.9} />
)}
</span>
</span>
)}
</button>
@@ -1782,6 +1782,17 @@ describe('PlaceInspector', () => {
expect(header.textContent).not.toContain('·');
});
it('FE-PLANNER-INSPECTOR-106b: the tags of the place are pills beside its category, each once and by name', () => {
const tags = [{ id: 8, name: 'Zone', color: '#10b981' }, { id: 7, name: 'Monument' }, { id: 8, name: 'Zone' }];
render(<PlaceInspector {...defaultProps} place={{ ...place, id: 716, category_id: cat.id, tags }} />);
const header = document.querySelector('header') as HTMLElement;
const pills = ['Landmark', 'Monument', 'Zone'].map(name => within(header).getByText(name));
expect(pills[0].compareDocumentPosition(pills[1]) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(pills[1].compareDocumentPosition(pills[2]) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
// The tag's own colour is on its mark only; the pill and the marker keep theirs.
expect((pills[2].querySelector('svg') as SVGElement).style.color).toBe('rgb(16, 185, 129)');
});
it('FE-PLANNER-INSPECTOR-107: the rating block is labelled and quotes the first usable review', async () => {
vi.mocked(mapsApi.details).mockResolvedValue({
place: { rating: 4.1, reviews: [{ text: 'meh' }, { text: 'Lovely staff and view' }] },
@@ -330,7 +330,7 @@ export default function PlaceInspector({
// periods next to them, in the place's own timezone. open_now stays the fallback.
// Hours the traveller typed in win over looked-up ones (#2472): they are what
// somebody actually checked, and a place nobody listed has no other source.
const ownHours = hoursLines(place.opening_hours, locale, t('places.hoursClosed'))
const ownHours = hoursLines(place.opening_hours, locale, t('places.hoursClosed'), t('places.hoursAllDay'))
const openingHours = ownHours ?? googleDetails?.opening_hours ?? null
const detailLat = place.lat ?? googleDetails?.lat
const detailLng = place.lng ?? googleDetails?.lng
@@ -1,8 +1,20 @@
import { Banknote, ChevronDown, ChevronUp, Mail, MapPin, MapPinOff, Phone, Star, X } from 'lucide-react';
import {
Banknote,
ChevronDown,
ChevronUp,
Mail,
MapPin,
MapPinOff,
Phone,
Star,
Tag as TagIcon,
X,
} from 'lucide-react';
import type { KeyboardEvent, ReactNode, RefObject } from 'react';
import { useTranslation } from '../../i18n';
import type { Category, Place } from '../../types';
import { tagChoices } from '../../utils/placeTags';
import AssistantAskButton from '../Assistant/AssistantAskButton';
import DawarichIcon from '../shared/DawarichIcon';
import { NEUTRAL_TINT, fs } from '../shared/DialogShell';
@@ -84,9 +96,12 @@ export function InspectorHead({
const hasCoords = !!(place.lat && place.lng);
// A typed address that never got coordinates: the place has no marker, and says why (#2837).
const offMap = addressWithoutCoordinates(place);
// The extra labels of the place, beside its one category. They never reach the marker.
const tags = tagChoices(place.tags);
const hasPills =
openNow !== null ||
!!category ||
tags.length > 0 ||
!!time ||
rating != null ||
!!price ||
@@ -174,6 +189,12 @@ export function InspectorHead({
{category.name}
</span>
)}
{tags.map((tag) => (
<span key={tag.id} className={HEAD_PILL} style={fs(10.5)}>
<TagIcon size={11} strokeWidth={2} className="flex-none" style={{ color: tag.color }} />
{tag.name}
</span>
))}
{time && <TimePill>{time}</TimePill>}
{rating != null && rating > 0 && (
<span className={HEAD_PILL} style={fs(10.5)}>
@@ -20,7 +20,8 @@ const LABEL: Record<RefreshField, string> = {
/** A value as the list shows it: hours as one line per day, the rest as stored. */
function shown(field: RefreshField, value: string, locale: string | undefined, t: Translate): string[] {
if (!value) return [t('places.refresh.empty')];
if (field === 'opening_hours') return hoursLines(value, locale, t('places.hoursClosed')) ?? [value];
if (field === 'opening_hours')
return hoursLines(value, locale, t('places.hoursClosed'), t('places.hoursAllDay')) ?? [value];
return [value];
}
@@ -0,0 +1,149 @@
// FE-PLANNER-SIDEBAR-TAGS-001 to FE-PLANNER-SIDEBAR-TAGS-005: the tags in the category filter
// of the desktop places list. The predicate itself is covered in utils/placesFilter.test.ts.
import userEvent from '@testing-library/user-event';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { buildCategory, buildPlace, buildTag, buildTrip, buildUser } from '../../../tests/helpers/factories';
import { render, screen, within } from '../../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { useAuthStore } from '../../store/authStore';
import { useTripStore } from '../../store/tripStore';
import PlacesSidebar from './PlacesSidebar';
// The rows' pictures would ask the server for photos.
vi.mock('../../services/photoService', () => ({
getCached: vi.fn(() => null),
isLoading: vi.fn(() => false),
fetchPhoto: vi.fn(),
onThumbReady: vi.fn(() => () => undefined),
}));
const monument = buildTag({ id: 7, trip_id: 1, name: 'Monument', color: '#6366f1' });
const zone = buildTag({ id: 8, trip_id: 1, name: 'Zone', color: '#10b981' });
const park = buildCategory({ id: 4, name: 'Park', color: '#22c55e' });
const tower = buildPlace({
name: 'Belem Tower',
address: 'Lisbon',
category_id: 4,
tags: [{ id: 7, name: 'Monument' }],
});
const garden = buildPlace({ name: 'Estrela Garden', address: 'Lisbon', category_id: 4 });
const market = buildPlace({
name: 'Time Out Market',
address: 'Lisbon',
category_id: null,
// A traveller's personal tag, put on the place through the API: the trip does not list it.
tags: [
{ id: 8, name: 'Zone' },
{ id: 50, name: 'Hidden gem' },
],
});
const props = {
tripId: 1,
places: [tower, garden, market],
categories: [park],
assignments: {},
selectedDayId: null,
selectedPlaceId: null,
onPlaceClick: vi.fn(),
onAddPlace: vi.fn(),
onAssignToDay: vi.fn(),
onEditPlace: vi.fn(),
onDeletePlace: vi.fn(),
days: [],
isMobile: false,
};
type User = ReturnType<typeof userEvent.setup>;
const trigger = () => screen.getByRole('button', { name: 'Categories' });
async function openFilter(user: User) {
if (trigger().getAttribute('aria-expanded') !== 'true') await user.click(trigger());
}
/** What the closed filter says is in force, read from its tooltip. */
async function filterLabel(user: User) {
if (trigger().getAttribute('aria-expanded') === 'true') await user.click(trigger());
// The tip opens when the pointer comes in, so it leaves first.
await user.unhover(trigger());
await user.hover(trigger());
const text = (await screen.findByRole('tooltip')).textContent;
await user.unhover(trigger());
return text;
}
beforeEach(() => {
resetAllStores();
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true });
seedStore(useTripStore, { trip: buildTrip({ id: 1 }), tripTags: [monument, zone] });
});
describe('PlacesSidebar category filter: tags', () => {
it('FE-PLANNER-SIDEBAR-TAGS-001: lists the tags under the categories, the ones of the trip and any other a place carries', async () => {
const user = userEvent.setup();
render(<PlacesSidebar {...props} />);
await openFilter(user);
expect(screen.getByText('Tags')).toBeInTheDocument();
for (const name of ['Park', 'No Category', 'Hidden gem', 'Monument', 'Zone']) {
expect(screen.getByRole('button', { name })).toHaveAttribute('aria-pressed', 'false');
}
});
it('FE-PLANNER-SIDEBAR-TAGS-002: a ticked tag keeps the places that carry it', async () => {
const user = userEvent.setup();
render(<PlacesSidebar {...props} />);
await openFilter(user);
await user.click(screen.getByRole('button', { name: 'Monument' }));
expect(screen.getByRole('button', { name: 'Monument' })).toHaveAttribute('aria-pressed', 'true');
expect(screen.getByText('Belem Tower')).toBeInTheDocument();
expect(screen.queryByText('Estrela Garden')).not.toBeInTheDocument();
expect(screen.queryByText('Time Out Market')).not.toBeInTheDocument();
expect(useTripStore.getState().placesCategoryFilter).toEqual(new Set(['tag:7']));
expect(await filterLabel(user)).toBe('Categories: Monument');
});
it('FE-PLANNER-SIDEBAR-TAGS-003: a category and a tag ticked together both have to hold, and the filter names them', async () => {
const user = userEvent.setup();
render(<PlacesSidebar {...props} />);
await openFilter(user);
await user.click(screen.getByRole('button', { name: 'Park' }));
expect(screen.getByText('Estrela Garden')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Monument' }));
expect(screen.getByText('Belem Tower')).toBeInTheDocument();
expect(screen.queryByText('Estrela Garden')).not.toBeInTheDocument();
expect(within(trigger()).getByText('2')).toBeInTheDocument();
expect(await filterLabel(user)).toBe('Categories: Park, Monument');
});
it('FE-PLANNER-SIDEBAR-TAGS-004: clearing the filter unticks the tags as well', async () => {
const user = userEvent.setup();
render(<PlacesSidebar {...props} />);
await openFilter(user);
await user.click(screen.getByRole('button', { name: 'Zone' }));
await user.click(screen.getByRole('button', { name: 'No Category' }));
expect(screen.getByText('Time Out Market')).toBeInTheDocument();
expect(screen.queryByText('Belem Tower')).not.toBeInTheDocument();
expect(await filterLabel(user)).toBe('Categories: No Category, Zone');
await openFilter(user);
await user.click(screen.getByText('Clear filter'));
expect(useTripStore.getState().placesCategoryFilter.size).toBe(0);
expect(screen.getByText('Belem Tower')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Zone' })).toHaveAttribute('aria-pressed', 'false');
});
it('FE-PLANNER-SIDEBAR-TAGS-005: a trip with tags and no category still has the filter; with neither it has none', async () => {
const user = userEvent.setup();
const { unmount } = render(<PlacesSidebar {...props} categories={[]} />);
await openFilter(user);
expect(screen.getByRole('button', { name: 'Monument' })).toBeInTheDocument();
unmount();
seedStore(useTripStore, { tripTags: [] });
render(<PlacesSidebar {...props} categories={[]} places={[garden]} />);
expect(screen.queryByRole('button', { name: 'Categories' })).not.toBeInTheDocument();
});
});
@@ -8,9 +8,10 @@ import { Eyebrow } from './bookings/bookingParts'
import { tintOf } from './planParts'
import { CategoryTile } from './PlacesBulkCategoryModal'
import type { SidebarState } from './usePlacesSidebar'
import { placesFilterTabs } from './usePlacesPool'
import { placesFilterTabs, usePlacesFilterTags } from './usePlacesPool'
import { PLACES_SORTS, type PlacesSort } from './placesSort'
import { RATING_FLOORS, UNCATEGORIZED } from '../../utils/placesFilter'
import { RATING_FLOORS, UNCATEGORIZED, tagFilterKey } from '../../utils/placesFilter'
import type { TagChoice } from '../../utils/placeTags'
/**
* Below this the two labels stop fitting side by side and both buttons fall back
@@ -249,22 +250,31 @@ function FilterDropdown({ label, active, badge, icon, open, setOpen, name, child
)
}
/** Which categories to show, many at once; the label says what is in force. */
/**
* What the category filter says is in force: nothing, the one name, or how many
* categories. Once a tag is ticked too it is no count of categories any more, so
* the names say it.
*/
function categoryFilterLabel({ t, categories, categoryFilters }: SidebarState, tags: TagChoice[]): string {
if (categoryFilters.size === 0) return t('places.allCategories')
const tagNames = tags.filter(tag => categoryFilters.has(tagFilterKey(tag.id))).map(tag => tag.name)
if (tagNames.length === 0 && categoryFilters.size > 1) {
return `${categoryFilters.size} ${t('places.categoriesSelected', { count: categoryFilters.size })}`
}
const names = categories.filter(c => categoryFilters.has(String(c.id))).map(c => c.name)
if (categoryFilters.has(UNCATEGORIZED)) names.push(t('places.noCategory'))
return [...names, ...tagNames].join(', ') || t('places.allCategories')
}
/** Which categories and which tags to show, many at once; the label says what is in force. */
function CategoryFilter(S: SidebarState) {
const { t, places, categories, categoryFilters, setCategoryFilters, toggleCategoryFilter } = S
const [open, setOpen] = useState(false)
if (categories.length === 0) return null
let label = t('places.allCategories')
if (categoryFilters.size === 1) {
const only = categories.find(c => categoryFilters.has(String(c.id)))
if (categoryFilters.has(UNCATEGORIZED)) label = t('places.noCategory')
else if (only) label = only.name
} else if (categoryFilters.size > 1) {
label = `${categoryFilters.size} ${t('places.categoriesSelected', { count: categoryFilters.size })}`
}
const tags = usePlacesFilterTags(places)
if (categories.length === 0 && tags.length === 0) return null
return (
<FilterDropdown name={t('categories.title')} label={label} active={categoryFilters.size > 0} badge={categoryFilters.size}
icon={<Tag size={14} strokeWidth={2} />} open={open} setOpen={setOpen}>
<FilterDropdown name={t('categories.title')} label={categoryFilterLabel(S, tags)} active={categoryFilters.size > 0}
badge={categoryFilters.size} icon={<Tag size={14} strokeWidth={2} />} open={open} setOpen={setOpen}>
{categories.map(c => (
<CategoryChoice
key={c.id}
@@ -282,6 +292,21 @@ function CategoryFilter(S: SidebarState) {
label={t('places.noCategory')}
/>
)}
{/* The tags, in the same list: a place has one category and any number of these. */}
{tags.length > 0 && <Eyebrow className="px-1.5 pb-1 pt-2">{t('places.tags')}</Eyebrow>}
{tags.map(tag => (
<CategoryChoice
key={tagFilterKey(tag.id)}
on={categoryFilters.has(tagFilterKey(tag.id))}
onClick={() => toggleCategoryFilter(tagFilterKey(tag.id))}
tile={(
<span className="grid h-[22px] w-[22px] flex-none place-items-center rounded-[7px] bg-surface-tertiary text-content-faint">
<Tag size={11} strokeWidth={2.2} style={{ color: tag.color }} />
</span>
)}
label={tag.name}
/>
))}
{categoryFilters.size > 0 && (
<button type="button" onClick={() => setCategoryFilters(new Set())}
className="mt-1 flex w-full items-center gap-1.5 rounded-[9px] border-t border-edge-faint px-1.5 pb-1 pt-2 text-start font-semibold text-content-muted hover:text-content"
@@ -0,0 +1,73 @@
// FE-PLANNER-TAGCOLORFIELD-001 to FE-PLANNER-TAGCOLORFIELD-003: the custom colour of the tag palette.
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '../../../tests/helpers/render';
import { TagColorField } from './TagColorField';
const t = (key: string) => key;
function renderField(value = '#ff0000') {
const onPreview = vi.fn();
const onPick = vi.fn();
render(<TagColorField value={value} onPreview={onPreview} onPick={onPick} t={t} />);
return { onPreview, onPick };
}
describe('TagColorField', () => {
it('FE-PLANNER-TAGCOLORFIELD-001: a complete typed code is shown at once and kept on Enter; a broken one goes back', () => {
const { onPreview, onPick } = renderField();
const code = screen.getByRole('textbox', { name: 'places.tagColorHex' });
expect(code).toHaveValue('#ff0000');
fireEvent.change(code, { target: { value: '#10b9' } });
expect(onPreview).not.toHaveBeenCalled();
fireEvent.change(code, { target: { value: '10b981' } });
expect(onPreview).toHaveBeenLastCalledWith('#10b981');
fireEvent.keyDown(code, { key: 'Enter' });
expect(onPick).toHaveBeenLastCalledWith('#10b981');
fireEvent.change(code, { target: { value: 'nope' } });
fireEvent.blur(code);
expect(code).toHaveValue('#10b981');
expect(onPick).toHaveBeenCalledTimes(1);
});
it('FE-PLANNER-TAGCOLORFIELD-002: the arrow keys move the field and the hue, and keep each step', () => {
const { onPick } = renderField('#ff0000');
const field = screen.getByRole('slider', { name: 'places.tagColorCustom' });
fireEvent.keyDown(field, { key: 'ArrowDown' });
// Full red, a little darker.
expect(onPick).toHaveBeenLastCalledWith('#f50000');
const hue = screen.getByRole('slider', { name: 'places.tagColorHue' });
expect(hue).toHaveAttribute('aria-valuenow', '0');
fireEvent.keyDown(hue, { key: 'ArrowRight' });
expect(hue).toHaveAttribute('aria-valuenow', '6');
fireEvent.keyDown(hue, { key: 'Tab' });
expect(onPick).toHaveBeenCalledTimes(2);
});
it('FE-PLANNER-TAGCOLORFIELD-003: a drag shows the colour as it goes and keeps the one it ends on', () => {
const { onPreview, onPick } = renderField('#ff0000');
const field = screen.getByRole('slider', { name: 'places.tagColorCustom' });
field.getBoundingClientRect = () => ({
left: 0,
top: 0,
width: 100,
height: 100,
right: 100,
bottom: 100,
x: 0,
y: 0,
toJSON: () => ({}),
});
field.setPointerCapture = vi.fn();
field.releasePointerCapture = vi.fn();
field.hasPointerCapture = () => true;
fireEvent.pointerDown(field, { pointerId: 1, clientX: 100, clientY: 0 });
fireEvent.pointerMove(field, { pointerId: 1, clientX: 0, clientY: 0 });
expect(onPreview).toHaveBeenLastCalledWith('#ffffff');
expect(onPick).not.toHaveBeenCalled();
fireEvent.pointerUp(field, { pointerId: 1, clientX: 0, clientY: 100 });
expect(onPick).toHaveBeenCalledTimes(1);
expect(onPick).toHaveBeenLastCalledWith('#000000');
});
});
@@ -0,0 +1,172 @@
import { useState, type KeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react';
import { hexToHsv, hsvToHex, hueHex, normalizeHex, type Hsv } from '../../utils/colorSpace';
import { fs } from '../shared/DialogShell';
type Translate = (key: string, params?: Record<string, string | number>) => string;
// The hue circle as a track, and the field over the picked hue: white to the right
// into the hue, black from the bottom up. Built as strings so no colour literal sits in a style.
const HUE_TRACK = `linear-gradient(to right, ${[0, 60, 120, 180, 240, 300, 360].map(hueHex).join(', ')})`;
const fieldBackground = (h: number) =>
`linear-gradient(to top, ${hsvToHex({ h: 0, s: 0, v: 0 })}, transparent), linear-gradient(to right, ${hsvToHex({ h: 0, s: 0, v: 1 })}, ${hueHex(h)})`;
const THUMB =
'pointer-events-none absolute h-4 w-4 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-surface-card shadow-md';
const KEY_STEP = 0.04;
const clamp = (n: number) => Math.min(1, Math.max(0, n));
/** Where a pointer is inside an element, as 0 to 1 across and down. */
function at(e: ReactPointerEvent<HTMLElement>): { x: number; y: number } {
const box = e.currentTarget.getBoundingClientRect();
return { x: clamp((e.clientX - box.left) / box.width), y: clamp((e.clientY - box.top) / box.height) };
}
/**
* The custom colour of the tag palette: a field for saturation and brightness,
* a slider for the hue and the hex code to type. Dragging shows the colour as it
* goes (onPreview); it is kept when the pointer lets go, or when a typed code is
* complete (onPick), so a drag sends one change and not one per pixel.
*/
export function TagColorField({
value,
onPreview,
onPick,
t,
}: {
value: string;
onPreview: (hex: string) => void;
onPick: (hex: string) => void;
t: Translate;
}) {
const [hsv, setHsv] = useState<Hsv>(() => hexToHsv(value));
const [typed, setTyped] = useState(value);
const hex = hsvToHex(hsv);
const show = (next: Hsv) => {
setHsv(next);
const nextHex = hsvToHex(next);
setTyped(nextHex);
onPreview(nextHex);
};
const drag = (read: (e: ReactPointerEvent<HTMLElement>) => Hsv) => ({
onPointerDown: (e: ReactPointerEvent<HTMLElement>) => {
e.currentTarget.setPointerCapture(e.pointerId);
show(read(e));
},
onPointerMove: (e: ReactPointerEvent<HTMLElement>) => {
if (e.currentTarget.hasPointerCapture(e.pointerId)) show(read(e));
},
onPointerUp: (e: ReactPointerEvent<HTMLElement>) => {
e.currentTarget.releasePointerCapture(e.pointerId);
onPick(hsvToHex(read(e)));
},
});
// The arrow keys move the field's point and the slider, and keep the colour at once.
const nudge = (patch: (cur: Hsv) => Hsv) => (e: KeyboardEvent<HTMLElement>) => {
const step = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: 1, ArrowDown: -1 }[e.key];
if (step === undefined) return;
e.preventDefault();
const next = patch({
...hsv,
...(e.key === 'ArrowUp' || e.key === 'ArrowDown'
? { v: clamp(hsv.v + step * KEY_STEP) }
: { s: clamp(hsv.s + step * KEY_STEP) }),
});
show(next);
onPick(hsvToHex(next));
};
const typeHex = (raw: string) => {
setTyped(raw);
const norm = normalizeHex(raw);
if (!norm) return;
setHsv(hexToHsv(norm));
onPreview(norm);
};
const keepTyped = () => {
const norm = normalizeHex(typed);
if (norm) onPick(norm);
else setTyped(hex);
};
return (
<div className="flex w-full flex-col gap-2.5">
<div
role="slider"
// The gradient runs left to right in every language; so does the pick on it.
dir="ltr"
tabIndex={0}
aria-label={t('places.tagColorCustom')}
aria-valuetext={hex}
aria-valuenow={Math.round(hsv.s * 100)}
aria-valuemin={0}
aria-valuemax={100}
className="relative h-28 cursor-crosshair touch-none rounded-[10px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--text-primary)]"
style={{ background: fieldBackground(hsv.h) }}
onKeyDown={nudge((next) => next)}
{...drag((e) => {
const p = at(e);
return { h: hsv.h, s: p.x, v: 1 - p.y };
})}
>
<span
className={THUMB}
style={{ insetInlineStart: `${hsv.s * 100}%`, top: `${(1 - hsv.v) * 100}%`, background: hex }}
/>
</div>
<div
role="slider"
// The gradient runs left to right in every language; so does the pick on it.
dir="ltr"
tabIndex={0}
aria-label={t('places.tagColorHue')}
aria-valuenow={Math.round(hsv.h)}
aria-valuemin={0}
aria-valuemax={360}
className="relative h-3 cursor-pointer touch-none rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--text-primary)]"
style={{ background: HUE_TRACK }}
onKeyDown={(e) => {
const step = { ArrowLeft: -6, ArrowRight: 6 }[e.key];
if (step === undefined) return;
e.preventDefault();
const next = { ...hsv, h: (hsv.h + step + 360) % 360 };
show(next);
onPick(hsvToHex(next));
}}
{...drag((e) => ({ ...hsv, h: at(e).x * 359.9 }))}
>
<span
className={`${THUMB} top-1/2`}
style={{ insetInlineStart: `${(hsv.h / 360) * 100}%`, background: hueHex(hsv.h) }}
/>
</div>
<div className="flex items-center gap-2">
<span
aria-hidden="true"
className="h-7 w-7 flex-none rounded-full ring-1 ring-inset ring-edge"
style={{ background: hex }}
/>
<input
type="text"
value={typed}
onChange={(e) => typeHex(e.target.value)}
onBlur={keepTyped}
onKeyDown={(e) => {
if (e.key !== 'Enter') return;
e.preventDefault();
keepTyped();
}}
maxLength={7}
spellCheck={false}
aria-label={t('places.tagColorHex')}
className="h-7 min-w-0 flex-1 rounded-[8px] border border-edge bg-surface-input px-2 font-mono uppercase text-content outline-none focus:border-content-faint"
style={fs(12, 'body')}
/>
</div>
</div>
);
}
@@ -0,0 +1,131 @@
import { Check, ChevronDown } from 'lucide-react';
import { useEffect, useRef, useState, type KeyboardEvent } from 'react';
import { TAG_COLORS } from '../../utils/placeTags';
import { fs } from '../shared/DialogShell';
import { TagColorField } from './TagColorField';
type Translate = (key: string, params?: Record<string, string | number>) => string;
const PANEL =
'absolute start-0 top-full z-20 mt-2 flex w-[240px] flex-col gap-2.5 rounded-[16px] border border-edge-faint bg-surface-card p-3 shadow-lg';
const SWATCH =
'grid h-8 w-8 place-items-center rounded-full ring-1 ring-inset ring-edge transition-transform duration-150 hover:scale-110 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[color:var(--text-primary)]';
/** The tick on the picked swatch, in a white badge like the tick on a picked tag. */
const TICK = 'grid h-4 w-4 place-items-center rounded-full bg-surface-card shadow-sm';
const CUSTOM_TOGGLE =
'flex items-center gap-2 rounded-[10px] px-1.5 py-1 font-semibold text-content-secondary transition-colors hover:bg-surface-hover hover:text-content';
/** The custom colour's mark: every colour of the palette round the wheel. */
const RAINBOW = `conic-gradient(${[...TAG_COLORS, TAG_COLORS[0]].join(', ')})`;
/**
* The palette under a tag's colour dot: the trip's colours as swatches, and
* under them a colour of one's own in TREK's own colour field. A swatch is kept
* at once and closes the palette; the field keeps its colour when a drag ends
* and stays open. Closes on a click outside or Escape, which stays here and does
* not close the dialog around it.
*/
export function TagColorPopover({
label,
value,
onPick,
onPreview,
onClose,
className = PANEL,
t,
}: {
/** What the palette colours, for its accessible name. */
label: string;
value: string | null;
onPick: (color: string) => void;
/** The colour while it is being dragged, for whoever can show it before it is kept. */
onPreview?: (color: string) => void;
onClose: () => void;
/** The frame: a floating card by default; the phone lays it into the sheet instead. */
className?: string;
t: Translate;
}) {
const ref = useRef<HTMLDivElement | null>(null);
const current = value?.toLowerCase() ?? null;
const isPreset = current !== null && TAG_COLORS.includes(current);
// A colour of its own opens with the field showing it.
const [custom, setCustom] = useState(current !== null && !isPreset);
// The latest close handler, so the listener below is set up once.
const close = useRef(onClose);
useEffect(() => {
close.current = onClose;
});
useEffect(() => {
const outside = (e: PointerEvent) => {
// The dot that opened it toggles it itself; a click there is not "outside".
const host = ref.current?.parentElement;
if (host && !host.contains(e.target as Node)) close.current();
};
document.addEventListener('pointerdown', outside);
return () => document.removeEventListener('pointerdown', outside);
}, []);
const pick = (color: string) => {
onPick(color);
onClose();
};
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
if (e.key !== 'Escape') return;
e.stopPropagation();
onClose();
};
return (
<div ref={ref} role="group" aria-label={label} className={className} onKeyDown={onKeyDown}>
<div className="grid grid-cols-5 justify-items-center gap-y-2">
{TAG_COLORS.map((color) => {
const on = current === color;
return (
<button
key={color}
type="button"
aria-label={color}
aria-pressed={on}
onClick={() => pick(color)}
className={SWATCH}
style={{ background: color }}
>
{on && (
<span className={TICK}>
<Check size={10} strokeWidth={3.4} aria-hidden="true" style={{ color }} />
</span>
)}
</button>
);
})}
</div>
<div className="h-px bg-[var(--border-faint)]" />
<button
type="button"
aria-expanded={custom}
onClick={() => setCustom(!custom)}
className={CUSTOM_TOGGLE}
style={fs(12, 'body')}
>
<span
aria-hidden="true"
className="grid h-5 w-5 place-items-center rounded-full"
style={{ background: RAINBOW }}
>
{current !== null && !isPreset && <span className="h-2 w-2 rounded-full bg-surface-card" />}
</span>
{t('places.tagColorCustom')}
<ChevronDown
size={14}
strokeWidth={2.2}
aria-hidden="true"
className={`ms-auto transition-transform ${custom ? 'rotate-180' : ''}`}
/>
</button>
{custom && (
<TagColorField value={value ?? TAG_COLORS[0]} onPreview={(hex) => onPreview?.(hex)} onPick={onPick} t={t} />
)}
</div>
);
}
@@ -357,7 +357,7 @@ describe('TransitSearchPanel', () => {
await user.click(fromInput)
const picks = (await screen.findAllByRole('button', { name: /Hotel Adlon|Stop \d|Hostel/ })).map(b => b.textContent)
expect(picks[0]).toBe('Hotel Adlon')
expect(picks.slice(1)).toEqual(['Stop 1', 'Stop 2', 'Stop 3', 'Stop 4', 'Stop 5', 'Stop 6', 'Stop 7', 'Stop 8'])
expect(picks.slice(1)).toEqual([...places.map(p => p.name), 'Later Hostel'])
await user.click(screen.getByRole('button', { name: 'Hotel Adlon' }))
expect(fromInput).toHaveValue('Hotel Adlon')
@@ -744,7 +744,7 @@ describe('quick picks from the bookings of the day (#1506)', () => {
const places = Array.from({ length: 12 }, (_, i) => buildPlace({ id: 100 + i, name: `P${i}`, lat: 52 + i / 100, lng: 13 }))
const picks = buildQuickPicks(day, [day], places as any, [], dayBookingStops(day, [flight] as any))
expect(picks.slice(0, 2).map(p => p.name)).toEqual(['FRA', 'BER Airport'])
expect(picks).toHaveLength(2 + 8)
expect(picks).toHaveLength(2 + places.length)
})
})
@@ -8,7 +8,8 @@ import { transitApi } from '../../api/client'
import { useSettingsStore } from '../../store/settingsStore'
import { useToast } from '../shared/Toast'
import { useTranslation } from '../../i18n'
import { getDayBookendHotels } from '../../utils/dayOrder'
import { getDayBookendHotels, isDayInAccommodationRange } from '../../utils/dayOrder'
import { orderTransitStaysByDate } from './transitStayOrder'
import type { Day, Place, Accommodation, Reservation } from '../../types'
import { useTripStore } from '../../store/tripStore'
import { isCarrierTransport } from '../../utils/dayMerge'
@@ -110,7 +111,11 @@ function fmtDuration(seconds: number, t: (k: string, p?: Record<string, string |
// ── quick picks ──────────────────────────────────────────────────────────────
const MAX_QUICK_PICKS = 8
const MAX_OTHER_DAY_STAYS = 8
function pickedPlaceKey(p: PickedPlace): string {
return JSON.stringify([p.name.trim().toLowerCase(), p.lat, p.lng])
}
function stayPick(a: Accommodation): PickedPlace | null {
return a.place_lat != null && a.place_lng != null && a.place_name ? { name: a.place_name, lat: a.place_lat, lng: a.place_lng } : null
@@ -143,28 +148,30 @@ export function dayBookingStops(day: Pick<Day, 'id' | 'date'>, reservations: Res
* starts in and the one it ends in come first and are never cut, since most
* connections of a day begin or end there (#2538); the day's airports and
* stations follow and are not cut either (#1506); then the day's own located
* places and the trip's other stays, up to MAX_QUICK_PICKS.
* places and remaining stays covering the day, without a limit. Only stays
* outside the selected day's range are capped, nearest in nights first.
*/
export function buildQuickPicks(day: Day, days: Day[], places: Place[], accommodations: Accommodation[], bookingStops: PickedPlace[] = []): PickedPlace[] {
const { morning, evening } = getDayBookendHotels(day, days, accommodations)
const dayStays = [morning, evening].filter((a): a is Accommodation => a != null)
const bookendStays = [morning, evening].filter((a): a is Accommodation => a != null)
const dayStays = accommodations.filter(a => isDayInAccommodationRange(day, a.start_day_id, a.end_day_id, days))
const seen = new Set<string>()
const unique = (p: PickedPlace | null): p is PickedPlace => {
if (!p) return false
const k = `${p.name}:${p.lat}`
const k = pickedPlaceKey(p)
if (seen.has(k)) return false
seen.add(k)
return true
}
const stays = dayStays.map(stayPick).filter(unique)
const stays = bookendStays.map(stayPick).filter(unique)
const stations = bookingStops.filter(unique)
const rest = [
...places.map(p => (p.lat != null && p.lng != null ? { name: p.name, lat: p.lat, lng: p.lng } : null)),
...accommodations.filter(a => !dayStays.includes(a)).map(stayPick),
].filter(unique)
return [...stays, ...stations, ...rest.slice(0, MAX_QUICK_PICKS)]
const dayPlaces = places.map(p => (p.lat != null && p.lng != null ? { name: p.name, lat: p.lat, lng: p.lng } : null)).filter(unique)
const remainingDayStays = dayStays.map(stayPick).filter(unique)
const otherStays = orderTransitStaysByDate(day, days, accommodations.filter(a => !dayStays.includes(a)))
.map(stayPick).filter(unique).slice(0, MAX_OTHER_DAY_STAYS)
return [...stays, ...stations, ...dayPlaces, ...remainingDayStays, ...otherStays]
}
// ── from/to stop picker ──────────────────────────────────────────────────────
@@ -221,6 +228,8 @@ function StopPicker({ label, value, onPick, quickPicks, near, placeholder }: {
const [results, setResults] = useState<TransitPlaceResult[]>([])
const [open, setOpen] = useState(false)
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
// Ignore lookups superseded by another query, a saved pick, or leaving this day.
const requestId = useRef(0)
const rootRef = useRef<HTMLDivElement>(null)
const fieldRef = useRef<HTMLDivElement>(null)
const listRef = useRef<HTMLDivElement>(null)
@@ -235,21 +244,45 @@ function StopPicker({ label, value, onPick, quickPicks, near, placeholder }: {
return () => document.removeEventListener('mousedown', close)
}, [])
useEffect(() => () => { if (debounceRef.current) clearTimeout(debounceRef.current) }, [])
useEffect(() => () => {
requestId.current += 1
if (debounceRef.current) clearTimeout(debounceRef.current)
}, [])
const search = (q: string) => {
const id = ++requestId.current
setText(q)
setResults([])
onPick(null)
if (debounceRef.current) clearTimeout(debounceRef.current)
if (q.trim().length < 2) { setResults([]); return }
if (q.trim().length < 2) return
debounceRef.current = setTimeout(() => {
transitApi.geocode(q, { lang: language, near: near || undefined })
.then((d: { results: TransitPlaceResult[] }) => setResults(d.results || []))
.catch(() => setResults([]))
.then((d: { results: TransitPlaceResult[] }) => { if (id === requestId.current) setResults(d.results || []) })
.catch(() => { if (id === requestId.current) setResults([]) })
}, 300)
}
const display = value ? value.name : text
const query = text.trim().toLowerCase()
const saved = quickPicks.filter(p => p.name.toLowerCase().includes(query))
const seen = new Set(saved.map(pickedPlaceKey))
const external = results.filter(p => {
const key = pickedPlaceKey(p)
if (seen.has(key)) return false
seen.add(key)
return true
})
const suggestions: (PickedPlace & { area?: string | null })[] = value ? [] : [...saved, ...external]
const pick = (p: PickedPlace) => {
requestId.current += 1
if (debounceRef.current) clearTimeout(debounceRef.current)
onPick({ name: p.name, lat: p.lat, lng: p.lng })
setText('')
setResults([])
setOpen(false)
}
return (
<div ref={rootRef} style={{ position: 'relative', flex: 1, minWidth: 0 }}>
@@ -267,34 +300,23 @@ function StopPicker({ label, value, onPick, quickPicks, near, placeholder }: {
style={{ border: 0, background: 'none', outline: 'none', fontSize: 'calc(13px * var(--fs-scale-body, 1))', width: '100%', fontFamily: 'inherit' }}
/>
</div>
{open && listPos && (results.length > 0 || (!value && text.trim().length < 2 && quickPicks.length > 0)) && createPortal(
{open && listPos && suggestions.length > 0 && createPortal(
// On the page rather than inside the dialog, so a dialog that scrolls or clips
// its content cannot cut the list off before anything is typed.
<div ref={listRef} className="bg-surface-card border border-edge z-[var(--z-toast)]" style={{ position: 'fixed', left: listPos.left, width: listPos.width, ...(listPos.above ? { bottom: listPos.bottom } : { top: listPos.top }), borderRadius: 10, boxShadow: 'var(--shadow-dropdown)', overflow: 'hidden', maxHeight: listPos.maxHeight, overflowY: 'auto' }}>
{results.length > 0
? results.map((r, i) => (
<button type="button" key={i} onClick={() => { onPick({ name: r.name, lat: r.lat, lng: r.lng }); setText(''); setResults([]); setOpen(false) }}
className="text-content"
style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%', textAlign: 'start', padding: '8px 10px', border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}
onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}
onMouseLeave={e => e.currentTarget.style.background = 'none'}>
<MapPin size={13} className="text-content-faint" style={{ flexShrink: 0 }} />
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{r.name}
{r.area && <span className="ms-1.5 text-content-faint">{r.area}</span>}
</span>
</button>
))
: quickPicks.map((p, i) => (
<button type="button" key={i} onClick={() => { onPick(p); setText(''); setOpen(false) }}
className="text-content"
style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%', textAlign: 'start', padding: '8px 10px', border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}
onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}
onMouseLeave={e => e.currentTarget.style.background = 'none'}>
<MapPin size={13} className="text-content-faint" style={{ flexShrink: 0 }} />
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.name}</span>
</button>
))}
{suggestions.map(r => (
<button type="button" key={pickedPlaceKey(r)} onClick={() => pick(r)}
className="text-content"
style={{ display: 'flex', alignItems: 'center', gap: 8, width: '100%', textAlign: 'start', padding: '8px 10px', border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}
onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'}
onMouseLeave={e => e.currentTarget.style.background = 'none'}>
<MapPin size={13} className="text-content-faint" style={{ flexShrink: 0 }} />
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{r.name}
{r.area && <span className="ms-1.5 text-content-faint">{r.area}</span>}
</span>
</button>
))}
</div>,
document.body,
)}
@@ -0,0 +1,684 @@
import userEvent from '@testing-library/user-event';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { buildAssignment, buildDay, buildPlace, buildTrip, buildUser } from '../../../tests/helpers/factories';
import { buildPlanner } from '../../../tests/helpers/mobileTrip';
import { act, fireEvent, render, screen, waitFor } from '../../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { useTranslation } from '../../i18n';
import MTransportFormSheet from '../../mobile/screens/trip/sheets/MTransportFormSheet';
import { useAuthStore } from '../../store/authStore';
import { useTripStore } from '../../store/tripStore';
import type { Accommodation, AssignmentsMap, Day, Place } from '../../types';
import type { TransitPrefill } from './transitLeg';
import { TransportModal } from './TransportModal';
// Keep the real day selectors, wrappers and shared stop picker. Only the external
// geocoder is controlled: a saved private place need not exist in that service.
const { geocode, plan } = vi.hoisted(() => ({ geocode: vi.fn(), plan: vi.fn() }));
vi.mock('../../api/client', async (importOriginal) => ({
...(await importOriginal<typeof import('../../api/client')>()),
transitApi: { geocode, plan },
}));
type Surface = 'desktop' | 'phone';
interface Fixture {
days: Day[];
places: Place[];
assignments: AssignmentsMap;
accommodations: Accommodation[];
transitPrefill?: TransitPrefill;
selectedDayId?: number;
}
function fixture(): Fixture {
const days = [
buildDay({ id: 101, trip_id: 1, day_number: 1, date: '2027-06-01', title: 'First day' }),
buildDay({ id: 205, trip_id: 1, day_number: 2, date: '2027-06-02', title: 'Second day' }),
buildDay({ id: 309, trip_id: 1, day_number: 3, date: '2027-06-03', title: 'Empty day' }),
];
const places = ['First private stop', 'Second private stop', 'Shared private stop'].map((name, i) =>
buildPlace({ id: 11 + i, trip_id: 1, name, lat: 52.5 + i / 100, lng: 13.4 })
);
const visit = (dayId: number, p: Place, order: number) =>
buildAssignment({ day_id: dayId, place_id: p.id, place: p, order_index: order });
return {
days,
places,
assignments: {
'101': [visit(101, places[0], 0), visit(101, places[2], 1)],
'205': [visit(205, places[1], 0), visit(205, places[2], 1)],
'309': [],
},
accommodations: [],
};
}
function buildStay(id: number, name: string, start: number, end: number): Accommodation {
return {
id,
trip_id: 1,
place_id: 1000 + id,
start_day_id: start,
end_day_id: end,
place_name: name,
place_lat: 52 + id / 1000,
place_lng: 13,
} as Accommodation;
}
function longTripFixture(): Fixture {
const days = Array.from({ length: 30 }, (_, i) =>
buildDay({
id: 5000 - i * 97,
trip_id: 1,
day_number: i + 1,
date: new Date(Date.UTC(2027, 2, i + 1)).toISOString().slice(0, 10),
title: `Day ${i + 1}`,
})
);
days[28] = { ...days[28], date: null };
const stay = (id: number, name: string, start: number, end: number) =>
buildStay(id, name, days[start - 1].id, days[end - 1].id);
const nearby = Array.from({ length: 4 }, (_, i) => [
stay(10 + i * 2, `Nearby before ${i + 1}`, 18 - i, 20 - i),
stay(11 + i * 2, `Nearby after ${i + 1}`, 22 + i, 24 + i),
]).flat();
return {
days,
places: [],
assignments: {},
selectedDayId: days[20].id,
accommodations: [
stay(1, 'First-week hotel created first', 1, 7),
stay(2, 'Undated hotel', 29, 30),
...nearby.slice().reverse(),
{ ...nearby[0], id: 99 },
stay(100, 'Morning hotel', 20, 21),
stay(101, 'Evening hotel', 21, 22),
...Array.from({ length: 10 }, (_, i) => stay(200 + i, `Current stay ${i + 1}`, 19, 23)),
],
};
}
function Harness({ surface, data }: { surface: Surface; data: Fixture }) {
const { t } = useTranslation();
if (surface === 'phone') {
const planner = buildPlanner({
t,
trip: buildTrip({ id: 1 }),
days: data.days,
places: data.places,
assignments: data.assignments,
storedAssignments: data.assignments,
tripAccommodations: data.accommodations,
showTransportModal: true,
transportModalDayId: data.selectedDayId ?? 101,
transportModalAutomated: true,
transitPrefill: data.transitPrefill ?? null,
});
return <MTransportFormSheet planner={planner} onOpenExpense={vi.fn()} />;
}
return (
<TransportModal
isOpen
onClose={vi.fn()}
onSave={vi.fn()}
reservation={null}
days={data.days}
selectedDayId={data.selectedDayId ?? 101}
initialAutomated
places={data.places}
assignments={data.assignments}
accommodations={data.accommodations}
transitPrefill={data.transitPrefill}
/>
);
}
const inputs = () => screen.getAllByPlaceholderText('Search stop or station…');
async function switchDay(user: ReturnType<typeof userEvent.setup>, current: string, next: string) {
await user.click(screen.getByText(current));
await user.click(screen.getByRole('button', { name: new RegExp(`^${next}`) }));
}
const pickNames = () => screen.queryAllByRole('button', { name: /private stop/ }).map((b) => b.textContent);
beforeEach(() => {
resetAllStores();
geocode.mockReset().mockResolvedValue({ results: [] });
plan.mockReset();
seedStore(useAuthStore, { user: buildUser(), isAuthenticated: true });
seedStore(useTripStore, { trip: buildTrip({ id: 1 }), reservations: [] });
});
describe.each<Surface>(['desktop', 'phone'])('Automated transport day selection: %s', (surface) => {
beforeEach(() => {
Object.defineProperty(window, 'innerWidth', { configurable: true, value: surface === 'phone' ? 390 : 1440 });
fireEvent(window, new Event('resize'));
});
it('scopes both pickers by day id and keeps a shared place when switching back and forth', async () => {
const user = userEvent.setup();
render(<Harness surface={surface} data={fixture()} />);
await user.click(inputs()[0]);
expect(pickNames()).toEqual(['First private stop', 'Shared private stop']);
await switchDay(user, 'First day', 'Second day');
await user.click(inputs()[1]);
expect(pickNames()).toEqual(['Second private stop', 'Shared private stop']);
await switchDay(user, 'Second day', 'First day');
await user.click(inputs()[0]);
expect(pickNames()).toEqual(['First private stop', 'Shared private stop']);
});
it('keeps all nine eligible day places available in the dropdown', async () => {
const user = userEvent.setup();
const data = fixture();
const stops = Array.from({ length: 9 }, (_, i) => buildPlace({ id: 50 + i, name: `Day stop ${i + 1}` }));
data.places.push(...stops);
data.assignments['101'] = stops.map((p, i) =>
buildAssignment({ day_id: 101, place_id: p.id, place: p, order_index: i })
);
render(<Harness surface={surface} data={data} />);
await user.click(inputs()[0]);
expect(screen.queryAllByRole('button', { name: /^Day stop/ }).map((b) => b.textContent)).toEqual(
stops.map((p) => p.name)
);
expect(screen.queryByRole('button', { name: 'Second private stop' })).not.toBeInTheDocument();
});
it('finds an assigned private place when the geocoder has no result', async () => {
const user = userEvent.setup();
render(<Harness surface={surface} data={fixture()} />);
await user.click(inputs()[0]);
await user.type(inputs()[0], 'First private');
await waitFor(() => expect(geocode).toHaveBeenCalled());
await act(async () => {
await Promise.resolve();
});
expect(screen.queryByRole('button', { name: 'First private stop' })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Second private stop' })).not.toBeInTheDocument();
});
it('ranks matching saved places before external matches and deduplicates by name and both coordinates', async () => {
const user = userEvent.setup();
const data = fixture();
const saved = data.places[0];
const other = { name: 'External private stop', lat: 52.8, lng: 13.8, area: 'Berlin' };
geocode.mockResolvedValue({
results: [
other,
{ name: saved.name.toUpperCase(), lat: saved.lat, lng: saved.lng, area: 'Duplicate' },
{ ...other },
{ name: saved.name, lat: saved.lat, lng: 13.9, area: 'Other longitude' },
],
});
render(<Harness surface={surface} data={data} />);
await user.type(inputs()[0], 'private');
await screen.findByRole('button', { name: /External private stop/ });
const rows = screen.getAllByRole('button', { name: /private stop/i });
expect(rows.map((row) => row.textContent)).toEqual([
'First private stop',
'Shared private stop',
'External private stopBerlin',
'First private stopOther longitude',
]);
expect(geocode).toHaveBeenCalledTimes(1);
await user.click(rows[0]);
expect(inputs()[0]).toHaveValue(saved.name);
});
it('limits only other-day stays, keeping current hotels, terminals and every selected-day place first', async () => {
const user = userEvent.setup();
const data = fixture();
const stops = Array.from({ length: 12 }, (_, i) => buildPlace({ id: 50 + i, name: `Day stop ${i + 1}` }));
// A same-name stop at a different longitude must not be dropped as a duplicate.
stops.push(buildPlace({ id: 62, name: stops[0].name, lat: stops[0].lat, lng: 10 }));
data.places.push(...stops);
data.assignments['101'] = stops.map((p, i) =>
buildAssignment({ day_id: 101, place_id: p.id, place: p, order_index: i })
);
data.accommodations = Array.from(
{ length: 12 },
(_, i) =>
({
id: 70 + i,
trip_id: 1,
place_id: 70 + i,
start_day_id: i === 0 ? 101 : 205,
end_day_id: i === 0 ? 101 : 205,
place_name: i === 0 ? 'Current hotel' : `Other hotel ${i}`,
place_lat: 52 + i / 100,
place_lng: 13,
}) as Accommodation
);
// Duplicate stays must not consume another slot of the other-day allowance.
data.accommodations.splice(2, 0, { ...data.accommodations[1], id: 90 });
seedStore(useTripStore, {
reservations: [
{
id: 81,
trip_id: 1,
type: 'train',
day_id: 101,
end_day_id: 101,
endpoints: [{ role: 'from', name: 'Current terminal', lat: 52, lng: 13, local_date: '2027-06-01' }],
},
] as ReturnType<typeof useTripStore.getState>['reservations'],
});
render(<Harness surface={surface} data={data} />);
for (const input of inputs()) {
await user.click(input);
const rows = screen.getAllByRole('button', { name: /Current hotel|Current terminal|Day stop|Other hotel/ });
expect(rows.map((row) => row.textContent)).toEqual([
'Current hotel',
'Current terminal',
...stops.map((p) => p.name),
...Array.from({ length: 8 }, (_, i) => `Other hotel ${i + 1}`),
]);
expect(screen.queryByRole('button', { name: 'Second private stop' })).not.toBeInTheDocument();
}
});
it('keeps more than eight current-day hotels selectable and searchable despite earlier other-day stays', async () => {
const user = userEvent.setup();
const data = fixture();
const current = Array.from({ length: 12 }, (_, i) => buildStay(200 + i, `Current day hotel ${i + 1}`, 101, 101));
const other = Array.from({ length: 9 }, (_, i) => buildStay(100 + i, `Other day hotel ${i + 1}`, 205, 205));
data.accommodations = [
...other,
...current,
{ ...current[8], id: 999 },
{ ...buildStay(300, 'Unlocated current hotel', 101, 101), place_lat: null },
];
render(<Harness surface={surface} data={data} />);
for (const input of inputs()) {
await user.click(input);
expect(screen.getAllByRole('button', { name: /^Current day hotel/ }).map((b) => b.textContent)).toEqual(
current.map((a) => a.place_name)
);
expect(screen.getAllByRole('button', { name: /^Other day hotel/ }).map((b) => b.textContent)).toEqual(
other.slice(0, 8).map((a) => a.place_name)
);
expect(screen.queryByRole('button', { name: 'Unlocated current hotel' })).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: 'First private stop' })).toBeInTheDocument();
}
await user.type(inputs()[1], 'current day hotel 12');
await user.click(screen.getByRole('button', { name: 'Current day hotel 12' }));
expect(inputs()[1]).toHaveValue('Current day hotel 12');
});
it('offers Hotel 09 on Day 3 for the manual-review booking pattern without using mirrored day places', async () => {
const user = userEvent.setup();
const data = fixture();
const a = buildStay(1, 'Hotel A — first night', 101, 205);
const b = buildStay(2, 'Hotel B — second night', 205, 309);
const sameDay = Array.from({ length: 9 }, (_, i) =>
buildStay(3 + i, `Other night hotel ${String(i + 1).padStart(2, '0')}`, 309, 309)
);
data.accommodations = [a, b, ...sameDay];
// Days hides accommodation-owned mirror assignments: hotels must come from the stays themselves.
data.assignments['309'] = [];
render(<Harness surface={surface} data={data} />);
await switchDay(user, 'First day', 'Empty day');
for (const input of inputs()) {
await user.click(input);
expect(
screen.getAllByRole('button', { name: /Hotel A|Hotel B|Other night hotel/ }).map((row) => row.textContent)
).toEqual([b.place_name, ...sameDay.map((stay) => stay.place_name), a.place_name]);
}
await user.click(screen.getByRole('button', { name: 'Other night hotel 09' }));
expect(inputs()[1]).toHaveValue('Other night hotel 09');
});
it('keeps multi-night stays and checkout-day stays uncapped, with bookends before the other current stays', async () => {
const user = userEvent.setup();
const data = fixture();
const other = Array.from({ length: 9 }, (_, i) => buildStay(100 + i, `Future hotel ${i + 1}`, 309, 309));
const spanning = Array.from({ length: 10 }, (_, i) => buildStay(200 + i, `Multi-night hotel ${i + 1}`, 101, 309));
const checkout = buildStay(300, 'Checks out today', 101, 205);
const checkin = buildStay(301, 'Checks in today', 205, 309);
data.accommodations = [...other, ...spanning, checkout, checkin];
render(<Harness surface={surface} data={data} />);
await switchDay(user, 'First day', 'Second day');
await user.click(inputs()[0]);
expect(
screen
.getAllByRole('button', { name: /Multi-night hotel|Checks (in|out) today|Future hotel/ })
.map((row) => row.textContent)
).toEqual([
spanning[0].place_name,
checkin.place_name,
...spanning.slice(1).map((stay) => stay.place_name),
checkout.place_name,
...other.slice(0, 8).map((stay) => stay.place_name),
]);
expect(screen.queryByRole('button', { name: 'Future hotel 9' })).not.toBeInTheDocument();
});
it('does not let a first-week hotel take a Day 21 slot from eight closer stays on a 30-day trip', async () => {
const user = userEvent.setup();
render(<Harness surface={surface} data={longTripFixture()} />);
for (const input of inputs()) {
await user.click(input);
expect(screen.queryByRole('button', { name: 'First-week hotel created first' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Undated hotel' })).not.toBeInTheDocument();
expect(
screen
.getAllByRole('button', { name: /Morning hotel|Evening hotel|Current stay|Nearby/ })
.map((row) => row.textContent)
).toEqual([
'Morning hotel',
'Evening hotel',
...Array.from({ length: 10 }, (_, i) => `Current stay ${i + 1}`),
...Array.from({ length: 4 }, (_, i) => [`Nearby before ${i + 1}`, `Nearby after ${i + 1}`]).flat(),
]);
}
});
it('puts undated stays last and orders identical dated intervals by stay id independently of input order', async () => {
const user = userEvent.setup();
const data = longTripFixture();
const dated = data.accommodations.find((stay) => stay.place_name === 'Nearby after 1');
if (!dated) throw new Error('Missing dated fixture');
const undated = data.accommodations.find((stay) => stay.place_name === 'Undated hotel');
if (!undated) throw new Error('Missing undated fixture');
data.accommodations = [
undated,
{ ...dated, id: 90, place_name: 'Same dates higher id', place_lng: 14 },
{ ...dated, id: 80, place_name: 'Same dates lower id', place_lng: 15 },
];
const view = render(<Harness surface={surface} data={data} />);
await user.click(inputs()[0]);
const names = () =>
screen.getAllByRole('button', { name: /Same dates|Undated hotel/ }).map((row) => row.textContent);
expect(names()).toEqual(['Same dates lower id', 'Same dates higher id', 'Undated hotel']);
view.rerender(
<Harness surface={surface} data={{ ...data, accommodations: data.accommodations.slice().reverse() }} />
);
expect(names()).toEqual(['Same dates lower id', 'Same dates higher id', 'Undated hotel']);
});
it('refreshes an open dropdown after places are added, removed and reordered', async () => {
const user = userEvent.setup();
const data = fixture();
const view = render(<Harness surface={surface} data={data} />);
await user.click(inputs()[0]);
expect(pickNames()).toEqual(['First private stop', 'Shared private stop']);
const added = buildPlace({ id: 99, name: 'Added private stop' });
const next = {
...data,
places: [...data.places, added],
assignments: {
...data.assignments,
'101': [
{ ...data.assignments['101'][1], order_index: 2 },
buildAssignment({ day_id: 101, place_id: added.id, place: added, order_index: 0 }),
],
},
};
view.rerender(<Harness surface={surface} data={next} />);
expect(pickNames()).toEqual(['Added private stop', 'Shared private stop']);
});
it('keeps place membership tied to ids when days and their dates are reordered', async () => {
const user = userEvent.setup();
const data = fixture();
const view = render(<Harness surface={surface} data={data} />);
const reordered = {
...data,
days: [
{ ...data.days[1], day_number: 1, date: data.days[0].date },
{ ...data.days[0], day_number: 2, date: data.days[1].date },
data.days[2],
],
};
view.rerender(<Harness surface={surface} data={reordered} />);
await user.click(inputs()[0]);
expect(pickNames()).toEqual(['First private stop', 'Shared private stop']);
await switchDay(user, 'First day', 'Second day');
await user.click(inputs()[0]);
expect(pickNames()).toEqual(['Second private stop', 'Shared private stop']);
});
it('does not retain endpoints from an unrelated day after selecting from and to', async () => {
const user = userEvent.setup();
const data = fixture();
// Make the first day's two endpoints exclusive to that day.
data.assignments['205'] = [data.assignments['205'][0]];
render(<Harness surface={surface} data={data} />);
await user.click(inputs()[0]);
await user.click(screen.getByRole('button', { name: 'First private stop' }));
await user.click(inputs()[1]);
await user.click(screen.getByRole('button', { name: 'Shared private stop' }));
await switchDay(user, 'First day', 'Second day');
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['', '']);
});
it('clears search state when changing days so the next day offers its own places', async () => {
const user = userEvent.setup();
geocode.mockResolvedValue({ results: [{ name: 'Old external station', lat: 52, lng: 13, area: null }] });
render(<Harness surface={surface} data={fixture()} />);
await user.type(inputs()[0], 'Old station');
await screen.findByRole('button', { name: 'Old external station' });
await switchDay(user, 'First day', 'Second day');
await user.click(inputs()[0]);
expect(screen.queryByRole('button', { name: 'Old external station' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Second private stop' })).toBeInTheDocument();
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['', '']);
});
it('scopes day-plan endpoint, time and walk prefills to the opening day', async () => {
const user = userEvent.setup();
const data = fixture();
data.transitPrefill = {
from: { name: 'Walk end', lat: 52.5, lng: 13.4 },
to: { name: 'Next walk start', lat: 52.6, lng: 13.5 },
time: '12:15',
walk: {
dayId: 101,
fromWalk: 'Old town',
toWalk: 'Harbour',
ends: '12:15',
endsNextDay: false,
endsAtLeast: false,
nextStarts: '13:00',
},
};
render(<Harness surface={surface} data={data} />);
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['Walk end', 'Next walk start']);
expect(screen.getByTestId('transit-walk-end')).toHaveTextContent('Old town');
expect(screen.getByDisplayValue('12:15')).toBeInTheDocument();
await switchDay(user, 'First day', 'Second day');
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['', '']);
expect(screen.queryByTestId('transit-walk-end')).not.toBeInTheDocument();
expect(screen.queryByDisplayValue('12:15')).not.toBeInTheDocument();
await switchDay(user, 'Second day', 'First day');
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['Walk end', 'Next walk start']);
expect(screen.getByTestId('transit-walk-end')).toHaveTextContent('Old town');
});
it('drops old itineraries when changing the day', async () => {
const user = userEvent.setup();
const data = fixture();
const stop = (name: string, time: string) => ({
name,
lat: 52.5,
lng: 13.4,
time,
scheduledTime: null,
track: null,
});
plan.mockResolvedValue({
itineraries: [
{
startTime: '2027-06-01T07:00:00Z',
endTime: '2027-06-01T07:30:00Z',
duration: 1800,
transfers: 0,
walkSeconds: 0,
legs: [
{
mode: 'SUBWAY',
from: stop('A', '2027-06-01T07:00:00Z'),
to: stop('B', '2027-06-01T07:30:00Z'),
duration: 1800,
distance: null,
headsign: null,
line: 'U88',
lineColor: null,
lineTextColor: null,
agency: null,
intermediateStops: 0,
},
],
},
],
});
render(<Harness surface={surface} data={data} />);
await user.click(inputs()[0]);
await user.click(screen.getByRole('button', { name: 'First private stop' }));
await user.click(inputs()[1]);
await user.click(screen.getByRole('button', { name: 'Shared private stop' }));
await user.click(screen.getByRole('button', { name: /^Search$/ }));
await screen.findByText('U88');
await switchDay(user, 'First day', 'Second day');
expect(screen.queryByText('U88')).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Add to day' })).not.toBeInTheDocument();
expect(inputs().map((i) => (i as HTMLInputElement).value)).toEqual(['', '']);
});
it('ignores an old geocoder response after the day changes', async () => {
const user = userEvent.setup();
let finish: (value: { results: { name: string; lat: number; lng: number; area: null }[] }) => void = () => {
throw new Error('lookup not started');
};
geocode.mockReturnValueOnce(
new Promise((resolve) => {
finish = resolve;
})
);
render(<Harness surface={surface} data={fixture()} />);
await user.type(inputs()[0], 'Old station');
await waitFor(() => expect(geocode).toHaveBeenCalledTimes(1));
await switchDay(user, 'First day', 'Second day');
await user.click(inputs()[0]);
await act(async () => {
finish({ results: [{ name: 'Late old station', lat: 52, lng: 13, area: null }] });
});
expect(screen.queryByRole('button', { name: 'Late old station' })).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Second private stop' })).toBeInTheDocument();
expect(inputs()[0]).toHaveValue('');
});
it('keeps the newest search results when an older lookup answers last', async () => {
type Answer = { results: { name: string; lat: number; lng: number; area: null }[] };
const pending: ((value: Answer) => void)[] = [];
geocode.mockImplementation(() => new Promise<Answer>((resolve) => pending.push(resolve)));
render(<Harness surface={surface} data={fixture()} />);
fireEvent.focus(inputs()[0]);
fireEvent.change(inputs()[0], { target: { value: 'Old' } });
await waitFor(() => expect(geocode).toHaveBeenCalledTimes(1));
fireEvent.change(inputs()[0], { target: { value: 'New' } });
await waitFor(() => expect(geocode).toHaveBeenCalledTimes(2));
await act(async () => {
pending[1]({ results: [{ name: 'New station', lat: 52.5, lng: 13.4, area: null }] });
});
await act(async () => {
pending[0]({ results: [{ name: 'Old station', lat: 52.6, lng: 13.5, area: null }] });
});
expect(screen.getByRole('button', { name: 'New station' })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Old station' })).not.toBeInTheDocument();
});
it('ignores a superseded geocoder response after a saved place is picked', async () => {
const user = userEvent.setup();
let finish: (value: { results: { name: string; lat: number; lng: number; area: null }[] }) => void = () => {
throw new Error('lookup not started');
};
geocode.mockReturnValueOnce(
new Promise((resolve) => {
finish = resolve;
})
);
render(<Harness surface={surface} data={fixture()} />);
fireEvent.change(inputs()[0], { target: { value: 'Old' } });
await waitFor(() => expect(geocode).toHaveBeenCalledTimes(1));
fireEvent.change(inputs()[0], { target: { value: 'First private' } });
fireEvent.focus(inputs()[0]);
fireEvent.click(screen.getByRole('button', { name: 'First private stop' }));
await act(async () => {
finish({ results: [{ name: 'Superseded station', lat: 52, lng: 13, area: null }] });
});
await user.clear(inputs()[0]);
expect(screen.queryByRole('button', { name: 'Superseded station' })).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: 'First private stop' })).toBeInTheDocument();
expect(geocode).toHaveBeenCalledTimes(1);
});
it('offers no unrelated regular places on an empty day', async () => {
const user = userEvent.setup();
render(<Harness surface={surface} data={fixture()} />);
await switchDay(user, 'First day', 'Empty day');
await user.click(inputs()[0]);
expect(pickNames()).toEqual([]);
});
it('offers the active stay and other trip stays intentionally, even on a booking-only day', async () => {
const user = userEvent.setup();
const data = fixture();
data.assignments['101'] = [];
const stay = (id: number, name: string, dayId: number): Accommodation =>
({
id,
trip_id: 1,
place_id: id,
start_day_id: dayId,
end_day_id: dayId,
place_name: name,
place_lat: 52 + id / 100,
place_lng: 13,
}) as Accommodation;
data.accommodations = [stay(70, 'Current hotel', 101), stay(71, 'Later hotel', 205)];
render(<Harness surface={surface} data={data} />);
await user.click(inputs()[0]);
expect(screen.getByRole('button', { name: 'Current hotel' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Later hotel' })).toBeInTheDocument();
expect(pickNames()).toEqual([]);
});
it('offers only the selected day transport terminals on a transport-only day', async () => {
const user = userEvent.setup();
const data = fixture();
data.assignments['101'] = [];
const endpoint = (role: 'from' | 'to', name: string, date: string) => ({
role,
name,
lat: 52,
lng: 13,
local_date: date,
});
seedStore(useTripStore, {
reservations: [
{
id: 81,
trip_id: 1,
type: 'train',
day_id: 101,
end_day_id: 205,
endpoints: [
endpoint('from', 'First terminal', '2027-06-01'),
endpoint('to', 'Second terminal', '2027-06-02'),
],
},
] as ReturnType<typeof useTripStore.getState>['reservations'],
});
render(<Harness surface={surface} data={data} />);
await user.click(inputs()[0]);
expect(screen.getByRole('button', { name: 'First terminal' })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Second terminal' })).not.toBeInTheDocument();
await switchDay(user, 'First day', 'Second day');
await user.click(inputs()[0]);
expect(screen.getByRole('button', { name: 'Second terminal' })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'First terminal' })).not.toBeInTheDocument();
});
});
@@ -20,6 +20,7 @@ import type { TripMember } from '../Budget/BudgetPanelMemberChips'
import type { BookingExpenseRequest } from './BookingCostsSection.types'
import type { BookingReviewDraft } from './parsedItemToDraft'
import TransitSearchPanel from './TransitSearchPanel'
import { getTransitDayPlaces } from './transitDayPlaces'
import type { TransitPrefill } from './transitLeg'
import { BookingDialogHeader, StatusPill } from './bookings/BookingDialogShell'
import { DialogShell, DialogSection, DialogFooter, FooterSpacer, DialogButton, DeleteButton } from '../shared/DialogShell'
@@ -287,22 +288,20 @@ export function TransportModal({ isOpen, onClose, onSave, reservation, days, sel
const transitSearch = () => {
const transitDay = days.find(d => d.id === Number(form.start_day_id))
if (!transitDay) return <p className="m-0 text-content-faint" style={fs(13, 'body')}>{t('transit.pickDay')}</p>
// Quick picks offer the chosen day's itinerary, not the whole trip (#1460).
const dayPlaces = (assignments[String(transitDay.id)] || [])
.slice().sort((a, b) => a.order_index - b.order_index)
.map(a => places.find(p => p.id === a.place_id))
.filter((p): p is Place => p != null)
const dayPlaces = getTransitDayPlaces(transitDay.id, assignments, places)
const dayPrefill = transitDay.id === selectedDayId ? transitPrefill : null
return (
<TransitSearchPanel
key={transitDay.id}
day={transitDay}
days={days}
places={dayPlaces}
accommodations={accommodations}
onAdd={(payload) => onSave(payload as Record<string, any> & { title: string })}
initialFrom={transitPrefill?.from ?? null}
initialTo={transitPrefill?.to ?? null}
initialTime={transitPrefill?.time ?? null}
walk={transitPrefill?.walk ?? null}
initialFrom={dayPrefill?.from ?? null}
initialTo={dayPrefill?.to ?? null}
initialTime={dayPrefill?.time ?? null}
walk={dayPrefill?.walk ?? null}
/>
)
}
@@ -2,7 +2,7 @@ import type { Day, Reservation, ReservationEndpoint } from '../../../types'
import { formatPriceText, formatTime, splitReservationDateTime } from '../../../utils/formatters'
import { getFlightLegs, getTrainLegs, usesStationRoute } from '../../../utils/flightLegs'
import { safeExternalHref } from '../../../utils/safeUrl'
import { daySpan, hotelStayTimes, parseMeta, type AssignmentLookupEntry } from './bookingsModel'
import { bookingDates, daySpan, hotelStayTimes, parseMeta, type AssignmentLookupEntry } from './bookingsModel'
export interface FactsContext {
t: (key: string, params?: Record<string, string | number>) => string
@@ -84,6 +84,7 @@ export function bookingFacts(r: Reservation, c: FactsContext): BookingFacts {
const eps = (r.endpoints || []).slice().sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0))
const from = eps.find(e => e.role === 'from')
const to = eps.find(e => e.role === 'to')
const dates = bookingDates(r, c.days)
const startTime = startDt.time || from?.local_time || null
const endTime = endDt.time || to?.local_time || null
// A stay backed by an accommodation says its times as check-in and check-out;
@@ -124,8 +125,8 @@ export function bookingFacts(r: Reservation, c: FactsContext): BookingFacts {
return {
day, time, startTime, endTime,
startDate: startDt.date || from?.local_date || span.start?.date || null,
endDate: endDt.date || to?.local_date || span.end?.date || null,
startDate: dates.start,
endDate: dates.end,
cells, endpoints: eps.length >= 2 ? eps : [], legCodes,
place: r.location || r.place_name || null,
accommodation: r.accommodation_name || null,
@@ -132,6 +132,23 @@ export function daySpan(r: Reservation, days: Day[]): DaySpan {
return { start: byId(r.day_id), end: byId(r.end_day_id) }
}
/**
* The calendar dates a booking starts and ends on, as "YYYY-MM-DD", or null where it
* knows none: its own date first, then the local date of its first or last stop,
* then the date of the day it is linked to. A day-linked transport often carries
* only times, so its day stands in.
*/
export function bookingDates(r: Reservation, days: Day[]): { start: string | null; end: string | null } {
const span = daySpan(r, days)
const eps = (r.endpoints || []).slice().sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0))
const from = eps.find(e => e.role === 'from')
const to = eps.find(e => e.role === 'to')
return {
start: splitReservationDateTime(r.reservation_time).date || from?.local_date || span.start?.date || null,
end: splitReservationDateTime(r.reservation_end_time).date || to?.local_date || span.end?.date || null,
}
}
/**
* The moment a booking starts, as "YYYY-MM-DDTHH:MM" in its own local time, or null
* without any date. A day-linked transport often carries no date in reservation_time,
@@ -54,6 +54,14 @@ describe('TransitLegs', () => {
expect(screen.getByText('BVG')).toBeInTheDocument();
});
it('FE-PLANNER-BKTRANSIT-009: stop names and a walk target wrap instead of being cut off (#3139)', () => {
render(<TransitLegs legs={[ride, walk]} compact />);
for (const text of ['Alexanderplatz', 'Eberswalder Str.', 'Walk to Mauerpark']) {
expect(screen.getByText(text)).not.toHaveClass('truncate');
expect(screen.getByText(text)).toHaveClass('break-words');
}
});
it('FE-PLANNER-BKTRANSIT-006: a walk reads as one and leaves out the ride facts', () => {
render(<TransitLegs legs={[walk]} compact />);
expect(screen.getByText('Walk to Mauerpark')).toBeInTheDocument();
@@ -48,9 +48,11 @@ export function TransitLegs({ legs, compact = false }: { legs: TransitLegDisplay
}}>{leg.line || leg.mode}</span>
)}
<div className={`flex min-w-0 flex-1 flex-col ${compact ? 'gap-1' : 'gap-1.5'}`}>
<div className="flex min-w-0 items-center gap-1 font-medium text-content" style={fs(compact ? 12 : 13, 'body')}>
{walk ? <span className="truncate text-content-muted">{t('transit.walkTo', { name: leg.to?.name || '' })}</span> : (
<><span className="truncate">{leg.from?.name}</span><ArrowRight size={compact ? 11 : 12} strokeWidth={2} className="flex-none text-content-faint" /><span className="truncate">{leg.to?.name}</span></>
{/* Detail views show a stop name whole: the names wrap and the
arrow moves to the next line with them when it has to (#3139). */}
<div className="flex min-w-0 flex-wrap items-center gap-1 font-medium text-content" style={fs(compact ? 12 : 13, 'body')}>
{walk ? <span className="min-w-0 break-words text-content-muted [overflow-wrap:anywhere]">{t('transit.walkTo', { name: leg.to?.name || '' })}</span> : (
<><span dir="auto" className="min-w-0 break-words [overflow-wrap:anywhere]">{leg.from?.name}</span><ArrowRight size={compact ? 11 : 12} strokeWidth={2} className="flex-none text-content-faint" /><span dir="auto" className="min-w-0 break-words [overflow-wrap:anywhere]">{leg.to?.name}</span></>
)}
</div>
<TransitMetaBadges size={compact ? 'sm' : 'md'} items={[
@@ -1,6 +1,6 @@
// FE-PLANNER-HOURS-001 to FE-PLANNER-HOURS-003
// FE-PLANNER-HOURS-001 to FE-PLANNER-HOURS-007
import { describe, expect, it } from 'vitest'
import { cleanWeek, emptyWeek, hoursLines, periodsFromWeek, readWeek, weekdayNames, weekFromPeriods, writeWeek } from './placeHours'
import { ALL_DAY, cleanWeek, emptyWeek, hoursLines, isAllDay, periodsFromWeek, readWeek, weekdayNames, weekFromPeriods, writeWeek } from './placeHours'
const week = JSON.stringify([
{ closed: false, open: '09:00', close: '17:00' },
@@ -61,5 +61,27 @@ describe('typing and taking over (#2472)', () => {
expect(weekFromPeriods(null)).toBeNull()
expect(weekFromPeriods([])).toBeNull()
})
})
it('FE-PLANNER-HOURS-006: a place open around the clock reads as all day, from the lookup and by hand', () => {
const p = (day: number, h: number, m = 0) => ({ day, hour: h, minute: m })
// Google writes a place open all week as one period on Sunday that never closes.
expect(weekFromPeriods([{ open: p(0, 0), close: null }])).toEqual(Array.from({ length: 7 }, () => ({ closed: false, ...ALL_DAY })))
// A day from midnight to the next midnight is the same.
expect(weekFromPeriods([{ open: p(1, 0), close: p(2, 0) }])?.[0]).toEqual({ closed: false, ...ALL_DAY })
expect(isAllDay({ closed: false, open: '00:00', close: '23:59' })).toBe(true)
expect(isAllDay({ closed: false, open: '00:00', close: '00:00' })).toBe(true)
expect(isAllDay({ closed: false, open: '00:00', close: '22:00' })).toBe(false)
expect(isAllDay({ closed: true })).toBe(false)
})
it('FE-PLANNER-HOURS-007: the inspector names an all-day day instead of 00:00 to 23:59', () => {
const week = emptyWeek()
week[0] = { closed: false, ...ALL_DAY }
week[1] = { closed: false, open: '09:00', close: '17:00' }
const lines = hoursLines(writeWeek(week), 'en', 'Closed', 'Open 24 hours') ?? []
expect(lines[0]).toBe('Monday: Open 24 hours')
expect(lines[1]).toBe('Tuesday: 09:00 – 17:00')
// Without the label the times stay, as before.
expect(hoursLines(writeWeek(week), 'en', 'Closed')?.[0]).toBe('Monday: 00:00 – 23:59')
})
})
+20 -4
View File
@@ -26,12 +26,21 @@ export function weekdayNames(locale: string | undefined, width: 'long' | 'short'
* looked-up hours (#2472): "Monday: 09:00 – 17:00", or the closed word. Null
* when the place has no hours of its own, so the looked-up ones take over.
*/
export function hoursLines(raw: string | null | undefined, locale: string | undefined, closedLabel: string): string[] | null {
/** Open around the clock, written the way the editor and the lookup both store it. */
export const ALL_DAY = { open: '00:00', close: '23:59' } as const
/** A day open around the clock: 00:00 to 23:59, or to 00:00 as some sources write it. */
export function isAllDay(day: PlaceOpeningHours[number]): boolean {
return !day.closed && day.open === ALL_DAY.open && (day.close === ALL_DAY.close || day.close === ALL_DAY.open)
}
export function hoursLines(raw: string | null | undefined, locale: string | undefined, closedLabel: string, allDayLabel?: string): string[] | null {
const week = parsePlaceHours(raw)
if (!hasPlaceHours(week)) return null
const names = weekdayNames(locale)
return week!.map((day, i) => {
if (day.closed) return `${names[i]}: ${closedLabel}`
if (allDayLabel && isAllDay(day)) return `${names[i]}: ${allDayLabel}`
if (!day.open && !day.close) return `${names[i]}: –`
return `${names[i]}: ${day.open ?? '…'} – ${day.close ?? '…'}`
})
@@ -80,11 +89,14 @@ interface Point { day: number; hour: number; minute: number }
* column shows, so a place edited later starts from them instead of from
* nothing. One range per day, the earliest opening to the latest closing, which
* is what the editor can hold; a day the provider names no period for is
* closed. A period that never closes is open around the clock. Null when the
* provider gave no periods at all.
* closed. A period that never closes is open around the clock: Google writes a
* place open all week as one such period on Sunday, so that alone opens every
* day. A span of a whole day or more is open around the clock too. Null when
* the provider gave no periods at all.
*/
export function weekFromPeriods(periods: { open: Point; close?: Point | null }[] | null | undefined): PlaceOpeningHours | null {
if (!periods?.length) return null
if (periods.length === 1 && !periods[0].close) return Array.from({ length: PLACE_HOURS_DAYS }, () => ({ closed: false, ...ALL_DAY }))
// Minutes after the day's own midnight; a close past midnight counts on top of 24h.
const span: ({ open: number; close: number } | null)[] = Array.from({ length: PLACE_HOURS_DAYS }, () => null)
for (const period of periods) {
@@ -96,6 +108,10 @@ export function weekFromPeriods(periods: { open: Point; close?: Point | null }[]
span[i] = cur ? { open: Math.min(cur.open, open), close: Math.max(cur.close, close) } : { open, close }
}
const clock = (m: number) => `${String(Math.floor(m / 60) % 24).padStart(2, '0')}:${String(m % 60).padStart(2, '0')}`
const week: PlaceOpeningHours = span.map(s => (s ? { closed: false, open: clock(s.open), close: clock(s.close) } : { closed: true }))
const week: PlaceOpeningHours = span.map(s => {
if (!s) return { closed: true }
if (s.open === 0 && s.close >= 24 * 60 - 1) return { closed: false, ...ALL_DAY }
return { closed: false, open: clock(s.open), close: clock(s.close) }
})
return week
}
@@ -0,0 +1,10 @@
import type { AssignmentsMap, Place } from '../../types';
/** Resolve the chosen day's places by day id, in itinerary order (#1460). */
export function getTransitDayPlaces(dayId: number, assignments: AssignmentsMap, places: Place[]): Place[] {
return (assignments[String(dayId)] ?? [])
.slice()
.sort((a, b) => a.order_index - b.order_index)
.map((a) => places.find((p) => p.id === a.place_id))
.filter((p): p is Place => p != null);
}
@@ -0,0 +1,47 @@
// FE-PLANNER-TRANSITDISPLAY-001 to FE-PLANNER-TRANSITDISPLAY-003
import { describe, expect, it } from 'vitest';
import { render, screen } from '../../../tests/helpers/render';
import type { TransitLegDisplay } from './transitDisplay';
import { TransitItineraryInline, TransitWalkDivider } from './transitDisplay';
const t = (key: string, params?: Record<string, string | number>) =>
params ? `${key}:${Object.values(params).join(',')}` : key;
const ride: TransitLegDisplay = {
mode: 'RAIL',
line: 'XC',
duration: 1260,
from: { name: 'Basingstoke', time: '12:48' },
to: { name: 'Reading', time: '13:09' },
};
const walk: TransitLegDisplay = { mode: 'WALK', duration: 240, to: { name: 'Reading station, Station Approach' } };
/** Whether a rendered element clips its text to one line. */
function clipsToOneLine(el: HTMLElement): boolean {
return el.style.whiteSpace === 'nowrap' || el.style.textOverflow === 'ellipsis';
}
describe('TransitItineraryInline (#3139)', () => {
it('FE-PLANNER-TRANSITDISPLAY-001: a ride shows both stop names in full', () => {
render(<TransitItineraryInline legs={[ride]} t={t} />);
for (const name of ['Basingstoke', 'Reading']) {
const el = screen.getByText(name);
expect(clipsToOneLine(el)).toBe(false);
expect(el.style.overflowWrap).toBe('anywhere');
}
});
it('FE-PLANNER-TRANSITDISPLAY-002: a ride shows its arrival time under its departure', () => {
render(<TransitItineraryInline legs={[ride, { ...ride, to: { name: 'Oxford' } }]} t={t} />);
expect(screen.getByText('13:09')).toBeInTheDocument();
expect(screen.getAllByText('12:48')).toHaveLength(2);
});
});
describe('TransitWalkDivider (#3139)', () => {
it('FE-PLANNER-TRANSITDISPLAY-003: the walk target wraps instead of being cut off', () => {
render(<TransitWalkDivider leg={walk} t={t} size="sm" />);
const text = screen.getByText(/transit\.walkTo:Reading station, Station Approach/);
expect(clipsToOneLine(text)).toBe(false);
});
});
@@ -41,14 +41,14 @@ export function TransitWalkDivider({ leg, t, size = 'md' }: {
background: `linear-gradient(to ${dir}, var(--text-faint), transparent)`,
opacity: 0.55,
})
// On phones the minutes lead so a long stop name only ever clips the name.
// On phones the minutes lead, so they stay on the first line when a long stop name wraps.
const text = isMobile
? `${mins ? `${t('transit.min', { count: mins })} · ` : ''}${t('transit.walkTo', { name: leg.to?.name || '' })}`
: `${t('transit.walkTo', { name: leg.to?.name || '' })}${mins ? ` · ${t('transit.min', { count: mins })}` : ''}`
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: size === 'sm' ? '1px 0' : '2px 0' }}>
<span style={rule('left')} />
<span className="text-content-faint" style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: size === 'sm' ? 'calc(10px * var(--fs-scale-caption, 1))' : 'calc(11.5px * var(--fs-scale-caption, 1))', fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: isMobile ? '85%' : '75%' }}>
<span className="text-content-faint" style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: size === 'sm' ? 'calc(10px * var(--fs-scale-caption, 1))' : 'calc(11.5px * var(--fs-scale-caption, 1))', fontWeight: 500, textAlign: 'center', overflowWrap: 'anywhere', maxWidth: isMobile ? '85%' : '75%' }}>
<Footprints size={size === 'sm' ? 11 : 12} style={{ flexShrink: 0 }} />
{text}
</span>
@@ -72,8 +72,10 @@ export function TransitItineraryInline({ legs, t }: {
const mins = leg.duration ? Math.round(leg.duration / 60) : null
return (
<div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 7 }}>
<span className="text-content-muted" style={{ width: 34, flexShrink: 0, textAlign: 'end', fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, paddingTop: 1 }}>
{leg.from?.time || ''}
{/* Departure beside the stops, arrival under it (#3139). */}
<span className="text-content-muted" style={{ width: 34, flexShrink: 0, alignSelf: 'stretch', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', textAlign: 'end', fontSize: 'calc(10px * var(--fs-scale-caption, 1))', fontWeight: 600, paddingTop: 1 }}>
<span>{leg.from?.time || ''}</span>
{leg.to?.time && <span className="text-content-faint">{leg.to.time}</span>}
</span>
<span style={{
display: 'inline-flex', alignItems: 'center', borderRadius: 4, padding: '0 5px',
@@ -84,10 +86,11 @@ export function TransitItineraryInline({ legs, t }: {
{leg.line || leg.mode}
</span>
<div style={{ flex: 1, minWidth: 0 }}>
<div className="text-content" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 500, display: 'flex', alignItems: 'center', gap: 4, minWidth: 0 }}>
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{leg.from?.name}</span>
{/* The folded-out itinerary is where a journey is read in full: stop names wrap (#3139). */}
<div className="text-content" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 500, display: 'flex', flexWrap: 'wrap', alignItems: 'center', columnGap: 4, minWidth: 0 }}>
<span dir="auto" style={{ minWidth: 0, overflowWrap: 'anywhere' }}>{leg.from?.name}</span>
<MoveRight size={10} className="text-content-faint" style={{ flexShrink: 0 }} />
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{leg.to?.name}</span>
<span dir="auto" style={{ minWidth: 0, overflowWrap: 'anywhere' }}>{leg.to?.name}</span>
</div>
<div className="text-content-faint" style={{ fontSize: 'calc(9.5px * var(--fs-scale-caption, 1))', marginTop: 1 }}>
{[
@@ -0,0 +1,89 @@
import { describe, expect, it } from 'vitest';
import { buildDay } from '../../../tests/helpers/factories';
import type { Accommodation } from '../../types';
import { orderTransitStaysByDate } from './transitStayOrder';
const day = buildDay({ id: 500, date: '2027-03-21', day_number: 21 });
const stay = (id: number, start: number, end = start) =>
({ id, start_day_id: start, end_day_id: end }) as Accommodation;
const refs = [
buildDay({ id: 900, date: '2027-03-01', day_number: 1 }),
buildDay({ id: 700, date: '2027-03-19', day_number: 19 }),
buildDay({ id: 600, date: '2027-03-20', day_number: 20 }),
day,
buildDay({ id: 400, date: '2027-03-22', day_number: 22 }),
buildDay({ id: 300, date: '2027-03-23', day_number: 23 }),
];
const ids = (stays: Accommodation[]) => stays.map((a) => a.id);
describe('orderTransitStaysByDate', () => {
it('uses the whole interval: an early check-in with a nearby checkout is close', () => {
const spanning = stay(1, 900, 600);
const future = stay(2, 400, 300);
const farther = stay(3, 700);
expect(ids(orderTransitStaysByDate(day, refs, [farther, future, spanning]))).toEqual([1, 2, 3]);
});
it('puts the earlier interval first at equal distance, then earlier checkout and stable stay id', () => {
const list = [stay(90, 400, 300), stay(2, 600), stay(80, 400, 300), stay(100, 400)];
expect(ids(orderTransitStaysByDate(day, refs, list))).toEqual([2, 100, 80, 90]);
expect(ids(orderTransitStaysByDate(day, refs, list.slice().reverse()))).toEqual([2, 100, 80, 90]);
});
it('places missing, incomplete and invalid calendar dates after dated stays', () => {
const dates = [
...refs,
buildDay({ id: 10, date: null }),
buildDay({ id: 11, date: '2027-02-30' }),
buildDay({ id: 12, date: 'not-a-date' }),
];
const list = [stay(4, 10), stay(3, 11), stay(2, 12), stay(5, 600, 10), stay(6, 99999), stay(9, 900)];
expect(ids(orderTransitStaysByDate(day, dates, list))).toEqual([9, 2, 3, 4, 5, 6]);
});
it('handles leap days without accepting a normalized invalid date', () => {
const selected = buildDay({ id: 1, date: '2028-03-01' });
const dates = [selected, buildDay({ id: 2, date: '2028-02-29' }), buildDay({ id: 3, date: '2027-02-29' })];
expect(ids(orderTransitStaysByDate(selected, dates, [stay(1, 3), stay(2, 2)]))).toEqual([2, 1]);
});
it('uses updated calendar dates after days are reordered, regardless of array order or numeric ids', () => {
const before = stay(1, 600);
const after = stay(2, 400);
const reordered = refs
.map((d) =>
d.id === 600
? { ...d, date: '2027-03-22', day_number: 22 }
: d.id === 400
? { ...d, date: '2027-03-20', day_number: 20 }
: d
)
.reverse();
expect(ids(orderTransitStaysByDate(day, refs, [after, before]))).toEqual([1, 2]);
expect(ids(orderTransitStaysByDate(day, reordered, [before, after]))).toEqual([2, 1]);
});
it('counts calendar nights equally across the spring DST boundary', () => {
const selected = buildDay({ id: 1, date: '2027-03-29' });
const dates = [selected, buildDay({ id: 2, date: '2027-03-28' }), buildDay({ id: 3, date: '2027-03-30' })];
expect(ids(orderTransitStaysByDate(selected, dates, [stay(1, 3), stay(2, 2)]))).toEqual([2, 1]);
});
it('normalizes reversed interval endpoints consistently with day-range membership', () => {
expect(ids(orderTransitStaysByDate(day, refs, [stay(1, 700), stay(2, 300, 600)]))).toEqual([2, 1]);
});
it('keeps dated stays ahead of undated ones when the selected day has no usable date', () => {
const selected = { ...day, date: null };
expect(ids(orderTransitStaysByDate(selected, refs, [stay(1, 99999), stay(3, 300), stay(2, 900)]))).toEqual([
2, 3, 1,
]);
});
it('does not mutate the caller list', () => {
const list = Object.freeze([stay(1, 300), stay(2, 600)]);
expect(ids(orderTransitStaysByDate(day, refs, list))).toEqual([2, 1]);
expect(ids([...list])).toEqual([1, 2]);
});
});
@@ -0,0 +1,37 @@
import type { Accommodation, Day } from '../../types';
/** A strict calendar date as a UTC day number, so DST never changes the number of nights. */
function nightNumber(value: string | null | undefined): number | null {
if (!value || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return null;
const time = Date.parse(`${value}T00:00:00Z`);
if (!Number.isFinite(time) || new Date(time).toISOString().slice(0, 10) !== value) return null;
return time / 86_400_000;
}
/** Rank other-day stays by the closest boundary of their complete booking interval. */
export function orderTransitStaysByDate(
day: Pick<Day, 'date'>,
days: readonly Pick<Day, 'id' | 'date'>[],
stays: readonly Accommodation[]
): Accommodation[] {
const selected = nightNumber(day.date);
const dates = new Map(days.map((d) => [d.id, nightNumber(d.date)]));
return stays
.map((stay) => {
const start = dates.get(stay.start_day_id);
const end = dates.get(stay.end_day_id);
// A partial or invalid interval has no usable proximity and follows every dated stay.
const lo = start != null && end != null ? Math.min(start, end) : Infinity;
const hi = start != null && end != null ? Math.max(start, end) : Infinity;
const distance = selected != null && lo !== Infinity ? Math.max(lo - selected, selected - hi, 0) : Infinity;
// Earlier check-in, then earlier check-out, then stable booking identity break ties.
return { stay, rank: [distance, lo, hi, stay.id] };
})
.sort((a, b) => {
for (let i = 0; i < a.rank.length; i++) {
if (a.rank[i] !== b.rank[i]) return a.rank[i] < b.rank[i] ? -1 : 1;
}
return 0;
})
.map((row) => row.stay);
}
@@ -0,0 +1,84 @@
import type { PlaceClientOrigin, PlaceOpeningHours } from '@trek/shared';
import { useEffect, useRef, useState } from 'react';
import { ALL_DAY, cleanWeek, isAllDay, readWeek, writeWeek } from './placeHours';
interface PlaceHoursOptions {
/** The stored hours text (JSON), empty when the place has none of its own. */
openingHours: string;
/** `origin` is set when the hours were taken over from the details lookup rather than typed. */
onChange: (value: string, origin?: PlaceClientOrigin) => void;
/**
* The hours the place details looked up, as a week. A place without hours of
* its own takes them over on its own; one that has some can take them over
* on request (takeOver).
*/
suggestedHours?: PlaceOpeningHours | null;
}
/**
* The opening hours of the place form (#2472): the one logic path behind the
* desktop dialog and the phone sheet, which draw their own rows over it. It
* keeps the editor's own draft, so a half-typed time ("09:3") stays on screen
* while only finished times reach the place, folds the week away until someone
* wants it, and switches a day closed or open around the clock.
*/
export function usePlaceHours({ openingHours, onChange, suggestedHours }: PlaceHoursOptions) {
const [week, setDraft] = useState(() => readWeek(openingHours));
const written = useRef(openingHours);
const [editing, setEditing] = useState(() => openingHours !== '');
// A value from outside (a picked search result, a reopened place) replaces the draft.
useEffect(() => {
if (openingHours === written.current) return;
written.current = openingHours;
setDraft(readWeek(openingHours));
if (openingHours) setEditing(true);
}, [openingHours]);
const setWeek = (next: PlaceOpeningHours, origin?: PlaceClientOrigin) => {
setDraft(next);
const text = writeWeek(cleanWeek(next));
written.current = text;
onChange(text, origin);
};
const setDay = (i: number, patch: Partial<PlaceOpeningHours[number]>) =>
setWeek(week.map((day, d) => (d === i ? { ...day, ...patch } : day)));
const toggleClosed = (i: number) =>
setDay(i, week[i].closed ? { closed: false } : { closed: true, open: undefined, close: undefined });
const toggleAllDay = (i: number) =>
setDay(i, isAllDay(week[i]) ? { open: undefined, close: undefined } : { closed: false, ...ALL_DAY });
const copyFirstToAll = () => setWeek(week.map(() => ({ ...week[0] })));
const clearHours = () => {
setWeek(readWeek(''));
setEditing(false);
};
// Looked-up hours are taken over by a place that has none yet, once per lookup.
const adopted = useRef<PlaceOpeningHours | null>(null);
useEffect(() => {
if (!suggestedHours || adopted.current === suggestedHours) return;
adopted.current = suggestedHours;
if (written.current) return;
setWeek(suggestedHours, 'enrichment');
setEditing(true);
// setWeek only reads refs and setters; the lookup is the trigger.
}, [suggestedHours]);
const canTakeOver = !!suggestedHours && writeWeek(suggestedHours) !== writeWeek(cleanWeek(week));
const takeOver = () => {
if (suggestedHours) setWeek(suggestedHours, 'enrichment');
};
return {
week,
editing,
setEditing,
setDay,
toggleClosed,
toggleAllDay,
copyFirstToAll,
clearHours,
canTakeOver,
takeOver,
};
}
@@ -0,0 +1,183 @@
// FE-PLANNER-PLTAGS-001 to FE-PLANNER-PLTAGS-008: the tags of the place form, the one logic
// path behind the desktop dialog and the phone sheet.
import { act, renderHook, waitFor } from '@testing-library/react';
import { useState, type KeyboardEvent } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { buildTag } from '../../../tests/helpers/factories';
import { resetAllStores } from '../../../tests/helpers/store';
import { useTripStore, type TripStoreState } from '../../store/tripStore';
import type { Place, Tag } from '../../types';
import { DEFAULT_FORM } from './PlaceFormModal.helpers';
import { usePlaceTags } from './usePlaceTags';
const t = (key: string) => key;
const makeToast = () => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() });
const monument = buildTag({ id: 7, trip_id: 5, name: 'Monument', color: '#6366f1' });
const zone = buildTag({ id: 8, trip_id: 5, name: 'Zone', color: '#10b981' });
/** A traveller's personal tag, put on the place through the API: the trip does not list it. */
const personal = { id: 50, name: 'Hidden gem', color: '#f59e0b' };
const addTripTag = vi.fn<TripStoreState['addTripTag']>();
let toast: ReturnType<typeof makeToast>;
function setOnline(online: boolean): void {
Object.defineProperty(navigator, 'onLine', { value: online, writable: true, configurable: true });
}
beforeEach(() => {
resetAllStores();
setOnline(true);
toast = makeToast();
addTripTag.mockReset();
useTripStore.setState({ tripTags: [monument, zone], addTripTag });
});
afterEach(() => {
setOnline(true);
});
/** The hook over a form of its own, as both shells run it. */
function setup(place: Pick<Place, 'tags'> | null = null) {
return renderHook(() => {
const [form, setForm] = useState(DEFAULT_FORM);
return { form, field: usePlaceTags({ tripId: 5, place, tags: form.tags, setForm, t, toast }) };
});
}
function key(name: string) {
const preventDefault = vi.fn();
return { event: { key: name, preventDefault } as unknown as KeyboardEvent<HTMLInputElement>, preventDefault };
}
describe('usePlaceTags', () => {
it('FE-PLANNER-PLTAGS-001: offers the tags of the trip by name, none ticked for a new place', () => {
const { result } = setup();
expect(result.current.field.options).toEqual([
{ id: 7, name: 'Monument', color: '#6366f1', on: false },
{ id: 8, name: 'Zone', color: '#10b981', on: false },
]);
// Nothing was touched, so the save has no tags to send.
expect(result.current.form.tags).toBeUndefined();
expect(result.current.field.canAdd).toBe(false);
});
it('FE-PLANNER-PLTAGS-002: ticks what the place carries and keeps a personal tag of it on offer', () => {
const { result } = setup({ tags: [{ id: 8, name: 'Zone (old name)' }, personal] });
expect(result.current.field.options).toEqual([
{ id: 50, name: 'Hidden gem', color: '#f59e0b', on: true },
{ id: 7, name: 'Monument', color: '#6366f1', on: false },
// The trip's own name and colour, not the copy on the place.
{ id: 8, name: 'Zone', color: '#10b981', on: true },
]);
expect(result.current.form.tags).toBeUndefined();
});
it('FE-PLANNER-PLTAGS-003: a tick writes the whole set into the form, starting from what the place carries', () => {
const { result } = setup({ tags: [{ id: 8, name: 'Zone' }, personal] });
act(() => result.current.field.toggle(7));
expect(result.current.form.tags).toEqual([8, 50, 7]);
expect(result.current.field.options.map((tag) => tag.on)).toEqual([true, true, true]);
act(() => result.current.field.toggle(50));
expect(result.current.form.tags).toEqual([8, 7]);
act(() => result.current.field.toggle(8));
act(() => result.current.field.toggle(7));
// Every tag off is an answer too: the save takes the tags off the place.
expect(result.current.form.tags).toEqual([]);
expect(result.current.field.options.map((tag) => tag.on)).toEqual([false, false, false]);
});
it('FE-PLANNER-PLTAGS-004: a typed name becomes a tag of the trip, ticked, and the field is empty again', async () => {
const viewpoint = buildTag({ id: 9, trip_id: 5, name: 'Viewpoint' });
addTripTag.mockResolvedValue(viewpoint);
const { result } = setup();
act(() => result.current.field.setName(' Viewpoint '));
expect(result.current.field.canAdd).toBe(true);
await act(() => result.current.field.addNew());
expect(addTripTag).toHaveBeenCalledWith(5, { name: 'Viewpoint', color: expect.stringMatching(/^#[0-9a-f]{6}$/) });
expect(result.current.form.tags).toEqual([9]);
expect(result.current.field.name).toBe('');
expect(result.current.field.saving).toBe(false);
expect(toast.error).not.toHaveBeenCalled();
});
it('FE-PLANNER-PLTAGS-005: a name the trip has already ticks that tag once, and an empty name asks nothing', async () => {
addTripTag.mockResolvedValue(zone);
const { result } = setup({ tags: [{ id: 8, name: 'Zone' }] });
act(() => result.current.field.setName(' '));
expect(result.current.field.canAdd).toBe(false);
await act(() => result.current.field.addNew());
expect(addTripTag).not.toHaveBeenCalled();
act(() => result.current.field.setName('zone'));
await act(() => result.current.field.addNew());
expect(result.current.form.tags).toEqual([8]);
});
it('FE-PLANNER-PLTAGS-006: a tag that could not be added says so and keeps the name; offline it asks for a connection', async () => {
addTripTag.mockRejectedValue(new Error('refused'));
const { result } = setup();
act(() => result.current.field.setName('Viewpoint'));
await act(() => result.current.field.addNew());
expect(toast.error).toHaveBeenLastCalledWith('places.tagCreateError');
expect(result.current.field.name).toBe('Viewpoint');
expect(result.current.field.saving).toBe(false);
expect(result.current.form.tags).toBeUndefined();
setOnline(false);
await act(() => result.current.field.addNew());
expect(toast.error).toHaveBeenLastCalledWith('common.needsConnection');
});
it('FE-PLANNER-PLTAGS-007: Enter in the name field adds the tag instead of saving the place; an empty field leaves the key alone', async () => {
addTripTag.mockResolvedValue(buildTag({ id: 9, trip_id: 5, name: 'Viewpoint' }));
const { result } = setup();
const empty = key('Enter');
act(() => result.current.field.handleNameKey(empty.event));
expect(empty.preventDefault).not.toHaveBeenCalled();
act(() => result.current.field.setName('Viewpoint'));
const letter = key('a');
act(() => result.current.field.handleNameKey(letter.event));
expect(letter.preventDefault).not.toHaveBeenCalled();
expect(addTripTag).not.toHaveBeenCalled();
const enter = key('Enter');
act(() => result.current.field.handleNameKey(enter.event));
await waitFor(() => expect(result.current.form.tags).toEqual([9]));
expect(enter.preventDefault).toHaveBeenCalledTimes(1);
expect(addTripTag).toHaveBeenCalledTimes(1);
});
it('FE-PLANNER-PLTAGS-008: a tick made while a tag is on its way is kept, and a second request waits for the first', async () => {
let answer: (tag: Tag) => void = () => undefined;
addTripTag.mockReturnValue(new Promise<Tag>((resolve) => (answer = resolve)));
const { result } = setup();
act(() => result.current.field.setName('Viewpoint'));
let pending: Promise<void> = Promise.resolve();
act(() => {
pending = result.current.field.addNew();
});
expect(result.current.field.saving).toBe(true);
expect(result.current.field.canAdd).toBe(false);
await act(() => result.current.field.addNew());
expect(addTripTag).toHaveBeenCalledTimes(1);
act(() => result.current.field.toggle(7));
await act(async () => {
answer(buildTag({ id: 9, trip_id: 5, name: 'Viewpoint' }));
await pending;
});
expect(result.current.form.tags).toEqual([7, 9]);
});
});
@@ -0,0 +1,103 @@
import { useMemo, useState, type Dispatch, type KeyboardEvent, type SetStateAction } from 'react';
import type { useTranslation } from '../../i18n';
import { useTripStore } from '../../store/tripStore';
import type { Place } from '../../types';
import { offlineOr } from '../../utils/needsConnection';
import { nextTagColor, placeTagIds, tagChoices } from '../../utils/placeTags';
import type { useToast } from '../shared/Toast';
import type { PlaceFormData } from './PlaceFormModal.helpers';
type Translate = ReturnType<typeof useTranslation>['t'];
type Toast = ReturnType<typeof useToast>;
interface PlaceTagsOptions {
tripId: number | string;
/** The place being edited, for the tags it carries already; none while a place is being added. */
place: Pick<Place, 'tags'> | null | undefined;
/** The form's own tags: absent until one is ticked or unticked. */
tags: PlaceFormData['tags'];
setForm: Dispatch<SetStateAction<PlaceFormData>>;
t: Translate;
toast: Toast;
}
/**
* The tags of the place form: the one logic path behind the desktop dialog and the
* phone sheet, which draw their own markup over it. It offers the trip's tags and any
* personal tag the place carries already, keeps which of them are ticked in the form
* itself, so the save sends them, and adds a new tag to the trip, ticked straight away.
*/
export function usePlaceTags({ tripId, place, tags, setForm, t, toast }: PlaceTagsOptions) {
const tripTags = useTripStore((s) => s.tripTags);
const addTripTag = useTripStore((s) => s.addTripTag);
const updateTripTag = useTripStore((s) => s.updateTripTag);
const carried = place?.tags;
const saved = useMemo(() => placeTagIds(carried), [carried]);
const selected = tags ?? saved;
const options = useMemo(
() => tagChoices(tripTags, carried).map((tag) => ({ ...tag, on: selected.includes(tag.id) })),
[tripTags, carried, selected]
);
const [name, setName] = useState('');
const [saving, setSaving] = useState(false);
// The colour picked for the next new tag; until one is picked, the trip's next one in turn.
const [pickedColor, setNewColor] = useState<string | null>(null);
const newColor = pickedColor ?? nextTagColor(tripTags);
/** Changes the ticked set from what it is when the change lands, not from what it was when it was asked for. */
const change = (next: (ids: number[]) => number[]) =>
setForm((prev) => ({ ...prev, tags: next(prev.tags ?? saved) }));
const toggle = (id: number) =>
change((ids) => (ids.includes(id) ? ids.filter((other) => other !== id) : [...ids, id]));
/** The typed name becomes a tag of the trip, or is the one it has already, and is ticked. */
const addNew = async () => {
const wanted = name.trim();
if (!wanted || saving) return;
setSaving(true);
try {
const tag = await addTripTag(tripId, { name: wanted, color: newColor });
change((ids) => (ids.includes(tag.id) ? ids : [...ids, tag.id]));
setName('');
setNewColor(null);
} catch {
toast.error(offlineOr(t, t('places.tagCreateError')));
} finally {
setSaving(false);
}
};
/** A new colour for one of the trip's tags, for every place that carries it. */
const recolor = async (id: number, color: string) => {
try {
await updateTripTag(tripId, id, { color });
} catch {
toast.error(offlineOr(t, t('places.tagColorError')));
}
};
/** Enter in the name field adds the tag; with a name typed it never reaches the place's own save. */
const handleNameKey = (e: KeyboardEvent<HTMLInputElement>) => {
if (e.key !== 'Enter' || !name.trim()) return;
e.preventDefault();
void addNew();
};
return {
options,
toggle,
name,
setName,
newColor,
setNewColor,
recolor,
saving,
canAdd: !!name.trim() && !saving,
addNew,
handleNameKey,
};
}
export type PlaceTagsField = ReturnType<typeof usePlaceTags>;
@@ -0,0 +1,71 @@
import { useState } from 'react';
type Translate = (key: string, params?: Record<string, string | number>) => string;
export type PlaceTextField = 'description' | 'notes' | 'assignment_notes';
interface PlaceTextTab {
field: PlaceTextField;
/** The tab's own short name. */
label: string;
/** The field's name for a screen reader, the one it always had. */
aria: string;
/** Where the text shows up, under the tabs. */
hint: string;
value: string;
/** Rendered as Markdown where it is shown, so the desktop offers the formatting bar. */
markdown: boolean;
maxLength?: number;
}
interface PlaceTextTabsOptions {
description: string;
notes: string;
/** null when no single day-assignment is in context. */
dayNotes: string | null;
/** The day that visit is on, to name the tab after it ("Only day 3"). */
dayNumber?: number | null;
t: Translate;
}
/**
* The place form's three texts as tabs: what the place is, notes on it, and the
* note for one day's visit, which is only there when the form edits one visit.
* The one logic path behind the desktop card and the phone sheet; each draws its
* own tabs and field over it.
*/
export function usePlaceTextTabs({ description, notes, dayNotes, dayNumber = null, t }: PlaceTextTabsOptions) {
const [active, setActive] = useState<PlaceTextField>('description');
const tabs: PlaceTextTab[] = [
{
field: 'description',
label: t('places.notesTabAbout'),
aria: t('places.formDescription'),
hint: t('places.notesHintDescription'),
value: description,
markdown: true,
},
{
field: 'notes',
label: t('places.formNotes'),
aria: t('places.formNotes'),
hint: t('places.notesHintNotes'),
value: notes,
markdown: true,
maxLength: 2000,
},
];
if (dayNotes !== null) {
tabs.push({
field: 'assignment_notes',
label: dayNumber ? t('places.notesTabDayN', { day: dayNumber }) : t('places.notesTabDay'),
aria: t('places.assignmentNotes'),
hint: t('places.notesHintDay'),
value: dayNotes,
markdown: false,
});
}
// The day tab can go away under an open form (the visit is removed elsewhere).
const shown = tabs.find((tab) => tab.field === active) ?? tabs[0];
return { tabs, shown, setActive };
}
@@ -1,9 +1,9 @@
// FE-PLANNER-POOL-001 to FE-PLANNER-POOL-016: the places pool's search, filters and
// FE-PLANNER-POOL-001 to FE-PLANNER-POOL-017: the places pool's search, filters and
// multi-select behind the desktop sidebar ('exit') and the phone browser ('prune').
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { buildPlace } from '../../../tests/helpers/factories';
import { buildPlace, buildTag } from '../../../tests/helpers/factories';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { collectionsApi } from '../../api/collections';
import { useTripStore } from '../../store/tripStore';
@@ -11,6 +11,7 @@ import {
placesFilterTabs,
poolHasTracks,
usePlacesCategoryFilter,
usePlacesFilterTags,
usePlacesPool,
type PlacesPoolOptions,
} from './usePlacesPool';
@@ -287,4 +288,29 @@ describe('usePlacesPool', () => {
act(() => result.current.setSelectedIds(new Set([12345])));
expect(result.current.selectedIds.size).toBe(0);
});
it('FE-PLANNER-POOL-017: the filter offers the tags of the trip and any other a listed place carries, by name', () => {
const monument = buildTag({ id: 7, name: 'Monument', color: '#6366f1' });
const zone = buildTag({ id: 8, name: 'Zone', color: 'not a colour' });
seedStore(useTripStore, { tripTags: [zone, monument] });
const places = [
buildPlace({ tags: [{ id: 7, name: 'Monument (old name)' }] }),
buildPlace({ tags: [{ id: 50, name: 'Hidden gem', color: '#f59e0b' }] }),
buildPlace(),
];
const { result, rerender } = renderHook((listed: typeof places) => usePlacesFilterTags(listed), {
initialProps: places,
});
expect(result.current).toEqual([
{ id: 50, name: 'Hidden gem', color: '#f59e0b' },
// The trip's own name, not the copy on the place.
{ id: 7, name: 'Monument', color: '#6366f1' },
// A colour that is no plain hex value is left out: the row keeps the colour of its text.
{ id: 8, name: 'Zone', color: undefined },
]);
// The same places and tags are the same list, so a row does not redraw for nothing.
const first = result.current;
rerender(places);
expect(result.current).toBe(first);
});
});
+12 -2
View File
@@ -5,6 +5,7 @@ import type { useTranslation } from '../../i18n';
import { useTripStore } from '../../store/tripStore';
import type { Place } from '../../types';
import { offlineOr } from '../../utils/needsConnection';
import { tagChoices } from '../../utils/placeTags';
import { useToast } from '../shared/Toast';
/** What the pool shows: everything, what is not on a day yet, what is, or the tracks. */
@@ -30,8 +31,8 @@ export function placesFilterTabs(t: Translate, hasTracks: boolean) {
/**
* The category filter of the places pool: a set of category ids (plus the
* no-category bucket), many at once. It lives in the trip store, so the list
* and the map markers filter on the same values (#1541).
* no-category bucket) and of tags, many at once. It lives in the trip store, so
* the list and the map markers filter on the same values (#1541).
*/
export function usePlacesCategoryFilter() {
const categoryFilters = useTripStore((s) => s.placesCategoryFilter);
@@ -45,6 +46,15 @@ export function usePlacesCategoryFilter() {
return { categoryFilters, setCategoryFilters, toggleCategoryFilter };
}
/**
* The tags the category filter offers under the categories, for both shells: the
* trip's own, and any other tag one of the listed places carries.
*/
export function usePlacesFilterTags(places: Place[]) {
const tripTags = useTripStore((s) => s.tripTags);
return useMemo(() => tagChoices(tripTags, ...places.map((place) => place.tags)), [tripTags, places]);
}
export interface PlacesPoolOptions {
tripId: number;
/** Every place of the trip: a selected place that is gone from here is gone. */
@@ -125,14 +125,15 @@ describe('stageMapData with a stage', () => {
expect(stageMapData(routes(), stage, true).lines).toEqual([LINES[1], LINES[2]])
})
it('FE-RTSTAGE-016: the drive into the next day is left off the stage', () => {
// With "connect the days" on, that leg is drawn in the colour of the day it leaves, so
it('FE-RTSTAGE-016: the drive in from the day before is left off the stage', () => {
// With "connect the days" on, that leg is drawn as the day it arrives on (#3123), so
// filtering by day number alone handed the stage a line running off it to a place the
// day never visits. On a phone, where the stage IS the map, it was the longest thing
// on screen and read as the day's own route.
const withJoin = routes({ lineJoins: [false, false, true, false] })
// on screen and read as the day's own route. The assembler emits it first among the
// lines of the day it reaches, ahead of that day's own legs.
const withJoin = routes({ lineJoins: [false, true, false, false] })
expect(stageMapData(withJoin, stage, true).lines).toEqual([LINES[1]])
expect(stageMapData(withJoin, stage, true).lines).toEqual([LINES[2]])
})
it('FE-RTSTAGE-020: a day that is nothing but driving keeps its connection rather than going blank', () => {
@@ -144,7 +145,7 @@ describe('stageMapData with a stage', () => {
})
it('FE-RTSTAGE-017: the colours still line up once a join has been dropped', () => {
const data = stageMapData(routes({ lineJoins: [false, false, true, false] }), stage, true)
const data = stageMapData(routes({ lineJoins: [false, true, false, false] }), stage, true)
expect(data.lineColors).toHaveLength(data.lines.length)
expect(data.lineColors).toEqual([dayColor(2)])
@@ -153,7 +154,7 @@ describe('stageMapData with a stage', () => {
it('FE-RTSTAGE-018: the all-days view keeps the joins, which is the view they are for', () => {
// The setting draws the whole drive as one connected line; that is what it is for, and
// on this map the connection has the other days beside it.
expect(stageMapData(routes({ lineJoins: [false, false, true, false] }), null, true).lines).toEqual(LINES)
expect(stageMapData(routes({ lineJoins: [false, true, false, false] }), null, true).lines).toEqual(LINES)
})
it('FE-RTSTAGE-019: routes from before the flag existed are drawn as they were', () => {
+8 -8
View File
@@ -50,15 +50,15 @@ export function stageMapData(
}
if (!routes.lines.length) return { ...EMPTY, placeIds: stagePlaceIds(stage), focusPoints: stagePoints(stage) }
// A stage is ONE day, so the drive into the next day is left off it.
// A stage is ONE day, so the drive in from the day before is left off it.
//
// With "connect the days" on, that leg is drawn in the colour of the day it leaves, so
// on the whole-drive map it reads as that day carrying on. Filtering by day number
// alone therefore handed a stage a line that runs off it to a place the day never
// visits: on a phone, where the stage IS the map, that read as the day's own route and
// was the longest thing on screen. The desktop has the same connection, but it has it
// beside every other day, which is the view the setting exists for; here that view is
// the "all days" one, a tap away on the same map.
// With "connect the days" on, that leg is drawn as the day it arrives on, the day whose
// distance counts it. Filtering by day number alone therefore handed a stage a line
// that runs off it to a place the day never visits: on a phone, where the stage IS the
// map, that read as the day's own route and was the longest thing on screen. The
// desktop has the same connection, but it has it beside every other day, which is the
// view the setting exists for; here that view is the "all days" one, a tap away on the
// same map.
const ofDay: number[] = []
routes.lineDays.forEach((n, i) => { if (n === stage.dayNumber) ofDay.push(i) })
const own = ofDay.filter(i => !routes.lineJoins?.[i])
@@ -631,7 +631,7 @@ describe('useRoadtripRoutes', () => {
expect(result.current.totalDistance).toBe(300000)
})
it('FE-ROADTRIP-ROUTES-022: the joining stroke wears the day it leaves, its kilometres the day it reaches', async () => {
it('FE-ROADTRIP-ROUTES-022: the joining stroke wears the day it reaches, like its kilometres (#3123)', async () => {
setting({ roadtrip_connect_days: true })
const { days: daysList, assignments } = twoDays()
const { result } = renderHook(() => useRoadtripRoutes(7, daysList, assignments))
@@ -639,10 +639,9 @@ describe('useRoadtripRoutes', () => {
// Same length and same order as `lines`, or a colour lands on the wrong day.
expect(result.current.lineDays).toHaveLength(result.current.lines.length)
// The stroke starts at a stop on day 1, so drawing it as day 2 would make day 2
// look like it begins somewhere it has no stop.
expect(result.current.lineDays).toEqual([1, 1, 2])
// The kilometres go the other way: they are driven on the day they arrive.
// Day 1 ends at its last stop, so the drive on to day 2 is driven on day 2: its
// kilometres are counted there, and drawn in day 1's colour the map said otherwise.
expect(result.current.lineDays).toEqual([1, 2, 2])
expect(result.current.days.map(d => d.distance)).toEqual([100000, 200000])
})
@@ -666,7 +665,8 @@ describe('useRoadtripRoutes', () => {
setting({ roadtrip_connect_days: true })
expect(result.current.lines).toHaveLength(3)
expect(result.current.lineDays).toEqual([1, 2, 2])
// The drive past midnight lands on day 2 and is drawn there, like day 2's own legs.
expect(result.current.lineDays).toEqual([2, 2, 2])
expect(result.current.days[0].distance).toBe(300000)
})
+16 -4
View File
@@ -174,12 +174,24 @@ export function PopoverListPanel({ list, label, className = '', children }: {
}
/** The dashed full-width button that adds a row: a stop, a leg. */
export function AddRowButton({ onClick, disabled, children }: { onClick: () => void; disabled?: boolean; children: ReactNode }) {
export function AddRowButton({ onClick, disabled, raised = false, children }: {
onClick: () => void
disabled?: boolean
/**
* On a PANEL: the white raised button of the cards (the costs' "Create expense"),
* at its size, instead of a dashed outline on grey.
*/
raised?: boolean
children: ReactNode
}) {
const look = raised
? 'gap-2 border-transparent bg-surface-card px-[13px] text-content shadow-sm ring-1 ring-edge-faint hover:bg-surface-hover'
: 'gap-1.5 border-dashed border-edge px-3 text-content-muted hover:border-content-faint hover:text-content'
return (
<button type="button" onClick={onClick} disabled={disabled}
className="flex w-full items-center justify-center gap-1.5 rounded-[10px] border border-dashed border-edge px-3 py-2 font-semibold text-content-muted hover:border-content-faint hover:text-content disabled:cursor-default disabled:opacity-50"
style={fs(12, 'body')}>
<Plus size={13} strokeWidth={2.2} />{children}
className={`flex w-full items-center justify-center rounded-[10px] border py-2 font-semibold transition-colors disabled:cursor-default disabled:opacity-50 ${look}`}
style={fs(raised ? 13 : 12, 'body')}>
<Plus size={raised ? 14 : 13} strokeWidth={2.2} />{children}
</button>
)
}
+12
View File
@@ -0,0 +1,12 @@
import type { Tag } from '@trek/shared';
import { offlineDb } from './offlineDb';
/** The trip's tags as the server last listed them; none while the device never read them. */
export async function cachedTripTags(tripId: number): Promise<Tag[]> {
return (await offlineDb.tripTags.get(tripId))?.tags ?? [];
}
/** Keeps the trip's tags as the server listed them. */
export async function cacheTripTags(tripId: number, tags: Tag[]): Promise<void> {
await offlineDb.tripTags.put({ tripId, tags });
}
+17
View File
@@ -70,6 +70,16 @@ interface CachedTourDraft {
draft: TourDraft;
}
/**
* The tags a trip owns, as the server last listed them: one row per trip, so the
* place form and the category filter still offer them offline. Not the `tags`
* table, which holds the signed-in user's personal ones.
*/
interface CachedTripTags {
tripId: number;
tags: Tag[];
}
/**
* A road route as the router answered it, kept on the device so a trip opens
* with its roads drawn instead of asking the router for every leg again (#2794).
@@ -293,6 +303,7 @@ export class TrekOfflineDb extends Dexie {
tourStationVisits!: Table<CachedTourStationVisit, [number, string]>;
tourDrafts!: Table<CachedTourDraft, number>;
routeCache!: Table<CachedRoute, string>;
tripTags!: Table<CachedTripTags, number>;
constructor(name: string = ANON_DB_NAME) {
super(name);
@@ -385,6 +396,10 @@ export class TrekOfflineDb extends Dexie {
// whole route shown opens drawn instead of re-routing every leg (#2794). Not per
// trip: the same waypoints are the same road in any trip; `savedAt` to prune.
this.version(14).stores({ routeCache: 'key, savedAt' });
// v15: the tags a trip owns, one list per trip, so they are offered offline
// and go with the trip.
this.version(15).stores({ tripTags: 'tripId' });
}
}
@@ -686,10 +701,12 @@ export async function clearTripData(tripId: number): Promise<void> {
offlineDb.ferrataTiles,
offlineDb.tourStationVisits,
offlineDb.tourDrafts,
offlineDb.tripTags,
],
async () => {
await offlineDb.roadtripPreferences.delete(tripId);
await offlineDb.tourDrafts.delete(tripId);
await offlineDb.tripTags.delete(tripId);
await offlineDb.budgetSettlements.delete(tripId);
await offlineDb.days.where('trip_id').equals(tripId).delete();
await offlineDb.places.where('trip_id').equals(tripId).delete();
+4
View File
@@ -69,6 +69,10 @@ export function useTripRangeGuard(): { checking: boolean; check: (trip: Pick<Tri
startDate: range.newStart,
endDate: range.newEnd,
dayCount: range.dayCount,
// The rule the server lays the days out by when bookings keep their dates,
// the default either dialog saves with. Shifting everything moves no day
// that this keeps, so the dated days it removes are the same.
keepDates: true,
})
if (plan.removed.length === 0) return null
+1
View File
@@ -14,6 +14,7 @@ import { useNativeCapabilities } from '../native/capabilities'
import { isNativeIos } from '../native/platform'
import { useWindowFold } from '../native/windowFold'
import './mobile.css'
import './corner.css'
interface MobileShellProps {
isPhone: boolean
@@ -48,7 +48,7 @@ export default function MImageViewer({
type="button"
onClick={onClose}
aria-label={t('collab.chat.closeImage')}
className="absolute end-4 top-[calc(var(--m-safe-top,12px)+4px)] z-10 flex h-10 w-10 items-center justify-center rounded-full bg-[color:var(--m-viewer-btn)] text-[color:var(--m-viewer-ink)]"
className="m-corner-beside absolute end-4 top-[calc(var(--m-safe-top,12px)+4px)] z-10 flex h-10 w-10 items-center justify-center rounded-full bg-[color:var(--m-viewer-btn)] text-[color:var(--m-viewer-ink)]"
>
<X size={20} strokeWidth={2} />
</button>
+9 -5
View File
@@ -1,4 +1,4 @@
import { useLayoutEffect, useRef, useState, type ReactNode, type RefObject } from 'react';
import { useCallback, useLayoutEffect, useRef, useState, type ReactNode, type RefObject } from 'react';
import { edgeFadeClass, useEdgeFade } from './useEdgeFade';
/**
@@ -30,6 +30,13 @@ export function MRail({
useEvenLines(listRef);
// On a short window the entries scroll; the cut edge fades, so the foot's entries read as more below.
const [list, setList] = useState<HTMLDivElement | null>(null);
// One function for the rail's lifetime: React 19 detaches and attaches a ref
// whose function changed, so an inline one set the state to null and back on
// every render and the trip's rail rendered itself into React's update limit.
const listNode = useCallback((node: HTMLDivElement | null) => {
listRef.current = node;
setList(node);
}, []);
const fade = useEdgeFade(list, 'y');
return (
<nav
@@ -38,10 +45,7 @@ export function MRail({
>
{head && <div className="mb-2 flex flex-none justify-center">{head}</div>}
<div
ref={(node) => {
listRef.current = node;
setList(node);
}}
ref={listNode}
className={`flex min-h-0 w-full flex-1 flex-col items-center gap-1 overflow-y-auto px-1 [scrollbar-width:none] ${edgeFadeClass(fade, 'y')}`}
>
{children}
+1 -1
View File
@@ -89,7 +89,7 @@ export function MSectionList({
* width on both screens.
*/
export const SECTION_SCREEN =
'px-4 pb-[calc(var(--bottom-nav-h,84px)+16px)] pt-[var(--m-safe-top,12px)] wide:mx-auto wide:max-w-[1040px] wide:px-6 split:grid split:max-w-[1240px] split:grid-cols-[260px_minmax(0,1fr)] split:items-start split:gap-8';
'm-corner-flow px-4 pb-[calc(var(--bottom-nav-h,84px)+16px)] pt-[var(--m-safe-top,12px)] wide:mx-auto wide:max-w-[1040px] wide:px-6 split:grid split:max-w-[1240px] split:grid-cols-[260px_minmax(0,1fr)] split:items-start split:gap-8';
interface MSectionNavProps {
title: string;
+4 -3
View File
@@ -86,11 +86,11 @@ type MSheetWideAnchor = 'center' | 'rail-foot'
* docked sheet just above the dock; neither lies across the dock.
*/
const REGION: Record<MSheetVariant, string> = {
card: 'inset-x-[14px] top-[var(--m-safe-top,12px)] bottom-[calc(var(--bottom-nav-h,84px)+12px)] justify-center',
card: 'inset-x-[14px] top-[max(var(--m-safe-top,12px),var(--m-corner-clear,0px))] bottom-[calc(var(--bottom-nav-h,84px)+12px)] justify-center',
// On a phone on its side the gap it keeps at the top would leave it a strip
// of a few rows, so there it may rise nearly to the top.
bottom:
'inset-x-4 top-[calc(var(--m-safe-top,12px)+56px)] bottom-[calc(var(--bottom-nav-h,84px)+16px)] justify-end short:top-[calc(var(--m-safe-top,12px)+8px)]',
'inset-x-4 top-[max(calc(var(--m-safe-top,12px)+56px),var(--m-corner-clear,0px))] bottom-[calc(var(--bottom-nav-h,84px)+16px)] justify-end short:top-[calc(var(--m-safe-top,12px)+8px)]',
drawer: 'start-0 top-0 bottom-0 w-[78%] max-w-[320px]',
}
@@ -116,7 +116,8 @@ const SHORT_FORM_BOX = 'short:max-w-[640px] short:flex-1'
function regionClass(variant: MSheetVariant, anchor: MSheetWideAnchor = 'center', form = false): string {
const base = 'pointer-events-none absolute flex flex-col'
if (variant === 'drawer') return `${base} ${REGION.drawer}`
return `${base} ${REGION[variant]} ${WIDE_REGION[anchor]}${form ? ` ${SHORT_FORM_REGION}` : ''}`
// m-corner-side: on a wide window the sheet keeps off a corner element's side (a Duo's status capsule).
return `${base} m-corner-side ${REGION[variant]} ${WIDE_REGION[anchor]}${form ? ` ${SHORT_FORM_REGION}` : ''}`
}
/** The sheet's own box inside the region: its width, and the arrow when it has one. */
+31
View File
@@ -0,0 +1,31 @@
/* ── An element in a top corner (an iPhone Duo's status capsule) ──────────────
Beside mobile.css, which holds the variables these read (--m-corner-*).
For the screens that place their own controls rather than sit in .m-page
(the trip, its map). Every variable is 0 without such an element, so these
change nothing on any other device.
m-corner-beside: a control row in the corner's height ends before it.
m-corner-side: a layer that fills the page ends before the corner's side on
a wide window (--m-corner-side-*, 0 upright, where content starts below the
corner through --m-corner-clear instead).
The element sits where the hardware puts it, whatever the reading
direction, so right to left swaps the two sides back. */
.m-corner-beside {
margin-inline: var(--m-corner-l-gap, 0px) var(--m-corner-r-gap, 0px);
}
html[dir='rtl'] .m-corner-beside {
margin-inline: var(--m-corner-r-gap, 0px) var(--m-corner-l-gap, 0px);
}
.m-corner-side {
margin-inline: var(--m-corner-side-l, 0px) var(--m-corner-side-r, 0px);
}
html[dir='rtl'] .m-corner-side {
margin-inline: var(--m-corner-side-r, 0px) var(--m-corner-side-l, 0px);
}
/* m-corner-beside-in: m-corner-beside for a row inside .m-page, upright only
(on a wide window the page itself already ends before the corner). */
.m-corner-beside-in {
margin-inline: var(--m-corner-in-l, 0px) var(--m-corner-in-r, 0px);
}
html[dir='rtl'] .m-corner-beside-in {
margin-inline: var(--m-corner-in-r, 0px) var(--m-corner-in-l, 0px);
}
+48 -3
View File
@@ -86,6 +86,23 @@
* the air is 0 too (min() of 0 and 8px). */
--m-safe-l-gap: calc(var(--m-bar-l) + min(var(--m-bar-l), 8px));
--m-safe-r-gap: calc(var(--m-bar-r) + min(var(--m-bar-r), 8px));
/* The corner element alone, with the same air, for the screens that place
* their own controls (the trip, the map): a control row in the corner's
* height ends this far from the screen's side (m-corner-beside). Physical
* sides, as the element is: right to left does not move it. */
--m-corner-l-gap: calc(var(--trek-native-corner-left, 0px) + min(var(--trek-native-corner-left, 0px), 8px));
--m-corner-r-gap: calc(var(--trek-native-corner-right, 0px) + min(var(--trek-native-corner-right, 0px), 8px));
/* Where the content of a screen that places its own scroll body begins at
* the latest, so its first row is not under the corner element: just below
* it (m-corner-below). Upright that is the cheaper way round; on a wide
* window the page gives up the corner's side instead (below). 0 elsewhere. */
--m-corner-clear: calc(var(--m-corner-b) + min(var(--m-corner-b), 10px));
--m-corner-side-l: 0px;
--m-corner-side-r: 0px;
/* The same air for a control row inside .m-page, which on a wide window has
* already given up the corner's side (m-corner-beside-in). */
--m-corner-in-l: var(--m-corner-l-gap);
--m-corner-in-r: var(--m-corner-r-gap);
/* 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;
@@ -98,10 +115,21 @@
* 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(var(--m-safe-l) + 100px);
--m-rail-w: calc(var(--m-bar-l) + 100px);
/* A wide window gives up the corner element's side over the whole height,
* as an iPhone on its side does for its camera: on an unfolded Duo lifting
* every page below the status capsule cost a quarter of the height. The
* rail already takes the leading side, so only the trailing side's corner
* counts here. */
--m-corner-clear: 0px;
--m-corner-side-r: var(--m-corner-r-gap);
--m-corner-in-l: 0px;
--m-corner-in-r: 0px;
}
html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-root {
--m-rail-w: calc(var(--m-safe-r) + 100px);
--m-rail-w: calc(var(--m-bar-r) + 100px);
--m-corner-side-l: var(--m-corner-l-gap);
--m-corner-side-r: 0px;
}
.dark .m-root {
@@ -631,13 +659,30 @@ html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-
the leading inset on a wide window. */
.m-page {
margin-inline: var(--m-page-l, 0px) var(--m-page-r, 0px);
padding-top: max(0px, calc(var(--m-corner-b, 0px) + 12px - var(--m-safe-top, 12px) - 70px));
padding-top: max(0px, calc(var(--m-corner-clear, 0px) + 2px - var(--m-safe-top, 12px) - 70px));
}
html[dir='rtl'] .m-page {
margin-inline: var(--m-page-r, 0px) var(--m-page-l, 0px);
}
/* The lift above counts on a floating top bar over the page. A screen whose
first row is part of the page (m-corner-flow: settings, administration,
collections) is lifted until that row starts below the corner element; one
that keeps clear of it by itself (m-corner-own: a map under its own bars, a
calendar under its own header) is not lifted at all. */
.m-page:has(.m-corner-flow) {
padding-top: max(0px, calc(var(--m-corner-clear, 0px) - var(--m-safe-top, 12px)));
}
.m-page:has(.m-corner-own) {
padding-top: 0;
}
/* On a wide window the page starts at the top and ends before the corner
element instead (--m-corner-side-*, 0 without one). */
html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-page {
margin-inline-start: 0;
margin-inline-end: max(var(--m-page-r, 0px), var(--m-corner-side-r, 0px));
}
html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-page {
margin-inline-end: max(var(--m-page-l, 0px), var(--m-corner-side-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
+1 -1
View File
@@ -122,7 +122,7 @@ export default function MAtlas() {
return (
// h-dvh, not h-full: the shell stopped providing a definite height (#1809)
// and a map on a percentage of an auto-height parent collapses to zero.
<div ref={rootRef} className="m-bleed relative h-dvh overflow-hidden">
<div ref={rootRef} className="m-bleed m-corner-own relative h-dvh overflow-hidden">
<div ref={mapRef} className="absolute inset-0 z-[1] bg-[color:var(--m-mapb)] [&_.leaflet-control-zoom]:hidden" />
{/* Region hover tooltip — positioned imperatively by useAtlas. */}
<div
@@ -50,7 +50,7 @@ export default function MAtlasSearch({
const q = query.trim().toLowerCase()
const rows = q ? options.filter((o) => o.label.toLowerCase().includes(q)).slice(0, 6) : suggestions
const scrimCls = 'm-fade-in fixed inset-0 z-[70] flex flex-col bg-[rgba(16,16,19,.28)] px-[18px] pt-[calc(var(--m-safe-top,12px)+12px)] backdrop-blur-[22px] backdrop-saturate-[1.6] wide:pt-[calc(var(--m-safe-top,12px)+72px)] wide:[&>*]:mx-auto wide:[&>*]:w-full wide:[&>*]:max-w-[640px]' // theme-lint-disable — fixed scrim value from the design
const scrimCls = 'm-fade-in fixed inset-0 z-[70] flex flex-col bg-[rgba(16,16,19,.28)] px-[18px] pt-[max(calc(var(--m-safe-top,12px)+12px),var(--m-corner-clear,0px))] backdrop-blur-[22px] backdrop-saturate-[1.6] wide:pt-[calc(var(--m-safe-top,12px)+72px)] wide:[&>*]:mx-auto wide:[&>*]:w-full wide:[&>*]:max-w-[640px]' // theme-lint-disable — fixed scrim value from the design
return (
<div
@@ -220,7 +220,7 @@ export default function MCollections() {
// Map view fills the viewport like the trip and journal maps do (#2104);
// h-dvh because the shell owns no scroll container (#1809). List view
// keeps the document as the scroller.
className={`px-4 pb-[calc(var(--bottom-nav-h,84px)+12px)] pt-[var(--m-safe-top,12px)] wide:px-6 split:grid split:grid-cols-[260px_minmax(0,1fr)] split:gap-8 ${c.view === 'map' ? 'flex h-dvh flex-col overflow-hidden' : 'wide:mx-auto wide:max-w-[1040px] split:max-w-[1240px] split:items-start'}`}
className={`m-corner-flow px-4 pb-[calc(var(--bottom-nav-h,84px)+12px)] pt-[var(--m-safe-top,12px)] wide:px-6 split:grid split:grid-cols-[260px_minmax(0,1fr)] split:gap-8 ${c.view === 'map' ? 'flex h-dvh flex-col overflow-hidden' : 'wide:mx-auto wide:max-w-[1040px] split:max-w-[1240px] split:items-start'}`}
>
{split && (
<nav
@@ -66,7 +66,7 @@ export default function MUserMenu({ open, onClose }: MUserMenuProps): React.Reac
}
return (
<MDropdownPanel open={open} onClose={onClose} className="end-4 top-[calc(var(--m-safe-top,12px)+68px)]">
<MDropdownPanel open={open} onClose={onClose} className="m-corner-beside end-4 top-[calc(var(--m-safe-top,12px)+68px)]">
<div className="flex items-center gap-[10px] p-[10px_10px_12px]">
<span className="flex h-10 w-10 flex-none items-center justify-center overflow-hidden rounded-full bg-[image:linear-gradient(135deg,#6A6A74,#1A1A1E)] text-[0.9375rem] font-bold text-white">
{user?.avatar_url
@@ -346,7 +346,7 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
return (
// h-dvh, not h-full: the shell stopped providing a definite height (#1809)
// and a map on a percentage of an auto-height parent collapses to zero.
<div ref={rootRef} className="m-bleed relative h-dvh overflow-hidden" style={headSlot ? IN_SHELL_ROW : undefined}>
<div ref={rootRef} className="m-bleed m-corner-own relative h-dvh overflow-hidden" style={headSlot ? IN_SHELL_ROW : undefined}>
{/* Integrated map — always mounted, the gallery overlays it. Beside the feed
it begins where the feed ends, so its controls and its framing stay in
the part that can be seen. */}
@@ -358,7 +358,7 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
ref={mapRef}
layers={mapLayers}
hideLayerControl
controlsTop="calc(var(--m-safe-top, 12px) + 50px)"
controlsTop="max(calc(var(--m-safe-top, 12px) + 50px), var(--m-corner-clear, 0px))"
// Its satellite switch sits in the bar above, beside the menu.
baseLayer={mapBase}
onOpenEntry={handleMarkerClick}
@@ -382,7 +382,7 @@ export default function MJourneyDetail({ journeyId, embedded = false }: JourneyD
{/* Gallery tab overlay */}
{view === 'gallery' && (
<div className="m-span-x absolute inset-y-0 z-[5] overflow-y-auto bg-[color:var(--m-bg)] bg-[image:var(--m-scr)] px-4 pt-[calc(var(--m-safe-top,12px)+56px)] pb-[calc(var(--bottom-nav-h,84px)+16px)] wide:px-6">
<div className="m-span-x absolute inset-y-0 z-[5] overflow-y-auto bg-[color:var(--m-bg)] bg-[image:var(--m-scr)] px-4 pt-[max(calc(var(--m-safe-top,12px)+56px),var(--m-corner-clear,0px))] pb-[calc(var(--bottom-nav-h,84px)+16px)] wide:px-6">
{gallery.length === 0 ? (
<div className="flex min-h-full flex-col items-center justify-center px-8 py-10 text-center">
<MDancingTrek scene="journey" className="mb-2" />

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