Compare commits

..

47 Commits

Author SHA1 Message Date
Maurice 965b519f23 test(notes): wait for the caret frame before typing in the numbered list test 2026-11-23 12:11:46 +01:00
Maurice 3ec7cc73b2 fix(notes): number list items in order from the format toolbar
The numbered list button always inserted '1. ' and only on the caret's line, so writing a list item by item left 1. 1. 1. in the field. It now continues from the item above and formats every line of a multi-line selection (bullets and quotes too).
2026-11-23 12:05:03 +01:00
Maurice 493571c559 fix(android): log the address and sender of a page that fails with an HTTP error
When the server's page came back with an error status, the app went to the
address screen with "HTTP 503" and logged nothing, not even which page it
was. A report could then not tell the server, a proxy in front of it and
something on the phone apart: the reporter's Cloudflare and Traefik logs
show no 503, and the page was not requested at all.

Every main-frame HTTP error is now logged under TrekShell with the page's
address (without its query, where a sign-in page carries a challenge), the
status, the reason phrase and the headers that name whoever answered
(Server, Via, CF-Ray, Content-Type). An answer with none of them says so,
which points at something on the phone. What the app does with the error
is unchanged.

Refs #3014
2026-11-22 22:58:02 +01:00
Maurice 4212fcdfc8 style(i18n): format the new PDF strings with an apostrophe
lint:format in shared: Prettier writes a string holding an apostrophe in
double quotes; the Catalan, French and Dutch PDF strings now follow it.
2026-11-22 22:39:01 +01:00
Maurice 28f750f7c4 fix(pdf): give formatMoney a locale, lower the strict entry of the export
lint:strict: a place's price passed the export's locale, which can be
undefined, to formatMoney; it falls back to en like the export's other
money figures. The rewritten TripPDF.tsx holds 1 strict error instead of 38,
and its entry is lowered to that.
2026-11-22 22:28:09 +01:00
Maurice 8c9cf4a80c fix(pdf): handle a failed cover bake where it happens, lower the eslint baseline
Client types: the overview test used Array.prototype.at, which the client's
lib setting does not include; it reads the last cell with slice instead.

Client lint: the export swallowed a failed cover bake with .catch(() => null).
bakePdfCover now catches a canvas that will not draw or encode itself and says
why, so the export calls it plainly. The rewrite also leaves fewer warnings,
and the baseline is lowered to the counts the run measured: complexity 216,
no-explicit-any 138, no-unused-vars 117, and in the tests
no-non-null-assertion 1872.
2026-11-22 22:19:51 +01:00
Maurice b33d592325 perf(pdf): draw the first pages once, not on every scroll
The cover and the route overview stuttered in the preview and in the saved
file, in every viewer:

- The cover photo was embedded at its upload size, 4000 px and more, under
  a translucent gradient across the whole page, which every viewer had to
  composite again on each redraw. The export now crops the photo to the
  page at print size (A4 at 150 dpi) and paints the shade into it, one flat
  JPEG. A photo from another origin keeps the photo and the gradient.
- The route overview drew every point of the routed roads, about 35,000 on
  a two-week trip and most of them on the same pixel, twice each (casing
  and line). Points that round onto the one before are dropped and the rest
  thinned within a third of a pixel (Douglas-Peucker): about 900 points,
  the same shape on paper.
- The cover's glass is a tinted fill without a backdrop blur, and the
  casing under the cover route is opaque.

Also spells out the span and status keys so the key check can follow them,
keeps types nothing imports private, and drops the export's theme and rtl
baseline entries, which reach zero.
2026-11-22 22:10:52 +01:00
Maurice 590b174dd1 feat(pdf): draw the trip's route on the cover, keep its figures on one line
The cover gains the trip's own shape: every routed day drawn in its map
colour on a glass card beside the title, a band of the days' colours with
the first and last date under it, and the dates on a pill above the title.
The figures sit in one row and never break inside a number.

Print engines leave out a backdrop blur, so the glass gets a tinted fill
that reads on paper; the blur stays for the preview. The dates of the day
overview are aligned to the start.
2026-11-22 21:52:27 +01:00
Maurice 2a833c4ba9 fix(pdf): keep a note's second line in its card, fill the preview width
A day note's time field is the free line the day plan prints under its
text, not a clock: it printed in the narrow time column and broke into a
word per line. It stays in the card again, and the time column is empty.

The preview showed the A4 sheet at its print width inside the wider
dialog, with a pale band on either side; on screen the document now fills
the frame, as it did before. The stops column of the day overview is
centred under its pin.

Tests for the day's cards, the cover and overview, and the new preview
switches.
2026-11-22 21:43:34 +01:00
Maurice a5de1bc52d feat(pdf): redesign the trip PDF
The trip PDF gets a new layout in the app's current look, with nothing it
printed before left out and more of each place on the page.

- Cover: the trip photo full bleed, title and dates over it, the trip's
  figures on frosted tiles.
- Overview: the route map, every day at a glance (colour, date, plan, the
  night's stay, stops, cost) and all bookings and stays with their codes.
- Days: the header in the day's map colour, a photo strip of the day's
  stops, where the night is spent, then the plan as a timeline with the
  times on the left.
- Places: photo or category tile, category, duration, price, rating, tags,
  address, coordinates, description, notes, opening hours of that day,
  phone, website, e-mail and the members going. The rating, e-mail, hours
  and reservation note come from the trip's place, since the assignment
  only carries a projection of it.
- Bookings: route first, then airline, number, seat or platform as badges,
  each leg with its own code, status and the booking's code.
- A second row of switches in the preview: overview, photos, coordinates,
  and contact and hours, next to page per day, large text and transport
  notes. Each one is a class on the document and remembered.

The document is split into modules for its helpers, icons, stylesheet,
cover and overview, and the day, so the export itself only gathers the data.
2026-11-22 21:34:29 +01:00
Maurice 1b20214a7f fix(planner): show the drive to a rental car's return and away from its pickup
On the day a rental car is picked up the route ended at the desk, and on the
day it is returned it started at the return, the way it does for an overnight
train. The drive with the car itself showed nowhere: a stop planned before the
return got no travel time to it, in the day plan on the phone and the desktop
and on the map, and neither did the first stop after the pickup.

A car or bicycle rental is now a stop the day's drive passes through on those
two days. Bookings that are ridden keep their one-sided endpoint, and two
bookings back to back still get no drive between them (#1394).
2026-11-22 19:48:34 +01:00
Maurice 3e8496dce6 feat(ios): hide the status bar where a corner capsule was measured
On a window where the app measured an element in a top corner, an iPhone
Duo's status capsule, it now hides the status bar, which is meant to take
the capsule away; whatever still covers the corner stays in the safe area
the page keeps clear of. Each window size keeps its answer once seen, so
hiding the bar never brings it back, and the folded and unfolded displays
decide on their own. Devices without such an element are not affected.
2026-11-22 19:36:31 +01:00
Maurice ea1b75e639 fix(mobile): keep every screen clear of the iPhone Duo's status capsule
The capsule in a top corner was handled screen by screen: the m-corner-*
classes and --m-corner-clear put bars beside it and lifted content below
it, so every layer that did not opt in sat under it, and testers found it
on almost every page.

It now counts as safe area in mobile.css. Upright the top inset reaches
below the capsule and the sides keep their full width; on a wide window
its side is given up over the whole height instead. The per-screen
handling and corner.css are gone. Control rows a screen places itself and
layers that fill the window keep to the side insets through m-safe-row and
m-safe-trail, and the trip's pane keeps its content off the capsule's side
on a wide window. On every other device the insets come out as before.
2026-11-22 19:36:31 +01:00
Maurice c0f6551cf4 test(server): send the API key requests without awaiting in a loop
Server lint counted one no-await-in-loop warning over the tests baseline, from the loop in the new API key test.
2026-11-22 18:24:15 +01:00
Maurice 1fdf74e7f2 fix(auth): mark an address the account moved before an admin saved it
Both backfills of email_self_asserted skip any account with an
admin.user_update row naming email. The edit dialog sends the email on every
save, so a role change made long after an account moved its own address kept
it at 0, and a verified SSO sign-in with that address still linked into it.

A new migration reads the address each admin save found (targetUser): an
account is marked when every save already found its current address, or when
the last save that found another one sent no email. A save that may have typed
the current address in still leaves the account alone, since the audit rows
cannot tell it from a change the account made itself before 5.0.0. Only rows
still at 0 are touched and nothing is cleared.
2026-11-22 18:15:51 +01:00
Maurice c7de823c78 fix(auth): renew a session cookie only after it verifies on its own
SessionRenewalInterceptor took req.user as proof that the trek_session cookie
had been verified. On a route with its own guard chain that does not hold:
ApiTokenGuard authenticates a public API key and sets req.user, and the cookie
sent beside it is never checked. Past half its lifetime such a cookie was
decoded without its signature and renewed, so a holder of a read-only key
could come away with a signed session of the key's owner.

The interceptor now runs the cookie through the guards' own check (signature,
expiry, password version, active session) before it renews, requires it to
name the request's user, and renews nothing on a request a public API key
authenticated.
2026-11-22 18:15:51 +01:00
Maurice 49b9ffc77d fix(client): keep the seat change clear of the sheet's held ref and of non-null assertions
Client lint was red: passing the ref-held reservation to bookingSeats added a react-hooks/refs warning in MTransportSheet, so the sheet now reads the seats from the legs it already has (seatsOfLegs). The new PDF test used a non-null assertion.
2026-11-21 15:45:04 +01:00
Maurice 7006891ce0 style(server): format the legs-only seat test
Server lint was red: lint:format found the new update_transport cases in tools-transports.test.ts unformatted.
2026-11-21 15:37:00 +01:00
Maurice 4d01439c75 test(server): type the created transport in the legs-only seat test
Server lint was red: the new MCP test cast its result to any, one no-explicit-any warning over the tests baseline.
2026-11-21 15:29:53 +01:00
Maurice adb6a2c80d fix(planner): show each leg's own seat on a flight with a stop
A flight with a stop saves a seat per leg, but every view read the
booking's flat seat, which mirrors the first leg's. A seat booked only on
the second leg showed nowhere, and one on the first leg showed on both.
#2701 had fixed this for trains only.

- getFlightLegs reads each leg's seat. The first leg falls back to the flat
  seat, as the booking form does, so older bookings keep theirs.
- bookingSeats lists the seat of every leg that has one with its route.
  The detail views (the phone's transport sheet, the booking detail) show
  each leg's seat under its route ("Seat IST → JFK"), and a leg opened
  from its row shows its own. The cards and field grids (bookings list,
  the phone's Bookings and Transports tabs, the day plan's transport
  detail) hold every seat in one Seat cell, so a card cutting its grid
  short no longer drops the second leg's.
- The day plan's flight leg rows carry their seat, and the PDF prints a
  flight's seat, direct or per leg.
- The watch and the Wallet pass name every leg's seat of the booking.
- A legs-only MCP update sets the flat seat, airline and flight number
  (train number and platform) again from the new first leg, so a seat
  taken off the first leg does not live on in the flat seat. A flat value
  the stored first leg never had stays.

Closes #3158
2026-11-21 15:24:52 +01:00
Maurice 1824cc77ec fix(ci): bring the per-trip addon tests and ratchets in step
The second run of #3157 was red in six jobs:
- Server types: ReminderJobsService takes AddonsService now; RJOB-007 built
  it with five arguments.
- Server tests 2/10: the doc-sync job tests stubbed AddonsService without
  isEnabledForTrip, which the sync asks per trip now.
- Client tests 4/10: toursPermissions mocked useAuthStore as a bare
  selector; tripAddonsStore keys its lists by account through getState.
- Server lint (knip): TripAddonRow was exported without a reader outside
  its file.
- Client lint and Client types: no-unused-vars and the strict errors in
  useTripPlanner.ts went down by one, so their entries are lowered.
2026-11-21 14:00:02 +01:00
Maurice 9e2805fc89 chore(lint): lower the server no-unused-vars baseline to 34
Server lint was red: the per-trip addon change left one unused variable fewer in src, and the ratchet fails on an entry above the count.
2026-11-21 13:28:06 +01:00
Maurice 77380ea5cf docs(wiki): describe the trip settings' Addons area and its MCP tools 2026-11-21 13:23:09 +01:00
Maurice 9956c58dd5 feat(client): follow and switch a trip's own addons
- The trip's addon list is read through tripAddonsRepo into
  tripAddonsStore (per account and trip, kept in Dexie version 16 for
  offline), refreshed when the connection returns and live on
  tripAddons:changed.
- The planner's tabs, dock, rail and deep links, the cost, tour and list
  readers, the PDF export, the share link options, the widgets and the
  watch follow the trip instead of the instance switch.
- Trip settings gets an Addons area for the owner, on the desktop dialog
  and the phone sheet, on one useTripAddonRows hook: each trip addon with
  its switch, marked "This trip only" while it differs from the instance.
  Switching back to the instance's value drops the trip's choice.
  Switching needs a connection.
2026-11-21 13:23:09 +01:00
Maurice 3f38621024 feat(server): let a trip owner switch trip addons for one trip
A trip can now turn a trip addon (lists, costs, documents, collab, road
trip, tours) on or off for itself, whatever the instance switch says. No
row in the new trip_addon_overrides table means the trip follows the
instance; a row is the owner's choice. Going back to the instance setting
deletes the row, and no addon data is touched either way.

- GET/PUT /api/trips/:tripId/addons[/:addonId] (every member reads, the
  owner writes) and the MCP tools get_trip_addons and set_trip_addon, on
  the shared tripAddons contract; tripAddons:changed tells the members.
- Every trip-scoped addon surface asks the trip: REST through
  TripAddonGuard, MCP through a per-call gate on the named or pinned trip,
  plugin RPC and events, the share link, the offline bundle, reminders,
  doc sync, the assistant (tools, keep_attached_file), booking costs, the
  trip summary prompt, and the cross-trip tour reads (library, Atlas
  stats, collection save).
- Routes without a trip open while the addon is on in any of the user's
  trips. Switching an addon on that the instance has off ends the members'
  MCP sessions so they reconnect with its tools.
- A copied trip takes its owner's choices along.

Behaviour changes: an anonymous call to an addon route that is off now
gets 401 instead of 404, and with an instance switch off the packing,
todo and files plugin RPC methods, the files MCP tools, todo reminder
mails, core plugin events, plugin view contributions, the share link's
lists, costs and chat sections and the offline bundle's lists follow it.
2026-11-21 13:23:09 +01:00
Maurice 2f7b8357ce fix(server): schema-qualify the table the move asks Postgres for its sequence
Server Postgres 18 3/3 was red on dev: PGMOVENUL-007 failed with relation "information_schema_catalog_name" does not exist. readTargetSchema called pg_get_serial_sequence(format('%I', table_name), ...) over information_schema.columns, and Postgres does not promise to apply the table_schema filter first, so the call could see rows of information_schema itself, whose bare names do not resolve on the search path. The name now carries its schema, so the call answers for every row whatever the plan. The fake Postgres of the move tests matches the new text.
2026-11-21 11:30:06 +01:00
Maurice 6861687b1f fix(server): queue the backfill's updates instead of awaiting them in a loop
Server lint was red on dev: lint:warnings counted 557 no-await-in-loop warnings in src against a baseline of 556, from the UPDATE the new admin-made account backfill awaited per account. The updates are now queued with addSql, the way the Ireland counties migration queues its row writes, with the id checked to be an integer. The migration does the same as before; it has not shipped in a release.
2026-11-21 11:22:47 +01:00
Maurice 8fc9fe7945 fix(auth): mark an address an admin-made account changed itself, so SSO no longer links to it
The 5.0.0 backfill (Migration20200101042800) set email_self_asserted only for accounts whose address moved away from their user.register audit row. An account created in Admin > Users has only an admin.user_create row, so it kept 0 even when the account had changed its own address in its settings before the upgrade, and a verified SSO sign-in asserting that address was still linked into it.

A new migration applies the same rule with the address in the admin.user_create row as the baseline: an admin-made account whose address is none it was created or registered with, and whose email no admin edited, is marked. Only rows still at 0 are touched and nothing is cleared. The shipped migration stays as it is.
2026-11-21 11:12:34 +01:00
Maurice f668eee227 test(client): drop the two new non-null assertions in the addon card tests
Client lint was red: lint:warnings counted 1877 no-non-null-assertion warnings in tests against a baseline of 1875, both from closest('section')! in FE-ADMIN-ADDON-045 and 046. Cast to HTMLElement like the other card lookups in the file.
2026-11-21 10:59:35 +01:00
Maurice 711015d5fd feat(admin): live flight status, booking mail import and paddle water data as rows of the addon cards
The addons page listed the trip, global and integration addons and then three
loose cards under them: live flight status, the booking mail import and the
paddle water data. They now sit where they belong, as rows of the cards:

- Live flight status is a row of the trip card, with its switch, locked when
  FLIGHT_LIVE_ENABLED holds it.
- The booking mail import is a row of the integration card with its switch;
  while it is on, "Set up mail import" opens the transport, address, AI
  allowance, test and status in a dialog, the way AI is set up.
- The paddle water data are a row under the Tours addon that opens the
  regions in a dialog, counting the open requests, else the regions.

The phone follows with the same rows and bottom sheets. The setup row and the
setup dialog are shared components (AddonSetupRow, AddonSetupDialog on the
desktop, MAdminOptionRow and MAdminSetupRow on the phone), the card counts
stay the addons' own, and the settings tab loses its features part.
2026-11-21 00:23:13 +01:00
Maurice 6ebd5cf0c7 fix(mobile): a road trip stage draws only its own rides, not the drive's flight home
The phone's road trip tab shows one stage at a time, but its map drew the
arcs of every ride that seams the whole drive, plus every booking switched on
for any day. A flight home on the 12th then crossed the map of the stage on
the 9th, with its airport label, as if it were part of that day.

The stage now draws the rides that seam its own drive, whatever day they were
booked on, and of the bookings switched on by hand only those that run on the
stage's day. The all-days view and the desktop, which shows the whole drive,
are unchanged.
2026-11-20 23:00:52 +01:00
Maurice 8ab7547edf fix(calendar): a booking linked to a plan stop gets its zone and is exported once
The calendar feed and the .ics export wrote a restaurant booking linked to a
plan stop twice, and the booking's copy without a time zone:

- The zone of a booking came only from its own place. A booking whose place
  is its linked stop (reservations.assignment_id) had none, so its DTSTART and
  DTEND went out as floating times and calendar apps placed them in the
  device's zone, an hour early for a London lunch read in Paris. The zone now
  comes from the booking's place, then its linked stop's place, then the zone
  all stops of its day or of the trip agree on. Transports keep their
  endpoint zones and still float when those are unknown, since either end can
  be in another zone.
- The stop and its booking were both emitted (trek-assign-<id> and
  trek-res-<id>). As for hotels, a stop whose booking yields a timed event on
  the same day is no longer emitted on its own; the booking event takes over
  the stop's place as LOCATION, its notes and, when it has none, its end. A
  booking without a clock, on another day, or still staged leaves the stop as
  it was, so no event is lost.

The VTIMEZONE builder moved unchanged into calendar-timezones.helpers.ts to
keep the service under the size cap.

Closes #3150
2026-11-20 22:19:11 +01:00
Maurice f599892a4b test(server): delete the tracked uploads together, not one await per loop turn 2026-11-20 21:49:40 +01:00
Maurice 1436cec35c test(server): suites remove only the uploads they stored, not whole shared folders
files, security, collections, journey and trips cleaned up by removing a whole
uploads category folder (uploads/files, covers, places, journey). Every suite
that boots the app writes into the same uploads tree, and on the Postgres lane
several run at once, so that removal took the files of the suite running
beside it: ATTE2E-008 then failed with "storage object not found" for its
attached file.

A small helper wraps StorageService.put on the app's instance, records what
the suite stores and deletes exactly that afterwards. The journey upload tests
that counted the files in uploads/journey (and so also counted what another
suite wrote there) now check that every object they stored is gone again.
2026-11-20 21:45:05 +01:00
Maurice fe90502955 fix(mobile): show stay names whole in the day card's chip strip
The stay chips in the day card's header shrank to fit beside the day pill and
the weather, so a name could end after one or two letters (H..., Br...). They
now keep their size and show the whole name; the strip scrolls sideways
instead, with its ends fading while more waits behind them.
2026-11-20 19:29:57 +01:00
Maurice 0431741ad7 fix(widgets): size the timeline's time column to the longest time shown
The day timeline in the trip widgets gave every time a fixed 38 pt column,
enough for 09:30 but not for a 12-hour clock: 5:45 AM was cut to 5:4... at
every widget size. The column now takes the width of the longest visible time
(and the now marker's label), at least the old 38 pt, so the dots still stand
in one line.
2026-11-20 19:29:56 +01:00
Maurice fa99940945 test(platform): a share-token photo whose copy fails to build is a 404 2026-11-20 19:15:48 +01:00
Maurice 09316025c3 test(share): sweep tests in the thumbnail job, tx and strict baselines follow the resolver split 2026-11-20 18:33:42 +01:00
Maurice 100313cfa9 fix(share): compare the pending rendition build with undefined 2026-11-20 18:23:20 +01:00
Maurice 411ec4af59 fix(share): keep private data and photo locations out of public trip and journey links
Public trip and journey share links handed out more than the owner chose to
share:

- A travel-only trip link still returned every day's title, and every link with
  the map returned the free-text day notes the shared page never shows. Days now
  go out through a public projection without notes, and travel-only links carry
  no day titles. Day notes, packing, budget and chat use explicit field lists
  too, and the category list holds only the categories the shared places use,
  without creator ids.
- The public journey payload spread whole entry and photo rows, including
  storage keys (file_path, thumbnail_path) and internal fields. It is now built
  from allow-lists and pinned by a strict response contract.
- /uploads/journey served every entry photo, original and video to anyone who
  knew the file name, so a URL kept working after a share link was revoked or
  the gallery switched off. It now serves journey covers and other non-entry
  objects only; entry media go through the token-checked proxy.
- Anonymous byte paths served stored originals unchanged, so EXIF GPS left the
  server even with map sharing off. Every public path (journey share proxy,
  covers, trip share photos, public uploads) now sends a copy with location
  data blanked in place (EXIF GPS, XMP and IPTC location, MP4/MOV location
  atoms), falling back to a metadata-free re-encode or a 404, never the raw
  file. Owners and members still get their originals.
- An entry's visibility field never decided the share link but was offered by
  MCP and the assistant as if it did. It is now documented as having no effect
  and no longer shown as a privacy label; is_draft keeps an entry off the link.
2026-11-20 18:18:50 +01:00
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
582 changed files with 14985 additions and 2790 deletions
+4 -4
View File
@@ -94,8 +94,8 @@ RUN echo 'deb [signed-by=/etc/apt/keyrings/pgdg.asc] http://apt.postgresql.org/p
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
@@ -173,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", "--"]
@@ -0,0 +1,60 @@
package com.liketrek.trek;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* The log line for a page of the server that came back with an error status.
* "HTTP 503" on the address screen cannot tell the server, a proxy in front of
* it and something on the phone apart, so the line names the page and the
* headers that say who answered (#3014).
*/
final class PageErrorLog {
/** The headers that name whoever answered a page, in the order they are logged. */
private static final String[] SENDER_HEADERS = { "Server", "Via", "CF-Ray", "Content-Type" };
private PageErrorLog() {}
/**
* For example "Page answered HTTP 503 Service Unavailable for
* https://trek.example.com/login (server: cloudflare, cf-ray: 8f1a2b3c4d5e6f70-FRA)".
* The address goes without its query and fragment, where a sign-in page
* carries a challenge or a code. A header the answer did not have is left
* out, and an answer with none of them says so: no server sends a page
* without at least its type, so that points at something on the phone.
*/
static String describe(String url, int status, String reason, Map<String, String> headers) {
StringBuilder line = new StringBuilder("Page answered HTTP ").append(status);
if (reason != null && !reason.trim().isEmpty()) line.append(' ').append(reason.trim());
line.append(" for ").append(withoutQuery(url));
List<String> senders = new ArrayList<>();
for (String name : SENDER_HEADERS) {
String value = header(headers, name);
if (value != null && !value.trim().isEmpty()) senders.add(name.toLowerCase(Locale.ROOT) + ": " + value.trim());
}
line.append(senders.isEmpty() ? " (no server headers)" : " (" + String.join(", ", senders) + ")");
return line.toString();
}
/** A header by name, whatever case the answer wrote it in. */
private static String header(Map<String, String> headers, String name) {
if (headers == null) return null;
for (Map.Entry<String, String> entry : headers.entrySet()) {
if (name.equalsIgnoreCase(entry.getKey())) return entry.getValue();
}
return null;
}
private static String withoutQuery(String url) {
if (url == null) return "";
int end = url.length();
int query = url.indexOf('?');
if (query >= 0) end = query;
int fragment = url.indexOf('#');
if (fragment >= 0 && fragment < end) end = fragment;
return url.substring(0, end);
}
}
@@ -202,14 +202,23 @@ class TrekWebViewClient extends BridgeWebViewClient {
* none, as Cloudflare does with a 403, sends the app to the address screen,
* which says so and offers to add one. Any other 4xx page (a proxy's block
* page, a certificate it refused) stays up with the bar and its way out, so
* the app is never stuck on a page without TREK's UI.
* the app is never stuck on a page without TREK's UI. Each one is logged
* with its address and whoever answered it (PageErrorLog).
*/
@Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
int status = errorResponse.getStatusCode();
if (!request.isForMainFrame()) {
super.onReceivedHttpError(view, request, errorResponse);
} else if (status >= 500 || (status >= 400 && wantedCertificate(request.getUrl()))) {
return;
}
Log.w("TrekShell", PageErrorLog.describe(
request.getUrl().toString(),
status,
errorResponse.getReasonPhrase(),
errorResponse.getResponseHeaders()
));
if (status >= 500 || (status >= 400 && wantedCertificate(request.getUrl()))) {
TrekServerStore.setFailure(view.getContext(), "HTTP " + status);
onUnreachable.run();
} else if (status >= 400) {
@@ -0,0 +1,51 @@
package com.liketrek.trek
import org.junit.Assert.assertEquals
import org.junit.Test
/** The log line for a page that came back with an error status (#3014). */
class PageErrorLogTest {
@Test
fun namesThePageItsStatusAndWhoAnswered() {
val line = PageErrorLog.describe(
"https://trek.example.com/login?redirect=%2F#top",
503,
"Service Unavailable",
mapOf(
"server" to "cloudflare",
"CF-RAY" to "8f1a2b3c4d5e6f70-FRA",
"content-type" to "text/html; charset=UTF-8",
"Set-Cookie" to "session=secret",
),
)
// Any case of a header name is read, only the naming headers are logged,
// and the query with its sign-in state is left off.
assertEquals(
"Page answered HTTP 503 Service Unavailable for https://trek.example.com/login " +
"(server: cloudflare, cf-ray: 8f1a2b3c4d5e6f70-FRA, content-type: text/html; charset=UTF-8)",
line,
)
}
@Test
fun anAnswerWithoutHeadersSaysSo() {
assertEquals(
"Page answered HTTP 503 for https://trek.example.com/ (no server headers)",
PageErrorLog.describe("https://trek.example.com/", 503, null, emptyMap()),
)
assertEquals(
"Page answered HTTP 502 Bad Gateway for (no server headers)",
PageErrorLog.describe(null, 502, "Bad Gateway", null),
)
}
@Test
fun aFragmentBeforeAQuestionMarkEndsTheAddressThere() {
assertEquals(
"Page answered HTTP 500 for https://trek.example.com/trips/4 (via: 1.1 proxy)",
PageErrorLog.describe("https://trek.example.com/trips/4#a?b", 500, " ", mapOf("Via" to "1.1 proxy")),
)
}
}
@@ -121,6 +121,9 @@ class TrekBridgeViewController: CAPBridgeViewController {
right: max(0, safe.right - (window.bounds.maxX - frame.maxX))
)
let corner = cornerElement(in: frame, window: window)
if corner != .zero, cornerWindowSizes.insert(sizeKey(window.bounds.size)).inserted {
setNeedsStatusBarAppearanceUpdate()
}
if !force, insets == publishedSafeArea, corner == publishedCorner { return }
publishedSafeArea = insets
publishedCorner = corner
@@ -139,15 +142,36 @@ class TrekBridgeViewController: CAPBridgeViewController {
private var publishedCorner: UIEdgeInsets?
// MARK: - The status bar beside a corner element
/// The window sizes on which a corner element was seen. On an iPhone Duo
/// that element is the status capsule, so the app hides the status bar
/// there to take the capsule away; whatever still covers the corner stays
/// in the safe area the page keeps clear of. A size stays in the set
/// once seen: with the bar hidden the next measure may find no corner, and
/// showing the bar again would bring the capsule back and start over. The
/// folded and the unfolded display differ in size, so each keeps its own
/// answer, and a device without such an element never hides its bar.
private var cornerWindowSizes = Set<String>()
private func sizeKey(_ size: CGSize) -> String {
"\(Int(size.width.rounded()))x\(Int(size.height.rounded()))"
}
override var prefersStatusBarHidden: Bool {
if super.prefersStatusBarHidden { return true }
guard let size = view.window?.bounds.size else { return false }
return cornerWindowSizes.contains(sizeKey(size))
}
/// An element in a top corner of the screen, such as the status capsule of
/// an iPhone Duo: how far down it reaches (top) and how wide it is on its
/// side (left/right), in the web view's coordinates; zero where there is
/// none. iOS 26 tells a corner apart from a whole edge: the safe area with
/// the corner avoided vertically reaches lower than the one avoiding it
/// horizontally, which in turn is wider on the corner's side. The page puts
/// its top bar beside the element and starts its content below it, using
/// the full width (mobile.css), instead of giving up a strip of the whole
/// height.
/// horizontally, which in turn is wider on the corner's side. The page
/// counts it into its safe area (mobile.css): upright its content starts
/// below the element, on a wide window it leaves the element's side free.
private func cornerElement(in frame: CGRect, window: UIWindow) -> UIEdgeInsets {
guard #available(iOS 26.0, *) else { return .zero }
let vertical = view.edgeInsets(for: .safeArea(cornerAdaptation: .vertical))
+29 -10
View File
@@ -512,8 +512,8 @@ struct StopList: View {
ForEach(Array(window.enumerated()), id: \.offset) { offset, stop in
let past = (stop.minutes ?? Int.max) < nowMinutes
let isNext = !past && (offset == 0 || (window[offset - 1].minutes ?? Int.max) < nowMinutes)
if isNext && offset > 0, let nowLabel { nowLine(nowLabel) }
row(stop, past: past, isNext: isNext, last: offset == window.count - 1)
if isNext && offset > 0, let nowLabel { nowLine(nowLabel, in: window) }
row(stop, in: window, past: past, isNext: isNext, last: offset == window.count - 1)
}
}
}
@@ -528,13 +528,33 @@ struct StopList: View {
private var ink: Color { onPhoto ? .white : Trek.ink(scheme) }
private func row(_ stop: WidgetSnapshot.Stop, past: Bool, isNext: Bool, last: Bool) -> some View {
/// The time column, as wide as the longest time in the window (and the now
/// marker's label): every row lays all of them over each other, hidden, so
/// "5:45 AM" fits as well as "09:30" and the dots still stand in one line.
private func timeColumn<Label: View>(_ window: [WidgetSnapshot.Stop], @ViewBuilder label: () -> Label) -> some View {
ZStack(alignment: .leading) {
ForEach(Array(window.enumerated()), id: \.offset) { _, stop in
Text(stop.time ?? "–").font(Trek.number(11.5, .heavy)).hidden()
}
if let nowLabel { nowText(nowLabel).hidden() }
label()
}
.lineLimit(1)
.fixedSize(horizontal: true, vertical: false)
.frame(minWidth: 38, alignment: .leading)
}
private func nowText(_ label: String) -> some View {
Text(label.uppercased()).font(.system(size: 8.5, weight: .heavy)).tracking(0.5).foregroundStyle(Trek.danger)
}
private func row(_ stop: WidgetSnapshot.Stop, in window: [WidgetSnapshot.Stop], past: Bool, isNext: Bool, last: Bool) -> some View {
let color = Color(css: stop.color) ?? (onPhoto ? .white : Trek.info)
return HStack(alignment: .top, spacing: 8) {
Text(stop.time ?? "–")
.font(Trek.number(11.5, isNext ? .heavy : .semibold))
.frame(width: 38, alignment: .leading)
.padding(.top, 1)
timeColumn(window) {
Text(stop.time ?? "–").font(Trek.number(11.5, isNext ? .heavy : .semibold))
}
.padding(.top, 1)
VStack(spacing: 0) {
ZStack {
Circle().fill(color).frame(width: isNext ? 11 : 8, height: isNext ? 11 : 8)
@@ -562,10 +582,9 @@ struct StopList: View {
.frame(height: 24, alignment: .top)
}
private func nowLine(_ label: String) -> some View {
private func nowLine(_ label: String, in window: [WidgetSnapshot.Stop]) -> some View {
HStack(spacing: 5) {
Text(label.uppercased()).font(.system(size: 8.5, weight: .heavy)).tracking(0.5).foregroundStyle(Trek.danger)
.frame(width: 38, alignment: .leading)
timeColumn(window) { nowText(label) }
Circle().fill(Trek.danger).frame(width: 5, height: 5).frame(width: 15)
Rectangle().fill(Trek.danger).frame(height: 1.2)
}
+5 -5
View File
@@ -3,16 +3,16 @@
"@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": 127,
"complexity": 216,
"@typescript-eslint/no-explicit-any": 138,
"trek/no-swallowed-catch": 126,
"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": 121,
"@typescript-eslint/no-unused-vars": 117,
"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": 1875,
"@typescript-eslint/no-non-null-assertion": 1872,
"@typescript-eslint/no-misused-promises": 22,
"@typescript-eslint/no-unused-vars": 51,
"@typescript-eslint/no-floating-promises": 33,
+3 -3
View File
@@ -190,7 +190,7 @@
{
"feature": "Booking mail import: admin card",
"hooks": ["src/components/Admin/mailIngest/useMailIngestAdmin.ts", "src/components/Admin/mailIngest/mailIngestAdminModel.ts"],
"desktop": ["src/components/Admin/mailIngest/MailIngestAdminCard.tsx"],
"desktop": ["src/components/Admin/mailIngest/MailIngestAddonTile.tsx"],
"mobile": ["src/mobile/screens/admin/MMailIngestAdminCard.tsx"]
},
{
@@ -1113,8 +1113,8 @@
"mobile": ["src/mobile/screens/admin/MAdminSchoolHolidayCatalog.tsx"]
},
{
"feature": "Trip settings: members, guests, public and invite link",
"hooks": ["src/components/Trips/useTripShare.ts"],
"feature": "Trip settings: members, guests, public and invite link, the trip's own addons",
"hooks": ["src/components/Trips/useTripShare.ts", "src/components/Trips/useTripAddonRows.ts"],
"desktop": ["src/components/Trips/TripShareDialog.tsx"],
"mobile": ["src/mobile/screens/trip/sheets/MTripSettingsSheet.tsx"]
}
-1
View File
@@ -1542,7 +1542,6 @@
"src/pages/journeyDetail/useJourneyDetail.ts",
"src/pages/journeyDetail/useProviderPhotoAdds.test.tsx",
"src/pages/journeyDetail/useProviderPhotoAdds.ts",
"src/pages/journeyPublic/journeyPublicModel.ts",
"src/pages/journeyPublic/useJourneyPublic.ts",
"src/pages/journeyStudio/useJourneyStudio.test.tsx",
"src/pages/journeyStudio/useJourneyStudio.ts",
-1
View File
@@ -35,7 +35,6 @@
"components/Map/nightPauseMarker.ts": 4,
"components/Map/ratingBadge.ts": 1,
"components/Map/switcherRow.ts": 1,
"components/PDF/TripPDF.tsx": 7,
"components/PDF/tripMapImage.ts": 1,
"components/Packing/PackingListPanelBagCard.tsx": 1,
"components/Packing/PackingListPanelCategoryGroup.tsx": 3,
+1 -1
View File
@@ -22,6 +22,6 @@
"src/pages/TripPlannerPage.tsx": 1128,
"src/pages/atlas/useAtlas.ts": 1207,
"src/pages/tripPlanner/useTripPlanner.roadtrip.test.tsx": 3518,
"src/pages/tripPlanner/useTripPlanner.test.tsx": 3269,
"src/pages/tripPlanner/useTripPlanner.test.tsx": 3267,
"src/styles/studio.css": 1918
}
+2 -3
View File
@@ -43,7 +43,7 @@
"src/components/Map/ReservationOverlay.test.tsx": 1,
"src/components/Map/transitGeometry.ts": 1,
"src/components/Map/useMarkerThumbs.ts": 1,
"src/components/PDF/TripPDF.tsx": 38,
"src/components/PDF/TripPDF.tsx": 1,
"src/components/Planner/DayPlanSidebar.constants.ts": 1,
"src/components/Planner/DayPlanSidebar.tsx": 52,
"src/components/Planner/DayPlanSidebarNoteModal.test.tsx": 1,
@@ -113,7 +113,6 @@
"src/pages/AtlasPage.tsx": 6,
"src/pages/FilesPage.tsx": 1,
"src/pages/JourneyDetailPage.tsx": 1,
"src/pages/JourneyPublicPage.test.tsx": 1,
"src/pages/LoginPage.tsx": 1,
"src/pages/VacayPage.tsx": 1,
"src/pages/admin/useAdmin.ts": 4,
@@ -130,7 +129,7 @@
"src/pages/tripPlanner/usePlaceEdits.ts": 2,
"src/pages/tripPlanner/usePlaceFormOpeners.test.ts": 2,
"src/pages/tripPlanner/usePlaceFormOpeners.ts": 1,
"src/pages/tripPlanner/useTripPlanner.ts": 2,
"src/pages/tripPlanner/useTripPlanner.ts": 1,
"src/repo/tripRepo.ts": 2,
"src/store/slices/budgetSlice.test.ts": 1,
"src/utils/formatters.test.ts": 1,
+1 -2
View File
@@ -72,7 +72,6 @@
"components/Map/ratingBadge.ts": 2,
"components/Map/reservationsMapbox.ts": 1,
"components/Map/switcherRow.ts": 1,
"components/PDF/TripPDF.tsx": 44,
"components/Packing/PackingListPanelBagModal.tsx": 2,
"components/Packing/PackingListPanelCategoryGroup.tsx": 5,
"components/Packing/PackingListPanelHeader.tsx": 3,
@@ -146,7 +145,7 @@
"mobile/components/MToastHost.tsx": 2,
"mobile/components/MUserPickerList.tsx": 1,
"mobile/screens/admin/MAdmin.tsx": 8,
"mobile/screens/admin/MAdminAddonManager.tsx": 4,
"mobile/screens/admin/MAdminAddonManager.tsx": 3,
"mobile/screens/admin/MAdminAuditLogPanel.tsx": 15,
"mobile/screens/admin/MAdminBackupPanel.tsx": 7,
"mobile/screens/admin/MAdminCategoryManager.tsx": 8,
+2
View File
@@ -30,6 +30,7 @@ import { takeResumeRoute, useRememberRoute } from './utils/resumeRoute'
import { usePermissionsStore, PermissionLevel } from './store/permissionsStore'
import { useInAppNotificationListener } from './hooks/useInAppNotificationListener.ts'
import { useRoadtripPreferencesSync } from './hooks/useRoadtripPreferencesSync'
import { useTripAddonsSync } from './hooks/useTripAddonsSync'
import { registerSyncTriggers, unregisterSyncTriggers } from './sync/syncTriggers'
import OfflineBanner from './components/Layout/OfflineBanner'
import NewVersionNotice from './components/Layout/NewVersionNotice'
@@ -379,6 +380,7 @@ export default function App() {
useInAppNotificationListener()
useRoadtripPreferencesSync()
useTripAddonsSync()
useEffect(() => {
if (isAuthenticated) {
+10
View File
@@ -0,0 +1,10 @@
import type { TripAddonsResponse, TripAddonUpdateRequest } from '@trek/shared';
import apiClient from './client';
/** The trip addons of one trip, each on or off for it: every member reads them, only the owner switches one. */
export const tripAddonsApi = {
list: (tripId: number): Promise<TripAddonsResponse> => apiClient.get(`/trips/${tripId}/addons`).then((r) => r.data),
/** `enabled: null` drops the trip's own choice, so the instance setting applies again. */
update: (tripId: number, addonId: string, body: TripAddonUpdateRequest): Promise<TripAddonsResponse> =>
apiClient.put(`/trips/${tripId}/addons/${encodeURIComponent(addonId)}`, body).then((r) => r.data),
};
+4
View File
@@ -46,6 +46,10 @@ export const HANDLED_OUTSIDE_TRIP_STORE = [
'roadtripVia:changed',
'roadtripTrack:changed',
'roadtripPreferences:changed',
// Per-trip addons: store/tripAddonsStore (watchTripAddons, mounted by App through
// hooks/useTripAddonsSync) puts the trip's list into the store and the device's copy, so the
// tabs and panels a trip switched off disappear for every member at once.
'tripAddons:changed',
// components/Roadtrip/useDayBoundaries reloads the shared boundaries.
'roadtripBoundary:changed',
// In-app notifications: hooks/useInAppNotificationListener, which also keeps
@@ -7,6 +7,7 @@ import { useAuthStore } from '../../store/authStore';
import { useSettingsStore } from '../../store/settingsStore';
import { useAddonStore } from '../../store/addonStore';
import { ToastContainer } from '../shared/Toast';
import { mailIngestRepo } from '../../repo/mailIngestRepo';
import AddonManager from './AddonManager';
function buildAddon(overrides = {}) {
@@ -691,4 +692,40 @@ describe('AddonManager', () => {
expect(roadtrip.querySelector('svg.lucide-car-front')).toBeInTheDocument();
expect(tours.querySelector('svg.lucide-puzzle')).not.toBeInTheDocument();
});
it('FE-ADMIN-ADDON-045: live flight status is a row of the trip card, switched there and locked by the environment', async () => {
server.use(addonsRoute([buildAddon({ id: 'packing', name: 'Lists', icon: 'ListChecks', type: 'trip', enabled: true })]));
const onToggle = vi.fn();
const { unmount } = render(<AddonManager flightLive={{ on: false, locked: false, managed: false, onToggle }} />);
const trip = (await screen.findByRole('heading', { name: 'Trip' })).closest('section') as HTMLElement;
await userEvent.click(within(trip).getByRole('button', { name: 'Follow booked flights live' }));
expect(onToggle).toHaveBeenCalledTimes(1);
// The count stays the addons': the flight row is an instance option beside them.
expect(within(trip).getByText('1/1')).toBeInTheDocument();
unmount();
render(<AddonManager flightLive={{ on: true, locked: true, managed: false, onToggle }} />);
expect(await screen.findByRole('button', { name: 'Follow booked flights live' })).toBeDisabled();
});
it('FE-ADMIN-ADDON-046: the booking mail import is a row of the integration card whose setup opens in a dialog', async () => {
server.use(addonsRoute([buildAddon({ id: 'mcp', name: 'MCP', icon: 'Terminal', type: 'integration', enabled: false })]));
vi.spyOn(mailIngestRepo, 'adminSettings').mockResolvedValue({ mail_ingest_enabled: 'true' });
vi.spyOn(mailIngestRepo, 'adminStatus').mockRejectedValue(new Error('no status'));
render(<AddonManager mailImport />);
const integration = (await screen.findByRole('heading', { name: 'Integration' })).closest('section') as HTMLElement;
expect(within(integration).getByText('Booking mail import')).toBeInTheDocument();
await userEvent.click(await within(integration).findByRole('button', { name: 'Set up mail import' }));
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByText('How mail arrives')).toBeInTheDocument();
});
it('FE-ADMIN-ADDON-047: without the mail option the integration card has no mail row and nothing is loaded', async () => {
server.use(addonsRoute([buildAddon({ id: 'mcp', name: 'MCP', icon: 'Terminal', type: 'integration', enabled: false })]));
const load = vi.spyOn(mailIngestRepo, 'adminSettings');
render(<AddonManager />);
await screen.findByRole('heading', { name: 'Integration' });
expect(screen.queryByText('Booking mail import')).not.toBeInTheDocument();
expect(load).not.toHaveBeenCalled();
});
});
+47 -8
View File
@@ -1,6 +1,6 @@
import type { ComponentType, ReactNode } from 'react'
import type { ComponentType } from 'react'
import { useTranslation } from '../../i18n'
import { Puzzle, ListChecks, Wallet, FileText, CalendarDays, Globe, Briefcase, Image, Terminal, Link2, Compass, BookOpen, Sparkles, Luggage, Plane, Bookmark, Users, Loader2, Mountain, CarFront } from 'lucide-react'
import { Puzzle, ListChecks, Wallet, FileText, CalendarDays, Globe, Briefcase, Image, Terminal, Link2, Compass, BookOpen, Sparkles, Luggage, Plane, Bookmark, Users, Loader2, Mountain, CarFront, Radar } from 'lucide-react'
import EmptyState from '../shared/EmptyState'
import DawarichIcon from '../shared/DawarichIcon'
import AirTrailIcon from '../shared/AirTrailIcon'
@@ -12,6 +12,9 @@ import { SettingsCard, SettingsColumns, StatusPill } from '../Settings/settingsK
import { type Addon, type CollabFeatures, COLLAB_SUB_FEATURES, getAddonLabel } from './addons/addonModel'
import { useAddonManager } from './addons/useAddonManager'
import AiAddonTile from './addons/AiAddonTile'
import MailIngestAddonTile from './mailIngest/MailIngestAddonTile'
import PaddleRegionsPanel from './paddle/PaddleRegionsPanel'
import ToggleSwitch from '../Settings/ToggleSwitch'
import { ImmichIcon, SynologyIcon } from './addons/PhotoProviderIcons'
import WandererMark from '../Tours/wanderer/WandererMark'
@@ -65,13 +68,24 @@ const TYPE_META: Record<string, { icon: ComponentType<{ size?: number }>; labelK
integration: { icon: Link2, labelKey: 'admin.addons.type.integration', hintKey: 'admin.addons.integrationHint' },
}
export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking, collabFeatures, onToggleCollabFeature, aside }: {
/** The live flight status switch, an instance setting that sits with the trip addons. */
export interface FlightLiveOption {
on: boolean
/** The server environment (FLIGHT_LIVE_ENABLED) holds it; the switch shows the state and says why. */
locked: boolean
managed: boolean
onToggle: () => void
}
export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking, collabFeatures, onToggleCollabFeature, flightLive, mailImport = false }: {
bagTrackingEnabled?: boolean
onToggleBagTracking?: () => void
collabFeatures?: CollabFeatures
onToggleCollabFeature?: (key: string) => void
/** Cards that set up what the integrations reach (flight status, booking mails), under them in the right column. */
aside?: ReactNode
/** Live flight status, a row of the trip card: it follows the trips' booked flights. */
flightLive?: FlightLiveOption
/** Booking mail import, a row of the integration card with its setup dialog; off on a managed install. */
mailImport?: boolean
}) {
const { t } = useTranslation()
const {
@@ -181,6 +195,8 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
onToggle={() => void toggle()}
/>
)),
// The paddle water data the tour planner reads, set up in a dialog of its own.
<PaddleRegionsPanel key="paddle-regions" />,
]
}
return null
@@ -202,6 +218,9 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
)
}
/** Whether a card holds rows beside its own addons: the AI tile, an instance option. */
const extraRows = (key: string) =>
(key === 'trip' && !!flightLive) || (key === 'integration' && (aiAddons.length > 0 || mailImport))
/* A card per type, the way every other admin tab sets its cards: Trip in the
left column, Global and Integration in the right one, each card with the
dialogs' head band carrying the type, its count and what it means. */
@@ -209,14 +228,14 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
{ key: 'trip', addons: tripAddons },
{ key: 'global', addons: globalAddons },
{ key: 'integration', addons: integrationAddons },
].filter(g => g.addons.length > 0 || (g.key === 'integration' && aiAddons.length > 0))
].filter(g => g.addons.length > 0 || extraRows(g.key))
const card = (g: (typeof groups)[number]) => {
const meta = TYPE_META[g.key]
const all = g.key === 'integration' ? [...aiAddons, ...g.addons] : g.addons
const visible = g.addons
const ai = g.key === 'integration' && aiAddons.length > 0
if (!visible.length && !ai) return null
if (!visible.length && !ai && !extraRows(g.key)) return null
const on = all.filter(a => a.enabled).length
return (
<SettingsCard
@@ -235,6 +254,10 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
{/* The AI addons share a connection and a settings dialog, so they head the card as one tile. */}
{ai && <AiAddonTile addons={aiAddons} onToggle={handleToggle} />}
{visible.map(tile)}
{/* Not addons but instance options of the same kind, as rows of the same card;
the count above stays the addons'. */}
{g.key === 'trip' && flightLive && <FlightLiveTile option={flightLive} />}
{g.key === 'integration' && mailImport && <MailIngestAddonTile />}
</div>
</SettingsCard>
)
@@ -251,5 +274,21 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking,
)
}
return <SettingsColumns start={cards.start} end={<>{cards.end}{aside}</>} />
return <SettingsColumns start={cards.start} end={cards.end} />
}
/** Live flight status as a trip row: on, it follows every booked flight on its day. */
function FlightLiveTile({ option }: { option: FlightLiveOption }) {
const { t } = useTranslation()
const name = t('flightLive.adminTitle')
const hint = option.managed ? t('flightLive.adminHintManaged') : t('flightLive.adminHint')
return (
<AddonTile
icon={<Radar size={18} />}
name={name}
description={option.locked ? `${hint} ${t('flightLive.envLocked')}` : hint}
enabled={option.on}
trailing={<ToggleSwitch on={option.on} label={t('flightLive.adminToggle')} disabled={option.locked} onToggle={option.onToggle} />}
/>
)
}
@@ -0,0 +1,68 @@
import React, { useId, type ReactNode } from 'react';
import { useTranslation } from '../../i18n';
import {
DialogButton,
DialogFooter,
DialogHeader,
DialogShell,
DialogTile,
FooterSpacer,
NEUTRAL_TINT,
} from '../shared/DialogShell';
/**
* The dialog an addon's setup row opens: the icon tile, the addon it belongs
* to above the title, what it sets up below, and one Close, since everything
* inside saves on its own (booking mails, paddle water data).
*/
export default function AddonSetupDialog({
icon,
eyebrow,
title,
sub,
onClose,
blocked = false,
children,
}: {
icon: ReactNode;
eyebrow: string;
title: string;
sub: string;
onClose: () => void;
/** A confirmation stacked on top holds the dialog while it is open. */
blocked?: boolean;
children: ReactNode;
}): React.ReactElement {
const { t } = useTranslation();
const labelId = useId();
return (
<DialogShell
onClose={onClose}
labelledBy={labelId}
width="detail"
blocked={blocked}
header={
<DialogHeader
tile={<DialogTile>{icon}</DialogTile>}
tint={NEUTRAL_TINT}
labelId={labelId}
eyebrow={eyebrow}
title={title}
sub={sub}
subWraps
onClose={onClose}
/>
}
footer={
<DialogFooter>
<FooterSpacer />
<DialogButton variant="primary" onClick={onClose}>
{t('common.close')}
</DialogButton>
</DialogFooter>
}
>
{children}
</DialogShell>
);
}
@@ -0,0 +1,38 @@
import { ChevronRight, Settings2 } from 'lucide-react';
import React, { type ReactNode } from 'react';
import { fs } from '../shared/DialogShell';
/**
* The last row of an addon's shelf that opens its settings dialog: a gear, what
* the dialog sets up, and a chevron. It keeps a card of addons as short as its
* switches and puts the long forms behind one tap (AI, booking mails, paddle
* water data). A badge says what waits inside, such as requests to look at.
*/
export default function AddonSetupRow({
label,
onOpen,
badge,
}: {
label: string;
onOpen: () => void;
badge?: ReactNode;
}): React.ReactElement {
return (
<li>
<button
type="button"
onClick={onOpen}
className="flex min-h-[44px] w-full items-center gap-2.5 border-0 bg-transparent py-1.5 pe-4 ps-[60px] text-start transition-colors hover:bg-surface-hover focus-visible:bg-surface-hover focus-visible:outline-none"
>
<span className="grid h-6 w-6 flex-none place-items-center text-content-muted">
<Settings2 size={14} />
</span>
<span className="min-w-0 flex-1 truncate font-medium text-content" style={fs(12.5, 'body')}>
{label}
</span>
{badge}
<ChevronRight size={15} strokeWidth={2.2} className="flex-none text-content-faint rtl:rotate-180" />
</button>
</li>
);
}
@@ -1,8 +1,9 @@
import { ChevronRight, Settings2, Sparkles } from 'lucide-react';
import { Sparkles } from 'lucide-react';
import React from 'react';
import { useTranslation } from '../../../i18n';
import { StatusPill } from '../../Settings/settingsKit';
import { fs } from '../../shared/DialogShell';
import AddonSetupRow from '../AddonSetupRow';
import AddonSubRow from '../AddonSubRow';
import AddonTile from '../AddonTile';
import { type Addon, getAddonLabel } from './addonModel';
@@ -54,23 +55,7 @@ export default function AiAddonTile({
/>
);
})}
{tile.canSetUp && (
<li>
<button
type="button"
onClick={tile.openDialog}
className="flex min-h-[44px] w-full items-center gap-2.5 border-0 bg-transparent py-1.5 pe-4 ps-[60px] text-start transition-colors hover:bg-surface-hover focus-visible:bg-surface-hover focus-visible:outline-none"
>
<span className="grid h-6 w-6 flex-none place-items-center text-content-muted">
<Settings2 size={14} />
</span>
<span className="min-w-0 flex-1 truncate font-medium text-content" style={fs(12.5, 'body')}>
{t('admin.addons.ai.setup')}
</span>
<ChevronRight size={15} strokeWidth={2.2} className="flex-none text-content-faint rtl:rotate-180" />
</button>
</li>
)}
{tile.canSetUp && <AddonSetupRow label={t('admin.addons.ai.setup')} onOpen={tile.openDialog} />}
</AddonTile>
{tile.dialogOpen && <AiSettingsDialog addons={addons} onClose={tile.closeDialog} />}
</>
@@ -1,22 +1,17 @@
import { AlertTriangle, CheckCircle, Copy, Loader2, Mail, PlugZap, Save, XCircle } from 'lucide-react';
import type { ReactNode } from 'react';
import { useState, type ReactNode } from 'react';
import { useTranslation } from '../../../i18n';
import type { TranslationFn } from '../../../types';
import { copyText } from '../../../utils/clipboard';
import { relativeTime } from '../../../utils/relativeTime';
import {
HintMark,
SETTINGS_BUTTON,
SETTINGS_BUTTON_PRIMARY,
SettingRow,
SettingRows,
SettingsCard,
StatusPill,
} from '../../Settings/settingsKit';
import { HintMark, SETTINGS_BUTTON, SETTINGS_BUTTON_PRIMARY, StatusPill } from '../../Settings/settingsKit';
import ToggleSwitch from '../../Settings/ToggleSwitch';
import CustomSelect from '../../shared/CustomSelect';
import { EditorField, GRID_2, INPUT, READONLY_BOX } from '../../shared/dialogParts';
import { useToast } from '../../shared/Toast';
import AddonSetupDialog from '../AddonSetupDialog';
import AddonSetupRow from '../AddonSetupRow';
import AddonTile from '../AddonTile';
import {
TRANSPORTS,
problemText,
@@ -306,32 +301,46 @@ function Setup({ admin, form, t, locale }: { admin: MailIngestAdmin; form: MailA
}
/**
* The booking mail import in the admin settings of a self-hosted install: the
* instance switch, how mail arrives (IMAP or a signed webhook), the forwarding
* address template, the AI allowance per person and day, a connection test and
* the status in counts. Not shown on a managed install, where the operator
* runs the TREK Cloud relay.
* The booking mail import as a row of the integration card: its switch, and
* while it is on one row to the dialog that sets it up (how mail arrives, the
* forwarding address template, the AI allowance per person and day, a
* connection test and the status in counts). Not shown on a managed install,
* where the operator runs the TREK Cloud relay.
*/
export default function MailIngestAdminCard() {
export default function MailIngestAddonTile() {
const { t, locale } = useTranslation();
const admin = useMailIngestAdmin(true);
const [open, setOpen] = useState(false);
const name = t('mailAdmin.title');
return (
<SettingsCard icon={Mail} title={t('mailAdmin.title')} hint={t('mailAdmin.hint')}>
<SettingRows>
<SettingRow
label={t('mailAdmin.enabled')}
hint={t('mailAdmin.enabledHint')}
control={
<ToggleSwitch
on={admin.enabled}
label={t('mailAdmin.enabled')}
disabled={!admin.loaded}
onToggle={() => admin.toggle(!admin.enabled)}
/>
}
/>
</SettingRows>
{admin.enabled && admin.form && <Setup admin={admin} form={admin.form} t={t} locale={locale} />}
</SettingsCard>
<>
<AddonTile
icon={<Mail size={15} />}
name={name}
description={`${t('mailAdmin.hint')} ${t('mailAdmin.enabledHint')}`}
enabled={admin.enabled}
trailing={
<ToggleSwitch
on={admin.enabled}
label={t('mailAdmin.enabled')}
disabled={!admin.loaded}
onToggle={() => admin.toggle(!admin.enabled)}
/>
}
>
{admin.enabled && admin.form && <AddonSetupRow label={t('mailAdmin.setup')} onOpen={() => setOpen(true)} />}
</AddonTile>
{open && admin.enabled && admin.form && (
<AddonSetupDialog
icon={<Mail size={20} strokeWidth={2} />}
eyebrow={name}
title={t('mailAdmin.setup')}
sub={t('mailAdmin.hint')}
onClose={() => setOpen(false)}
>
<Setup admin={admin} form={admin.form} t={t} locale={locale} />
</AddonSetupDialog>
)}
</>
);
}
@@ -78,17 +78,22 @@ function adminState(overrides: Partial<Admin> = {}, search: Partial<Admin['searc
};
}
function show(overrides: Partial<Admin> = {}, search: Partial<Admin['search']> = {}) {
/** The panel as the Tours shelf shows it: a setup row, opened into its dialog unless asked not to. */
function show(overrides: Partial<Admin> = {}, search: Partial<Admin['search']> = {}, { open = true } = {}) {
const state = adminState(overrides, search);
hook.usePaddleRegionsAdmin.mockReturnValue(state);
return { state, ...render(<PaddleRegionsPanel />) };
const view = render(
<ul>
<PaddleRegionsPanel />
</ul>
);
if (open && state.toursOn) fireEvent.click(setupRow());
return { state, ...view };
}
/** The card's title row, where the number of regions sits beside the title. */
function titleRow(): HTMLElement {
const row = screen.getByRole('heading', { name: 'Paddle water data' }).parentElement;
if (!row) throw new Error('no title row');
return row;
/** The shelf row that opens the dialog, where the count of requests or regions sits beside the title. */
function setupRow(): HTMLElement {
return screen.getAllByRole('button', { name: /^Paddle water data/ })[0];
}
function rowOf(name: string): HTMLElement {
@@ -100,7 +105,7 @@ function rowOf(name: string): HTMLElement {
describe('PaddleRegionsPanel', () => {
it('FE-ADMIN-PADDLEREG-001: renders nothing while the Tours addon is off', () => {
const { container } = show({ toursOn: false, regions: [READY] });
expect(container).toBeEmptyDOMElement();
expect(container.querySelector('ul')).toBeEmptyDOMElement();
});
it('FE-ADMIN-PADDLEREG-002: shows the card with its hint, the attribution and the empty state', () => {
@@ -110,7 +115,7 @@ describe('PaddleRegionsPanel', () => {
expect(screen.getByText(EMPTY)).toBeInTheDocument();
expect(screen.getByText(ATTRIBUTION)).toBeInTheDocument();
// No count beside the title while there is no region.
expect(titleRow()).toHaveTextContent(/^Paddle water data$/);
expect(setupRow()).toHaveTextContent(/^Paddle water data$/);
const search = screen.getByRole('searchbox', { name: 'Add a region' });
expect(search).toBeEnabled();
expect(search).toHaveAttribute('placeholder', 'Search Geofabrik, for example Oberpfalz');
@@ -277,12 +282,31 @@ describe('PaddleRegionsPanel', () => {
}
});
it('FE-ADMIN-PADDLEREG-019: the title carries the number of regions', () => {
it('FE-ADMIN-PADDLEREG-019: the setup row carries the open requests, else the number of regions', () => {
show({ regions: [READY, WAITING, FAILED_FIRST] });
expect(within(titleRow()).getByText('3')).toBeInTheDocument();
expect(within(setupRow()).getByText('3')).toBeInTheDocument();
expect(screen.getAllByTestId('paddle-region-row')).toHaveLength(3);
});
it('FE-ADMIN-PADDLEREG-019b: an open request outranks the region count, a declined one does not count', () => {
const base = { bytes: 1, requested_by: 'elmo', requested_at: '2026-10-18T09:00:00Z' };
show(
{
regions: [READY, WAITING],
requests: [
{ ...base, id: 'norway', name: 'Norway', reason: 'too_large', declined: true },
{ ...base, id: 'saale', name: 'Saale', reason: 'limit', declined: false },
],
},
{},
{ open: false }
);
expect(within(setupRow()).getByText('1')).toBeInTheDocument();
expect(within(setupRow()).queryByText('2')).toBeNull();
// Closed until the row is opened.
expect(screen.queryByRole('dialog')).toBeNull();
});
it('FE-ADMIN-PADDLEREG-020: removing asks first, naming the region, and confirming hands it to the hook', () => {
const { state } = show({ regions: [READY], removing: READY });
const message = 'Oberpfalz and its obstacle data are removed. Paddle tours there then show no data.';
@@ -1,6 +1,6 @@
import type { PaddleRegion, PaddleRegionCatalogEntry } from '@trek/shared';
import { Check, ChevronRight, Loader2, Plus, RefreshCw, Search, Trash2, Waves, WifiOff } from 'lucide-react';
import { useId } from 'react';
import { useId, useState } from 'react';
import { useDateFormat } from '../../../hooks/useDateFormat';
import { useTranslation } from '../../../i18n';
import { formatDisplayDate } from '../../../utils/dateFormat';
@@ -8,7 +8,6 @@ import {
SettingRows,
SETTINGS_BUTTON,
SETTINGS_ICON_BUTTON,
SettingsCard,
SettingsHint,
StatusPill,
} from '../../Settings/settingsKit';
@@ -17,6 +16,8 @@ import { EditorField, INPUT } from '../../shared/dialogParts';
import { fs } from '../../shared/DialogShell';
import ErrorBoundary from '../../shared/ErrorBoundary';
import { Tooltip } from '../../shared/Tooltip';
import AddonSetupDialog from '../AddonSetupDialog';
import AddonSetupRow from '../AddonSetupRow';
import { AutoLoadSettings, AutoOriginPill, RequestList } from './PaddleAutoLoadParts';
import { progressPercent, regionStatusTone } from './paddleRegionsModel';
import { usePaddleRegionsAdmin } from './usePaddleRegionsAdmin';
@@ -27,8 +28,10 @@ type Admin = ReturnType<typeof usePaddleRegionsAdmin>;
* PAD-05A in the admin area: the regions TREK reads paddle obstacles for,
* picked from Geofabrik's list, and (PAD-11C) how TREK loads the region of a
* place a paddler plans in by itself, with the regions that wait for an admin.
* The desktop admin shows this card under the addons while the Tours addon
* is on; the phone has MAdminPaddleRegionsPanel on the same hook.
* The desktop admin shows it as a row of the Tours addon that opens it as a
* dialog while the addon is on; the row counts what waits for the admin (the
* requests) or else the regions. The phone has MAdminPaddleRegionsPanel on
* the same hook.
*/
export default function PaddleRegionsPanel() {
return (
@@ -41,14 +44,42 @@ export default function PaddleRegionsPanel() {
function Panel() {
const { t } = useTranslation();
const admin = usePaddleRegionsAdmin();
const [open, setOpen] = useState(false);
if (!admin.toursOn) return null;
const title = t('admin.paddleRegions.title');
// A declined request no longer waits for anyone; only the open ones ask for a look.
const waiting = admin.requests.filter((r) => !r.declined).length;
const badge =
waiting > 0 ? (
<StatusPill tone="warning">{waiting}</StatusPill>
) : admin.regions.length > 0 ? (
<StatusPill>{admin.regions.length}</StatusPill>
) : undefined;
const close = () => setOpen(false);
return (
<SettingsCard
icon={Waves}
title={t('admin.paddleRegions.title')}
hint={t('admin.paddleRegions.hint')}
badge={admin.regions.length > 0 ? <StatusPill>{admin.regions.length}</StatusPill> : undefined}
>
<>
<AddonSetupRow label={title} onOpen={() => setOpen(true)} badge={badge} />
{open && (
<AddonSetupDialog
icon={<Waves size={20} strokeWidth={2} />}
eyebrow={t('admin.addons.catalog.tours.name')}
title={title}
sub={t('admin.paddleRegions.hint')}
onClose={close}
blocked={admin.removing !== null}
>
<PanelBody admin={admin} />
</AddonSetupDialog>
)}
</>
);
}
/** What the dialog holds: the state of the list, the settings, the requests, the search and the regions. */
function PanelBody({ admin }: { admin: Admin }) {
const { t } = useTranslation();
return (
<div className="flex flex-col gap-4">
{admin.offline && (
<p
role="status"
@@ -86,7 +117,7 @@ function Panel() {
message={t('admin.paddleRegions.removeMessage', { name: admin.removing?.name ?? '' })}
confirmLabel={t('common.remove')}
/>
</SettingsCard>
</div>
);
}
@@ -47,7 +47,6 @@ function look(over: Partial<JourneyEntryLook> = {}): JourneyEntryLook {
photoId: 7,
video: false,
photoCount: 1,
visibility: 'private',
draft: false,
fromTripPlace: false,
dayIndex: 0,
@@ -86,13 +85,15 @@ afterEach(() => {
describe('the journal entries card', () => {
it('FE-AI-JOURNEY-001: one entry reads as a row with its photo, facts, marks and text under the journal', () => {
const { container } = block([card([look({ visibility: 'public', draft: true, photoCount: 4, video: true })])]);
// A card stored while entries carried a visibility: it reads, and says nothing of it.
const stored = { ...look({ draft: true, photoCount: 4, video: true }), visibility: 'public' };
const { container } = block([card([stored])]);
expect(screen.getByRole('region', { name: 'Journal entries' })).toBeInTheDocument();
expect(screen.getByText('Sunset at the Spree')).toBeInTheDocument();
expect(screen.getByText('14:30')).toBeInTheDocument();
expect(screen.getByText('Berlin')).toBeInTheDocument();
expect(screen.getByText('The light over the river was unreal.')).toBeInTheDocument();
expect(screen.getByText('Public')).toBeInTheDocument();
expect(screen.queryByText('Public')).toBeNull();
expect(screen.getByText('Draft')).toBeInTheDocument();
expect(screen.getByText('4 photos')).toBeInTheDocument();
expect(screen.getByText('Opens with a video')).toBeInTheDocument();
@@ -225,13 +226,12 @@ describe('a change row of a journal entry', () => {
}
it('FE-AI-JOURNEY-008: a waiting delete shows the photo, the text and that it goes back to a suggestion; a receipt opens it', () => {
const entry = look({ fromTripPlace: true, visibility: 'shared' });
const entry = look({ fromTripPlace: true });
const held = card([entry], { change: 'willDelete', tripJournal: true });
const onOpen = vi.fn();
const first = inView(<AssistantChangeCard items={[item('pending', held)]} />, { onOpen });
expect(screen.getByText('Delete the journal entry')).toBeInTheDocument();
expect(screen.getByText('The light over the river was unreal.')).toBeInTheDocument();
expect(screen.getByText('Shared')).toBeInTheDocument();
expect(screen.getByText('Goes back to a suggestion')).toBeInTheDocument();
expect(screen.getByText('Tue, Oct 21')).toBeInTheDocument();
expect(screen.getByText('Museum Island')).toBeInTheDocument();
@@ -255,7 +255,6 @@ describe('a change row of a journal entry', () => {
{ op: 'change', labelKey: 'name', before: 'Sunset', after: 'Sunset at the Spree' },
{ op: 'change', labelKey: 'time', before: '14:30', after: '' },
{ op: 'change', labelKey: 'text', before: 'Old story', after: 'New story' },
{ op: 'change', labelKey: 'field', field: 'visibility', before: 'private', after: 'public' },
{ op: 'change', labelKey: 'field', field: 'mood', before: 'good', after: '' },
{ op: 'change', labelKey: 'field', field: 'weather', before: 'sunny', after: 'Drizzle' },
{ op: 'change', labelKey: 'field', field: 'is_draft', before: '✓', after: '✗' },
@@ -267,8 +266,6 @@ describe('a change row of a journal entry', () => {
expect(screen.getByText('14:30')).toHaveClass('line-through');
expect(screen.getByText('Old story')).toHaveClass('line-through');
expect(screen.getByText('New story')).toBeInTheDocument();
expect(screen.getByText('Private')).toHaveClass('line-through');
expect(screen.getByText('Public')).toBeInTheDocument();
expect(screen.getByText('Good')).toHaveClass('line-through');
expect(screen.getByText('Sunny')).toHaveClass('line-through');
expect(screen.getByText('Drizzle')).toBeInTheDocument();
@@ -28,7 +28,6 @@ const ENTRY: JourneyEntryLook = {
photoId: null,
video: false,
photoCount: 0,
visibility: 'private',
draft: false,
fromTripPlace: false,
dayIndex: null,
@@ -1,5 +1,5 @@
import type { JourneyEntryLook } from '@trek/shared';
import { CalendarDays, Globe, Images, MapPin, Play, Tag, ThumbsDown, ThumbsUp, Users } from 'lucide-react';
import { CalendarDays, Images, MapPin, Play, Tag, ThumbsDown, ThumbsUp } from 'lucide-react';
import { useTranslation } from '../../../../i18n';
import { cardDateLabel, cardPlace } from '../../../Journey/journeyCard';
@@ -12,8 +12,8 @@ import { moodOf, weatherOf } from './journeyTones';
/**
* The pieces a journal entry is drawn from in the chat, the same in an
* answer, a change row and a receipt: its photo, the facts of when and where
* as the planner's badges, the marks of how it reads (shared, draft, mood,
* weather, more photos) and the start of its text. Every fact wraps, none is
* as the planner's badges, the marks of how it reads (draft, mood, weather,
* more photos) and the start of its text. Every fact wraps, none is
* cut.
*/
@@ -63,19 +63,6 @@ export function EntryWhen({ look }: { look: JourneyEntryLook }) {
);
}
/** Shared or public; nothing for a private entry. */
function VisibilityMark({ visibility }: { visibility: JourneyEntryLook['visibility'] }) {
const { t } = useTranslation();
if (visibility === 'private') return null;
const shared = visibility === 'shared';
const Icon = shared ? Users : Globe;
return (
<SoftPill tone="info" icon={<Icon size={10} strokeWidth={2.2} aria-hidden="true" />}>
{shared ? t('journey.visibility.shared') : t('journey.visibility.public')}
</SoftPill>
);
}
/** A mood the journal knows, in its own colour; nothing for any other. */
function MoodMark({ id }: { id: string | null }) {
const { t } = useTranslation();
@@ -129,17 +116,16 @@ function ListMarks({ look }: { look: JourneyEntryLook }) {
);
}
/** How the entry reads: shared or public, a draft, its mood and weather, its photos past the first, its tags and verdict. */
/** How the entry reads: a draft, its mood and weather, its photos past the first, its tags and verdict. */
export function EntryMarks({ look }: { look: JourneyEntryLook }) {
const { t } = useTranslation();
const mood = moodOf(look.mood) !== null;
const lists = (look.tags?.length ?? 0) > 0 || !!look.verdict;
if (look.visibility === 'private' && !look.draft && !mood && !look.weather && look.photoCount < 2 && !lists) {
if (!look.draft && !mood && !look.weather && look.photoCount < 2 && !lists) {
return null;
}
return (
<CardFacts>
<VisibilityMark visibility={look.visibility} />
{look.draft && <SoftPill tone="warning">{t('journey.entry.draft')}</SoftPill>}
<MoodMark id={look.mood} />
<WeatherMark weather={look.weather} />
@@ -31,7 +31,6 @@ function look(over: Partial<JourneyEntryLook> = {}): JourneyEntryLook {
photoId: null,
video: false,
photoCount: 0,
visibility: 'private',
draft: false,
fromTripPlace: false,
dayIndex: null,
@@ -97,12 +96,13 @@ describe('journeyCardModel', () => {
});
it('FE-AI-JOURNEY-MODEL-009: the states an update sets are named by field, flags by on and off', () => {
expect(stateOf('visibility', 'public')?.labelKey).toBe('journey.visibility.public');
// The stored visibility keeps nothing off the share link, so it has no name to show.
expect(stateOf('visibility', 'private')).toBeNull();
expect(stateOf('type', 'skeleton')?.labelKey).toBe('journey.entry.suggestion');
expect(stateOf('mood', 'good')?.labelKey).toBe('journey.mood.good');
expect(stateOf('weather', 'cold')?.labelKey).toBe('journey.weather.cold');
expect(stateOf('weather', 'Drizzle')).toBeNull();
expect(stateOf('visibility', 'toString')).toBeNull();
expect(stateOf('type', 'toString')).toBeNull();
expect(stateOf(undefined, 'public')).toBeNull();
expect(flagOf('is_draft', '✓')?.labelKey).toBe('journey.entry.draft');
expect(flagOf('is_draft', '✗')?.labelKey).toBe('assistant.card.journey.notDraft');
@@ -7,8 +7,6 @@ import {
Eye,
EyeOff,
Frown,
Globe,
Lock,
type LucideIcon,
MapPinCheck,
Meh,
@@ -19,14 +17,13 @@ import {
Snowflake,
Sparkles,
Sun,
Users,
} from 'lucide-react';
/**
* How the states of a journal entry read in the chat, the way the journal
* draws them: its moods with the glyphs of its tiles, its weathers, and the
* words for what an update sets beyond the text (who sees the entry, its
* kind, a draft, the route, a waved-away suggestion).
* words for what an update sets beyond the text (its kind, a draft, the
* route, a waved-away suggestion).
*/
/** How a state is drawn: its glyph and the key of its name. */
@@ -57,12 +54,6 @@ const WEATHERS: Readonly<Record<string, EntryTone>> = {
cold: { Icon: Snowflake, labelKey: 'journey.weather.cold' },
};
const VISIBILITIES: Readonly<Record<string, EntryTone>> = {
private: { Icon: Lock, labelKey: 'journey.visibility.private' },
shared: { Icon: Users, labelKey: 'journey.visibility.shared' },
public: { Icon: Globe, labelKey: 'journey.visibility.public' },
};
const TYPES: Readonly<Record<string, EntryTone>> = {
entry: { Icon: BookOpenText, labelKey: 'assistant.card.journey.typeEntry' },
checkin: { Icon: MapPinCheck, labelKey: 'assistant.card.journey.typeCheckin' },
@@ -119,7 +110,6 @@ export function flagOf(field: string | undefined, value: string): EntryTone | nu
export function stateOf(field: string | undefined, value: string | null): EntryTone | null {
if (field === 'mood') return moodOf(value);
if (field === 'weather') return weatherOf(value);
if (field === 'visibility') return own(VISIBILITIES, value);
if (field === 'type') return own(TYPES, value);
return null;
}
@@ -8,6 +8,7 @@ import { OnlineOnlyError } from '../../repo/onlineOnly';
import { useAddonStore } from '../../store/addonStore';
import { chatOf, useAssistantStore } from '../../store/assistantStore';
import { useCanDo } from '../../store/permissionsStore';
import { useTripAddonEnabled } from '../../store/tripAddonsStore';
import { useTripStore } from '../../store/tripStore';
import { useToast } from '../shared/Toast';
import { chatTextOf } from './assistantShare';
@@ -35,7 +36,10 @@ export function useAssistantShare(tripId: number, message: AssistantMessage, wri
const { offline } = useNetworkMode();
const can = useCanDo();
const trip = useTripStore((s) => (s.trip?.id === tripId ? s.trip : null));
const chatOn = useAddonStore((s) => s.collabChat && s.addons.some((a) => a.id === 'collab' && a.enabled));
// The chat is an instance-wide part of Collab, which this trip may have on or off.
const chatFeatureOn = useAddonStore((s) => s.collabChat);
const collabOn = useTripAddonEnabled(tripId, 'collab');
const chatOn = chatFeatureOn && collabOn;
const threadId = useAssistantStore((s) => chatOf(s, tripId).threadId);
const [previewing, setPreviewing] = useState(false);
const [includeChanges, setIncludeChanges] = useState(true);
@@ -34,6 +34,7 @@ vi.mock('../../native/widgets', async (importOriginal) => {
};
});
import { collabSummary, packingDetail } from '../../native/widgetOnline';
import NativeWidgetsSync from './NativeWidgetsSync';
const trip = {
@@ -69,6 +70,8 @@ describe('NativeWidgetsSync', () => {
vi.useRealTimers();
await offlineDb.trips.clear();
await offlineDb.days.clear();
await offlineDb.todoItems.clear();
await offlineDb.tripAddons.clear();
});
it('FE-NATIVE-WSYNC-001: writes today and every day ahead, so the widgets turn the day without the app', async () => {
@@ -84,4 +87,29 @@ describe('NativeWidgetsSync', () => {
['2026-11-08', 'Market'],
]);
});
it('FE-NATIVE-WSYNC-002: a trip with Lists and Collab switched off shows neither its todos nor its chat', async () => {
await offlineDb.todoItems.put({ id: 70, trip_id: 7, name: 'Book ferry', checked: 0 } as never);
const off = (id: string) => ({ id, name: id, icon: null, enabled: false, instanceEnabled: true, overridden: true });
await offlineDb.tripAddons.put({ tripId: 7, addons: [off('packing'), off('collab')] });
vi.mocked(packingDetail).mockClear();
vi.mocked(collabSummary).mockClear();
render(<NativeWidgetsSync />);
await waitFor(() => expect(published.calls.length).toBeGreaterThan(0));
const snapshot = published.calls[0][0] as { todos?: unknown; collab?: unknown };
expect(snapshot.todos).toBeUndefined();
expect(snapshot.collab).toBeUndefined();
expect(vi.mocked(packingDetail)).not.toHaveBeenCalled();
expect(vi.mocked(collabSummary)).not.toHaveBeenCalled();
});
it('FE-NATIVE-WSYNC-003: a trip the device never read the addons of shows its todos, as before', async () => {
await offlineDb.todoItems.put({ id: 71, trip_id: 7, name: 'Book ferry', checked: 0 } as never);
render(<NativeWidgetsSync />);
await waitFor(() => expect(published.calls.length).toBeGreaterThan(0));
const snapshot = published.calls[0][0] as { todos?: { items?: unknown[] } };
expect(snapshot.todos).toBeDefined();
});
});
@@ -32,12 +32,15 @@ import {
type TripWidgetSnapshot,
type WidgetLabels,
} from '../../native/widgets';
import { cachedTripAddons } from '../../repo/tripAddonsRepo';
import { instanceAddonOn, useAddonStore } from '../../store/addonStore';
import { useAuthStore } from '../../store/authStore';
import { useFlightLiveStore } from '../../store/flightLiveStore';
import { useSettingsStore } from '../../store/settingsStore';
import { useTripStore } from '../../store/tripStore';
import type { Day, Place, Reservation, TranslationFn, Trip } from '../../types';
import { formatTime } from '../../utils/formatters';
import { tripAddonEnabled } from '../../utils/tripAddons';
import { localDateStr } from '../../vacay/monthGrid';
const REFRESH_MS = 15 * 60 * 1000;
@@ -120,15 +123,31 @@ async function flightOf(trip: Trip, reservations: Reservation[], path: string, c
return widgetFlight(legs, Date.now(), path, { locale: context.language, timeFormat: context.timeFormat });
}
/**
* Whether the trip has Lists and Collab on, from the list the device kept for it
* (the sync reads it with the trip). A trip it never read follows the instance,
* and while that is not known either the widgets show both, as they always did.
*/
async function tripSections(tripId: number): Promise<{ lists: boolean; collab: boolean }> {
const own = await cachedTripAddons(tripId);
const instance = useAddonStore.getState();
const on = (id: string) => tripAddonEnabled(own, id, instanceAddonOn(instance, id, true));
return { lists: on('packing'), collab: on('collab') };
}
async function tripExtras(trip: Trip, days: Day[], context: SyncContext) {
const { today, language, unit, time } = context;
const [places, reservations, todos, packing, memberRows] = await Promise.all([
const [places, reservations, todoRows, packingRows, memberRows, sections] = await Promise.all([
offlineDb.places.where('trip_id').equals(trip.id).toArray(),
offlineDb.reservations.where('trip_id').equals(trip.id).toArray(),
offlineDb.todoItems.where('trip_id').equals(trip.id).toArray(),
offlineDb.packingItems.where('trip_id').equals(trip.id).toArray(),
offlineDb.tripMembers.where('tripId').equals(trip.id).toArray(),
tripSections(trip.id),
]);
// A trip with Lists off shows no todos or packing, on the widgets and the watch alike.
const todos = sections.lists ? todoRows : [];
const packing = sections.lists ? packingRows : [];
const members = memberRows.length;
const names = [trip.owner_username, ...memberRows.map((m) => m.username)].filter((n): n is string => !!n);
const path = `/trips/${trip.id}`;
@@ -144,13 +163,15 @@ async function tripExtras(trip: Trip, days: Day[], context: SyncContext) {
const [weather, cover, bags, collab, flight] = await Promise.all([
spot && inRange ? widgetWeather(spot, { date: weatherDate, lang: language, unit, place }) : Promise.resolve(null),
widgetCover(trip.cover_image),
packingDetail(trip.id, packing),
collabSummary(
trip.id,
`/trips/${trip.id}?tab=collab`,
[...new Set(names)],
useAuthStore.getState().user?.id ?? null
),
sections.lists ? packingDetail(trip.id, packing) : Promise.resolve(null),
sections.collab
? collabSummary(
trip.id,
`/trips/${trip.id}?tab=collab`,
[...new Set(names)],
useAuthStore.getState().user?.id ?? null
)
: Promise.resolve(null),
flightOf(trip, reservations, path, context),
]);
const packed = packingSummary(packing, `/trips/${trip.id}?tab=listen`);
@@ -166,7 +187,7 @@ async function tripExtras(trip: Trip, days: Day[], context: SyncContext) {
memberCount: members > 0 ? members + 1 : 0,
weather,
bookings: bookingsAhead(reservations, { dayDates, today, tripPath: path, formatTime: time }),
todos: todosSummary(todos, `${path}?tab=listen`),
todos: sections.lists ? todosSummary(todos, `${path}?tab=listen`) : undefined,
packing: packed && bags ? { ...packed, ...bags } : packed,
collab,
flight,
@@ -5,7 +5,7 @@ import {
type TripRouteAnswers, type TripRouteSummary,
} from './tripRouteGeometry'
import { useSettingsStore } from '../../store/settingsStore'
import { useAddonStore } from '../../store/addonStore'
import { useTripAddonEnabled } from '../../store/tripAddonsStore'
import type { RoadtripVia } from '@trek/shared'
import type { Accommodation, AssignmentsMap, Day, Place, Reservation } from '../../types'
import type { TourStageStops } from './dayTourProjection'
@@ -51,7 +51,7 @@ export function useTripRouteOverview(
tourStageStops?: TourStageStops,
): TripRouteOverview {
const optimizeFromAccommodation = useSettingsStore(s => s.settings.optimize_from_accommodation)
const toursEnabled = useAddonStore(s => s.isEnabled('tours'))
const toursEnabled = useTripAddonEnabled(tripId, 'tours')
// Leg text is formatted at compute time, so a km↔mi switch has to re-run (#1300).
const distanceUnit = useSettingsStore(s => s.settings.distance_unit)
const [result, setResult] = useState<TripRouteOverview>(EMPTY)
@@ -245,7 +245,7 @@ describe('trip route map in the PDF', () => {
expect(html).toContain('<svg class="trip-map-svg"')
// Between the cover and the days, which is where it is meant to read.
expect(html.indexOf('class="trip-map"')).toBeGreaterThan(html.indexOf('class="cover"'))
expect(html.indexOf('class="trip-map"')).toBeLessThan(html.indexOf('class="day-section"'))
expect(html.indexOf('class="trip-map"')).toBeLessThan(html.indexOf('class="day-section'))
})
it('FE-COMP-TRIPPDF-MAP-011: prefers the real basemap when it renders', async () => {
+118 -57
View File
@@ -37,6 +37,41 @@ function plannedStat(html: string): number | null {
return match ? Number(match[1]) : null
}
/** The days of the document, without the cover and the overview's booking list before them. */
function daysOf(html: string): string {
return html.slice(html.indexOf('<table class="day-section'))
}
const textOf = (el: Element | null | undefined) => el?.textContent?.trim() ?? ''
/**
* Each booking on the days' timelines, read the way it prints: the span label over the
* title, the start and end in the time column, one line per leg (its route, then its
* facts, then its own code, as one string) and the codes of the whole booking.
*/
function bookingsOf(html: string) {
const doc = new DOMParser().parseFromString(html, 'text/html')
return [...doc.querySelectorAll('.timeline .tl-booking')].map(item => ({
kicker: textOf(item.querySelector('.note-kicker')),
title: textOf(item.querySelector('.note-text')),
start: textOf(item.querySelector('.tl-start')),
end: textOf(item.querySelector('.tl-end')),
lines: [...item.querySelectorAll('.note-line')].map(line =>
[...line.children].map(part => textOf(part)).filter(Boolean).join(' · ')),
codes: [...item.querySelectorAll('.note-extra .code-chip')].map(code => textOf(code)),
}))
}
/** Every line printed under the bookings' titles, across the days. */
const bookingLines = (html: string) => bookingsOf(html).flatMap(b => b.lines)
/** The booking of that title and span label, as bookingsOf reads it. */
function bookingCard(html: string, title: string, kicker = '') {
const card = bookingsOf(html).find(b => b.title === title && b.kicker === kicker)
if (!card) throw new Error(`no booking "${title}" labelled "${kicker}"`)
return card
}
// ── Setup ─────────────────────────────────────────────────────────────────────
beforeEach(() => {
@@ -175,8 +210,8 @@ describe('downloadTripPDF', () => {
expect(srcdoc).toContain('<table class="day-section')
expect(srcdoc).toContain('<thead class="day-header">')
expect(srcdoc).toContain('<tbody class="day-body-group">')
// The dark bar (background/padding/flex) lives in an inner wrapper inside the thead.
expect(srcdoc).toContain('class="day-header-bar"')
// The header (number, date, title, figures) lives in an inner wrapper inside the thead.
expect(srcdoc).toContain('<thead class="day-header"><tr><td><div class="day-head">')
// Day content still renders inside the new structure.
expect(srcdoc).toContain('Rome Day')
expect(srcdoc).toContain('Colosseum')
@@ -188,10 +223,10 @@ describe('downloadTripPDF', () => {
const srcdoc = iframe!.srcdoc
// The thead is repeated on every overflow page, so the spacing below the header bar
// must be declared on its cell...
expect(srcdoc).toContain('.day-header > tr > td { padding-bottom: 12px; }')
expect(srcdoc).toContain('.day-header > tr > td { padding: 0 var(--gutter) 5mm; }')
// ...and not as a block-start padding on .day-body, which the print engine only paints
// on the first fragment of the (fragmented) body cell.
expect(srcdoc).toContain('.day-body { padding: 0 28px 6px; }')
expect(srcdoc).toContain('.day-body { padding: 0 var(--gutter) 4mm; }')
})
it('FE-COMP-TRIPPDF-006: escHtml prevents XSS in trip title', async () => {
@@ -255,8 +290,27 @@ describe('downloadTripPDF', () => {
const iframe = getIframe()
expect(iframe!.srcdoc).toContain('Flight to Rome')
expect(iframe!.srcdoc).toContain('ABC123')
// Single-leg flight keeps its full-route subtitle.
expect(iframe!.srcdoc).toContain('Air Italia · AI123 · CDG → FCO')
// Single-leg flight keeps its full route, then airline and number as badges.
expect(bookingLines(iframe!.srcdoc)).toContain('CDG → FCO · Air Italia · AI123')
})
it('FE-COMP-TRIPPDF-013s: a flight prints its seat, a direct one and each leg of one with a stop alike', async () => {
const direct = { ...transportReservation, metadata: JSON.stringify({ airline: 'Air Italia', flight_number: 'AI123', seat: '31A', departure_airport: 'CDG', arrival_airport: 'FCO' }) }
const stopover = {
...multiLegFlight,
metadata: JSON.stringify({
legs: [
{ from: 'FRA', to: 'BER', airline: 'Lufthansa', flight_number: 'LH1' },
{ from: 'BER', to: 'HND', airline: 'Lufthansa', flight_number: 'LH2', seat: '14C' },
],
departure_airport: 'FRA', arrival_airport: 'HND', airline: 'Lufthansa', flight_number: 'LH1',
}),
}
await downloadTripPDF({ ...richArgs, reservations: [direct, stopover] })
const lines = bookingLines(getIframe()?.srcdoc ?? '')
expect(lines).toContain('CDG → FCO · Air Italia · AI123 · reservations.meta.seat 31A')
expect(lines).toContain('BER → HND · Lufthansa · LH2 · reservations.meta.seat 14C')
expect(lines).toContain('FRA → BER · Lufthansa · LH1')
})
it('FE-COMP-TRIPPDF-013f: the stop a booked night wrote is not listed, so a morning flight prints before the hotel (#2434)', async () => {
@@ -310,15 +364,14 @@ describe('downloadTripPDF', () => {
const iframe = getIframe()
// Without the landing time the reader cannot tell what is left of the day.
expect(iframe!.srcdoc).toContain('14:30 – 16:45')
expect(bookingCard(iframe!.srcdoc, 'Flight to Rome')).toMatchObject({ start: '14:30', end: '16:45' })
})
it('FE-COMP-TRIPPDF-013d: a flight without a landing time still shows its departure', async () => {
await downloadTripPDF(richArgs)
const iframe = getIframe()
expect(iframe!.srcdoc).toContain('14:30')
expect(iframe!.srcdoc).not.toContain('14:30 –')
expect(bookingCard(iframe!.srcdoc, 'Flight to Rome')).toMatchObject({ start: '14:30', end: '' })
})
it('FE-COMP-TRIPPDF-013e: an overnight flight keeps its arrival on the arrival day (#1310)', async () => {
@@ -332,16 +385,16 @@ describe('downloadTripPDF', () => {
})
const iframe = getIframe()
expect(iframe!.srcdoc).not.toContain('14:30 – 06:15')
expect(iframe!.srcdoc).toContain('06:15')
const html = iframe!.srcdoc
expect(bookingCard(html, 'Flight to Rome', 'reservations.span.departure')).toMatchObject({ start: '14:30', end: '' })
expect(bookingCard(html, 'Flight to Rome', 'reservations.span.arrival')).toMatchObject({ start: '06:15' })
})
it('FE-COMP-TRIPPDF-013b: renders every flight number for a multi-leg flight', async () => {
await downloadTripPDF({ ...richArgs, reservations: [multiLegFlight] })
const iframe = getIframe()
// One subtitle line per leg, each with its own flight number and segment route.
expect(iframe!.srcdoc).toContain('Lufthansa · LH1 · FRA → BER')
expect(iframe!.srcdoc).toContain('Lufthansa · LH2 · BER → HND')
// One line per leg, each with its own flight number and segment route.
expect(bookingLines(iframe!.srcdoc)).toEqual(['FRA → BER · Lufthansa · LH1', 'BER → HND · Lufthansa · LH2'])
})
it('FE-COMP-TRIPPDF-014: renders cover image when trip has cover_image', async () => {
@@ -741,11 +794,9 @@ describe('downloadTripPDF remaining branches', () => {
}]))
const html = srcdoc()
expect(html).toContain('reservations.span.start: Nordic Cruise')
expect(html).toContain('reservations.span.ongoing: Nordic Cruise')
expect(html).toContain('reservations.span.end: Nordic Cruise')
expect(html).toContain('09:00')
expect(html).toContain('18:00')
expect(bookingCard(html, 'Nordic Cruise', 'reservations.span.start').start).toBe('09:00')
expect(bookingCard(html, 'Nordic Cruise', 'reservations.span.ongoing').start).toBe('')
expect(bookingCard(html, 'Nordic Cruise', 'reservations.span.end').start).toBe('18:00')
})
it('FE-W5PDF-002: a multi-day flight uses departure/arrival wording', async () => {
@@ -756,8 +807,8 @@ describe('downloadTripPDF remaining branches', () => {
}]))
const html = srcdoc()
expect(html).toContain('reservations.span.departure: Red Eye')
expect(html).toContain('reservations.span.arrival: Red Eye')
expect(bookingCard(html, 'Red Eye', 'reservations.span.departure').start).toBe('23:00')
expect(bookingCard(html, 'Red Eye', 'reservations.span.arrival').start).toBe('06:00')
})
it('FE-W5PDF-003: a multi-day car hire is labelled pickup/return and skips the middle day', async () => {
@@ -767,8 +818,10 @@ describe('downloadTripPDF remaining branches', () => {
}]))
const html = srcdoc()
expect(html).toContain('reservations.span.pickup: Rental')
expect(html).toContain('reservations.span.return: Rental')
expect(bookingsOf(html).map(b => [b.kicker, b.title])).toEqual([
['reservations.span.pickup', 'Rental'],
['reservations.span.return', 'Rental'],
])
expect(html).not.toContain('reservations.span.active')
})
@@ -779,8 +832,10 @@ describe('downloadTripPDF remaining branches', () => {
}]))
const html = srcdoc()
expect(html).toContain('reservations.span.dropOff: Airport Parking')
expect(html).toContain('reservations.span.pickup: Airport Parking')
expect(bookingsOf(html).map(b => [b.kicker, b.title])).toEqual([
['reservations.span.dropOff', 'Airport Parking'],
['reservations.span.pickup', 'Airport Parking'],
])
expect(html).not.toContain('reservations.span.ongoing')
// Day B holds nothing else, so it prints the empty-day hint rather than the booking.
expect(html).toContain('dayplan.emptyDay')
@@ -809,7 +864,7 @@ describe('downloadTripPDF remaining branches', () => {
}]))
const html = srcdoc()
expect(html).toContain('ICE 599 · reservations.meta.platform 7 · reservations.meta.seat 21A · FRA → BER')
expect(bookingLines(html)).toEqual(['FRA → BER · ICE 599 · reservations.meta.platform 7 · reservations.meta.seat 21A'])
})
it('FE-W5PDF-006: a multi-leg train renders one line per leg', async () => {
@@ -824,8 +879,7 @@ describe('downloadTripPDF remaining branches', () => {
}]))
const html = srcdoc()
expect(html).toContain('IC 1 · reservations.meta.platform 3 · BER → MUC')
expect(html).toContain('EC 2 · MUC → ZRH')
expect(bookingLines(html)).toEqual(['BER → MUC · IC 1 · reservations.meta.platform 3', 'MUC → ZRH · EC 2'])
})
it('FE-W5PDF-007: restaurant, event, tour and unknown types get their own subtitles', async () => {
@@ -837,7 +891,8 @@ describe('downloadTripPDF remaining branches', () => {
]))
const html = srcdoc()
expect(html).toContain('4 guests')
// The party size needs no word: it prints beside the people icon.
expect(bookingCard(html, 'Dinner').lines).toEqual(['4'])
expect(html).toContain('Arena')
expect(html).toContain('GuideCo')
expect(html).toContain('Mystery')
@@ -870,8 +925,7 @@ describe('downloadTripPDF remaining branches', () => {
}]))
const html = srcdoc()
expect(html).toContain('AirX · X1')
expect(html).toContain('AirX · X2 · AAA → BBB')
expect(bookingLines(html)).toEqual(['AirX · X1', 'AAA → BBB · AirX · X2'])
})
it('FE-W5PDF-030: a stopover flight prints the booking code of each segment that has one (#1943)', async () => {
@@ -886,11 +940,12 @@ describe('downloadTripPDF remaining branches', () => {
}]))
const html = srcdoc()
expect(html).toContain('LH · LH1 · FRA → BER · ABC123')
// Each leg is its own card, the way the day plan shows it, with its own line.
const legs = bookingsOf(html).filter(b => b.title === 'Layover')
expect(legs.map(leg => leg.lines)).toEqual([['FRA → BER · LH · LH1 · ABC123'], ['BER → HND · ANA · NH2']])
// A segment without one keeps the line it had before, and the booking's own
// reference still prints once for the whole card.
expect(html).toContain('ANA · NH2 · BER → HND')
expect(html).toContain('Code: BOOK1')
// reference still prints on its card.
expect(legs[0].codes).toEqual(['BOOK1'])
})
it('FE-W5PDF-010: a single-leg flight with waypoints joins the whole route', async () => {
@@ -900,7 +955,7 @@ describe('downloadTripPDF remaining branches', () => {
metadata: { airline: 'LH', flight_number: 'LH7' },
}]))
expect(srcdoc()).toContain('LH · LH7 · FRA → Berlin → HND')
expect(bookingLines(srcdoc())).toEqual(['FRA → Berlin → HND · LH · LH7'])
})
it('FE-W5PDF-011: an assignment without a place contributes nothing', async () => {
@@ -984,9 +1039,11 @@ describe('downloadTripPDF remaining branches', () => {
await downloadTripPDF(spanArgs([]))
const html = srcdoc()
expect(html.indexOf('Earlier Inn')).toBeLessThan(html.indexOf('Later Inn'))
const days = daysOf(html)
expect(days.indexOf('Earlier Inn')).toBeGreaterThan(-1)
expect(days.indexOf('Earlier Inn')).toBeLessThan(days.indexOf('Later Inn'))
// the shared days list two hotels, so they lose the single-column class
expect(html).toContain('class="day-accommodations "')
expect(html).toContain('class="day-accommodations"')
})
it('FE-W5PDF-017: a trip without dated days prints no date range and no day dates', async () => {
@@ -999,7 +1056,7 @@ describe('downloadTripPDF remaining branches', () => {
expect(html).not.toContain('class="cover-dates"')
expect(html).not.toContain('class="day-date"')
expect(html).toContain('class="cover-circle-ph"')
expect(html).toContain('<section class="cover cover-plain">')
})
it('FE-W5PDF-018: the print button asks the preview frame to print', async () => {
@@ -1026,7 +1083,7 @@ describe('downloadTripPDF remaining branches', () => {
trip: { id: 1, title: 'Cover Trip', description: null, cover_image: '/uploads/cover.svg' } as any,
})
expect(srcdoc()).not.toContain('/uploads/cover.svg')
expect(srcdoc()).toContain('class="cover-circle-ph"')
expect(srcdoc()).toContain('<section class="cover cover-plain">')
})
it('FE-W5PDF-020: plugin sections render their paragraphs and tables', async () => {
@@ -1062,7 +1119,7 @@ describe('downloadTripPDF defaults', () => {
// no translator, no days, no places, no notes
expect(html).toContain('pdf.travelPlan')
expect(html).toContain('<div class="cover-title">My Trip</div>')
expect(html).toContain('<h1 class="cover-title">My Trip</h1>')
expect(html).toContain('<div class="cover-stat-num">0</div>')
})
@@ -1127,11 +1184,9 @@ describe('downloadTripPDF defaults', () => {
reservations: [{ id: 1, title: 'Overnight Bus', type: 'bus', day_id: 1, end_day_id: 2, reservation_time: '22:00', reservation_end_time: null }] as any[],
})
const html = srcdoc()
const endSection = html.slice(html.indexOf('End Day'))
expect(html).toContain('reservations.span.start: Overnight Bus')
expect(endSection).toContain('reservations.span.end: Overnight Bus')
expect(endSection).not.toContain('22:00')
expect(bookingCard(html, 'Overnight Bus', 'reservations.span.start').start).toBe('22:00')
expect(bookingCard(html, 'Overnight Bus', 'reservations.span.end')).toMatchObject({ start: '', end: '' })
})
it('FE-W5PDF-027: an export without a locale still renders, with lang="en"', async () => {
@@ -1198,12 +1253,16 @@ describe('page breaks between days (#1292)', () => {
expect(toggle()!.style.background).toContain('--border-primary')
})
it('FE-PDF-BREAK-003: the first day never carries a break of its own', async () => {
// The first day opens the plan after the cover and the overview, so it always starts a
// sheet; the switch decides only whether the days after it do.
it('FE-PDF-BREAK-003: the first day never carries the switchable break', async () => {
await downloadTripPDF(twoDays)
const html = getIframe()!.srcdoc
expect(html.indexOf('<table class="day-section">')).toBeGreaterThan(-1)
expect(html.indexOf('<table class="day-section day-first"')).toBeGreaterThan(-1)
expect(html.match(/day-section day-break/g)).toHaveLength(1)
expect(html).toContain('.day-first { break-before: page; }')
expect(html).toContain('.pdf-flow .day-break { break-before: auto; }')
})
it('FE-PDF-BREAK-004: turning the breaks off is remembered and shown at once', async () => {
@@ -1286,8 +1345,8 @@ describe('a printed day follows the plan (#1978)', () => {
const d2 = { id: 22, day_number: 2, title: 'Day Two', date: '2025-06-02' } as any
const srcdoc = () => getIframe()!.srcdoc
/** Where each needle first appears, so order can be asserted without parsing. */
const positions = (html: string, needles: string[]) => needles.map(n => html.indexOf(n))
/** Where each needle first appears in the days, so order can be asserted without parsing. */
const positions = (html: string, needles: string[]) => needles.map(n => daysOf(html).indexOf(n))
it('orders the day by the clock, not by the order the API sent rows in', async () => {
await downloadTripPDF({
@@ -1371,7 +1430,7 @@ describe('a printed day follows the plan (#1978)', () => {
dayId: 21,
}).map(item => (item.type === 'place' ? item.data.place.name : item.data.title))
const seen = expected.map(name => html.indexOf(name))
const seen = expected.map(name => daysOf(html).indexOf(name))
for (const at of seen) expect(at).toBeGreaterThan(-1)
expect(seen).toEqual([...seen].sort((a, b) => a - b))
})
@@ -1454,18 +1513,20 @@ describe('downloadTripPDF — large text', () => {
expect(html).not.toContain('pdf-large-text"')
expect(largeToggle().getAttribute('aria-checked')).toBe('false')
// One scale and one set of greys, at today's values unless the class is on.
expect(html).toContain('--pdf-text: 1;')
expect(html).toContain('--t: 1;')
expect(html).toContain('body.pdf-large-text {')
expect(html).toContain('.place-name { font-size: calc(11.5px * var(--pdf-text));')
expect(html).toContain('.note-text { font-size: calc(9.5px * var(--pdf-text)); color: var(--pdf-ink);')
expect(html).toContain('.place-name { flex: 1; font-size: calc(12px * var(--t));')
expect(html).toContain('.note-text { font-size: calc(9.5px * var(--t)); color: var(--ink);')
})
it('FE-PDF-LARGE-002: the clock and the booking code of a transport scale with the rest', async () => {
await downloadTripPDF(richArgs)
const html = previewFrame().srcdoc
expect(html).toContain('<span class="note-clock">')
expect(html).toContain('<div class="note-time note-code">Code: ABC123</div>')
// The clock sits in the time column and the code in its chip, both on the scale.
expect(bookingCard(html, 'Flight to Rome')).toMatchObject({ start: '14:30', codes: ['ABC123'] })
expect(html).toContain('.tl-start { display: block; font-size: calc(9.5px * var(--t));')
expect(html).toContain('font-family: var(--num); font-size: calc(8px * var(--t)); font-weight: 600; letter-spacing: 0.04em;')
expect(html).not.toContain('font-size:10px;')
})
@@ -1530,14 +1591,14 @@ describe('downloadTripPDF — photos at thumbnail size', () => {
await downloadTripPDF(withImage('/uploads/colosseum.jpg'))
const html = previewFrame().srcdoc
expect(html).toContain(`<img class="place-thumb" src="${JPEG}" />`)
expect(html).toContain(`<img class="place-thumb" src="${JPEG}" alt="" />`)
expect(html).not.toContain('colosseum.jpg')
})
it('FE-PDF-THUMB-002: a photo from another origin keeps its URL', async () => {
await downloadTripPDF(withImage('https://images.example.com/colosseum.jpg'))
expect(previewFrame().srcdoc).toContain('<img class="place-thumb" src="https://images.example.com/colosseum.jpg" />')
expect(previewFrame().srcdoc).toContain('<img class="place-thumb" src="https://images.example.com/colosseum.jpg" alt="" />')
})
it('FE-PDF-THUMB-003: a closed export dialog stops the photos and opens nothing', async () => {
File diff suppressed because it is too large Load Diff
+53 -5
View File
@@ -8,13 +8,15 @@ import { http, HttpResponse } from 'msw';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { server } from '../../../tests/helpers/msw/server';
import { shrinkPdfImages } from './pdfImages';
import { bakePdfCover, shrinkPdfImages, STRIP_PX } from './pdfImages';
const origin = window.location.origin;
const JPEG = 'data:image/jpeg;base64,c21hbGw=';
let bitmapSize = { width: 1200, height: 800 };
let drawn: { width: number; height: number }[] = [];
let drawCalls: unknown[][] = [];
let stops: [number, string][] = [];
let inFlight = 0;
let mostInFlight = 0;
@@ -24,7 +26,11 @@ function fakeContext(this: HTMLCanvasElement, type: string) {
return {
fillStyle: '',
fillRect: vi.fn(),
drawImage: vi.fn(() => drawn.push({ width: this.width, height: this.height })),
drawImage: vi.fn((...args: unknown[]) => {
drawCalls.push(args);
drawn.push({ width: this.width, height: this.height });
}),
createLinearGradient: vi.fn(() => ({ addColorStop: (at: number, colour: string) => stops.push([at, colour]) })),
};
}
@@ -35,6 +41,8 @@ function imageResponse(type = 'image/jpeg') {
beforeEach(() => {
bitmapSize = { width: 1200, height: 800 };
drawn = [];
drawCalls = [];
stops = [];
inFlight = 0;
mostInFlight = 0;
vi.stubGlobal(
@@ -64,19 +72,27 @@ afterEach(() => {
});
describe('shrinkPdfImages', () => {
it('FE-PDFIMAGES-001: a same-origin photo comes back as a JPEG with its short side at 156 px', async () => {
it('FE-PDFIMAGES-001: a same-origin photo comes back as a JPEG with its short side at 222 px', async () => {
const url = `${origin}/uploads/places/a.jpg`;
const shrunk = await shrinkPdfImages([url]);
expect(shrunk.get(url)).toBe(JPEG);
expect(drawn).toEqual([{ width: 234, height: 156 }]);
expect(drawn).toEqual([{ width: 333, height: 222 }]);
expect(HTMLCanvasElement.prototype.toDataURL).toHaveBeenCalledWith('image/jpeg', expect.any(Number));
});
it('FE-PDFIMAGES-001b: a photo is decoded near thumbnail size, not in full', async () => {
await shrinkPdfImages([`${origin}/uploads/places/a.jpg`]);
expect(createImageBitmap).toHaveBeenCalledWith(expect.any(Blob), { resizeHeight: 312, resizeQuality: 'medium' });
expect(createImageBitmap).toHaveBeenCalledWith(expect.any(Blob), { resizeHeight: 444, resizeQuality: 'medium' });
});
it('FE-PDFIMAGES-001c: the photo strip of a day asks for a larger copy, decoded at twice its size', async () => {
const url = `${origin}/uploads/places/a.jpg`;
await shrinkPdfImages([url], undefined, STRIP_PX);
expect(drawn).toEqual([{ width: 720, height: 480 }]);
expect(createImageBitmap).toHaveBeenCalledWith(expect.any(Blob), { resizeHeight: 960, resizeQuality: 'medium' });
});
it('FE-PDFIMAGES-002: a photo from another origin keeps its URL and is never fetched', async () => {
@@ -135,3 +151,35 @@ describe('shrinkPdfImages', () => {
expect(shrunk.has(url)).toBe(false);
});
});
describe('bakePdfCover', () => {
it('FE-PDFIMAGES-010: the photo is cropped to the page and the shade painted into one JPEG', async () => {
bitmapSize = { width: 4000, height: 2252 };
const url = `${origin}/uploads/places/cover.jpg`;
const baked = await bakePdfCover(url, [
[0, 0.35],
[0.92, 0.82],
]);
expect(baked).toBe(JPEG);
// Decoded at the page's height, not in full.
expect(createImageBitmap).toHaveBeenCalledWith(expect.any(Blob), { resizeHeight: 1754, resizeQuality: 'medium' });
// A4 at 150 dpi, the landscape photo scaled to the page height and centred.
expect(drawn).toEqual([{ width: 1240, height: 1754 }]);
const [, x, y, width, height] = drawCalls[0] as number[];
expect(height).toBeCloseTo(1754, 0);
expect(width).toBeCloseTo((4000 * 1754) / 2252, 0);
expect(x).toBeCloseTo((1240 - width) / 2, 3);
expect(y).toBeCloseTo(0, 3);
expect(stops).toEqual([
[0, 'rgba(10, 10, 14, 0.35)'],
[0.92, 'rgba(10, 10, 14, 0.82)'],
]);
});
it('FE-PDFIMAGES-011: a cover from another origin or one that cannot be read is left to print as before', async () => {
expect(await bakePdfCover('https://elsewhere.example/cover.jpg', [[0, 0.5]])).toBeNull();
expect(await bakePdfCover(`${origin}/uploads/missing.jpg`, [[0, 0.5]])).toBeNull();
expect(drawn).toEqual([]);
});
});
+81 -19
View File
@@ -12,16 +12,16 @@
* than FETCH_TIMEOUT_MS.
*/
/** The short side of a copy: three times the 52 px thumbnail, sharp at print resolution. */
const THUMB_PX = 156;
/** The short side of a place card's copy: three times its 74 px photo, sharp at print resolution. */
const THUMB_PX = 222;
/** The short side of a copy for the photo strip that opens a day, which runs the width of the page. */
export const STRIP_PX = 480;
const JPEG_QUALITY = 0.72;
/**
* Photos in flight at once: a trip of hundreds should neither queue one by one nor
* decode all at once. Kept low for the phone, where each decode costs memory.
*/
const CONCURRENCY = 3;
/** Height a photo is decoded at: twice THUMB_PX, so a portrait one still has room to shrink. */
const DECODE_PX = THUMB_PX * 2;
const FETCH_TIMEOUT_MS = 10_000;
/** Anything larger is not read into memory for a thumbnail; it keeps its URL. */
const MAX_BYTES = 20 * 1024 * 1024;
@@ -31,14 +31,18 @@ const MAX_BYTES = 20 * 1024 * 1024;
* missing from the result prints as it is. Stops starting new photos once
* `signal` aborts, and returns what it has.
*/
export async function shrinkPdfImages(urls: Iterable<string>, signal?: AbortSignal): Promise<Map<string, string>> {
export async function shrinkPdfImages(
urls: Iterable<string>,
signal?: AbortSignal,
shortSide = THUMB_PX
): Promise<Map<string, string>> {
const shrunk = new Map<string, string>();
const queue = [...new Set(urls)].filter(isSameOrigin);
if (queue.length === 0 || !canShrink()) return shrunk;
const worker = async () => {
for (let url = queue.shift(); url !== undefined && !signal?.aborted; url = queue.shift()) {
const copy = await shrinkImage(url, signal);
const copy = await shrinkImage(url, shortSide, signal);
if (copy) shrunk.set(url, copy);
}
};
@@ -61,7 +65,24 @@ function canShrink(): boolean {
return typeof createImageBitmap === 'function' && document.createElement('canvas').getContext('2d') !== null;
}
async function shrinkImage(url: string, signal?: AbortSignal): Promise<string | null> {
async function shrinkImage(url: string, shortSide: number, signal?: AbortSignal): Promise<string | null> {
// Decoded at twice the short side, so a portrait photo still has room to shrink.
const bitmap = await fetchBitmap(url, shortSide * 2, signal);
if (!bitmap) return null;
try {
return toJpeg(bitmap, shortSide);
} finally {
bitmap.close();
}
}
/**
* The photo at `url` decoded at `height` pixels, or null when it cannot be had. Decoded
* near the size it is drawn at: a 48 MP phone photo decoded in full holds about 190 MB,
* which can end the web view on a phone. Browsers without the option decode in full and
* the canvas scales down as before.
*/
async function fetchBitmap(url: string, height: number, signal?: AbortSignal): Promise<ImageBitmap | null> {
// A controller and a timer rather than AbortSignal.timeout/any, which Safari only
// has from 16 and 17.4 on; a throw there would cost the whole export.
const fetching = new AbortController();
@@ -73,15 +94,7 @@ async function shrinkImage(url: string, signal?: AbortSignal): Promise<string |
if (!res.ok || Number(res.headers.get('content-length') ?? 0) > MAX_BYTES) return null;
const blob = await res.blob();
if (!blob.type.startsWith('image/') || blob.size > MAX_BYTES) return null;
// Decoded near thumbnail size: a 48 MP phone photo decoded in full holds about
// 190 MB, which can end the web view on a phone. Browsers without the option
// decode in full and toJpeg scales down as before.
const bitmap = await createImageBitmap(blob, { resizeHeight: DECODE_PX, resizeQuality: 'medium' });
try {
return toJpeg(bitmap);
} finally {
bitmap.close();
}
return await createImageBitmap(blob, { resizeHeight: height, resizeQuality: 'medium' });
} catch {
// Offline, timed out, aborted or undecodable: the photo prints from its URL.
return null;
@@ -91,9 +104,58 @@ async function shrinkImage(url: string, signal?: AbortSignal): Promise<string |
}
}
/** The bitmap with its short side at THUMB_PX, or null when it is that small already. */
function toJpeg(bitmap: ImageBitmap): string | null {
const scale = THUMB_PX / Math.min(bitmap.width, bitmap.height);
/** The cover page in pixels: A4 at 150 dpi, enough for a photo behind the type. */
const COVER_W = 1240;
const COVER_H = 1754;
const COVER_QUALITY = 0.82;
/** One stop of the shade over the cover photo: how far down the page, 0 to 1, and how dark. */
export type ShadeStop = readonly [at: number, alpha: number];
/**
* The cover photo cropped to the page with its shade painted in, as one JPEG at print
* size. A page-sized photo under a translucent gradient is composited again by every
* viewer on every redraw, which made the first pages stutter in the preview and in the
* saved file; one flat picture is drawn once. Null for a photo from another origin or
* one that cannot be read: the cover then prints the photo and the shade as before.
*/
export async function bakePdfCover(
url: string,
shade: readonly ShadeStop[],
signal?: AbortSignal
): Promise<string | null> {
if (!isSameOrigin(url) || !canShrink()) return null;
const bitmap = await fetchBitmap(url, COVER_H, signal);
if (!bitmap) return null;
try {
const canvas = document.createElement('canvas');
canvas.width = COVER_W;
canvas.height = COVER_H;
const ctx = canvas.getContext('2d');
if (!ctx) return null;
// Cropped the way background-size: cover crops it, around the middle.
const scale = Math.max(COVER_W / bitmap.width, COVER_H / bitmap.height);
const width = bitmap.width * scale;
const height = bitmap.height * scale;
ctx.drawImage(bitmap, (COVER_W - width) / 2, (COVER_H - height) / 2, width, height);
const gradient = ctx.createLinearGradient(0, 0, 0, COVER_H);
for (const [at, alpha] of shade) gradient.addColorStop(at, `rgba(10, 10, 14, ${alpha})`);
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, COVER_W, COVER_H);
const baked = canvas.toDataURL('image/jpeg', COVER_QUALITY);
return baked.startsWith('data:image/jpeg') ? baked : null;
} catch {
// A canvas the browser will not draw or encode (out of memory on a phone, say):
// the cover then prints the photo and its shade as separate layers, as before.
return null;
} finally {
bitmap.close();
}
}
/** The bitmap with its short side at `shortSide`, or null when it is that small already. */
function toJpeg(bitmap: ImageBitmap, shortSide: number): string | null {
const scale = shortSide / Math.min(bitmap.width, bitmap.height);
if (!Number.isFinite(scale) || scale >= 1) return null;
const canvas = document.createElement('canvas');
canvas.width = Math.max(1, Math.round(bitmap.width * scale));
+54 -2
View File
@@ -1,12 +1,21 @@
/**
* FE-PDFPREVIEW-001 to FE-PDFPREVIEW-007: the trip PDF's preview and the control
* FE-PDFPREVIEW-001 to FE-PDFPREVIEW-009: the trip PDF's preview and the control
* that saves it. An iPhone or iPad ignores print() in the Home Screen app, so
* there the preview hands the export to Safari instead of offering a button that
* does nothing.
*/
import { afterEach, describe, expect, it, vi } from 'vitest';
import { LARGE_TEXT_KEY, PAGE_BREAK_KEY, openPdfPreview, type PdfPreviewOptions } from './pdfPreview';
import {
COORDINATES_KEY,
DETAILS_KEY,
LARGE_TEXT_KEY,
OVERVIEW_KEY,
PAGE_BREAK_KEY,
PHOTOS_KEY,
openPdfPreview,
type PdfPreviewOptions,
} from './pdfPreview';
const tr = (key: string) => key;
@@ -20,6 +29,10 @@ function open(overrides: Partial<PdfPreviewOptions> = {}) {
showTransportNotes: true,
hasTransportNotes: false,
largeText: false,
photos: true,
overview: true,
coordinates: true,
details: true,
...overrides,
});
}
@@ -111,4 +124,43 @@ describe('openPdfPreview', () => {
}
expect(document.getElementById('pdf-large-text-toggle')?.getAttribute('aria-checked')).toBe('true');
});
it('FE-PDFPREVIEW-008: the switches sit in a row of their own under the title and the actions', () => {
open({ hasTransportNotes: true });
const row = document.getElementById('pdf-settings-row');
const ids = [...(row?.querySelectorAll('[role="switch"]') ?? [])].map((toggle) => toggle.id);
expect(ids).toEqual([
'pdf-daybreak-toggle',
'pdf-large-text-toggle',
'pdf-overview-toggle',
'pdf-photos-toggle',
'pdf-coordinates-toggle',
'pdf-details-toggle',
'pdf-transport-notes-toggle',
]);
// The header keeps only the title and its two actions.
expect(row?.previousElementSibling?.querySelector('[role="switch"]')).toBeNull();
expect(row?.previousElementSibling?.querySelector('#pdf-print-btn')).not.toBeNull();
});
it.each([
['pdf-overview-toggle', OVERVIEW_KEY, 'pdf-no-overview'],
['pdf-photos-toggle', PHOTOS_KEY, 'pdf-no-photos'],
['pdf-coordinates-toggle', COORDINATES_KEY, 'pdf-no-coords'],
['pdf-details-toggle', DETAILS_KEY, 'pdf-no-details'],
])('FE-PDFPREVIEW-009: %s hides its part of the open document at once and is remembered', (id, key, hidden) => {
open();
const toggle = document.getElementById(id);
const body = document.querySelector<HTMLIFrameElement>('#pdf-preview-overlay iframe')?.contentDocument?.body;
expect(toggle?.getAttribute('aria-checked')).toBe('true');
toggle?.click();
expect(toggle?.getAttribute('aria-checked')).toBe('false');
expect(localStorage.getItem(key)).toBe('0');
if (body) expect(body.classList.contains(hidden)).toBe(true);
toggle?.click();
expect(localStorage.getItem(key)).toBe('1');
if (body) expect(body.classList.contains(hidden)).toBe(false);
});
});
+50 -16
View File
@@ -25,6 +25,17 @@ export const TRANSPORT_NOTES_KEY = 'trek_pdf_transport_notes';
*/
export const LARGE_TEXT_KEY = 'trek_pdf_large_text';
/**
* What the document shows besides the plan itself, each on by default and each a
* switch in the preview: the photos of the places and stays, the overview pages
* (route map, the days at a glance, bookings and stays), the coordinates under the
* addresses, and the contact lines, opening hours and companions of a place.
*/
export const PHOTOS_KEY = 'trek_pdf_photos';
export const OVERVIEW_KEY = 'trek_pdf_overview';
export const COORDINATES_KEY = 'trek_pdf_coordinates';
export const DETAILS_KEY = 'trek_pdf_details';
/* The overlay is imperative DOM, so the switch from Settings/ToggleSwitch is
rebuilt here rather than rendered — as static markup it would carry no
behaviour. Same geometry and the same tokens, so it reads as the same control. */
@@ -52,6 +63,10 @@ export interface PdfPreviewOptions {
/** The transport-notes switch only shows when there is a note to hide. */
hasTransportNotes: boolean;
largeText: boolean;
photos: boolean;
overview: boolean;
coordinates: boolean;
details: boolean;
}
/**
@@ -84,6 +99,10 @@ export function openPdfPreview({
showTransportNotes,
hasTransportNotes,
largeText,
photos,
overview,
coordinates,
details,
}: PdfPreviewOptions): void {
// Open in modal with srcdoc iframe (no URL loading = no X-Frame-Options issue)
const overlay = document.createElement('div');
@@ -104,10 +123,7 @@ export function openPdfPreview({
'display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap;padding:10px 16px;border-bottom:1px solid var(--border-primary);flex-shrink:0;';
header.innerHTML = `
<span style="font-size:13px;font-weight:600;color:var(--text-primary);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${escapeHtml(title)}</span>
<div style="display:flex;align-items:center;justify-content:flex-end;flex-wrap:wrap;gap:8px">
${hasTransportNotes ? previewSwitch('pdf-transport-notes-toggle', tr('pdf.transportNotes'), showTransportNotes) : ''}
${previewSwitch('pdf-daybreak-toggle', tr('pdf.pageBreakPerDay'), breaksPerDay)}
${previewSwitch('pdf-large-text-toggle', tr('pdf.largeText'), largeText)}
<div style="display:flex;align-items:center;justify-content:flex-end;gap:8px">
${save.html}
<button type="button" id="pdf-close-btn" style="background:none;border:none;cursor:pointer;color:var(--text-faint);display:flex;padding:4px;border-radius:6px">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
@@ -115,6 +131,23 @@ export function openPdfPreview({
</div>
`;
// The document's switches in a row of their own under the header: the layout first,
// then what it shows, so the header keeps only the title and the actions.
const settings = document.createElement('div');
settings.id = 'pdf-settings-row';
settings.style.cssText =
'display:flex;align-items:center;flex-wrap:wrap;gap:8px 18px;padding:8px 16px;border-bottom:1px solid var(--border-primary);background:var(--bg-secondary);flex-shrink:0;';
settings.innerHTML = [
previewSwitch('pdf-daybreak-toggle', tr('pdf.pageBreakPerDay'), breaksPerDay),
previewSwitch('pdf-large-text-toggle', tr('pdf.largeText'), largeText),
'<span aria-hidden="true" style="width:1px;align-self:stretch;background:var(--border-primary)"></span>',
previewSwitch('pdf-overview-toggle', tr('pdf.showOverview'), overview),
previewSwitch('pdf-photos-toggle', tr('pdf.showPhotos'), photos),
previewSwitch('pdf-coordinates-toggle', tr('collections.coordinates'), coordinates),
previewSwitch('pdf-details-toggle', tr('pdf.showDetails'), details),
hasTransportNotes ? previewSwitch('pdf-transport-notes-toggle', tr('pdf.transportNotes'), showTransportNotes) : '',
].join('');
const iframe = document.createElement('iframe');
iframe.style.cssText = 'flex:1;width:100%;border:none;';
// No script runs inside the document (print is parent-initiated), so withhold
@@ -123,6 +156,7 @@ export function openPdfPreview({
iframe.srcdoc = html;
card.appendChild(header);
card.appendChild(settings);
if (save.hint) {
const hint = document.createElement('p');
hint.id = 'pdf-safari-hint';
@@ -145,18 +179,18 @@ export function openPdfPreview({
// Each choice differs by one class on <body>, so switching is instant in the
// preview and there is no need to re-fetch photos or rebuild the document.
wirePreviewSwitch(header, 'pdf-daybreak-toggle', (on) => {
rememberPdfSwitch(PAGE_BREAK_KEY, on);
iframe.contentDocument?.body.classList.toggle('pdf-flow', !on);
});
wirePreviewSwitch(header, 'pdf-transport-notes-toggle', (on) => {
rememberPdfSwitch(TRANSPORT_NOTES_KEY, on);
iframe.contentDocument?.body.classList.toggle('pdf-no-transport-notes', !on);
});
wirePreviewSwitch(header, 'pdf-large-text-toggle', (on) => {
rememberPdfSwitch(LARGE_TEXT_KEY, on);
iframe.contentDocument?.body.classList.toggle('pdf-large-text', on);
});
const bodyClass = (id: string, key: string, className: string, addWhenOn: boolean) =>
wirePreviewSwitch(settings, id, (on) => {
rememberPdfSwitch(key, on);
iframe.contentDocument?.body.classList.toggle(className, addWhenOn ? on : !on);
});
bodyClass('pdf-daybreak-toggle', PAGE_BREAK_KEY, 'pdf-flow', false);
bodyClass('pdf-transport-notes-toggle', TRANSPORT_NOTES_KEY, 'pdf-no-transport-notes', false);
bodyClass('pdf-large-text-toggle', LARGE_TEXT_KEY, 'pdf-large-text', true);
bodyClass('pdf-overview-toggle', OVERVIEW_KEY, 'pdf-no-overview', false);
bodyClass('pdf-photos-toggle', PHOTOS_KEY, 'pdf-no-photos', false);
bodyClass('pdf-coordinates-toggle', COORDINATES_KEY, 'pdf-no-coords', false);
bodyClass('pdf-details-toggle', DETAILS_KEY, 'pdf-no-details', false);
}
/**
+23 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
import { buildTripMapSvg } from './tripMapSvg'
import { buildTripMapSvg, drawnPoints } from './tripMapSvg'
import type { TripOverviewDay } from '../Map/tripRouteGeometry'
const day = (over: Partial<TripOverviewDay> = {}): TripOverviewDay => ({
@@ -78,3 +78,25 @@ describe('buildTripMapSvg', () => {
expect(svg).toContain('width="720"')
})
})
// A routed road carries a point every few metres; drawn as it came, a trip map held
// tens of thousands of them and stuttered in every viewer.
describe('drawnPoints', () => {
// One degree is one map pixel, so the tolerance reads in degrees here.
const flat = (lat: number, lng: number): [number, number] => [lng, -lat]
it('FE-PDF-MAPSVG-020: a dense straight road keeps only its ends', () => {
const road = Array.from({ length: 5000 }, (_, i) => [0, i / 10] as [number, number])
expect(drawnPoints(road, flat)).toBe('0,0 499.9,0')
})
it('FE-PDF-MAPSVG-021: a turn is kept, a wobble under the tolerance is not', () => {
const road: [number, number][] = [[0, 0], [-0.1, 50], [0, 100], [-60, 100], [-0.2, 100.1]]
expect(drawnPoints(road, flat)).toBe('0,0 100,0 100,60 100.1,0.2')
})
it('FE-PDF-MAPSVG-022: points that round onto the same pixel are drawn once', () => {
const road: [number, number][] = [[0, 0], [0, 0.01], [0, 0.02], [0, 0.04]]
expect(drawnPoints(road, flat)).toBe('0,0')
})
})
+51 -2
View File
@@ -125,6 +125,55 @@ export interface RouteOverlayOptions {
formatDistance: (km: number) => string
}
/** How far, in map pixels, a point may sit off the line its neighbours make before it is kept. */
const SIMPLIFY_TOLERANCE = 0.35
/**
* A run projected onto the map and thinned for drawing. A routed road carries a point
* every few metres: at the scale of a trip map that is tens of thousands of points, most
* rounding onto the same pixel, each drawn twice (casing and line) and drawn again by
* every viewer on every scroll, which made the page stutter. Points that round onto the
* one before are dropped, then every point closer than SIMPLIFY_TOLERANCE to the line
* through the points kept around it (Douglas-Peucker). The shape on paper is the same.
*/
export function drawnPoints(line: [number, number][], project: (lat: number, lng: number) => [number, number]): string {
const round = (n: number) => Math.round(n * 10) / 10
const pts: [number, number][] = []
for (const [lat, lng] of line) {
const [x, y] = project(lat, lng)
const point: [number, number] = [round(x), round(y)]
const prev = pts[pts.length - 1]
if (!prev || prev[0] !== point[0] || prev[1] !== point[1]) pts.push(point)
}
const keep = new Uint8Array(pts.length)
keep[0] = 1
keep[pts.length - 1] = 1
const ranges: [number, number][] = [[0, pts.length - 1]]
for (let range = ranges.pop(); range; range = ranges.pop()) {
const [from, to] = range
if (to - from < 2) continue
const [ax, ay] = pts[from]
const [bx, by] = pts[to]
const dx = bx - ax
const dy = by - ay
const length = Math.hypot(dx, dy)
let farthest = -1
let distance = 0
for (let i = from + 1; i < to; i++) {
const [px, py] = pts[i]
const d = length === 0 ? Math.hypot(px - ax, py - ay) : Math.abs(dy * px - dx * py + bx * ay - by * ax) / length
if (d > distance) {
distance = d
farthest = i
}
}
if (farthest < 0 || distance <= SIMPLIFY_TOLERANCE) continue
keep[farthest] = 1
ranges.push([from, farthest], [farthest, to])
}
return pts.filter((_, i) => keep[i]).map(p => p.join(',')).join(' ')
}
/**
* The routes, their stops and the scale bar — everything drawn *over* the ground.
*
@@ -138,7 +187,7 @@ export function buildRouteOverlay(days: TripOverviewDay[], opts: RouteOverlayOpt
const drawn = days.filter(d => [...d.lines, ...(d.tourLines ?? [])].some(line => line.length > 1))
const routes = drawn.flatMap(day => day.lines.filter(l => l.length > 1).map(line => {
const pts = line.map(([lat, lng]) => project(lat, lng).map(round).join(',')).join(' ')
const pts = drawnPoints(line, project)
// The day's own darkened casing rather than a flat white one: it is what keeps a
// warm colour readable over water and forest, and it matches what the map draws.
return `<polyline points="${pts}" fill="none" stroke="${strokeColour(day.color.casing)}" stroke-width="5.5" stroke-linecap="round" stroke-linejoin="round"/>`
@@ -147,7 +196,7 @@ export function buildRouteOverlay(days: TripOverviewDay[], opts: RouteOverlayOpt
// Where each run starts and ends — the stops, rather than every vertex of the road.
const tours = drawn.flatMap(day => (day.tourLines ?? []).filter(line => line.length > 1).map(line => {
const pts = line.map(([lat, lng]) => project(lat, lng).map(round).join(',')).join(' ')
const pts = drawnPoints(line, project)
return `<polyline points="${pts}" fill="none" stroke="#ffffff" stroke-width="5" stroke-linecap="round" stroke-linejoin="round"/>`
+ `<polyline points="${pts}" fill="none" stroke="#14805e" stroke-width="2.8" stroke-linecap="round" stroke-linejoin="round"/>`
}))
@@ -0,0 +1,264 @@
/**
* FE-PDFDAY-001 to FE-PDFDAY-012: one day of the trip PDF, built piece by piece.
* The whole export is covered by TripPDF.test.ts; these pin what each card prints
* from the data it is given, the trip's full place included.
*/
import { describe, expect, it } from 'vitest';
import type { Accommodation, Assignment, Category, Day, DayNote, Place } from '../../types';
import { dayHeader, noteItem, photoStrip, placeItem, staysBlock, type PdfDayContext } from './tripPdfDay';
const day = { id: 10, day_number: 3, title: 'Kyoto', date: '2026-05-06' } as Day; // a Wednesday
const category = { id: 4, name: 'Temple', icon: 'landmark', color: '#c2410c' } as Category;
/** Monday first, like the stored week; Wednesday has hours, Thursday is closed. */
const week = JSON.stringify([
{ closed: false, open: '08:00', close: '18:00' },
{ closed: false, open: '08:00', close: '18:00' },
{ closed: false, open: '09:00', close: '17:30' },
{ closed: true },
{ closed: false, open: '08:00', close: '18:00' },
{ closed: false, open: '08:00', close: '18:00' },
{ closed: false, open: '08:00', close: '18:00' },
]);
const fullPlace = {
id: 7,
name: 'Kiyomizu-dera',
category_id: 4,
address: '1 Chome-294 Kiyomizu, Kyoto',
lat: 34.994856,
lng: 135.785046,
rating_avg: 4.64,
rating_count: 12,
email: 'info@kiyomizudera.or.jp',
phone: '+81 75-551-1234',
website: 'https://www.kiyomizudera.or.jp/en/',
opening_hours: week,
reservation_notes: 'Tickets at the west gate',
tags: [{ name: 'Must see', color: '#16a34a' }],
} as unknown as Place;
function context(over: Partial<PdfDayContext> = {}): PdfDayContext {
return {
tr: (key, params) => (params ? `${key}:${JSON.stringify(params)}` : key),
fmtTime: (value) => value ?? '',
locale: 'en-US',
tripCurrency: 'JPY',
categories: [category],
placesById: new Map([[fullPlace.id, fullPlace]]),
photoOf: () => null,
markdown: (text) => `<p>${text}</p>`,
...over,
};
}
/** The assignment as the API hands it over: a projection of its place, without the rating, e-mail or hours. */
function assignment(over: Record<string, unknown> = {}): Assignment {
return {
id: 200,
day_id: 10,
order_index: 0,
notes: 'Go early',
participants: [
{ user_id: 1, username: 'mia' },
{ user_id: 2, username: 'leo' },
],
place: {
id: 7,
name: 'Kiyomizu-dera',
category_id: 4,
address: '1 Chome-294 Kiyomizu, Kyoto',
lat: 34.994856,
lng: 135.785046,
place_time: '09:30',
end_time: '11:00',
duration_minutes: 90,
price: 500,
currency: null,
description: 'Wooden **stage** over the hill',
notes: null,
tags: [{ name: 'Must see', color: '#16a34a' }],
...over,
},
} as unknown as Assignment;
}
const parse = (html: string) => new DOMParser().parseFromString(html, 'text/html');
const texts = (doc: Document, selector: string) =>
[...doc.querySelectorAll(selector)].map((el) => el.textContent?.replace(/\s+/g, ' ').trim());
describe('placeItem', () => {
it('FE-PDFDAY-001: prints the stop with its number, times, facts, address and coordinates', () => {
const doc = parse(placeItem(assignment(), 2, day, context()));
expect(texts(doc, '.tl-marker')).toEqual(['2']);
expect(texts(doc, '.tl-start')).toEqual(['09:30']);
expect(texts(doc, '.tl-end')).toEqual(['11:00']);
expect(texts(doc, '.place-name')).toEqual(['Kiyomizu-dera']);
expect(texts(doc, '.cat-badge')).toEqual(['Temple']);
const facts = texts(doc, '.facts .chip');
expect(facts[0]).toBe('1 h 30 min');
expect(facts[1]).toMatch(/500/);
expect(facts.slice(2)).toEqual(['4.6 (12)', 'Must see']);
expect(texts(doc, '.info-row .info-text')).toEqual(['1 Chome-294 Kiyomizu, Kyoto', '34.99486, 135.78505']);
expect(doc.querySelector('.coords')).not.toBeNull();
});
it('FE-PDFDAY-002: reads the rating, e-mail, hours and reservation note off the trip place', () => {
const doc = parse(placeItem(assignment(), 1, day, context()));
// The day is a Wednesday: its hours, not Monday's.
expect(texts(doc, '.details .detail')).toEqual([
'inspector.openingHours 09:00 – 17:30',
'+81 75-551-1234',
'kiyomizudera.or.jp',
'info@kiyomizudera.or.jp',
'inspector.participants: mia, leo',
]);
expect(texts(doc, '.place-note')).toEqual(['Tickets at the west gate', 'Go early']);
expect(doc.querySelector('.place-text')?.innerHTML).toBe('<p>Wooden **stage** over the hill</p>');
});
it('FE-PDFDAY-003: a day the place is closed says so', () => {
const thursday = { ...day, date: '2026-05-07' } as Day;
const doc = parse(placeItem(assignment(), 1, thursday, context()));
expect(texts(doc, '.details .detail')[0]).toBe('inspector.openingHours inspector.closed');
});
it('FE-PDFDAY-004: a place with neither photo nor extras prints its category tile and nothing empty', () => {
const bare = {
id: 201,
day_id: 10,
order_index: 0,
place: { id: 99, name: 'Corner shop', category_id: 4, lat: null, lng: null },
} as unknown as Assignment;
const doc = parse(placeItem(bare, 1, { ...day, date: null } as Day, context()));
expect(doc.querySelector('.place-thumb-fallback')).not.toBeNull();
expect(doc.querySelector('.place-card')?.getAttribute('style')).toBe('--cat:#c2410c');
for (const empty of ['.facts', '.info-row', '.details', '.place-note', '.place-text', '.tl-start', '.tl-end']) {
expect(doc.querySelector(empty)).toBeNull();
}
});
it('FE-PDFDAY-005: the photo the export picked prints, and a hostile name and tag colour stay inert', () => {
const hostile = assignment({
name: '<img src=x onerror=alert(1)>',
tags: [{ name: 'x', color: 'red;background:url(x)' }],
});
const html = placeItem(hostile, 1, day, context({ photoOf: () => 'data:image/jpeg;base64,AAA' }));
const doc = parse(html);
expect(doc.querySelector('img.place-thumb')?.getAttribute('src')).toBe('data:image/jpeg;base64,AAA');
expect(doc.querySelectorAll('img')).toHaveLength(1);
expect(texts(doc, '.place-name')).toEqual(['<img src=x onerror=alert(1)>']);
expect(doc.querySelector('.chip-tag')?.getAttribute('style')).toBe('--tag:#6b6b75');
});
});
describe('noteItem', () => {
it('FE-PDFDAY-006: a coloured note carries its colour as the edge, an unknown colour none', () => {
const note = {
id: 1,
day_id: 10,
text: 'Buy <tickets>',
time: '08:00',
icon: 'Ticket',
color: '#2563eb',
} as DayNote;
const tinted = parse(noteItem(note));
expect(tinted.querySelector('.note-card')?.className).toBe('note-card note-tinted');
expect(tinted.querySelector('.note-card')?.getAttribute('style')).toBe('--note:#2563eb');
expect(texts(tinted, '.note-text')).toEqual(['Buy <tickets>']);
// The note's time field is its free second line, kept in the card, not a clock.
expect(texts(tinted, '.note-time')).toEqual(['08:00']);
expect(tinted.querySelector('.tl-start')).toBeNull();
const plain = parse(noteItem({ ...note, color: 'not-a-colour', time: null } as DayNote));
expect(plain.querySelector('.note-card')?.className).toBe('note-card');
expect(plain.querySelector('.note-time')).toBeNull();
});
});
describe('staysBlock', () => {
const stay = {
id: 1,
start_day_id: 10,
end_day_id: 12,
place_name: 'Hotel Gion',
place_address: 'Gion 1',
check_in: '15:00',
check_out: '10:00',
confirmation: 'HX-42',
notes: 'Late arrival',
place_image: null,
} as unknown as Accommodation;
it('FE-PDFDAY-007: the arrival day gets the full card with time, address, notes and code', () => {
const doc = parse(staysBlock([stay], day, context()));
expect(doc.querySelector('.day-accommodations')?.className).toBe('day-accommodations single');
expect(texts(doc, '.stay-kicker')).toEqual(['reservations.meta.checkIn 15:00']);
expect(texts(doc, '.stay-name')).toEqual(['Hotel Gion']);
expect(texts(doc, '.stay-line')).toEqual(['Gion 1', 'Late arrival']);
expect(texts(doc, '.code-chip')).toEqual(['HX-42']);
});
it('FE-PDFDAY-008: a night in between is one quiet line, the leaving day the check-out', () => {
const middle = parse(staysBlock([stay], { ...day, id: 11 } as Day, context()));
expect(middle.querySelector('.stay-quiet')).not.toBeNull();
expect(texts(middle, '.stay-kicker')).toEqual(['reservations.meta.linkAccommodation']);
expect(middle.querySelector('.stay-line')).toBeNull();
const leaving = parse(staysBlock([stay], { ...day, id: 12 } as Day, context()));
expect(texts(leaving, '.stay-kicker')).toEqual(['reservations.meta.checkOut 10:00']);
expect(leaving.querySelector('.code-chip')).toBeNull();
});
it('FE-PDFDAY-009: no stay prints nothing, two drop the single-column class', () => {
expect(staysBlock([], day, context())).toBe('');
const doc = parse(staysBlock([stay, { ...stay, id: 2, place_name: 'Ryokan' } as Accommodation], day, context()));
expect(doc.querySelector('.day-accommodations')?.className).toBe('day-accommodations');
});
});
describe('dayHeader', () => {
it('FE-PDFDAY-010: the number, date and title, with only the figures the day has', () => {
const doc = parse(dayHeader(day, { stops: 4, distance: '12 km', cost: '¥3,000' }, context()));
expect(texts(doc, '.day-tag-lbl')).toEqual(['pdf.day']);
expect(texts(doc, '.day-tag-num')).toEqual(['3']);
expect(texts(doc, '.day-date')[0]).toMatch(/May/);
expect(texts(doc, '.day-title')).toEqual(['Kyoto']);
expect(texts(doc, '.meta-pill, .day-cost')).toEqual(['4', '12 km', '¥3,000']);
const untitled = parse(
dayHeader({ ...day, title: null, date: null } as Day, { stops: 0, distance: null, cost: null }, context())
);
expect(texts(untitled, '.day-title')).toEqual(['dayplan.dayN:{"n":3}']);
expect(untitled.querySelector('.day-date')).toBeNull();
expect(untitled.querySelector('.day-meta')).toBeNull();
});
});
describe('photoStrip', () => {
it('FE-PDFDAY-011: up to three photos, each named on its label; none prints nothing', () => {
expect(photoStrip([])).toBe('');
const doc = parse(
photoStrip([
{ url: 'https://a.example/1.jpg', caption: 'Gate <one>' },
{ url: 'https://a.example/2.jpg', caption: 'Stage' },
])
);
expect(doc.querySelector('.day-strip')?.className).toBe('day-strip day-strip-2');
expect(texts(doc, '.glass-label')).toEqual(['Gate <one>', 'Stage']);
expect([...doc.querySelectorAll('img')].map((img) => img.getAttribute('src'))).toEqual([
'https://a.example/1.jpg',
'https://a.example/2.jpg',
]);
});
});
+434
View File
@@ -0,0 +1,434 @@
import { parsePlaceHours } from '@trek/shared';
import type { Accommodation, Assignment, Category, Day, DayNote, Place, Reservation } from '../../types';
import { getDisplayTimeForDay, getSpanPhase } from '../../utils/dayMerge';
import { getFlightLegs, getTrainLegs, usesStationRoute } from '../../utils/flightLegs';
import { formatMoney, splitReservationDateTime } from '../../utils/formatters';
import type { TransportLegDetail } from '../Planner/transportDetailModel';
import { escHtml, hexColour, safeImg, shortDate, websiteHost } from './tripPdfHtml';
import { bookingIcon, bookingTint, categoryIcon, glyph, noteIcon } from './tripPdfIcons';
/*
* One day of the trip PDF: its header, where the night is spent, and the day's plan
* as a timeline, times on the left, a rail in the day's colour, and a card for every
* stop, booking and note.
*/
type Translate = (key: string, params?: Record<string, string | number>) => string;
/** A booking as the day merge hands it over, a leg of a multi-leg booking included. */
export type PdfBooking = Reservation & { __leg?: TransportLegDetail & { total?: number } };
/** What the day's markup needs from the export around it. */
export interface PdfDayContext {
tr: Translate;
fmtTime: (value?: string | null) => string;
locale: string | undefined;
tripCurrency: string;
categories: readonly Category[];
/** The trip's full places by id: an assignment carries only a projection of its place. */
placesById: ReadonlyMap<number, Place>;
/** The picture to print for a place, already shrunk where it could be; null for none. */
photoOf: (place: Assignment['place']) => string | null;
/** A place's description or notes as sanitized markdown. */
markdown: (text: string) => string;
}
const NEUTRAL = '#6b6b75';
function metadataOf(r: PdfBooking): Record<string, unknown> {
if (!r.metadata) return {};
try {
const parsed: unknown = typeof r.metadata === 'string' ? JSON.parse(r.metadata) : r.metadata;
return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : {};
} catch {
return {};
}
}
const text = (value: unknown): string => (typeof value === 'string' || typeof value === 'number' ? String(value) : '');
/** "1 h 30 min", or null for no duration at all. */
function durationLabel(minutes: number | null | undefined): string | null {
if (typeof minutes !== 'number' || !Number.isFinite(minutes) || minutes <= 0) return null;
const whole = Math.round(minutes);
const h = Math.floor(whole / 60);
const m = whole % 60;
if (h === 0) return `${m} min`;
return m === 0 ? `${h} h` : `${h} h ${m} min`;
}
function timeColumn(start: string, end: string): string {
return `<div class="tl-time">${start ? `<span class="tl-start">${escHtml(start)}</span>` : ''}${
end ? `<span class="tl-end">${escHtml(end)}</span>` : ''
}</div>`;
}
function item(kind: string, time: string, marker: string, body: string, style = ''): string {
return `<li class="tl-item tl-${kind}"${style ? ` style="${style}"` : ''}>${time}<div class="tl-rail"><span class="tl-marker">${marker}</span></div><div class="tl-body">${body}</div></li>`;
}
// ── Bookings ──────────────────────────────────────────────────────────────
/** "Departure", "Pick-up" and the like, for a booking that spans days; null on its single day. */
function spanLabel(r: PdfBooking, phase: string, tr: Translate): string | null {
if (phase === 'single') return null;
// Each key spelled out, so the key check can follow every branch to its string.
const start = phase === 'start';
const end = phase === 'end';
if (r.type === 'flight') return tr(`reservations.span.${start ? 'departure' : end ? 'arrival' : 'inTransit'}`);
if (r.type === 'car') return tr(`reservations.span.${start ? 'pickup' : end ? 'return' : 'active'}`);
// Parking reuses span.pickup for its end day: you drop the car off and collect it
// again later, so the rental car's wording carries over without a second key.
if (r.type === 'parking') return tr(`reservations.span.${start ? 'dropOff' : end ? 'pickup' : 'ongoing'}`);
return tr(`reservations.span.${start ? 'start' : end ? 'end' : 'ongoing'}`);
}
function stopsOf(r: PdfBooking, label: 'code' | 'name'): string[] {
return (r.endpoints || [])
.slice()
.sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0))
.map((e) => (label === 'code' ? e.code || e.name : e.name) || '')
.filter(Boolean);
}
/** One line under a booking's title: the way it goes, its facts as badges and its own booking code. */
interface BookingLine {
route: string;
facts: string[];
code: string;
/** A table's party size, printed with the people icon so it needs no word. */
people?: string;
}
/**
* The lines under a booking's title. A multi-leg flight or train gets one per leg, each
* with its own number and booking code, since that is the code the gate asks for
* (#1943); a leg row prints its own leg; everything else gets one line or none.
*/
function bookingLines(r: PdfBooking, tr: Translate): BookingLine[] {
const meta = metadataOf(r);
const route = (from?: string | null, to?: string | null) =>
from || to ? [from, to].filter(Boolean).join(' → ') : '';
const seat = (value: unknown) => (text(value) ? `${tr('reservations.meta.seat')} ${text(value)}` : '');
const platform = (value: unknown) => (text(value) ? `${tr('reservations.meta.platform')} ${text(value)}` : '');
const line = (way: string, facts: unknown[], code: unknown = ''): BookingLine => ({
route: way,
facts: facts.map(text).filter(Boolean),
code: text(code),
});
const filled = (lines: BookingLine[]) => lines.filter((l) => l.route || l.facts.length || l.code);
if (r.__leg) {
const l = r.__leg;
const source = (usesStationRoute(r.type) ? getTrainLegs(r) : getFlightLegs(r))[l.index];
return filled([
line(
route(l.from, l.to),
[l.airline, l.flight_number, l.train_number, platform(l.platform), seat(l.seat)],
source?.confirmation_number
),
]);
}
if (r.type === 'flight') {
const legs = getFlightLegs(r);
if (legs.length > 1) {
return filled(
legs.map((l) => line(route(l.from, l.to), [l.airline, l.flight_number, seat(l.seat)], l.confirmation_number))
);
}
const stops = stopsOf(r, 'code');
const way = stops.length >= 2 ? stops.join(' → ') : route(text(meta.departure_airport), text(meta.arrival_airport));
return filled([line(way, [meta.airline, meta.flight_number, seat(meta.seat)])]);
}
if (r.type === 'train') {
const legs = getTrainLegs(r);
if (legs.length > 1) {
return filled(
legs.map((l) =>
line(route(l.from, l.to), [l.train_number, platform(l.platform), seat(l.seat)], l.confirmation_number)
)
);
}
const stops = stopsOf(r, 'code');
return filled([
line(stops.length >= 2 ? stops.join(' → ') : '', [meta.train_number, platform(meta.platform), seat(meta.seat)]),
]);
}
if (r.type === 'car') {
// A rental with stops is a drive, and the printout is what people take into the car
// (#1797). Consecutive repeats collapse, and a chain of one place is no route: the
// ordinary rental is picked up and returned at the same desk.
const stops = stopsOf(r, 'name').filter((name, i, all) => name !== all[i - 1]);
return new Set(stops).size >= 2 ? [line(stops.join(' → '), [])] : [];
}
if (r.type === 'restaurant') return text(meta.party_size) ? [{ ...line('', []), people: text(meta.party_size) }] : [];
if (r.type === 'event') return filled([line('', [meta.venue])]);
if (r.type === 'tour') return filled([line('', [meta.operator])]);
return [];
}
function bookingLineHtml(l: BookingLine): string {
return `<div class="note-line">${l.route ? `<span class="route">${escHtml(l.route)}</span>` : ''}${
l.people ? `<span class="chip">${glyph('people', 9)}${escHtml(l.people)}</span>` : ''
}${l.facts
.map((fact) => `<span class="chip">${escHtml(fact)}</span>`)
.join('')}${l.code ? `<span class="code-chip">${glyph('key', 9)}${escHtml(l.code)}</span>` : ''}</div>`;
}
/** A booking's lines on their own, for the booking list of the overview. */
export function bookingLinesHtml(r: PdfBooking, tr: Translate): string {
return bookingLines(r, tr).map(bookingLineHtml).join('');
}
/** A booking on the day's timeline. Sets `flags.transportNote` when it prints a note. */
export function bookingItem(r: PdfBooking, day: Day, ctx: PdfDayContext, flags: { transportNote: boolean }): string {
const { tr, fmtTime } = ctx;
const phase = getSpanPhase(r, day.id);
const span = spanLabel(r, phase, tr);
// Start and end the way the day plan draws them (#1310). The landing time only on a
// booking that begins and ends this day: across a span the arrival belongs to the
// arrival day, which shows it as its own time.
const start = fmtTime(splitReservationDateTime(getDisplayTimeForDay(r, day.id)).time);
const end = phase === 'single' ? fmtTime(splitReservationDateTime(r.reservation_end_time).time) : '';
const note = typeof r.notes === 'string' ? r.notes.trim() : '';
if (note) flags.transportNote = true;
const meta = metadataOf(r);
const location = r.location || text(meta.location);
const status =
r.status === 'confirmed' ? tr('reservations.confirmed') : r.status === 'pending' ? tr('reservations.pending') : '';
const tint = hexColour(bookingTint(r.type), NEUTRAL);
const extras = [
r.confirmation_number
? `<span class="code-chip note-code">${glyph('key', 9)}${escHtml(r.confirmation_number)}</span>`
: '',
status ? `<span class="chip">${escHtml(status)}</span>` : '',
].filter(Boolean);
const card = `<div class="note-card booking-card">
<span class="note-icon">${bookingIcon(r.type)}</span>
<div class="note-body">
${span ? `<div class="note-kicker">${escHtml(span)}</div>` : ''}
<div class="note-text">${escHtml(r.title)}</div>
${bookingLines(r, tr).map(bookingLineHtml).join('')}
${location ? `<div class="note-time">${escHtml(location)}</div>` : ''}
${extras.length ? `<div class="note-extra">${extras.join('')}</div>` : ''}
${note ? `<div class="note-time transport-note">${escHtml(note)}</div>` : ''}
</div>
</div>`;
return item('booking', timeColumn(start, end), bookingIcon(r.type, 11), card, `--kind:${tint}`);
}
// ── Notes ─────────────────────────────────────────────────────────────────
/**
* A day note. A coloured note carries its colour as the rule along its edge and its
* icon (#1629), not as a fill: a tint costs ink and reads as grey on a mono printer.
*/
export function noteItem(note: DayNote): string {
const colour = note.color ? hexColour(note.color, '') : '';
// A note's `time` is the free line the day plan prints under its text, not a clock,
// so it stays in the card and the time column stays empty.
const subtitle = typeof note.time === 'string' ? note.time.trim() : '';
const card = `<div class="note-card${colour ? ' note-tinted' : ''}"${colour ? ` style="--note:${colour}"` : ''}>
<span class="note-icon">${noteIcon(note.icon)}</span>
<div class="note-body"><div class="note-text">${escHtml(note.text)}</div>${
subtitle ? `<div class="note-time">${escHtml(subtitle)}</div>` : ''
}</div>
</div>`;
return item('note', timeColumn('', ''), '', card);
}
// ── Places ────────────────────────────────────────────────────────────────
/** The day's opening hours of a place, Monday first like the stored week; null when unknown. */
function hoursOnDay(place: Partial<Place>, day: Day, ctx: PdfDayContext): string | null {
const week = parsePlaceHours(place.opening_hours);
if (!week || !day.date) return null;
const weekday = (new Date(day.date + 'T00:00:00Z').getUTCDay() + 6) % 7;
const hours = week[weekday];
if (!hours) return null;
if (hours.closed) return ctx.tr('inspector.closed');
if (!hours.open && !hours.close) return null;
return [ctx.fmtTime(hours.open), ctx.fmtTime(hours.close)].filter(Boolean).join(' – ');
}
function placeFacts(place: Assignment['place'] & Partial<Place>, ctx: PdfDayContext): string[] {
const facts: string[] = [];
const duration = durationLabel(place.duration_minutes);
if (duration) facts.push(`<span class="chip">${glyph('duration', 9)}${escHtml(duration)}</span>`);
const price = Number(place.price);
if (Number.isFinite(price) && price > 0) {
facts.push(
`<span class="chip chip-green">${glyph('price', 9)}${escHtml(formatMoney(price, place.currency || ctx.tripCurrency, ctx.locale || 'en'))}</span>`
);
}
if (typeof place.rating_avg === 'number' && place.rating_avg > 0) {
const count = place.rating_count ? ` (${place.rating_count})` : '';
facts.push(`<span class="chip chip-rating">${glyph('star', 9)}${place.rating_avg.toFixed(1)}${count}</span>`);
}
for (const tag of place.tags || []) {
if (!tag.name) continue;
facts.push(
`<span class="chip chip-tag" style="--tag:${hexColour(tag.color, NEUTRAL)}">${escHtml(tag.name)}</span>`
);
}
return facts;
}
function placeDetails(
place: Assignment['place'] & Partial<Place>,
assignment: Assignment,
day: Day,
ctx: PdfDayContext
): string[] {
const details: string[] = [];
const hours = hoursOnDay(place, day, ctx);
if (hours)
details.push(
`<span class="detail">${glyph('hours', 9)}${escHtml(ctx.tr('inspector.openingHours'))} ${escHtml(hours)}</span>`
);
if (place.phone) details.push(`<span class="detail">${glyph('phone', 9)}${escHtml(place.phone)}</span>`);
if (place.website)
details.push(`<span class="detail">${glyph('web', 9)}${escHtml(websiteHost(place.website))}</span>`);
if (place.email) details.push(`<span class="detail">${glyph('mail', 9)}${escHtml(place.email)}</span>`);
const people = (assignment.participants || []).map((p) => p.username).filter(Boolean);
if (people.length) {
details.push(
`<span class="detail">${glyph('people', 9)}${escHtml(ctx.tr('inspector.participants'))}: ${escHtml(people.join(', '))}</span>`
);
}
return details;
}
/** A planned place on the day's timeline, numbered like the stops on the map. */
export function placeItem(assignment: Assignment, number: number, day: Day, ctx: PdfDayContext): string {
// The assignment carries a projection of its place; the rating, the e-mail, the
// hours and the reservation note are only on the trip's own place.
const place: Assignment['place'] & Partial<Place> = {
...ctx.placesById.get(assignment.place.id),
...assignment.place,
};
const category = ctx.categories.find((c) => c.id === place.category_id);
const catColour = hexColour(category?.color, NEUTRAL);
const photo = ctx.photoOf(assignment.place);
const media = photo
? `<img class="place-thumb" src="${escHtml(photo)}" alt="" />`
: `<div class="place-thumb-fallback">${categoryIcon(category?.icon)}</div>`;
const facts = placeFacts(place, ctx);
const details = placeDetails(place, assignment, day, ctx);
const hasPosition = place.lat != null && place.lng != null;
const notes = [place.notes, place.reservation_notes, assignment.notes].filter(
(value): value is string => typeof value === 'string' && value.trim() !== ''
);
const card = `<div class="place-card" style="--cat:${catColour}">
${media}
<div class="place-info">
<div class="place-name-row">
<span class="place-name">${escHtml(place.name)}</span>
${category ? `<span class="cat-badge">${escHtml(category.name)}</span>` : ''}
</div>
${facts.length ? `<div class="facts">${facts.join('')}</div>` : ''}
${place.address ? `<div class="info-row">${glyph('pin')}<span class="info-text">${escHtml(place.address)}</span></div>` : ''}
${
hasPosition
? `<div class="info-row coords">${glyph('coords')}<span class="info-text muted">${Number(place.lat).toFixed(5)}, ${Number(place.lng).toFixed(5)}</span></div>`
: ''
}
${place.description ? `<div class="place-text">${ctx.markdown(place.description)}</div>` : ''}
${notes.map((note) => `<div class="place-note">${ctx.markdown(note)}</div>`).join('')}
${details.length ? `<div class="details">${details.join('')}</div>` : ''}
</div>
</div>`;
const start = ctx.fmtTime(place.place_time);
const end = ctx.fmtTime(place.end_time);
return item('place', timeColumn(start, end), String(number), card);
}
// ── Stays ─────────────────────────────────────────────────────────────────
/**
* Where the day's night is spent. The day of arrival and the day of leaving get the
* full card with the time, the address and the booking code; the nights in between a
* quiet line, since the same hotel on every page is the plan's least news.
*/
export function staysBlock(stays: readonly Accommodation[], day: Day, ctx: PdfDayContext): string {
if (!stays.length) return '';
const cards = stays.map((stay) => {
const isCheckIn = day.id === stay.start_day_id;
const isCheckOut = day.id === stay.end_day_id;
const name = stay.place_name || stay.reservation_title || '';
const photo = safeImg(stay.place_image);
const media = `<span class="stay-media">${photo ? `<img src="${escHtml(photo)}" alt="" />` : glyph(isCheckOut ? 'checkOut' : isCheckIn ? 'checkIn' : 'bed', 16)}</span>`;
if (!isCheckIn && !isCheckOut) {
return `<div class="day-accommodation stay-quiet">${media}<div class="stay-main">
<div class="stay-kicker">${escHtml(ctx.tr('reservations.meta.linkAccommodation'))}</div>
<div class="stay-name">${escHtml(name)}</div>
</div></div>`;
}
const label = ctx.tr(isCheckIn ? 'reservations.meta.checkIn' : 'reservations.meta.checkOut');
const time = ctx.fmtTime(isCheckIn ? stay.check_in : stay.check_out);
const extras = [
isCheckIn && stay.confirmation
? `<span class="code-chip">${glyph('key', 9)}${escHtml(stay.confirmation)}</span>`
: '',
].filter(Boolean);
return `<div class="day-accommodation">${media}<div class="stay-main">
<div class="stay-kicker">${escHtml(label)}${time ? ` <span class="num">${escHtml(time)}</span>` : ''}</div>
<div class="stay-name">${escHtml(name)}</div>
${stay.place_address ? `<div class="stay-line">${escHtml(stay.place_address)}</div>` : ''}
${stay.notes ? `<div class="stay-line">${escHtml(stay.notes)}</div>` : ''}
${extras.length ? `<div class="stay-extra">${extras.join('')}</div>` : ''}
</div></div>`;
});
return `<div class="day-accommodations${stays.length === 1 ? ' single' : ''}">${cards.join('')}</div>`;
}
// ── Header ────────────────────────────────────────────────────────────────
interface DayHeaderFacts {
stops: number;
distance: string | null;
cost: string | null;
}
/** The day's header: its number in the day's colour, the date, the title and its figures. */
export function dayHeader(day: Day, facts: DayHeaderFacts, ctx: PdfDayContext): string {
const n = day.day_number ?? 0;
const pills = [
facts.stops > 0 ? `<span class="meta-pill">${glyph('pin', 9)}${facts.stops}</span>` : '',
facts.distance ? `<span class="meta-pill">${glyph('route', 9)}${escHtml(facts.distance)}</span>` : '',
facts.cost ? `<span class="day-cost">${glyph('price', 9)}${facts.cost}</span>` : '',
].filter(Boolean);
return `<div class="day-head">
<span class="day-tag"><span class="day-tag-lbl">${escHtml(ctx.tr('pdf.day'))}</span><span class="day-tag-num">${n}</span></span>
<div class="day-head-main">
${day.date ? `<div class="day-date">${escHtml(shortDate(day.date, ctx.locale))}</div>` : ''}
<div class="day-title">${escHtml(day.title || ctx.tr('dayplan.dayN', { n }))}</div>
</div>
${pills.length ? `<div class="day-meta">${pills.join('')}</div>` : ''}
</div>`;
}
// ── Photo strip ───────────────────────────────────────────────────────────
interface StripPhoto {
url: string;
caption: string;
}
/**
* The strip that opens a day: up to three of its photographed stops side by side, the
* first one widest, each named on a frosted label. Nothing for a day without photos.
*/
export function photoStrip(photos: readonly StripPhoto[]): string {
if (!photos.length) return '';
return `<div class="day-strip day-strip-${photos.length}">${photos
.map(
(p) =>
`<figure class="day-strip-photo"><img src="${escHtml(p.url)}" alt="" /><figcaption class="glass-label">${escHtml(p.caption)}</figcaption></figure>`
)
.join('')}</div>`;
}
+82
View File
@@ -0,0 +1,82 @@
/*
* The small text and URL helpers every part of the trip PDF builds its markup with.
* The document is an HTML string assembled outside React, so every value that comes
* from the trip goes through escHtml before it lands in it.
*/
/** Text for element content or a double-quoted attribute. */
export function escHtml(value: unknown): string {
if (value === null || value === undefined || value === '') return '';
return String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
/**
* The style attribute is decoded back into raw quotes before the CSS is parsed, so
* escHtml alone cannot stop a cover_image from closing the url() and appending its own
* declaration. Percent-encoding is transparent to the fetch.
*/
export function cssUrl(url: string): string {
return url.replace(/["'()\\\s]/g, (c) => '%' + (c.codePointAt(0) ?? 0).toString(16).padStart(2, '0'));
}
/**
* A colour that goes into a style attribute built by string concatenation. Anything
* that is not a plain hex triple is not a colour and gets the fallback instead of a
* chance to close the declaration.
*/
export function hexColour(value: unknown, fallback: string): string {
return /^#[0-9a-f]{6}$/i.test(String(value)) ? String(value) : fallback;
}
/** A path on this server as an absolute URL, so the print frame can load it. */
export function absUrl(url: string | null | undefined): string | null {
if (!url) return null;
if (url.startsWith('http://') || url.startsWith('https://') || url.startsWith('data:')) return url;
return window.location.origin + (url.startsWith('/') ? '' : '/') + url;
}
/**
* A picture the document may load: any web URL, the in-app place-photo proxy (it
* streams a JPEG under a path without an extension) and uploaded files with an image
* extension. Anything else prints as the fallback tile.
*/
export function safeImg(url: string | null | undefined): string | null {
if (!url) return null;
if (url.startsWith('https://') || url.startsWith('http://')) return url;
if (url.startsWith('/api/maps/place-photo/')) return absUrl(url);
return /\.(jpe?g|png|gif|webp|bmp|tiff?)(\?.*)?$/i.test(url) ? absUrl(url) : null;
}
/** "Mon, 5 May" in the reader's language; empty for a day without a date. */
export function shortDate(date: string | null | undefined, locale: string | undefined): string {
if (!date) return '';
return new Date(date + 'T00:00:00Z').toLocaleDateString(locale, {
weekday: 'short',
day: 'numeric',
month: 'short',
timeZone: 'UTC',
});
}
/** "3 May – 24 May 2026" over the dated days, or null when none has a date. */
export function longDateRange(
days: readonly { date?: string | null; day_number?: number }[],
locale: string | undefined
): string | null {
const dated = days.filter((d) => d.date).sort((a, b) => (a.day_number ?? 0) - (b.day_number ?? 0));
if (!dated.length) return null;
const first = new Date(dated[0].date + 'T00:00:00Z');
const last = new Date(dated[dated.length - 1].date + 'T00:00:00Z');
const from = first.toLocaleDateString(locale, { day: 'numeric', month: 'long', timeZone: 'UTC' });
const to = last.toLocaleDateString(locale, { day: 'numeric', month: 'long', year: 'numeric', timeZone: 'UTC' });
return `${from} – ${to}`;
}
/** The host of a website, which is what fits on a printed line. */
export function websiteHost(url: string): string {
try {
return new URL(/^https?:\/\//i.test(url) ? url : `https://${url}`).host.replace(/^www\./, '');
} catch {
return url;
}
}
+165
View File
@@ -0,0 +1,165 @@
import { createElement } from 'react';
import { renderIconMarkup } from '../../utils/iconMarkup';
import { getCategoryIcon } from '../shared/categoryIcons';
import {
AlertTriangle,
BedDouble,
Bike,
Bookmark,
Bus,
CableCar,
Camera,
Car,
CarTaxiFront,
Clock,
Coffee,
Crosshair,
FileText,
Flag,
Globe,
Heart,
Hourglass,
Info,
KeyRound,
Lightbulb,
LogIn,
LogOut,
Mail,
MapPin,
Navigation,
ParkingSquare,
Phone,
Plane,
Route,
Sailboat,
Ship,
ShoppingBag,
Star,
StickyNote,
Store,
Tag,
Ticket,
Train,
Users,
Utensils,
Wallet,
type LucideIcon,
} from 'lucide-react';
/*
* Every icon of the trip PDF as SVG markup. They draw in currentColor, so the
* stylesheet decides their colour, which keeps the palette in one place.
*/
function iconSvg(Icon: LucideIcon, size: number, strokeWidth = 1.9): string {
return renderIconMarkup(createElement(Icon, { size, strokeWidth, color: 'currentColor', 'aria-hidden': 'true' }));
}
/** The small glyphs of the facts, contact lines and stay rows. */
const GLYPHS = {
pin: MapPin,
coords: Crosshair,
clock: Clock,
duration: Hourglass,
price: Wallet,
star: Star,
phone: Phone,
web: Globe,
mail: Mail,
hours: Store,
people: Users,
note: StickyNote,
tag: Tag,
route: Route,
bed: BedDouble,
checkIn: LogIn,
checkOut: LogOut,
key: KeyRound,
} satisfies Record<string, LucideIcon>;
type PdfGlyph = keyof typeof GLYPHS;
export function glyph(name: PdfGlyph, size = 10): string {
return iconSvg(GLYPHS[name], size);
}
const NOTE_ICONS: Record<string, LucideIcon> = {
FileText,
Info,
Clock,
MapPin,
Navigation,
Train,
Plane,
Bus,
Car,
Ship,
Coffee,
Ticket,
Star,
Heart,
Camera,
Flag,
Lightbulb,
AlertTriangle,
ShoppingBag,
Bookmark,
};
/** A day note's own icon, the note icon for one that names none. */
export function noteIcon(iconId: string | null | undefined, size = 13): string {
return iconSvg((iconId && NOTE_ICONS[iconId]) || FileText, size);
}
const BOOKING_ICONS: Record<string, LucideIcon> = {
flight: Plane,
train: Train,
bus: Bus,
car: Car,
taxi: CarTaxiFront,
bicycle: Bike,
cruise: Ship,
ferry: Sailboat,
cable_car: CableCar,
transport_other: Route,
restaurant: Utensils,
event: Ticket,
tour: Users,
parking: ParkingSquare,
other: FileText,
};
/** A booking's type icon; a type the export does not know gets the ticket. */
export function bookingIcon(type: string | null | undefined, size = 14): string {
return iconSvg((type && BOOKING_ICONS[type]) || Ticket, size);
}
/** The tint of each booking type, the same hues the day plan gives them. */
const BOOKING_TINTS: Record<string, string> = {
flight: '#3b82f6',
train: '#0891b2',
bus: '#059669',
car: '#64748b',
taxi: '#ca8a04',
bicycle: '#65a30d',
cruise: '#0284c7',
ferry: '#0d9488',
cable_car: '#dc2626',
transport_other: '#64748b',
restaurant: '#e11d48',
event: '#d97706',
tour: '#059669',
parking: '#2563eb',
other: '#64748b',
};
export function bookingTint(type: string | null | undefined): string {
return (type && BOOKING_TINTS[type]) || BOOKING_TINTS.flight;
}
/** A category's icon for the tile a place without a photo prints. */
export function categoryIcon(iconName: string | null | undefined, size = 22): string {
return iconSvg(getCategoryIcon(iconName), size, 1.7);
}
@@ -0,0 +1,196 @@
/**
* FE-PDFOVERVIEW-001 to FE-PDFOVERVIEW-005: the trip PDF's cover and overview pages,
* built from the figures the export hands them.
*/
import { describe, expect, it } from 'vitest';
import { coverHtml, coverRouteSvg, glanceHtml, ledgerHtml, type GlanceRow, type LedgerRow } from './tripPdfOverview';
const tr = (key: string) => key;
const parse = (html: string) => new DOMParser().parseFromString(html, 'text/html');
const texts = (doc: Document, selector: string) =>
[...doc.querySelectorAll(selector)].map((el) => el.textContent?.replace(/\s+/g, ' ').trim());
describe('coverHtml', () => {
const base = {
title: 'Autumn <in> Japan',
description: 'Temples and trains',
range: '1 November – 22 November 2026',
logo: 'https://trek.example/logo-light.svg',
stats: [
{ value: '22', label: 'days' },
{ value: '1,234 km', label: 'pdf.distanceLabel' },
],
route: [],
ribbon: [],
ribbonEnds: null,
tr,
};
it('FE-PDFOVERVIEW-001: the photo, the escaped title, the dates and a tile per figure', () => {
const doc = parse(coverHtml({ ...base, image: 'https://cdn.example/cover.jpg' }));
expect(doc.querySelector('section')?.className).toBe('cover');
expect(doc.querySelector('.cover-bg')?.getAttribute('style')).toBe(
"background-image:url('https://cdn.example/cover.jpg')"
);
expect(texts(doc, '.cover-title')).toEqual(['Autumn <in> Japan']);
expect(texts(doc, '.cover-dates')).toEqual(['1 November – 22 November 2026']);
expect(texts(doc, '.cover-desc')).toEqual(['Temples and trains']);
expect(texts(doc, '.cover-stat-num')).toEqual(['22', '1,234 km']);
expect(texts(doc, '.cover-top .eyebrow')).toEqual(['pdf.travelPlan']);
});
it('FE-PDFOVERVIEW-002: without a photo the cover is plain, and a hostile url cannot leave url()', () => {
const plain = parse(coverHtml({ ...base, image: null, description: null, range: null }));
expect(plain.querySelector('section')?.className).toBe('cover cover-plain');
expect(plain.querySelector('.cover-bg')?.hasAttribute('style')).toBe(false);
expect(plain.querySelector('.cover-desc')).toBeNull();
expect(plain.querySelector('.cover-dates')).toBeNull();
const hostile = parse(coverHtml({ ...base, image: "https://a/x.jpg');background:url('https://b/leak.jpg" }));
const style = hostile.querySelector('.cover-bg')?.getAttribute('style') ?? '';
expect(style.match(/url\(/g)).toHaveLength(1);
expect(style).not.toContain("');");
});
});
describe('the cover route and day band', () => {
const base = { title: 'Japan', description: null, range: null, image: null, logo: null, stats: [], tr };
it('FE-PDFOVERVIEW-006: the route is drawn day by day in its colours, the band has a segment per day', () => {
const doc = parse(
coverHtml({
...base,
route: [
{
colour: '#ff0000',
lines: [
[
[35.68, 139.76],
[35.0, 135.77],
],
],
},
{
colour: '#00ff00',
lines: [
[
[35.0, 135.77],
[34.69, 135.5],
],
],
},
],
ribbon: ['#ff0000', '#00ff00', '#0000ff'],
ribbonEnds: ['Sun, Nov 1', 'Tue, Nov 3'],
})
);
const coloured = [...doc.querySelectorAll('.cover-route-svg path[stroke]')].map((p) => p.getAttribute('stroke'));
expect(coloured).toEqual(['#ff0000', '#00ff00']);
expect(doc.querySelectorAll('.cover-route-glow path')).toHaveLength(2);
expect(texts(doc, '.cover-route-lbl')).toEqual(['pdf.mapTitle']);
expect(doc.querySelectorAll('.cover-ribbon span')).toHaveLength(3);
expect(texts(doc, '.cover-ribbon-ends span')).toEqual(['Sun, Nov 1', 'Tue, Nov 3']);
// Every point lands inside the drawing.
const numbers = [...doc.querySelectorAll('.cover-route-svg path[stroke]')].flatMap((p) =>
(p.getAttribute('d') ?? '').split(/[ML ]/).filter(Boolean).map(Number)
);
for (const n of numbers) expect(n).toBeGreaterThanOrEqual(0);
for (const n of numbers) expect(n).toBeLessThanOrEqual(240);
});
it('FE-PDFOVERVIEW-007: nothing routed, one point or one spot draws no card, one day no band', () => {
expect(coverRouteSvg([])).toBe('');
expect(coverRouteSvg([{ colour: '#ff0000', lines: [[[1, 1]]] }])).toBe('');
expect(
coverRouteSvg([
{
colour: '#ff0000',
lines: [
[
[1, 1],
[1, 1],
],
],
},
])
).toBe('');
const doc = parse(coverHtml({ ...base, route: [], ribbon: ['#ff0000'], ribbonEnds: null }));
expect(doc.querySelector('.cover-route')).toBeNull();
expect(doc.querySelector('.cover-ribbon')).toBeNull();
});
it('FE-PDFOVERVIEW-008: a long road is thinned to a drawable number of points', () => {
const road = Array.from({ length: 20000 }, (_, i) => [45 + i / 20000, 7 + i / 10000] as [number, number]);
const svg = coverRouteSvg([{ colour: '#ff0000', lines: [road] }]);
const d = /<path d="([^"]+)" stroke=/.exec(svg)?.[1] ?? '';
expect(d.split('L').length).toBeLessThanOrEqual(1700);
});
});
describe('glanceHtml', () => {
const row = (over: Partial<GlanceRow> = {}): GlanceRow => ({
number: 1,
colour: '#0a84ff',
date: 'Sun, Nov 1',
title: 'Tokyo',
stops: 3,
stay: 'Hotel Gracery',
cost: null,
...over,
});
it('FE-PDFOVERVIEW-003: one row per day in its colour, the cost column only when a day has one', () => {
const without = parse(glanceHtml([row(), row({ number: 2, stops: 0 })], tr));
expect(texts(without, 'thead th')).toEqual(['pdf.day', 'common.date', 'pdf.plan', 'pdf.stay', '']);
expect(texts(without, 'tbody tr:first-child td')).toEqual(['1', 'Sun, Nov 1', 'Tokyo', 'Hotel Gracery', '3']);
// A day without stops leaves the cell empty rather than printing a zero.
expect(texts(without, 'tbody tr:last-child td').slice(-1)[0]).toBe('');
expect(without.querySelector('tbody tr')?.getAttribute('style')).toBe('--day:#0a84ff');
const withCost = parse(glanceHtml([row(), row({ number: 2, cost: '¥3,000' })], tr));
expect(texts(withCost, 'thead th').slice(-1)[0]).toBe('pdf.costLabel');
expect(texts(withCost, 'tbody tr:last-child td').slice(-1)[0]).toBe('¥3,000');
expect(glanceHtml([], tr)).toBe('');
});
});
describe('ledgerHtml', () => {
it('FE-PDFOVERVIEW-004: each booking and stay with its date and the code to show', () => {
const rows: LedgerRow[] = [
{
icon: '<svg></svg>',
tint: '#3b82f6',
title: 'LH716 <FRA>',
sub: '<span>FRA → HND</span>',
when: 'Sat, Oct 31',
code: 'ABC123',
},
{
icon: '<svg></svg>',
tint: '#17171c',
title: 'Hotel Gracery',
sub: '',
when: 'Sun, Nov 1 – Wed, Nov 4',
code: null,
},
];
const doc = parse(ledgerHtml(rows, tr));
expect(texts(doc, '.sec-title')).toEqual(['pdf.bookings']);
expect(texts(doc, '.ledger-title')).toEqual(['LH716 <FRA>', 'Hotel Gracery']);
expect(texts(doc, '.ledger-sub')).toEqual(['FRA → HND']);
expect(texts(doc, '.ledger-when .code-chip')).toEqual(['ABC123']);
expect(doc.querySelectorAll('.ledger-when')[1]?.textContent).toBe('Sun, Nov 1 – Wed, Nov 4');
expect(doc.querySelectorAll('.code-chip')).toHaveLength(1);
expect(doc.querySelector('.ledger-row')?.getAttribute('style')).toBe('--kind:#3b82f6');
});
it('FE-PDFOVERVIEW-005: a trip without bookings or stays prints no list at all', () => {
expect(ledgerHtml([], tr)).toBe('');
});
});
@@ -0,0 +1,239 @@
import type { ShadeStop } from './pdfImages';
import { cssUrl, escHtml } from './tripPdfHtml';
import { glyph } from './tripPdfIcons';
/*
* The trip PDF's first pages: the cover, then the overview with the route map, every
* day at a glance and the list of bookings and stays with their codes.
*/
type Translate = (key: string, params?: Record<string, string | number>) => string;
export interface CoverStat {
value: string;
label: string;
}
/** One day of the route as the cover draws it: its colour and its roads, `[lat, lng]`. */
interface CoverRouteDay {
colour: string;
lines: readonly (readonly [number, number])[][];
}
interface CoverInput {
title: string;
description: string | null;
range: string | null;
/** The cover photo, already checked to be one the document may load. */
image: string | null;
/** Whether the shade is already painted into `image`, so none is laid over it. */
baked?: boolean;
/** The light TREK logo, absolute. */
logo: string | null;
stats: readonly CoverStat[];
/** The routed days, drawn as the trip's shape; empty when nothing was routed. */
route: readonly CoverRouteDay[];
/** Every day's colour in trip order, for the band under the title. */
ribbon: readonly string[];
/** The first and the last day's short date, under the band's ends. */
ribbonEnds: readonly [string, string] | null;
tr: Translate;
}
/**
* The shade over the cover photo, top to bottom: a little at the top for the logo, clear
* through the middle, dark at the foot for the title and the figures. Painted into the
* photo when the export could bake it, laid over it as a gradient when not.
*/
export const COVER_SHADE: readonly ShadeStop[] = [
[0, 0.35],
[0.22, 0],
[0.36, 0],
[0.92, 0.82],
];
/** The cover shade as a CSS gradient, for a photo the export could not bake. */
export function coverShadeCss(): string {
return `linear-gradient(180deg, ${COVER_SHADE.map(([at, alpha]) => `rgba(10, 10, 14, ${alpha}) ${at * 100}%`).join(', ')})`;
}
const ROUTE_W = 240;
const ROUTE_H = 170;
const ROUTE_PAD = 14;
/** Points drawn at most: a road trip routes to tens of thousands, the shape needs far fewer. */
const ROUTE_MAX_POINTS = 1600;
type LatLng = readonly [number, number];
/**
* The trip's roads as one small drawing, each day in its colour on a soft glow, with a
* ring where the trip starts and a dot where it ends. Projected flat with the longitude
* scaled to the middle latitude, which is true enough at the size of a trip. Empty when
* there is no shape to draw.
*/
export function coverRouteSvg(days: readonly CoverRouteDay[]): string {
const lines = days.flatMap((d) => d.lines.filter((l) => l.length > 1).map((l) => ({ colour: d.colour, points: l })));
const points = lines.flatMap((l) => l.points);
if (!lines.length) return '';
const lats = points.map((p) => p[0]);
const midLat = (Math.min(...lats) + Math.max(...lats)) / 2;
const k = Math.cos((midLat * Math.PI) / 180);
const xs = points.map((p) => p[1] * k);
const ys = points.map((p) => -p[0]);
const minX = Math.min(...xs);
const minY = Math.min(...ys);
const w = Math.max(...xs) - minX;
const h = Math.max(...ys) - minY;
const scale = Math.min(
w > 0 ? (ROUTE_W - 2 * ROUTE_PAD) / w : Infinity,
h > 0 ? (ROUTE_H - 2 * ROUTE_PAD) / h : Infinity
);
if (!Number.isFinite(scale)) return '';
const offX = (ROUTE_W - w * scale) / 2;
const offY = (ROUTE_H - h * scale) / 2;
const x = (p: LatLng) => (offX + (p[1] * k - minX) * scale).toFixed(1);
const y = (p: LatLng) => (offY + (-p[0] - minY) * scale).toFixed(1);
const step = Math.max(1, Math.ceil(points.length / ROUTE_MAX_POINTS));
const path = (line: readonly LatLng[]) =>
line
.filter((_, i) => i % step === 0 || i === line.length - 1)
.map((p, i) => `${i ? 'L' : 'M'}${x(p)} ${y(p)}`)
.join('');
const drawn = lines.map((l) => ({ colour: l.colour, d: path(l.points) }));
const first = lines[0];
const last = lines[lines.length - 1];
const start = first.points[0];
const end = last.points[last.points.length - 1];
return `<svg class="cover-route-svg" viewBox="0 0 ${ROUTE_W} ${ROUTE_H}" preserveAspectRatio="xMidYMid meet" aria-hidden="true">
<g class="cover-route-glow" fill="none" stroke="currentColor" stroke-width="4.6" stroke-linecap="round" stroke-linejoin="round">${drawn
.map((l) => `<path d="${l.d}"/>`)
.join('')}</g>
<g fill="none" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">${drawn
.map((l) => `<path d="${l.d}" stroke="${l.colour}"/>`)
.join('')}</g>
<circle class="cover-route-start" cx="${x(start)}" cy="${y(start)}" r="4.2" stroke="${first.colour}" stroke-width="2.2"/>
<circle class="cover-route-end" cx="${x(end)}" cy="${y(end)}" r="4.2" fill="${last.colour}" stroke-width="1.6"/>
</svg>`;
}
/** The cover: the trip's photo left bright, the title, the dates and its figures. */
export function coverHtml({
title,
description,
range,
image,
baked = false,
logo,
stats,
route,
ribbon,
ribbonEnds,
tr,
}: CoverInput): string {
const routeSvg = coverRouteSvg(route);
const routeCard = routeSvg
? `<div class="cover-route"><div class="cover-route-lbl">${escHtml(tr('pdf.mapTitle'))}</div>${routeSvg}</div>`
: '';
const ends = ribbonEnds
? `<div class="cover-ribbon-ends"><span>${escHtml(ribbonEnds[0])}</span><span>${escHtml(ribbonEnds[1])}</span></div>`
: '';
const band =
ribbon.length > 1
? `<div class="cover-ribbon">${ribbon.map((c) => `<span style="background:${c}"></span>`).join('')}</div>${ends}`
: '';
return `<section class="cover${image ? '' : ' cover-plain'}">
<div class="cover-bg"${image ? ` style="background-image:url('${escHtml(cssUrl(image))}')"` : ''}></div>
${baked ? '' : '<div class="cover-shade"></div>'}
<div class="cover-top">
${logo ? `<img src="${escHtml(logo)}" alt="TREK" />` : '<span></span>'}
<span class="eyebrow">${escHtml(tr('pdf.travelPlan'))}</span>
</div>
<div class="cover-body">
<div class="cover-main">
<div class="cover-head">
${range ? `<div class="cover-dates">${escHtml(range)}</div>` : ''}
<h1 class="cover-title">${escHtml(title)}</h1>
${description ? `<p class="cover-desc">${escHtml(description)}</p>` : ''}
</div>
${routeCard}
</div>
${band}
<div class="cover-stats">${stats
.map(
(s) =>
`<div class="cover-stat"><div class="cover-stat-num">${escHtml(s.value)}</div><div class="cover-stat-lbl">${escHtml(s.label)}</div></div>`
)
.join('')}</div>
</div>
</section>`;
}
export interface GlanceRow {
number: number;
colour: string;
date: string;
title: string;
stops: number;
stay: string;
cost: string | null;
}
/** Every day in one table: its colour, date and title, where the night is spent and what it costs. */
export function glanceHtml(rows: readonly GlanceRow[], tr: Translate): string {
if (!rows.length) return '';
const withCost = rows.some((r) => r.cost);
return `<div class="sec-block">
<div class="sec-head"><span class="sec-title">${escHtml(tr('pdf.atAGlance'))}</span></div>
<table class="glance">
<thead><tr>
<th>${escHtml(tr('pdf.day'))}</th>
<th>${escHtml(tr('common.date'))}</th>
<th>${escHtml(tr('pdf.plan'))}</th>
<th>${escHtml(tr('pdf.stay'))}</th>
<th class="glance-stops">${glyph('pin', 9)}</th>
${withCost ? `<th class="glance-end">${escHtml(tr('pdf.costLabel'))}</th>` : ''}
</tr></thead>
<tbody>${rows
.map(
(r) => `<tr style="--day:${r.colour}">
<td><span class="glance-day">${r.number}</span></td>
<td class="num glance-date">${escHtml(r.date)}</td>
<td class="glance-title">${escHtml(r.title)}</td>
<td>${escHtml(r.stay)}</td>
<td class="num glance-stops">${r.stops || ''}</td>
${withCost ? `<td class="num">${r.cost ?? ''}</td>` : ''}
</tr>`
)
.join('')}</tbody>
</table>
</div>`;
}
export interface LedgerRow {
/** The type's icon, already markup. */
icon: string;
/** The type's tint, a checked hex colour. */
tint: string;
title: string;
/** Markup under the title: the route, the address or the booking's facts. */
sub: string;
when: string;
code: string | null;
}
/** The trip's bookings and stays in date order, each with the code to show at the desk. */
export function ledgerHtml(rows: readonly LedgerRow[], tr: Translate): string {
if (!rows.length) return '';
return `<div class="sec-block ledger-block">
<div class="sec-head"><span class="sec-title">${escHtml(tr('pdf.bookings'))}</span></div>
<div class="ledger">${rows
.map(
(r) => `<div class="ledger-row" style="--kind:${r.tint}">
<span class="ledger-icon">${r.icon}</span>
<div><div class="ledger-title">${escHtml(r.title)}</div>${r.sub ? `<div class="ledger-sub">${r.sub}</div>` : ''}</div>
<div class="ledger-when">${escHtml(r.when)}${r.code ? `<div><span class="code-chip">${glyph('key', 9)}${escHtml(r.code)}</span></div>` : ''}</div>
</div>`
)
.join('')}</div>
</div>`;
}
+411
View File
@@ -0,0 +1,411 @@
import geist400 from '@fontsource/geist-sans/files/geist-sans-latin-400-normal.woff2?url';
import geist500 from '@fontsource/geist-sans/files/geist-sans-latin-500-normal.woff2?url';
import geist600 from '@fontsource/geist-sans/files/geist-sans-latin-600-normal.woff2?url';
import { PDF_MARKDOWN_CSS } from './pdfMarkdown';
import { coverShadeCss } from './tripPdfOverview';
/*
* The trip PDF's stylesheet. A print document has a fixed palette rather than the
* reader's scheme, so its colours are declared once, as the custom properties at the
* top, and every rule below names them. The type follows the app: Poppins for words,
* Geist for figures, times and the small capitals.
*
* Every switch of the preview is one class on <body> (pdfPreview.ts), so turning one
* over is instant and needs no rebuild:
* pdf-flow days run on instead of each starting a page
* pdf-large-text larger type and darker greys
* pdf-no-transport-notes the notes of flights, trains and rentals left out
* pdf-no-photos no photos on the places and stays
* pdf-no-overview no route map, day overview or booking list
* pdf-no-coords no coordinates under the addresses
* pdf-no-details no contact lines, opening hours or companions
*/
export function tripPdfCss(): string {
return `
@font-face { font-family: 'Poppins'; font-style: normal; font-weight: 400; src: url('/fonts/Poppins-Regular.ttf') format('truetype'); }
@font-face { font-family: 'Poppins'; font-style: italic; font-weight: 400; src: url('/fonts/Poppins-Italic.ttf') format('truetype'); }
@font-face { font-family: 'Poppins'; font-style: normal; font-weight: 500; src: url('/fonts/Poppins-Medium.ttf') format('truetype'); }
@font-face { font-family: 'Poppins'; font-style: normal; font-weight: 600; src: url('/fonts/Poppins-SemiBold.ttf') format('truetype'); }
@font-face { font-family: 'Poppins'; font-style: normal; font-weight: 700; src: url('/fonts/Poppins-Bold.ttf') format('truetype'); }
@font-face { font-family: 'Geist PDF'; font-weight: 400; src: url('${geist400}') format('woff2'); }
@font-face { font-family: 'Geist PDF'; font-weight: 500; src: url('${geist500}') format('woff2'); }
@font-face { font-family: 'Geist PDF'; font-weight: 600; src: url('${geist600}') format('woff2'); }
:root {
--ink: #17171c;
--ink-2: #3e3e47;
--ink-3: #6a6a74;
--ink-4: #9a9aa4;
--hair: #e7e5e0;
--paper: #ffffff;
--wash: #f6f5f2;
--wash-2: #eeede8;
--night: #141418;
--glass: rgba(255, 255, 255, 0.13);
--glass-edge: rgba(255, 255, 255, 0.22);
--glass-dark: rgba(14, 14, 18, 0.42);
--glass-tile: rgba(18, 18, 24, 0.34);
--glass-deep: rgba(12, 12, 16, 0.5);
--on-night: rgba(255, 255, 255, 0.78);
--on-night-2: rgba(255, 255, 255, 0.56);
--gold: #b7791f;
--day: var(--ink);
--t: 1;
--sans: 'Poppins', system-ui, -apple-system, 'Segoe UI', sans-serif;
--num: 'Geist PDF', 'Poppins', system-ui, sans-serif;
--gutter: 14mm;
}
body.pdf-large-text {
--t: 1.3;
--ink-2: #2b2b33;
--ink-3: #4b4b55;
--ink-4: #62626c;
}
@page { size: A4; margin: 12mm 0 14mm; }
@page :first { margin: 0; }
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
html, body { background: var(--paper); }
body {
font-family: var(--sans); color: var(--ink);
font-size: calc(9.5px * var(--t)); line-height: 1.5;
-webkit-print-color-adjust: exact; print-color-adjust: exact;
}
img { display: block; }
svg { flex-shrink: 0; }
.num { font-family: var(--num); font-variant-numeric: tabular-nums; }
.eyebrow {
font-family: var(--num); font-size: calc(7.5px * var(--t)); font-weight: 600;
letter-spacing: 0.14em; text-transform: uppercase; color: var(--ink-3);
}
.page-break { break-before: page; }
/* ── Cover ───────────────────────────────────────────────── */
.cover {
position: relative; height: 297mm; overflow: hidden;
background: var(--night); color: var(--paper); break-after: page;
}
.cover-bg { position: absolute; inset: 0; background-size: cover; background-position: center; }
.cover-plain .cover-bg {
background: radial-gradient(120% 80% at 85% 10%, var(--ink-2) 0%, var(--night) 60%);
}
.cover-shade {
position: absolute; inset: 0;
background: ${coverShadeCss()};
}
.cover-top {
position: absolute; inset-block-start: 14mm; inset-inline: var(--gutter);
display: flex; align-items: center; justify-content: space-between;
}
.cover-top img { height: 22px; }
.cover-top .eyebrow { color: var(--on-night); }
.cover-body { position: absolute; inset-inline: var(--gutter); inset-block-end: 15mm; }
.cover-main { display: flex; align-items: flex-end; gap: 8mm; }
.cover-head { flex: 1; min-width: 0; }
.cover-dates {
display: inline-block; font-family: var(--num); font-size: 9px; font-weight: 600; letter-spacing: 0.16em;
text-transform: uppercase; color: var(--paper); padding: 5px 11px; border-radius: 99px;
background: var(--glass-tile); border: 1px solid var(--glass-edge);
}
.cover-title { font-size: 54px; font-weight: 700; line-height: 1; letter-spacing: -0.025em; margin: 5mm 0 3.5mm; }
.cover-desc { max-width: 120mm; font-size: 12px; line-height: 1.6; color: var(--on-night); }
.cover-route {
flex: 0 0 66mm; padding: 9px 10px 6px; border-radius: 18px;
background: var(--glass-deep); border: 1px solid var(--glass-edge);
}
.cover-route-lbl {
font-family: var(--num); font-size: 7px; font-weight: 600; letter-spacing: 0.16em;
text-transform: uppercase; color: var(--on-night-2);
}
.cover-route-svg { display: block; width: 100%; height: auto; }
.cover-route-glow { color: var(--paper); }
.cover-route-start { fill: var(--paper); }
.cover-route-end { stroke: var(--paper); }
.cover-ribbon { display: flex; gap: 2px; height: 5px; margin-block-start: 8mm; }
.cover-ribbon span { flex: 1; border-radius: 3px; }
.cover-ribbon-ends {
display: flex; justify-content: space-between; margin-block-start: 5px;
font-family: var(--num); font-size: 7.5px; font-weight: 600; letter-spacing: 0.12em;
text-transform: uppercase; color: var(--on-night-2);
}
.cover-stats { display: flex; flex-wrap: wrap; gap: 8px; margin-block-start: 6mm; }
.cover-stat {
flex: 1 1 0; min-width: max-content;
background: var(--glass-tile); border: 1px solid var(--glass-edge); border-radius: 16px;
padding: 12px 14px 11px;
}
.cover-stat-num {
font-family: var(--num); font-size: 19px; font-weight: 600; line-height: 1.1;
white-space: nowrap; font-variant-numeric: tabular-nums;
}
.cover-stat-lbl {
font-family: var(--num); font-size: 7.5px; font-weight: 500; letter-spacing: 0.14em;
text-transform: uppercase; color: var(--on-night-2); margin-block-start: 5px;
}
/* The glass is a tinted fill, not a backdrop blur: print engines leave a blur out, and
in the preview a blur over the full-page photo had to be redrawn on every scroll. */
/* ── Overview: route map, the days at a glance, bookings and stays ─────── */
.overview { padding: 2mm var(--gutter) 0; }
.pdf-no-overview .overview { display: none; }
.sec-head { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; margin-block-end: 4mm; }
.sec-title { font-size: calc(17px * var(--t)); font-weight: 600; letter-spacing: -0.01em; }
.sec-block { break-inside: avoid; margin-block-end: 9mm; }
.trip-map { margin-block-end: 9mm; }
.trip-map-head { display: flex; align-items: baseline; justify-content: space-between; gap: 16px; margin-block-end: 4mm; }
.trip-map-title { font-size: calc(17px * var(--t)); font-weight: 600; letter-spacing: -0.01em; }
.trip-map-total {
font-family: var(--num); font-size: calc(9px * var(--t)); font-weight: 600; color: var(--ink-2);
background: var(--wash); border-radius: 99px; padding: 4px 10px;
}
.trip-map-note { font-size: 9px; font-weight: 600; color: var(--gold); margin: -2mm 0 3mm; }
.trip-map-svg { width: 100%; height: auto; border-radius: 16px; border: 1px solid var(--hair); display: block; overflow: hidden; }
.trip-map-legend { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 5px 14px; margin-block-start: 4mm; }
.trip-map-leg { display: flex; align-items: center; gap: 6px; min-width: 0; font-size: calc(8.5px * var(--t)); color: var(--ink-2); }
.trip-map-leg-name { flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.trip-map-dot { width: 8px; height: 8px; border-radius: 50%; }
.trip-map-leg-dist { font-family: var(--num); color: var(--ink-4); white-space: nowrap; }
.trip-map-credit { font-size: 7px; color: var(--ink-4); margin-block-start: 3mm; }
.glance { width: 100%; border-collapse: collapse; font-size: calc(8.5px * var(--t)); }
.glance th {
font-family: var(--num); font-size: calc(7px * var(--t)); font-weight: 600; letter-spacing: 0.12em;
text-transform: uppercase; color: var(--ink-4); text-align: start; padding: 0 6px 6px;
border-block-end: 1px solid var(--hair);
}
.glance td { padding: 6px; border-block-end: 1px solid var(--wash-2); vertical-align: top; color: var(--ink-2); }
.glance tr { break-inside: avoid; }
.glance-day { display: inline-flex; align-items: center; justify-content: center; min-width: 22px; height: 18px; padding: 0 5px; border-radius: 6px; background: var(--day); color: var(--paper); font-family: var(--num); font-weight: 600; font-size: calc(8px * var(--t)); }
.glance-title { color: var(--ink); font-weight: 500; }
.glance .num, .glance-end { text-align: end; white-space: nowrap; }
.glance .glance-stops { text-align: center; }
.glance .glance-date { text-align: start; }
.glance th.glance-stops svg { display: inline-block; vertical-align: -1px; }
.ledger { display: grid; gap: 5px; }
.ledger-row {
display: grid; grid-template-columns: 26px 1fr auto; gap: 10px; align-items: center;
padding: 7px 10px; border: 1px solid var(--hair); border-radius: 12px; break-inside: avoid;
}
.ledger-icon {
width: 26px; height: 26px; border-radius: 8px; display: flex; align-items: center; justify-content: center;
background: color-mix(in srgb, var(--kind) 14%, var(--paper)); color: var(--kind);
}
.ledger-title { font-weight: 600; font-size: calc(9.5px * var(--t)); }
.ledger-sub { font-size: calc(8px * var(--t)); color: var(--ink-3); }
.ledger-when { font-family: var(--num); font-size: calc(8px * var(--t)); color: var(--ink-3); text-align: end; white-space: nowrap; }
/* ── Day ─────────────────────────────────────────────────── */
/* A real <table>, so the browser repeats the <thead> day header on every page an
overflowing day spills onto (#1471); CSS table-header-group on a <div> is not
repeated by Chromium's print engine. */
.day-section { width: 100%; border-collapse: collapse; table-layout: fixed; }
.day-break { break-before: page; }
/* The first day always opens a page of its own, after the cover or the overview. */
.day-first { break-before: page; }
.pdf-flow .day-break { break-before: auto; }
.pdf-flow .day-section + .day-section { margin-block-start: 8mm; }
/* Hold a flowing day together where it fits, so a header is never stranded at the
foot of a sheet with its content on the next one (#1471). */
.pdf-flow .day-section { break-inside: avoid; page-break-inside: avoid; }
/* The gap under the header sits inside the repeated cell: a block-start padding on the
body is only painted on its first fragment (#1531). */
.day-header > tr > td { padding: 0 var(--gutter) 5mm; }
.day-head {
display: flex; align-items: center; gap: 12px; padding-block: 3mm 3.5mm;
border-block-end: 1px solid var(--hair); position: relative;
}
.day-head::after {
content: ''; position: absolute; inset-inline-start: 0; inset-block-end: -1px;
width: 26mm; height: 2px; border-radius: 2px; background: var(--day);
}
.day-tag {
width: 42px; height: 42px; border-radius: 13px; background: var(--day); color: var(--paper);
display: flex; flex-direction: column; align-items: center; justify-content: center; flex-shrink: 0;
}
.day-tag-lbl { font-family: var(--num); font-size: 6.5px; font-weight: 600; letter-spacing: 0.14em; opacity: 0.85; }
.day-tag-num { font-family: var(--num); font-size: 17px; font-weight: 600; line-height: 1; }
.day-head-main { flex: 1; min-width: 0; }
.day-date { font-family: var(--num); font-size: calc(8px * var(--t)); font-weight: 600; letter-spacing: 0.1em; text-transform: uppercase; color: var(--ink-3); }
.day-title { font-size: calc(17px * var(--t)); font-weight: 600; line-height: 1.25; letter-spacing: -0.01em; }
.day-meta { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 5px; max-width: 70mm; }
.meta-pill, .day-cost {
display: inline-flex; align-items: center; gap: 4px; white-space: nowrap;
font-family: var(--num); font-size: calc(8px * var(--t)); font-weight: 600; color: var(--ink-2);
background: var(--wash); border-radius: 99px; padding: 4px 9px;
}
.meta-pill svg, .day-cost svg { color: var(--ink-4); }
.day-body { padding: 0 var(--gutter) 4mm; }
.day-intro {
margin-block-end: 4mm; padding: 9px 12px; border-radius: 12px; background: var(--wash);
font-size: calc(9px * var(--t)); color: var(--ink-2); white-space: pre-line;
}
/* ── Photo strip ─────────────────────────────────────────── */
.day-strip { display: grid; gap: 4px; height: 48mm; margin-block-end: 5mm; border-radius: 16px; overflow: hidden; }
.day-strip-1 { grid-template-columns: 1fr; }
.day-strip-2 { grid-template-columns: 3fr 2fr; }
.day-strip-3 { grid-template-columns: 2fr 1fr 1fr; }
.day-strip-photo { position: relative; min-width: 0; overflow: hidden; background: var(--wash-2); }
.day-strip-photo img { width: 100%; height: 100%; object-fit: cover; }
.glass-label {
position: absolute; inset-inline-start: 8px; inset-block-end: 8px; max-width: calc(100% - 16px);
padding: 4px 10px; border-radius: 99px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
font-size: calc(8px * var(--t)); font-weight: 500; color: var(--paper);
background: var(--glass-dark); border: 1px solid var(--glass-edge);
}
.pdf-no-photos .day-strip { display: none; }
/* ── Stays ───────────────────────────────────────────────── */
.day-accommodations { display: grid; grid-template-columns: repeat(auto-fit, minmax(80mm, 1fr)); gap: 6px; margin-block-end: 5mm; }
.day-accommodation {
display: flex; gap: 10px; align-items: center; padding: 8px 10px;
border: 1px solid var(--hair); border-radius: 14px; break-inside: avoid;
}
.day-accommodation.stay-quiet { padding: 6px 10px; background: var(--wash); border-color: transparent; }
.stay-media {
width: 40px; height: 40px; border-radius: 11px; overflow: hidden; flex-shrink: 0;
display: flex; align-items: center; justify-content: center;
background: color-mix(in srgb, var(--day) 12%, var(--paper)); color: var(--day);
}
.stay-quiet .stay-media { width: 26px; height: 26px; border-radius: 8px; }
.stay-media img { width: 100%; height: 100%; object-fit: cover; }
.pdf-no-photos .stay-media img { display: none; }
.stay-main { flex: 1; min-width: 0; }
.stay-kicker { font-family: var(--num); font-size: calc(7.5px * var(--t)); font-weight: 600; letter-spacing: 0.12em; text-transform: uppercase; color: var(--day); }
.stay-name { font-size: calc(10.5px * var(--t)); font-weight: 600; line-height: 1.35; }
.stay-quiet .stay-name { font-size: calc(9px * var(--t)); font-weight: 500; }
.stay-line { font-size: calc(8.5px * var(--t)); color: var(--ink-3); }
.stay-extra { display: flex; flex-wrap: wrap; gap: 4px; margin-block-start: 4px; }
/* ── Timeline ────────────────────────────────────────────── */
.timeline { list-style: none; }
.tl-item { display: grid; grid-template-columns: 13mm 22px minmax(0, 1fr); column-gap: 8px; break-inside: avoid; }
.tl-time { text-align: end; padding-block-start: 11px; font-family: var(--num); font-variant-numeric: tabular-nums; }
.tl-start { display: block; font-size: calc(9.5px * var(--t)); font-weight: 600; color: var(--ink); }
.tl-end { display: block; font-size: calc(8px * var(--t)); color: var(--ink-4); }
.tl-rail { position: relative; display: flex; justify-content: center; }
.tl-rail::before {
content: ''; position: absolute; inset-block: 0; inset-inline-start: calc(50% - 0.75px); width: 1.5px;
background: color-mix(in srgb, var(--day) 26%, var(--paper));
}
.tl-item:first-child .tl-rail::before { inset-block-start: 14px; }
.tl-item:last-child .tl-rail::before { inset-block-end: auto; height: 14px; }
.tl-item:only-child .tl-rail::before { display: none; }
.tl-marker {
position: relative; margin-block-start: 8px; width: 22px; height: 22px; border-radius: 50%;
display: flex; align-items: center; justify-content: center;
background: var(--paper); border: 1.5px solid var(--day); color: var(--day);
font-family: var(--num); font-size: calc(8.5px * var(--t)); font-weight: 600;
}
.tl-place .tl-marker { background: var(--day); color: var(--paper); }
.tl-booking .tl-marker { border-color: var(--kind); color: var(--kind); }
.tl-note .tl-marker { width: 10px; height: 10px; margin-block-start: 13px; background: var(--wash-2); border-color: var(--wash-2); }
.tl-body { padding-block: 3px 7px; min-width: 0; }
.empty-day { padding: 10mm 0; text-align: center; color: var(--ink-4); font-size: calc(9px * var(--t)); }
/* ── Place ───────────────────────────────────────────────── */
.place-card {
display: flex; gap: 11px; padding: 10px; border: 1px solid var(--hair); border-radius: 14px;
background: var(--paper); break-inside: avoid;
}
.place-thumb, .place-thumb-fallback { width: 74px; height: 74px; border-radius: 11px; flex-shrink: 0; }
.place-thumb { object-fit: cover; }
.place-thumb-fallback {
display: flex; align-items: center; justify-content: center;
background: color-mix(in srgb, var(--cat) 14%, var(--paper)); color: var(--cat);
}
.pdf-no-photos .place-thumb, .pdf-no-photos .place-thumb-fallback { display: none; }
.place-info { flex: 1; min-width: 0; }
.place-name-row { display: flex; align-items: flex-start; gap: 8px; }
.place-name { flex: 1; font-size: calc(12px * var(--t)); font-weight: 600; line-height: 1.3; letter-spacing: -0.005em; }
.cat-badge {
display: inline-flex; align-items: center; gap: 4px; white-space: nowrap; flex-shrink: 0;
font-family: var(--num); font-size: calc(7.5px * var(--t)); font-weight: 600;
border-radius: 99px; padding: 3px 8px;
background: color-mix(in srgb, var(--cat) 13%, var(--paper));
color: color-mix(in srgb, var(--cat) 78%, var(--ink));
}
.facts { display: flex; flex-wrap: wrap; gap: 4px; margin-block-start: 5px; }
.chip {
display: inline-flex; align-items: center; gap: 4px; white-space: nowrap;
font-family: var(--num); font-size: calc(8px * var(--t)); font-weight: 500; color: var(--ink-2);
background: var(--wash); border-radius: 99px; padding: 2px 8px;
}
.chip svg { color: var(--ink-4); }
.chip-rating { color: var(--gold); }
.chip-rating svg { color: var(--gold); fill: var(--gold); }
.chip-tag { background: color-mix(in srgb, var(--tag) 12%, var(--paper)); color: color-mix(in srgb, var(--tag) 75%, var(--ink)); }
.chip-tag::before { content: ''; width: 6px; height: 6px; border-radius: 50%; background: var(--tag); }
.code-chip {
display: inline-flex; align-items: center; gap: 4px; white-space: nowrap;
font-family: var(--num); font-size: calc(8px * var(--t)); font-weight: 600; letter-spacing: 0.04em;
color: var(--ink); background: var(--wash-2); border-radius: 6px; padding: 2px 7px;
}
.code-chip svg { color: var(--ink-3); }
.info-row { display: flex; align-items: flex-start; gap: 5px; margin-block-start: 4px; }
.info-row svg { color: var(--ink-4); margin-block-start: 1px; }
.info-text { font-size: calc(8.5px * var(--t)); color: var(--ink-2); line-height: 1.5; min-width: 0; }
.info-text.muted { color: var(--ink-3); }
.info-spacer { display: none; }
.coords { font-family: var(--num); color: var(--ink-4); font-size: calc(8px * var(--t)); }
.pdf-no-coords .coords { display: none; }
.place-text { margin-block-start: 5px; font-size: calc(9px * var(--t)); color: var(--ink-2); line-height: 1.55; }
.place-text .info-row { margin: 0; }
.place-text .info-text { font-size: inherit; color: inherit; }
.place-note {
margin-block-start: 6px; padding: 6px 9px; border-radius: 9px; background: var(--wash);
font-size: calc(8.5px * var(--t)); color: var(--ink-2);
}
.place-note .info-row { margin: 0; }
.place-note .info-text { color: inherit; }
.details { display: flex; flex-wrap: wrap; gap: 3px 12px; margin-block-start: 6px; }
.detail { display: inline-flex; align-items: center; gap: 4px; font-size: calc(8px * var(--t)); color: var(--ink-3); }
.detail svg { color: var(--ink-4); }
.pdf-no-details .details { display: none; }
${PDF_MARKDOWN_CSS}
/* ── Bookings and notes ──────────────────────────────────── */
.note-card {
display: flex; gap: 10px; align-items: flex-start; padding: 9px 11px; border-radius: 14px;
break-inside: avoid; background: var(--wash);
}
.booking-card {
background: color-mix(in srgb, var(--kind) 6%, var(--paper));
border: 1px solid color-mix(in srgb, var(--kind) 20%, var(--paper));
}
.note-icon {
width: 26px; height: 26px; border-radius: 8px; flex-shrink: 0;
display: flex; align-items: center; justify-content: center; color: var(--ink-3); background: var(--paper);
}
.booking-card .note-icon { background: var(--kind); color: var(--paper); }
.note-tinted { border-inline-start: 3px solid var(--note); }
.note-tinted .note-icon { color: var(--note); }
.note-body { flex: 1; min-width: 0; }
.note-kicker { font-family: var(--num); font-size: calc(7.5px * var(--t)); font-weight: 600; letter-spacing: 0.12em; text-transform: uppercase; color: var(--kind, var(--ink-3)); }
.note-text { font-size: calc(9.5px * var(--t)); color: var(--ink); line-height: 1.5; }
.booking-card .note-text { font-size: calc(11px * var(--t)); font-weight: 600; line-height: 1.35; }
.note-time { font-size: calc(8.5px * var(--t)); color: var(--ink-3); margin-block-start: 2px; white-space: pre-line; }
.note-line { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; margin-block-start: 4px; }
.note-line .route { font-family: var(--num); font-size: calc(9px * var(--t)); font-weight: 600; color: var(--ink); margin-inline-end: 2px; }
.booking-card .chip { background: var(--paper); }
.note-extra { display: flex; flex-wrap: wrap; gap: 4px; margin-block-start: 5px; }
.transport-note { font-style: italic; white-space: pre-line; }
.pdf-no-transport-notes .transport-note { display: none; }
/* ── Plugin sections ─────────────────────────────────────── */
.plugin-sections { padding: 2mm var(--gutter) 4mm; }
.plugin-section { margin-block-end: 6mm; break-inside: avoid; }
.plugin-section-title { font-size: calc(13px * var(--t)); font-weight: 600; margin-block-end: 2mm; padding-block-end: 2mm; border-block-end: 1px solid var(--hair); }
.plugin-section-text { font-size: calc(9.5px * var(--t)); color: var(--ink-2); line-height: 1.55; margin-block-end: 5px; }
.plugin-section-table { width: 100%; border-collapse: collapse; margin-block-start: 6px; }
.plugin-section-table th { font-family: var(--num); font-size: calc(7.5px * var(--t)); font-weight: 600; color: var(--ink-4); text-transform: uppercase; letter-spacing: 0.1em; text-align: start; padding: 4px 8px; border-block-end: 1px solid var(--hair); }
.plugin-section-table td { font-size: calc(9px * var(--t)); color: var(--ink-2); padding: 4px 8px; border-block-end: 1px solid var(--wash-2); }
.doc-end { display: flex; align-items: center; justify-content: center; gap: 6px; padding: 8mm 0 4mm; color: var(--ink-4); font-size: 7.5px; letter-spacing: 0.06em; }
.doc-end img { height: 10px; opacity: 0.55; }
`;
}
@@ -33,6 +33,7 @@ import { useTripStore } from '../../store/tripStore'
import { useCanDo } from '../../store/permissionsStore'
import { useSettingsStore } from '../../store/settingsStore'
import { useAddonStore } from '../../store/addonStore'
import { useTripAddonEnabled } from '../../store/tripAddonsStore'
import { openSaveToCollection } from '../Collections/saveTarget'
import { computeMultiDayMove as computeMultiDayMoveIn, getDayOrder as getDayOrderIn, type SpanPhase } from './DayPlanSidebar.multiDayMove'
import { useTranslation } from '../../i18n'
@@ -41,7 +42,6 @@ import { Tooltip } from '../shared/Tooltip'
import { NEUTRAL_TINT, fs } from '../shared/DialogShell'
import { BarButton, MoreButton, SoftPill, TimePill, tintOf } from './planParts'
import './dayPlanRows.css'
import { TypeTile } from './bookings/bookingParts'
import { typeInfo } from './bookings/bookingsModel'
import { transportSubtitle } from './transportDetailModel'
@@ -218,7 +218,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
const toast = useToast()
const { t, locale } = useTranslation()
const mirrorServiceStops = useRoadtripSettings(s => s.roadtrip_service_stops_in_days !== false)
const toursEnabled = useAddonStore(s => s.isEnabled('tours'))
const toursEnabled = useTripAddonEnabled(tripId, 'tours')
const tripActions = useRef(useTripStore.getState()).current
const { noteUi, setNoteUi, noteInputRef, dayNotes, openAddNote: _openAddNote, openEditNote: _openEditNote, cancelNote, saveNote, deleteNote: _deleteNote, moveNote: _moveNote } = useDayNotes(tripId)
@@ -1098,7 +1098,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
// Total Cost reads the expenses in Costs when it is on (#2551).
const budgetItems = useTripStore(s => s.budgetItems)
const costsEnabled = useAddonStore(s => s.isEnabled('budget'))
const costsEnabled = useTripAddonEnabled(tripId, 'budget')
const totalCostLabel = useMemo(() => {
return formatMoneySum(planCosts({ days, assignments, reservations, budgetItems, costsEnabled, tripCurrency: currency, displayCurrency: costBase }).total, costBase, locale, fxRates)
}, [days, assignments, reservations, budgetItems, costsEnabled, currency, costBase, locale, fxRates])
@@ -1276,7 +1276,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
const optimizeFromAccommodation = useSettingsStore(s => s.settings.optimize_from_accommodation)
const dateFirst = useSettingsStore(s => s.settings.day_date_first === true)
const collectionsEnabled = useAddonStore(s => s.isEnabled('collections'))
const toursEnabled = useAddonStore(s => s.isEnabled('tours'))
const toursEnabled = useTripAddonEnabled(tripId, 'tours')
// Plugin time contributions in the day plan (dayScheduleProvider hook).
const daySchedule = usePluginDaySchedule(tripId)
// Per-day colours from the dayTintProvider hook — e.g. which leg of the trip a
@@ -8,7 +8,7 @@ import { BlurredCode } from '../shared/BookingCode'
import { DialogButton, DialogFooter, DialogSection, DialogShell, FooterSpacer, PILL } from '../shared/DialogShell'
import { useTripStore } from '../../store/tripStore'
import { formatTime, splitReservationDateTime } from '../../utils/formatters'
import { parseReservationMetadata } from '../../utils/flightLegs'
import { parseReservationMetadata, seatCells } from '../../utils/flightLegs'
import { BookingDialogHeader } from './bookings/BookingDialogShell'
import { BOX, Eyebrow, Field, fs, toneColor, toneOf } from './bookings/bookingParts'
import { filesFor } from '../../utils/reservationFiles'
@@ -175,11 +175,13 @@ function detailCells(res: Reservation, meta: Record<string, unknown>, t: Transla
add(t('reservations.meta.flightNumber'), meta.flight_number)
add(t('reservations.meta.from'), meta.departure_airport)
add(t('reservations.meta.to'), meta.arrival_airport)
add(t('reservations.meta.seat'), meta.seat)
} else if (res.type === 'train') {
add(t('reservations.meta.trainNumber'), meta.train_number)
add(t('reservations.meta.platform'), meta.platform)
add(t('reservations.meta.seat'), meta.seat)
}
// Each leg's seat under its route on a booking with a stop, not just the first leg's.
if (res.type === 'flight' || res.type === 'train') {
for (const c of seatCells(res, t('reservations.meta.seat'))) add(c.label, c.value)
}
add(t('reservations.confirmationCode'), res.confirmation_number, true)
// A stopover booking can carry its own reference per segment (#1943); the
@@ -2,6 +2,7 @@ import { useState, useEffect, useRef, useMemo, useCallback, useId, type ReactNod
import type { PlaceClientOrigin, RoadtripStopType, TourListItem } from '@trek/shared'
import { useAuthStore } from '../../store/authStore'
import { useAddonStore } from '../../store/addonStore'
import { useTripAddonEnabled } from '../../store/tripAddonsStore'
import { useCanDo } from '../../store/permissionsStore'
import { useTripStore } from '../../store/tripStore'
import { useSettingsStore } from '../../store/settingsStore'
@@ -120,7 +121,7 @@ function usePlaceFormModal(props: PlaceFormModalProps) {
const tripObj = useTripStore((s) => s.trip)
const canUploadFiles = can('file_upload', tripObj)
const collectionsEnabled = useAddonStore((s) => s.isEnabled('collections'))
const isBudgetEnabled = useAddonStore((s) => s.isEnabled('budget'))
const isBudgetEnabled = useTripAddonEnabled(tripId, 'budget')
const deleteBudgetItem = useTripStore((s) => s.deleteBudgetItem)
const {
form, setForm, autoFilledRef, pendingFiles, addFilesFromInput, removeFile, handlePaste, isSaving, setIsSaving,
@@ -1,7 +1,7 @@
import { useEffect, useRef, useMemo, useId } from 'react'
import { useParams } from 'react-router'
import { useTripStore } from '../../store/tripStore'
import { useAddonStore } from '../../store/addonStore'
import { useTripAddonEnabled } from '../../store/tripAddonsStore'
import CustomSelect from '../shared/CustomSelect'
import { BookingCodeInput } from '../shared/BookingCode'
import { buildAssignmentOptions } from './assignmentOptions'
@@ -71,7 +71,7 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
const fileInputRef = useRef(null)
const titleId = useId()
const isBudgetEnabled = useAddonStore(s => s.isEnabled('budget'))
const isBudgetEnabled = useTripAddonEnabled(Number(tripId), 'budget')
const deleteBudgetItem = useTripStore(s => s.deleteBudgetItem)
// Set right before submit when the user clicked create/edit expense.
const expense = useBookingExpenseIntent(() => handleSubmit(), {
@@ -12,7 +12,7 @@ import { toLocationPicks } from './locationPicks'
import { useTranslation } from '../../i18n'
import { useToast } from '../shared/Toast'
import { useTripStore } from '../../store/tripStore'
import { useAddonStore } from '../../store/addonStore'
import { useTripAddonEnabled } from '../../store/tripAddonsStore'
import type { Day, Place, Accommodation, Reservation, TripFile, AssignmentsMap } from '../../types'
import { BookingNotesFilesCosts } from './BookingNotesFilesCosts'
import { TravelerPicker } from './TravelerPicker'
@@ -83,10 +83,10 @@ export function TransportModal({ isOpen, onClose, onSave, reservation, days, sel
const toast = useToast()
// The trip's places, offered by every location field of the manual tab (#2468).
const locationPicks = useMemo(() => toLocationPicks(places), [places])
const isBudgetEnabled = useAddonStore(s => s.isEnabled('budget'))
const budgetItems = useTripStore(s => s.budgetItems)
const deleteBudgetItem = useTripStore(s => s.deleteBudgetItem)
const { id: tripId } = useParams<{ id: string }>()
const isBudgetEnabled = useTripAddonEnabled(Number(tripId), 'budget')
// Set right before submitting when the user clicked "create/edit expense", so
// the post-save handler knows to open the Costs editor for the saved booking.
const expense = useBookingExpenseIntent(() => handleSubmit(), {
@@ -118,6 +118,19 @@ describe('BookingDetailDialog', () => {
expect(screen.getByText('#SEG2')).toBeInTheDocument();
});
it('FE-PLANNER-BKDETAIL-015: a flight with a stop shows the seat booked on its second leg, once, under that leg', () => {
const r = buildReservation({
title: 'MXP to JFK', type: 'flight',
metadata: JSON.stringify({ class: 'Economy', legs: [{ from: 'MXP', to: 'IST' }, { from: 'IST', to: 'JFK', seat: '14C' }] }),
});
renderDetail(r);
const dialog = screen.getByRole('dialog', { name: 'MXP to JFK' });
expect(within(dialog).getByText('14C')).toBeInTheDocument();
expect(within(dialog).getByText('Seat IST → JFK')).toBeInTheDocument();
// The tile stands for it; the field grid does not repeat it.
expect(within(dialog).queryByText('14C, Economy')).toBeNull();
});
it('FE-PLANNER-BKDETAIL-006: place, accommodation, linked stop, link, travelers and notes', () => {
const place = buildPlace({ name: 'Kinkaku-ji', place_time: '10:00' });
const a = buildAssignment({ id: 4401, day_id: 1302, place });
@@ -27,7 +27,7 @@ import { BookingDialogHeader, StatusPill, TypePill } from './BookingDialogShell'
import { DeleteButton, DialogButton, DialogFooter, DialogSection as Section, DialogShell, FooterSpacer, PILL } from '../../shared/DialogShell'
import FlightLiveCard from '../flightLive/FlightLiveCard'
import { useFlightLiveCardLegs } from '../flightLive/useFlightLiveCard'
import { getFlightLegs } from '../../../utils/flightLegs'
import { bookingSeats, getFlightLegs, seatLabel } from '../../../utils/flightLegs'
export interface BookingDetailDialogProps {
r: Reservation
@@ -84,6 +84,7 @@ export default function BookingDetailDialog(p: BookingDetailDialogProps) {
const subParts = [meta.airline, meta.flight_number, meta.train_number, facts.endpoints.length >= 2 ? facts.endpoints.map(e => e.code || e.name).join(' → ') : null].filter(Boolean)
const sub = subParts.length ? subParts.join(' ') : null
const seats = bookingSeats(r)
const stats: { value: string; label: string }[] = []
if (facts.isHotel) {
stats.push(...stayStats(facts, meta, t, locale))
@@ -100,7 +101,8 @@ export default function BookingDetailDialog(p: BookingDetailDialogProps) {
// Under a minute of walking is not worth a tile.
if (transit && transit.walk > 59) stats.push({ value: t('transit.min', { count: Math.round(transit.walk / 60) }), label: t('transit.walkLabel') })
if (meta.platform) stats.push({ value: meta.platform, label: t('reservations.meta.platform') })
if (meta.seat) stats.push({ value: meta.seat, label: t('reservations.meta.seat') })
// Each leg's seat under its route on a booking with a stop, not just the first leg's.
for (const s of seats) stats.push({ value: s.seat, label: seatLabel(t('reservations.meta.seat'), s.route) })
}
// Cells already shown as a stat stay out of the field grid below.
const shownAsStat = new Set([t('reservations.meta.platform'), t('reservations.meta.seat'), t('reservations.meta.checkIn'), t('reservations.meta.checkOut')])
@@ -4,6 +4,7 @@ import type { Reservation } from '../../../types'
import { useTranslation } from '../../../i18n'
import { BlurredCode } from '../../shared/BookingCode'
import { formatMoney } from '../../../utils/formatters'
import { bookingSeats } from '../../../utils/flightLegs'
import { TransitLegChips } from '../transitDisplay'
import { displayTitle, parseMeta, type BookingGroup, type CostTotal } from './bookingsModel'
import type { BookingFacts } from './bookingFacts'
@@ -82,7 +83,7 @@ function Row({ r, p, facts, files, costs, t, locale }: {
const sub = facts.endpoints.length >= 2
? facts.endpoints.map(e => e.code || e.name).join(' → ')
: facts.accommodation || facts.place || ''
const extras: string[] = [meta.airline && meta.flight_number ? `${meta.airline} ${meta.flight_number}` : meta.flight_number || meta.airline, meta.train_number, meta.seat, meta.platform].filter(Boolean)
const extras: string[] = [meta.airline && meta.flight_number ? `${meta.airline} ${meta.flight_number}` : meta.flight_number || meta.airline, meta.train_number, ...bookingSeats(r).map(s => s.seat), meta.platform].filter(Boolean)
return (
<div
@@ -231,3 +231,14 @@ describe('bookingFacts: codes, links and places', () => {
expect(bookingFacts(buildReservation({ url: 'javascript:alert(1)' }), ctx()).url?.href).toBeNull();
});
});
describe('bookingFacts: seats of a flight with a stop', () => {
it('FE-PLANNER-BKFACTS-025: the Seat cell holds the seat booked only on the second leg', () => {
const r = buildReservation({
type: 'flight',
metadata: JSON.stringify({ class: 'Economy', legs: [{ from: 'MXP', to: 'IST' }, { from: 'IST', to: 'JFK', seat: '14C' }] }),
});
const facts = bookingFacts(r, ctx());
expect(cell(facts, 'reservations.meta.seat')).toBe('14C, Economy');
});
});
@@ -1,6 +1,6 @@
import type { Day, Reservation, ReservationEndpoint } from '../../../types'
import { formatPriceText, formatTime, splitReservationDateTime } from '../../../utils/formatters'
import { getFlightLegs, getTrainLegs, usesStationRoute } from '../../../utils/flightLegs'
import { getFlightLegs, getTrainLegs, seatCells, usesStationRoute } from '../../../utils/flightLegs'
import { safeExternalHref } from '../../../utils/safeUrl'
import { bookingDates, daySpan, hotelStayTimes, parseMeta, type AssignmentLookupEntry } from './bookingsModel'
@@ -102,7 +102,8 @@ export function bookingFacts(r: Reservation, c: FactsContext): BookingFacts {
if (!hasEndpoints && meta.arrival_airport) cells.push({ label: t('reservations.meta.to'), value: meta.arrival_airport })
if (meta.train_number) cells.push({ label: t('reservations.meta.trainNumber'), value: meta.train_number })
if (meta.platform) cells.push({ label: t('reservations.meta.platform'), value: meta.platform })
if (meta.seat) cells.push({ label: t('reservations.meta.seat'), value: meta.class ? `${meta.seat}, ${meta.class}` : meta.seat })
// One seat per leg on a booking with a stop, each under its route; otherwise the booking's own.
cells.push(...seatCells(r, t('reservations.meta.seat'), meta.class ? `, ${meta.class}` : ''))
if (!c.hasLinkedCost && meta.price != null && meta.price !== '') {
cells.push({ label: t('reservations.price'), value: formatPriceText(meta.price, meta.priceCurrency, c.tripCurrency, locale) })
}
@@ -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={[
@@ -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 }}>
{[
@@ -1,11 +1,12 @@
// FE-PLANNER-TRIPEXPORT-001 to -014: the trip exports behind the desktop export
// FE-PLANNER-TRIPEXPORT-001 to -015: the trip exports behind the desktop export
// dialog and the phone's export sheet.
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest';
import { buildAssignment, buildReservation, buildTrip, buildUser } from '../../../tests/helpers/factories';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { resetAllStores, seedInstanceAddons, seedStore } from '../../../tests/helpers/store';
import { useAuthStore } from '../../store/authStore';
import { useTripAddonsStore } from '../../store/tripAddonsStore';
import type { DayNote } from '../../types';
import { downloadTripPDF } from '../PDF/TripPDF';
import { flatDayNotes, saveBlob, useTripExport, type TripExportOptions } from './useTripExport';
@@ -133,6 +134,17 @@ describe('useTripExport', () => {
expect(vi.mocked(downloadTripPDF).mock.calls[1][0]).toMatchObject({ onlyUserId: 9 });
});
it('FE-PLANNER-TRIPEXPORT-015: the PDF prints costs and tours as the trip has them, not the instance', async () => {
seedInstanceAddons(['budget']);
useTripAddonsStore.getState().publish(3, [
{ id: 'budget', name: 'Costs', icon: null, enabled: false, instanceEnabled: true, overridden: true },
{ id: 'tours', name: 'Tours', icon: null, enabled: true, instanceEnabled: false, overridden: true },
]);
const { result } = renderHook(() => useTripExport(options()));
await act(() => result.current.exportPdf());
expect(vi.mocked(downloadTripPDF).mock.calls[0][0]).toMatchObject({ costsEnabled: false, toursEnabled: true });
});
it('FE-PLANNER-TRIPEXPORT-005: the phone stays open after the PDF and prints nothing without a trip', async () => {
const opts = options(PHONE);
const { result } = renderHook(() => useTripExport(opts));
@@ -3,6 +3,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import { useRoadtripSettings } from '../../hooks/useRoadtripSettings';
import { useAuthStore } from '../../store/authStore';
import { useSettingsStore } from '../../store/settingsStore';
import { useTripAddonEnabled } from '../../store/tripAddonsStore';
import type { AssignmentsMap, Category, Day, DayNote, Place, Reservation, Trip } from '../../types';
import { importChunk } from '../../utils/chunkReload';
import type { ViasByDay } from '../../utils/dayRouteVias';
@@ -144,6 +145,9 @@ export function useTripExport({
// them, so it needs the same switch the plan reads.
const showServiceStops = useRoadtripSettings((s) => s.roadtrip_service_stops_in_days !== false, tripId);
const myId = useAuthStore((s) => s.user?.id);
// The sections the trip has on, as the plan shows them: costs in the figures, tours on the route.
const costsEnabled = useTripAddonEnabled(tripId, 'budget');
const toursEnabled = useTripAddonEnabled(tripId, 'tours');
const offerMine = myId != null && hasPersonalPlan(data.assignments, data.reservations);
const fileBase = data.trip?.title || 'trip';
@@ -185,6 +189,8 @@ export function useTripExport({
timeFormat,
distanceUnit,
showServiceStops,
costsEnabled,
toursEnabled,
onlyUserId: mine ? myId : undefined,
route: { viasByDay: data.viasByDay, tourStageStops: data.tourStageStops, ...routing },
signal: givenUp,
@@ -1,9 +1,9 @@
import { describe, expect, it } from 'vitest'
import { dayColor } from './dayColors'
import { stageMapData, stagePlaceIds, stagePoints } from './stageMap'
import { stageConnectionIds, stageMapData, stagePlaceIds, stagePoints } from './stageMap'
import type { AccessSpur, RoadtripDay, RoadtripRoutes, RoadtripStop } from '@trek/shared/roadtrip'
// FE-RTSTAGE-001 to FE-RTSTAGE-021
// FE-RTSTAGE-001 to FE-RTSTAGE-023
function stop(name: string, over: Partial<RoadtripStop> = {}): RoadtripStop {
return {
@@ -268,3 +268,23 @@ describe('a stage that starts or ends at a booked night', () => {
expect(data.accessLines).toEqual([walk])
})
})
describe('stageConnectionIds', () => {
const flight = (reservationId: number, role: 'arrival' | 'departure') =>
stop('Airport', { carrier: { reservationId, type: 'flight', role, title: 'Flight', code: null, at: null } })
it("FE-RTSTAGE-022: a stage draws its own rides, not the drive's ride home from a later day", () => {
// The flight in (31) seams this stage; the flight home (32) belongs to a stage days later
// and is not on this one at all.
const stage = day([flight(31, 'arrival'), stop('Ubud')])
expect(stageConnectionIds(stage, [], () => true)).toEqual([31])
})
it('FE-RTSTAGE-023: of the bookings switched on by hand only those running on the stage day stay', () => {
const stage = day([stop('Ubud')])
const onThisDay = new Set([40])
expect(stageConnectionIds(stage, [40, 41], id => onThisDay.has(id))).toEqual([40])
// A ride that seams the stage stays even when it was booked on another day.
expect(stageConnectionIds(day([flight(31, 'arrival')]), [31], () => false)).toEqual([31])
})
})
@@ -1,4 +1,5 @@
import { dayColor } from './dayColors'
import { carrierReservationIds } from '@trek/shared/roadtrip'
import type { AccessSpur, RoadtripDay, RoadtripRoutes } from '@trek/shared/roadtrip'
/**
@@ -88,6 +89,20 @@ export function stagePlaceIds(stage: RoadtripDay): Set<number> {
return new Set(stage.stops.filter(s => !s.automaticNight).map(s => s.placeId))
}
/**
* The bookings the map draws as arcs on ONE stage: the rides that seam this stage's
* drive, whatever day they were booked on, and of the ones switched on by hand only
* those that run on the stage's day. Taking the rides of the whole drive put a flight
* home across every stage before it, as if it were part of that day.
*/
export function stageConnectionIds(
stage: RoadtripDay,
switchedOn: readonly number[],
runsOnStageDay: (reservationId: number) => boolean,
): number[] {
return [...new Set([...switchedOn.filter(runsOnStageDay), ...carrierReservationIds([stage])])]
}
/** The stage's stops as coordinates, for the fit. */
export function stagePoints(stage: RoadtripDay): [number, number][] {
return stage.stops
@@ -447,7 +447,28 @@ describe('CollectionToursSection', () => {
expect(await screen.findByTestId('kept-tour-preview')).toBeInTheDocument();
unmount();
useAddonStore.setState({ addons: [{ id: 'collections', enabled: true }] as never });
const off = { response: { status: 404, data: { error: 'Tours addon is not enabled' } } };
list.mockRejectedValue(off);
render(<CollectionToursSection collectionId={3} canRemove />);
await waitFor(() => expect(list).toHaveBeenLastCalledWith(3));
expect(screen.queryByTestId('collection-tours')).toBeNull();
expect(screen.queryByText('The tours of this list could not be loaded.')).toBeNull();
});
it('FE-COLLECTION-TOURS-021: with Tours off for the instance, the tours show once the server hands them over', async () => {
useAddonStore.setState({ addons: [{ id: 'collections', enabled: true }] as never });
// A trip of the user switched Tours on for itself, so the server answers.
vi.spyOn(collectionToursRepo, 'list').mockResolvedValue({ tours: [kept()] });
render(<CollectionToursSection collectionId={3} canRemove />);
expect(await screen.findByTestId('kept-tour-4')).toHaveTextContent('Ridge');
});
it('FE-COLLECTION-TOURS-022: with Tours off for the instance, a failed read shows nothing, as it always did', async () => {
useAddonStore.setState({ addons: [{ id: 'collections', enabled: true }] as never });
const list = vi.spyOn(collectionToursRepo, 'list').mockRejectedValue(new Error('500'));
render(<CollectionToursSection collectionId={3} canRemove />);
await waitFor(() => expect(list).toHaveBeenCalled());
expect(screen.queryByText('The tours of this list could not be loaded.')).toBeNull();
expect(screen.queryByTestId('collection-tours')).toBeNull();
});
@@ -13,23 +13,26 @@ import { useToast } from '../../shared/Toast';
/**
* LIB-03: the tours a collection keeps, for the collection's page. Read when
* the collection opens and kept current while its members keep or remove one;
* nothing at all while the Tours addon is off. Removing asks first and says
* nothing at all while the Tours addon is off. Tours counts as on while the
* instance has it on or any of the user's trips switched it on for itself;
* only the server knows the second, so with the instance off the tours are
* read all the same and its refusal hides them. Removing asks first and says
* how it went.
*/
export function useCollectionTours(collectionId: number) {
const { t } = useTranslation();
const toast = useToast();
const enabled = useAddonStore((state) => state.isEnabled('tours'));
const instanceOn = useAddonStore((state) => state.isEnabled('tours'));
const { tours, status, shownFor } = useCollectionTourStore(
useShallow((state) => ({ tours: state.tours, status: state.status, shownFor: state.collectionId }))
);
const [removing, setRemoving] = useState<CollectionTourItem | null>(null);
// Read again when the instance switch flips, since the answer may change with it.
useEffect(() => {
if (!enabled) return undefined;
void useCollectionTourStore.getState().load(collectionId);
return watchCollectionTours();
}, [collectionId, enabled]);
}, [collectionId, instanceOn]);
const confirmRemove = async () => {
const tour = removing;
@@ -44,6 +47,9 @@ export function useCollectionTours(collectionId: number) {
};
const current = shownFor === collectionId;
// With the instance on nothing changes; with it off only tours the server handed over show,
// so an install without a trip of its own choice shows nothing, as it always did.
const enabled = instanceOn ? !(current && status === 'off') : current && status === 'ready';
return {
enabled,
tours: enabled && current ? tours : [],
@@ -9,7 +9,7 @@ import {
import { useCallback, useEffect, useMemo, useState } from 'react';
import { translateApiError, useTranslation } from '../../../i18n';
import { tourPackingLinkRepo } from '../../../repo/tourPackingLinkRepo';
import { useAddonStore } from '../../../store/addonStore';
import { useTripAddonEnabled } from '../../../store/tripAddonsStore';
import { useTripStore } from '../../../store/tripStore';
import type { PackingItem } from '../../../types';
import { packingCategoryOrder, packingViewItems } from '../../Packing/packingListModel';
@@ -42,7 +42,7 @@ interface TourPackingCategory extends PackingCategoryChoice {
export function useTourPackingLink({ tripId, tour }: { tripId: number; tour: TourListItem }) {
const { t } = useTranslation();
const toast = useToast();
const packingEnabled = useAddonStore((state) => state.isEnabled('packing'));
const packingEnabled = useTripAddonEnabled(tripId, 'packing');
const items = useTripStore((state) => state.packingItems);
const placeId = tour.place_id;
const key = `${tripId}:${placeId}`;
@@ -23,7 +23,7 @@ const state = vi.hoisted(() => ({
}))
vi.mock('../../store/tripStore', () => ({ useTripStore: (selector: (store: unknown) => unknown) => selector({ trip: state.trip, loadTrip: state.loadTrip, refreshPlaces: state.refreshPlaces, places: [], packingItems: state.packingItems }) }))
vi.mock('../../store/authStore', () => ({ useAuthStore: (selector: (store: unknown) => unknown) => selector({ user: state.user }) }))
vi.mock('../../store/authStore', () => ({ useAuthStore: Object.assign((selector: (store: unknown) => unknown) => selector({ user: state.user }), { getState: () => ({ user: state.user }) }) }))
vi.mock('../../store/settingsStore', () => ({ useSettingsStore: (selector: (store: unknown) => unknown) => selector({ settings: { distance_unit: 'metric' } }) }))
vi.mock('../Map/MapViewAuto', () => ({ MapViewAuto: () => null }))
vi.mock('../../repo/tourRepo', () => ({ tourRepo: { importGpx: state.importGpx, previewGpx: state.previewGpx, create: state.create, update: state.update, detail: state.detail } }))
@@ -7,7 +7,7 @@ import { server } from '../../../tests/helpers/msw/server';
import { useAuthStore } from '../../store/authStore';
import { useTripStore } from '../../store/tripStore';
import { usePermissionsStore } from '../../store/permissionsStore';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { resetAllStores, seedInstanceAddons, seedStore } from '../../../tests/helpers/store';
import { buildUser, buildTrip } from '../../../tests/helpers/factories';
import TripMembersModal from './TripMembersModal';
@@ -101,6 +101,8 @@ beforeEach(() => {
);
seedStore(useAuthStore, { user: ownerUser, isAuthenticated: true });
seedStore(useTripStore, { trip: buildTrip({ id: 1, title: 'Test Trip' }) });
// The instance has the three addons a link section belongs to; the trip names none of its own.
seedInstanceAddons(['packing', 'budget', 'collab']);
addToast = vi.fn<AddToast>(() => 0);
window.__addToast = addToast;
});
@@ -1131,4 +1133,34 @@ describe('TripMembersModal', () => {
expect(await screen.findByText('owner')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Edit Trip' })).toBeNull();
});
it('FE-COMP-MEMBERS-064: the owner switches the trip addons in an area of their own', async () => {
const user = userEvent.setup();
const bodies: unknown[] = [];
const list = [
{ id: 'budget', name: 'Budget', icon: 'Wallet', enabled: false, instanceEnabled: true, overridden: true },
];
server.use(
http.get('/api/trips/1/addons', () => HttpResponse.json({ tripId: 1, addons: list })),
http.put('/api/trips/1/addons/:addonId', async ({ request }) => {
bodies.push(await request.json());
return HttpResponse.json({ tripId: 1, addons: list });
}),
);
render(<TripMembersModal {...defaultProps} />);
const nav = await screen.findByRole('navigation', { name: 'Trip settings' });
await user.click(await within(nav).findByRole('button', { name: 'Addons' }));
expect(await screen.findByText('This trip only')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Costs' }));
await waitFor(() => expect(bodies).toEqual([{ enabled: null }]));
});
it('FE-COMP-MEMBERS-065: a member who is not the owner gets no Addons area', async () => {
seedStore(useAuthStore, { user: memberUser, isAuthenticated: true });
render(<TripMembersModal {...defaultProps} />);
expect(await screen.findByText('owner')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Addons' })).toBeNull();
});
});
@@ -1,8 +1,9 @@
import { useId, useState, type ComponentProps, type ReactNode } from 'react'
import { Check, Copy, Crown, Link2, LogOut, Pencil, Plus, Settings, Trash2, UserMinus, UserPlus, UserRound, Users } from 'lucide-react'
import { Check, Copy, Crown, Link2, LogOut, Pencil, Plus, Puzzle, Settings, Trash2, UserMinus, UserPlus, UserRound, Users } from 'lucide-react'
import { useTranslation } from '../../i18n'
import CustomSelect from '../shared/CustomSelect'
import ConfirmDialog from '../shared/ConfirmDialog'
import ToggleSwitch from '../Settings/ToggleSwitch'
import { Tooltip } from '../shared/Tooltip'
import { DialogButton, DialogHeader, DialogSection, DialogShell, DialogTile, NEUTRAL_TINT, PILL, fs } from '../shared/DialogShell'
import { AddRowButton, CardHead, INPUT, LABEL, PANEL } from '../shared/dialogParts'
@@ -12,7 +13,8 @@ import TripFormModal from './TripFormModal'
import { TripJournalLinkSection } from './TripJournalLinkSection'
import { TripMemberAvatar } from './TripMemberAvatar'
import { useTripJournalSectionVisible } from './useTripJournalLink'
import { SHARE_OPTIONS, SHARE_SECTIONS, useShareLink, useTripInviteLink, useTripMembers, type TripMembersState } from './useTripShare'
import { useTripAddonRows } from './useTripAddonRows'
import { SHARE_OPTIONS, useShareLink, useTripInviteLink, useTripMembers, type TripMembersState } from './useTripShare'
interface TripShareDialogProps {
isOpen: boolean
@@ -57,19 +59,21 @@ const NAV_ENTRY_OFF = 'text-content-muted hover:bg-surface-hover hover:text-cont
/**
* The trip's Settings on the desktop: who is on the trip, its guests, the two
* links that let others in, and the journal the trip shows.
* links that let others in, the journal the trip shows, and for the owner
* which addons the trip uses.
*/
export default function TripShareDialog(props: TripShareDialogProps) {
return props.isOpen ? <OpenDialog {...props} /> : null
}
type Area = 'people' | 'sharing' | 'journal' | 'trip'
type Area = 'people' | 'sharing' | 'journal' | 'addons' | 'trip'
/** The areas of the dialog, each with its icon, its name and the line under the name. */
const AREAS: { id: Area; icon: (on: boolean) => ReactNode; labelKey: string; hintKey: string }[] = [
{ id: 'people', icon: () => <Users size={16} strokeWidth={2} />, labelKey: 'trip.settings.people', hintKey: 'trip.settings.peopleHint' },
{ id: 'sharing', icon: () => <Link2 size={16} strokeWidth={2} />, labelKey: 'trip.settings.sharing', hintKey: 'trip.settings.sharingHint' },
{ id: 'journal', icon: () => <LinkedJournalIcon size={16} />, labelKey: 'trip.journal.title', hintKey: 'trip.journal.hint' },
{ id: 'addons', icon: () => <Puzzle size={16} strokeWidth={2} />, labelKey: 'trip.settings.addons', hintKey: 'trip.settings.addonsHint' },
{ id: 'trip', icon: () => <Pencil size={16} strokeWidth={2} />, labelKey: 'dashboard.editTrip', hintKey: 'trip.settings.editTripHint' },
]
@@ -81,7 +85,7 @@ function OpenDialog({ onClose, tripId, tripTitle, onMembersChanged, editTrip }:
const [area, setArea] = useState<Area>('people')
const [tripReviewing, setTripReviewing] = useState(false)
const journalSection = useTripJournalSectionVisible(tripId)
const shows: Record<Area, boolean> = { people: true, sharing: m.canManageShare, journal: journalSection, trip: !!editTrip }
const shows: Record<Area, boolean> = { people: true, sharing: m.canManageShare, journal: journalSection, addons: m.isCurrentOwner, trip: !!editTrip }
const areas = AREAS.filter(a => shows[a.id])
const current = areas.find(a => a.id === area) ?? areas[0]
const panelOf = (id: Area) => areas.find(a => a.id === id)
@@ -132,6 +136,11 @@ function OpenDialog({ onClose, tripId, tripTitle, onMembersChanged, editTrip }:
<TripJournalLinkSection tripId={tripId} framed={false} />
</AreaPanel>
)}
{m.isCurrentOwner && (
<AreaPanel area={panelOf('addons')} shown={current.id === 'addons'} titled>
<TripAddonsList tripId={tripId} />
</AreaPanel>
)}
{editTrip && (
<AreaPanel area={panelOf('trip')} shown={current.id === 'trip'} titled>
<TripFormModal embedded isOpen onClose={onClose} onReviewChange={setTripReviewing} {...editTrip} />
@@ -418,6 +427,32 @@ function PermChip({ on, disabled, label, hint, onToggle }: { on: boolean; disabl
return hint ? <Tooltip label={hint}>{chip}</Tooltip> : chip
}
/** The trip addons, each with its switch; a badge marks the ones the owner set apart from the instance. */
function TripAddonsList({ tripId }: { tripId: number }) {
const { t } = useTranslation()
const { rows, loading } = useTripAddonRows(tripId)
if (loading) return <div className="h-[120px] animate-pulse rounded-[14px] bg-surface-secondary" />
return (
<div className={ROWS}>
{rows.map(row => (
<div key={row.id} className={ROW}>
<span className={`flex h-8 w-8 flex-none items-center justify-center rounded-[10px] bg-surface-tertiary ${row.enabled ? 'text-content' : 'text-content-faint'}`}>
<row.Icon size={16} strokeWidth={2} />
</span>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<span className="truncate font-semibold text-content" style={fs(13.5, 'body')}>{row.name}</span>
{row.ownChoice && <span className={`${BADGE} bg-surface-tertiary text-content-muted`} style={fs(10.5, 'caption')}>{t('trip.addons.thisTripOnly')}</span>}
</div>
{row.description && <p className="m-0 truncate text-content-muted" style={fs(12, 'caption')}>{row.description}</p>}
</div>
<ToggleSwitch on={row.enabled} onToggle={row.toggle} label={row.name} disabled={row.busy} />
</div>
))}
</div>
)
}
/** The read-only public link, and which parts of the trip it shows. */
function PublicLink({ tripId }: { tripId: number }) {
const { t } = useTranslation()
@@ -429,7 +464,7 @@ function PublicLink({ tripId }: { tripId: number }) {
<div>
<span className={LABEL}>{t('share.options')}</span>
<div className="flex flex-wrap gap-1.5">
{SHARE_SECTIONS.map(opt => (
{link.sections.map(opt => (
<PermChip key={opt.key} on={link.perms[opt.key]} disabled={opt.always} label={t(opt.label)}
onToggle={() => void link.setPerm(opt.key, !link.perms[opt.key])} />
))}
@@ -0,0 +1,84 @@
// FE-TRIPADDONROWS-001 to FE-TRIPADDONROWS-003: the rows of the trip settings' Addons area,
// shared by the desktop dialog and the phone sheet.
import { act, renderHook, waitFor } from '@testing-library/react';
import type { TripAddon } from '@trek/shared';
import 'fake-indexeddb/auto';
import { CarFront, ListChecks, Puzzle } from 'lucide-react';
import { http, HttpResponse } from 'msw';
import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { buildUser } from '../../../tests/helpers/factories';
import { server } from '../../../tests/helpers/msw/server';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { clearAll } from '../../db/offlineDb';
import { TranslationProvider } from '../../i18n/TranslationContext';
import { useAuthStore } from '../../store/authStore';
import { useTripAddonRows } from './useTripAddonRows';
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }));
vi.mock('../shared/Toast', () => ({ useToast: () => toast }));
const LIST: TripAddon[] = [
{ id: 'packing', name: 'Packing', icon: 'ListChecks', enabled: true, instanceEnabled: true, overridden: false },
{ id: 'roadtrip', name: 'Road trip', icon: 'Route', enabled: false, instanceEnabled: true, overridden: true },
{ id: 'someplugin', name: 'Some plugin', icon: 'Unknown', enabled: true, instanceEnabled: false, overridden: true },
];
function wrapper({ children }: { children: ReactNode }) {
return <TranslationProvider>{children}</TranslationProvider>;
}
let bodies: unknown[] = [];
beforeEach(async () => {
await clearAll();
resetAllStores();
bodies = [];
seedStore(useAuthStore, { user: buildUser({ id: 1 }), isAuthenticated: true });
server.use(
http.get('/api/trips/4/addons', () => HttpResponse.json({ tripId: 4, addons: LIST })),
http.put('/api/trips/4/addons/:addonId', async ({ request }) => {
bodies.push(await request.json());
return HttpResponse.json({ tripId: 4, addons: LIST });
})
);
});
describe('useTripAddonRows', () => {
it('FE-TRIPADDONROWS-001: names each addon from the catalog, with its icon and whether the trip chose it', async () => {
const { result } = renderHook(() => useTripAddonRows(4), { wrapper });
expect(result.current.loading).toBe(true);
await waitFor(() => expect(result.current.rows).toHaveLength(3));
const [packing, roadtrip, plugin] = result.current.rows;
expect(packing).toMatchObject({ name: 'Lists', Icon: ListChecks, enabled: true, ownChoice: false });
expect(packing.description).not.toBe('');
expect(roadtrip).toMatchObject({ Icon: CarFront, enabled: false, ownChoice: true });
// An addon the catalog does not know keeps the server's name, no description and the fallback icon.
expect(plugin).toMatchObject({ name: 'Some plugin', description: '', Icon: Puzzle });
expect(result.current.loading).toBe(false);
});
it('FE-TRIPADDONROWS-002: a switch away from the instance stores the choice, back to it drops the choice', async () => {
const { result } = renderHook(() => useTripAddonRows(4), { wrapper });
await waitFor(() => expect(result.current.rows).toHaveLength(3));
act(() => result.current.rows[0].toggle());
await waitFor(() => expect(bodies).toEqual([{ enabled: false }]));
await waitFor(() => expect(result.current.rows[0].busy).toBe(false));
act(() => result.current.rows[1].toggle());
await waitFor(() => expect(bodies).toEqual([{ enabled: false }, { enabled: null }]));
});
it('FE-TRIPADDONROWS-003: a second switch while one is saving is ignored', async () => {
const { result } = renderHook(() => useTripAddonRows(4), { wrapper });
await waitFor(() => expect(result.current.rows).toHaveLength(3));
act(() => result.current.rows[0].toggle());
expect(result.current.rows[0].busy).toBe(true);
act(() => result.current.rows[2].toggle());
await waitFor(() => expect(result.current.rows[0].busy).toBe(false));
expect(bodies).toEqual([{ enabled: false }]);
});
});
@@ -0,0 +1,74 @@
import {
CarFront,
Compass,
FileText,
ListChecks,
Mountain,
Puzzle,
Users,
Wallet,
type LucideIcon,
} from 'lucide-react';
import { useState } from 'react';
import { useTranslation } from '../../i18n';
import { useTripAddons } from './useTripAddons';
/** The addons table's `icon` names of the trip addons; road trip was seeded as `Route`, the car says it better. */
const ICONS: Readonly<Record<string, LucideIcon>> = {
ListChecks,
Wallet,
FileText,
Users,
Route: CarFront,
Mountain,
Compass,
};
/** One trip addon as the trip settings list it. */
interface TripAddonRow {
id: string;
name: string;
description: string;
Icon: LucideIcon;
enabled: boolean;
/** The owner chose this for the trip, so it differs from the instance. */
ownChoice: boolean;
busy: boolean;
toggle: () => void;
}
/**
* The rows of the trip settings' Addons area, the same on the desktop dialog and
* the phone sheet. Flipping a switch back to what the instance says drops the
* trip's own choice instead of storing a copy of it, so a later change by the
* admin reaches the trip again and no reset button is needed.
*/
export function useTripAddonRows(tripId: number) {
const { t } = useTranslation();
const trip = useTripAddons(tripId);
const [busy, setBusy] = useState<string | null>(null);
const rows: TripAddonRow[] = trip.addons.map((addon) => {
// Spelled out inside t() so the key check sees which catalog keys this reaches.
const name = t(`admin.addons.catalog.${addon.id}.name`);
const description = t(`admin.addons.catalog.${addon.id}.description`);
return {
id: addon.id,
name: name === `admin.addons.catalog.${addon.id}.name` ? addon.name : name,
description: description === `admin.addons.catalog.${addon.id}.description` ? '' : description,
Icon: (addon.icon && ICONS[addon.icon]) || Puzzle,
enabled: addon.enabled,
ownChoice: addon.overridden,
busy: busy === addon.id,
toggle: () => {
if (busy) return;
const next = !addon.enabled;
setBusy(addon.id);
void trip.setOverride(addon.id, next === addon.instanceEnabled ? null : next).finally(() => setBusy(null));
},
};
});
return { rows, loading: trip.loading && rows.length === 0 };
}
@@ -0,0 +1,182 @@
// FE-TRIPADDONS-HOOK-001 to FE-TRIPADDONS-HOOK-006: the trip addons of one trip for the
// planner and the trip settings: read, refreshed when the connection returns, switched
// by the owner online only.
import { act, renderHook, waitFor } from '@testing-library/react';
import type { TripAddon } from '@trek/shared';
import 'fake-indexeddb/auto';
import { http, HttpResponse } from 'msw';
import type { ReactNode } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { buildUser } from '../../../tests/helpers/factories';
import { server } from '../../../tests/helpers/msw/server';
import { resetAllStores, seedInstanceAddons, seedStore } from '../../../tests/helpers/store';
import { clearAll } from '../../db/offlineDb';
import { TranslationProvider } from '../../i18n/TranslationContext';
import { useAuthStore } from '../../store/authStore';
import { useTripAddons } from './useTripAddons';
const env = vi.hoisted(() => ({
offline: false,
modeListeners: [] as Array<() => void>,
toast: { success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() },
}));
vi.mock('../../sync/networkMode', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../sync/networkMode')>();
return {
...actual,
isEffectivelyOffline: () => env.offline,
onNetworkModeChange: (fn: () => void) => {
env.modeListeners.push(fn);
return () => {
env.modeListeners = env.modeListeners.filter((l) => l !== fn);
};
},
};
});
vi.mock('../shared/Toast', () => ({ useToast: () => env.toast }));
const addon = (id: string, enabled: boolean, instanceEnabled: boolean): TripAddon => ({
id,
name: id,
icon: null,
enabled,
instanceEnabled,
overridden: enabled !== instanceEnabled,
});
function wrapper({ children }: { children: ReactNode }) {
return <TranslationProvider>{children}</TranslationProvider>;
}
function tripHas(addons: TripAddon[]) {
server.use(http.get('/api/trips/4/addons', () => HttpResponse.json({ tripId: 4, addons })));
}
beforeEach(async () => {
await clearAll();
resetAllStores();
vi.clearAllMocks();
env.offline = false;
env.modeListeners = [];
seedStore(useAuthStore, { user: buildUser({ id: 1 }), isAuthenticated: true });
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('useTripAddons', () => {
it('FE-TRIPADDONS-HOOK-001: reads the trip’s list, and until then answers with the instance switches', async () => {
seedInstanceAddons(['budget']);
tripHas([addon('budget', false, true), addon('tours', true, false)]);
const { result } = renderHook(() => useTripAddons(4), { wrapper });
expect(result.current.loading).toBe(true);
expect(result.current.loaded).toBe(false);
expect(result.current.isEnabled('budget')).toBe(true);
await waitFor(() => expect(result.current.loaded).toBe(true));
expect(result.current.loading).toBe(false);
expect(result.current.addons.map((a) => a.id)).toEqual(['budget', 'tours']);
expect(result.current.isEnabled('budget')).toBe(false);
expect(result.current.isEnabled('tours')).toBe(true);
// Not a trip addon: the instance decides.
expect(result.current.isEnabled('dawarich')).toBe(false);
});
it('FE-TRIPADDONS-HOOK-002: reads again when the connection comes back, and no trip reads nothing', async () => {
let asked = 0;
server.use(
http.get('/api/trips/4/addons', () => {
asked++;
return HttpResponse.json({ tripId: 4, addons: [addon('budget', asked > 1, true)] });
})
);
const { result } = renderHook(() => useTripAddons(4), { wrapper });
await waitFor(() => expect(result.current.loading).toBe(false));
expect(result.current.isEnabled('budget')).toBe(false);
expect(env.modeListeners).toHaveLength(1);
act(() => env.modeListeners.forEach((listener) => listener()));
await waitFor(() => expect(result.current.isEnabled('budget')).toBe(true));
expect(asked).toBe(2);
const none = renderHook(() => useTripAddons(null), { wrapper });
expect(none.result.current).toMatchObject({ addons: [], loading: false, loaded: false });
});
it('FE-TRIPADDONS-HOOK-003: the owner switches an addon, and the trip follows the answer', async () => {
let sent: unknown = null;
server.use(
http.put('/api/trips/4/addons/budget', async ({ request }) => {
sent = await request.json();
return HttpResponse.json({ tripId: 4, addons: [addon('budget', true, false)] });
})
);
const { result } = renderHook(() => useTripAddons(4), { wrapper });
await waitFor(() => expect(result.current.loaded).toBe(true));
let ok = false;
await act(async () => {
ok = await result.current.setOverride('budget', true);
});
expect(ok).toBe(true);
expect(sent).toEqual({ enabled: true });
expect(result.current.isEnabled('budget')).toBe(true);
expect(env.toast.error).not.toHaveBeenCalled();
});
it('FE-TRIPADDONS-HOOK-004: offline the switch is refused with a word why, and nothing is sent', async () => {
let sent = false;
server.use(
http.put('/api/trips/4/addons/:addonId', () => {
sent = true;
return HttpResponse.json({ tripId: 4, addons: [] });
})
);
const { result } = renderHook(() => useTripAddons(4), { wrapper });
env.offline = true;
let ok = true;
await act(async () => {
ok = await result.current.setOverride('budget', false);
});
expect(ok).toBe(false);
expect(sent).toBe(false);
expect(env.toast.error).toHaveBeenCalledWith(expect.stringMatching(/connection/i));
});
it('FE-TRIPADDONS-HOOK-005: a refusal from the server is said in its own words', async () => {
server.use(
http.put('/api/trips/4/addons/budget', () =>
HttpResponse.json({ error: 'Only the owner can change the addons of this trip' }, { status: 403 })
)
);
const { result } = renderHook(() => useTripAddons(4), { wrapper });
let ok = true;
await act(async () => {
ok = await result.current.setOverride('budget', null);
});
expect(ok).toBe(false);
expect(env.toast.error).toHaveBeenCalledWith('Only the owner can change the addons of this trip');
});
it('FE-TRIPADDONS-HOOK-006: a failure without the server’s words falls back to the localized one', async () => {
server.use(http.put('/api/trips/4/addons/budget', () => HttpResponse.json({}, { status: 500 })));
const { result } = renderHook(() => useTripAddons(4), { wrapper });
await act(async () => {
await result.current.setOverride('budget', true);
});
expect(env.toast.error).toHaveBeenCalledWith('The addons of this trip could not be changed.');
});
});
@@ -0,0 +1,79 @@
import type { TripAddon } from '@trek/shared';
import { useCallback, useEffect, useMemo } from 'react';
import { useTranslation } from '../../i18n';
import { useAddonStore } from '../../store/addonStore';
import { tripAddonsEntry, useTripAddonsStore } from '../../store/tripAddonsStore';
import { onNetworkModeChange } from '../../sync/networkMode';
import { getApiErrorMessage } from '../../types';
import { refusedOffline } from '../../utils/needsConnection';
import { tripAddonEnabled } from '../../utils/tripAddons';
import { useToast } from '../shared/Toast';
const NONE: TripAddon[] = [];
/**
* The trip addons of one trip, each on or off for it, for the trip planner and
* the trip's settings. Reads the trip's list when the trip changes and again
* when the connection comes back; a change another member's owner made arrives
* live through useTripAddonsSync.
*
* - `addons`: every trip addon as the trip sees it, in the admin's order; empty
* until the first read answered (or offline with nothing kept).
* - `isEnabled(id)`: whether an addon applies here; before the list is known,
* and for an addon it does not name, the instance switch.
* - `setOverride(id, enabled)`: the owner switches one addon for the trip,
* `null` going back to the instance setting. Online only: offline it says so
* and answers false. Answers whether the server took the change.
*/
export function useTripAddons(tripId: number | null | undefined) {
const toast = useToast();
const { t } = useTranslation();
const validId = tripId != null && Number.isSafeInteger(tripId) && tripId > 0 ? tripId : null;
const entry = useTripAddonsStore((state) => tripAddonsEntry(state, validId));
// The instance list, so isEnabled answers anew once it is read.
const instanceAddons = useAddonStore((state) => state.addons);
useEffect(() => {
if (validId == null) return;
const load = () => void useTripAddonsStore.getState().load(validId);
load();
return onNetworkModeChange(load);
}, [validId]);
const isEnabled = useCallback(
(addonId: string) =>
tripAddonEnabled(
entry?.addons,
addonId,
instanceAddons.some((addon) => addon.id === addonId && addon.enabled)
),
[entry?.addons, instanceAddons]
);
const setOverride = useCallback(
async (addonId: string, enabled: boolean | null): Promise<boolean> => {
if (validId == null || refusedOffline(toast, t)) return false;
try {
await useTripAddonsStore.getState().setOverride(validId, addonId, enabled);
return true;
} catch (err) {
toast.error(getApiErrorMessage(err, t('trip.addons.saveFailed')));
return false;
}
},
[validId, toast, t]
);
return useMemo(
() => ({
addons: entry?.addons ?? NONE,
loading: validId != null && (!entry || entry.status === 'loading'),
/** A list is held, or the first read failed; until then isEnabled is the instance switch. */
loaded: !!entry && (entry.addons != null || entry.status !== 'loading'),
isEnabled,
setOverride,
}),
[entry, validId, isEnabled, setOverride]
);
}
+11 -6
View File
@@ -9,6 +9,7 @@ import { useTranslation } from '../../i18n'
import { getApiErrorMessage } from '../../types'
import { useCopied } from '../../hooks/useCopied'
import { refusedOffline } from '../../utils/needsConnection'
import { useTripAddons } from './useTripAddons'
// The state behind the share dialog, shared by the desktop dialog and the one the
// phone opens from its More sheet. The questions ("Remove this member?") are the
@@ -22,13 +23,13 @@ const DEFAULT_PERMS: SharePerms = {
share_travel_only: false, share_hide_images: false,
}
/** What the link shows, one tab each. */
export const SHARE_SECTIONS: { key: SharePerm; label: string; always?: boolean }[] = [
/** What the link shows, one tab each; a tab of an addon only while the trip has that addon on. */
const SHARE_SECTIONS: { key: SharePerm; label: string; always?: boolean; addon?: string }[] = [
{ key: 'share_map', label: 'share.permMap', always: true },
{ key: 'share_bookings', label: 'share.permBookings' },
{ key: 'share_packing', label: 'share.permPacking' },
{ key: 'share_budget', label: 'share.permBudget' },
{ key: 'share_collab', label: 'share.permCollab' },
{ key: 'share_packing', label: 'share.permPacking', addon: 'packing' },
{ key: 'share_budget', label: 'share.permBudget', addon: 'budget' },
{ key: 'share_collab', label: 'share.permCollab', addon: 'collab' },
]
/** How the plan it shows is narrowed (#1712). */
@@ -45,6 +46,10 @@ export function useShareLink(tripId: number) {
const { copied, copy } = useCopied()
const toast = useToast()
const { t } = useTranslation()
// A section of an addon the trip has off is not offered: the link would not show it
// anyway. Its stored choice stays and counts again once the addon is back on.
const tripAddons = useTripAddons(tripId)
const sections = SHARE_SECTIONS.filter(section => !section.addon || tripAddons.isEnabled(section.addon))
useEffect(() => {
shareApi.getLink(tripId).then(d => {
@@ -85,7 +90,7 @@ export function useShareLink(tripId: number) {
} catch { toast.error(t('common.error')) }
}
return { loading, url, perms, copied, create, setPerm, remove, copy: () => copy(url) }
return { loading, url, perms, sections, copied, create, setPerm, remove, copy: () => copy(url) }
}
/** The rotating link an existing user opens to join the trip (#1143). */
@@ -1,5 +1,5 @@
import { describe, it, expect, vi } from 'vitest'
import { screen, waitFor } from '@testing-library/react'
import { act, screen, waitFor } from '@testing-library/react'
import { render } from '../../../tests/helpers/render'
import userEvent from '@testing-library/user-event'
import { useRef, useState } from 'react'
@@ -74,6 +74,34 @@ describe('NoteFormatToolbar', () => {
expect(field().value).toBe('already a list')
})
it('FE-NOTEBAR-010: pressing the numbered list button on each new line counts up instead of repeating 1.', async () => {
const user = userEvent.setup()
render(<Harness />)
const numbered = screen.getByRole('button', { name: /numbered list/i })
select(0, 0)
for (const [i, item] of ['Breakfast', 'Lunch', 'Dinner'].entries()) {
if (i > 0) await user.keyboard('{Enter}')
await user.click(numbered)
// The toolbar puts the caret back one frame later; typing before that
// frame would have it jump into the middle of the word.
await act(() => new Promise<void>(resolve => requestAnimationFrame(() => resolve())))
await user.keyboard(item)
}
expect(field().value).toBe('1. Breakfast\n2. Lunch\n3. Dinner')
})
it('FE-NOTEBAR-011: a multi-line selection gets a marker on every line', async () => {
const user = userEvent.setup()
render(<Harness initial={'Breakfast\nLunch\nDinner'} />)
select(0, 22)
await user.click(screen.getByRole('button', { name: /numbered list/i }))
expect(field().value).toBe('1. Breakfast\n2. Lunch\n3. Dinner')
})
it('FE-NOTEBAR-005: the link button leaves a placeholder URL to type over', async () => {
const user = userEvent.setup()
render(<Harness initial="opening hours" />)
@@ -2,10 +2,11 @@ import { useRef } from 'react'
import { Bold, Italic, Strikethrough, List, ListOrdered, Link2, Quote, Code } from 'lucide-react'
import { useTranslation } from '../../i18n'
import { Tooltip } from './Tooltip'
import { toggleLineMarker, type LineMarker } from './noteLineMarker'
type FormatAction =
| { type: 'wrap'; before: string; after: string }
| { type: 'line'; prefix: string }
| { type: 'line'; marker: LineMarker }
interface Props {
/** The field being formatted. Must be mounted before a button is pressed. */
@@ -26,9 +27,9 @@ const ACTIONS: Array<{ icon: typeof Bold; labelKey: string; action: FormatAction
{ icon: Strikethrough, labelKey: 'notes.format.strike', action: { type: 'wrap', before: '~~', after: '~~' } },
{ icon: Code, labelKey: 'notes.format.code', action: { type: 'wrap', before: '`', after: '`' } },
{ icon: Link2, labelKey: 'notes.format.link', action: { type: 'wrap', before: '[', after: '](https://)' } },
{ icon: List, labelKey: 'notes.format.list', action: { type: 'line', prefix: '- ' } },
{ icon: ListOrdered, labelKey: 'notes.format.orderedList', action: { type: 'line', prefix: '1. ' } },
{ icon: Quote, labelKey: 'notes.format.quote', action: { type: 'line', prefix: '> ' } },
{ icon: List, labelKey: 'notes.format.list', action: { type: 'line', marker: 'bullet' } },
{ icon: ListOrdered, labelKey: 'notes.format.orderedList', action: { type: 'line', marker: 'ordered' } },
{ icon: Quote, labelKey: 'notes.format.quote', action: { type: 'line', marker: 'quote' } },
]
/**
@@ -68,13 +69,9 @@ export default function NoteFormatToolbar({ textareaRef, onChange, compact, vari
? [start + action.before.length, end + action.before.length]
: [start + action.before.length, start + action.before.length]
} else {
const lineStart = value.lastIndexOf('\n', start - 1) + 1
const alreadyPrefixed = value.startsWith(action.prefix, lineStart)
next = alreadyPrefixed
? value.slice(0, lineStart) + value.slice(lineStart + action.prefix.length)
: value.slice(0, lineStart) + action.prefix + value.slice(lineStart)
const shift = alreadyPrefixed ? -action.prefix.length : action.prefix.length
caret = [Math.max(lineStart, start + shift), Math.max(lineStart, end + shift)]
const result = toggleLineMarker(value, start, end, action.marker)
next = result.value
caret = result.selection
}
pendingSelection.current = caret
@@ -0,0 +1,63 @@
import { describe, expect, it } from 'vitest';
import { toggleLineMarker } from './noteLineMarker';
describe('toggleLineMarker', () => {
it('FE-NOTELINE-001: numbers a new item after the one above instead of starting at 1 again', () => {
const value = '1. Breakfast\nLunch';
expect(toggleLineMarker(value, value.length, value.length, 'ordered').value).toBe('1. Breakfast\n2. Lunch');
});
it('FE-NOTELINE-002: keeps counting from whatever number the item above has', () => {
const value = '4. Museum\nDinner';
expect(toggleLineMarker(value, value.length, value.length, 'ordered').value).toBe('4. Museum\n5. Dinner');
});
it('FE-NOTELINE-003: starts at 1 when the line above is no numbered item', () => {
expect(toggleLineMarker('Meals\nBreakfast', 8, 8, 'ordered').value).toBe('Meals\n1. Breakfast');
expect(toggleLineMarker('Breakfast', 0, 0, 'ordered').value).toBe('1. Breakfast');
});
it('FE-NOTELINE-004: numbers every selected line in order and skips the blank ones', () => {
const value = 'Breakfast\nLunch\n\nDinner';
const result = toggleLineMarker(value, 0, value.length, 'ordered');
expect(result.value).toBe('1. Breakfast\n2. Lunch\n\n3. Dinner');
expect(result.selection).toEqual([0, result.value.length]);
});
it('FE-NOTELINE-005: renumbers a selection that mixes numbered and plain lines', () => {
const value = '1. Breakfast\n1. Lunch\nDinner';
expect(toggleLineMarker(value, 0, value.length, 'ordered').value).toBe('1. Breakfast\n2. Lunch\n3. Dinner');
});
it('FE-NOTELINE-006: removes the numbers when every selected line already has one', () => {
const value = '1. Breakfast\n2. Lunch';
expect(toggleLineMarker(value, 0, value.length, 'ordered').value).toBe('Breakfast\nLunch');
});
it('FE-NOTELINE-007: removes the number from a single item, whatever the number is', () => {
const result = toggleLineMarker('1. a\n12. Dinner', 10, 10, 'ordered');
expect(result.value).toBe('1. a\nDinner');
expect(result.selection).toEqual([6, 6]);
});
it('FE-NOTELINE-008: bullets and quotes apply to each selected line, without doubling an existing marker', () => {
const value = 'one\n- two\nthree';
expect(toggleLineMarker(value, 0, value.length, 'bullet').value).toBe('- one\n- two\n- three');
expect(toggleLineMarker('one\ntwo', 0, 7, 'quote').value).toBe('> one\n> two');
});
it('FE-NOTELINE-009: a selection ending right after a newline leaves the next line alone', () => {
const value = 'one\ntwo\nthree';
expect(toggleLineMarker(value, 0, 8, 'bullet').value).toBe('- one\n- two\nthree');
});
it('FE-NOTELINE-010: the caret moves with the text on a single line', () => {
const value = 'first\nsecond';
expect(toggleLineMarker(value, 8, 8, 'bullet')).toEqual({ value: 'first\n- second', selection: [10, 10] });
});
it('FE-NOTELINE-011: an empty line still gets the marker, so a list can be started on it', () => {
expect(toggleLineMarker('', 0, 0, 'ordered')).toEqual({ value: '1. ', selection: [3, 3] });
expect(toggleLineMarker('1. Breakfast\n', 13, 13, 'ordered').value).toBe('1. Breakfast\n2. ');
});
});
@@ -0,0 +1,64 @@
export type LineMarker = 'bullet' | 'ordered' | 'quote';
const PATTERN: Record<LineMarker, RegExp> = {
bullet: /^- /,
ordered: /^\d+\. /,
quote: /^> /,
};
const FIXED_PREFIX: Record<Exclude<LineMarker, 'ordered'>, string> = {
bullet: '- ',
quote: '> ',
};
export interface LineMarkerResult {
value: string;
selection: [number, number];
}
/** The number an ordered item gets when it is added right below `lineStart`'s previous line. */
function nextNumberAt(value: string, lineStart: number): number {
if (lineStart === 0) return 1;
const prevStart = value.lastIndexOf('\n', lineStart - 2) + 1;
const match = /^(\d+)\. /.exec(value.slice(prevStart, lineStart - 1));
return match ? Number(match[1]) + 1 : 1;
}
/**
* Adds or removes a line marker (bullet, number, quote) on every line the
* selection touches.
*
* Numbers continue from the item above, so pressing the button on each new
* line writes 1. 2. 3. instead of 1. 1. 1. Markdown renders both the same,
* but the field is what people read while they write. A selection over several
* lines is formatted line by line and skips the blank ones in between.
*/
export function toggleLineMarker(value: string, start: number, end: number, marker: LineMarker): LineMarkerResult {
const blockStart = value.lastIndexOf('\n', start - 1) + 1;
// A selection that ends right after a newline stops on the line above it.
const last = end > start && value[end - 1] === '\n' ? end - 1 : end;
const newline = value.indexOf('\n', last);
const blockEnd = newline === -1 ? value.length : newline;
const lines = value.slice(blockStart, blockEnd).split('\n');
const multi = lines.length > 1;
const formats = (line: string) => !multi || line.trim() !== '';
const pattern = PATTERN[marker];
const remove = lines.some(formats) && lines.filter(formats).every((line) => pattern.test(line));
let number = nextNumberAt(value, blockStart);
const next = lines.map((line) => {
if (!formats(line)) return line;
if (remove) return line.replace(pattern, '');
if (marker === 'ordered') return `${number++}. ${line.replace(pattern, '')}`;
return pattern.test(line) ? line : FIXED_PREFIX[marker] + line;
});
const block = next.join('\n');
const result = value.slice(0, blockStart) + block + value.slice(blockEnd);
if (multi) return { value: result, selection: [blockStart, blockStart + block.length] };
// One line: the caret moves with the text, never in front of the line.
const shift = block.length - (blockEnd - blockStart);
return { value: result, selection: [Math.max(blockStart, start + shift), Math.max(blockStart, end + shift)] };
}
+17 -1
View File
@@ -1,4 +1,4 @@
import type { Ferrata, RoadtripPreferences, TourActivity, TourDraft, TourListItem, TourObstacleCheck, TourPackingLink, TourProvenance, TourVisit, TourWaypoint } from '@trek/shared';
import type { Ferrata, RoadtripPreferences, TripAddon, TourActivity, TourDraft, TourListItem, TourObstacleCheck, TourPackingLink, TourProvenance, TourVisit, TourWaypoint } from '@trek/shared';
import Dexie, { type Table } from 'dexie';
import type { Trip, Day, Place, PackingItem, TodoItem, BudgetItem, Reservation, TripFile, Accommodation, TripMember, Tag, Category } from '../types';
@@ -80,6 +80,15 @@ interface CachedTripTags {
tags: Tag[];
}
/**
* The trip addons of one trip as the server last listed them, each on or off for
* that trip: one row per trip, so a trip opened offline shows the tabs it had.
*/
interface CachedTripAddons {
tripId: number;
addons: TripAddon[];
}
/**
* 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).
@@ -304,6 +313,7 @@ export class TrekOfflineDb extends Dexie {
tourDrafts!: Table<CachedTourDraft, number>;
routeCache!: Table<CachedRoute, string>;
tripTags!: Table<CachedTripTags, number>;
tripAddons!: Table<CachedTripAddons, number>;
constructor(name: string = ANON_DB_NAME) {
super(name);
@@ -400,6 +410,10 @@ export class TrekOfflineDb extends Dexie {
// 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' });
// v16: the trip addons of each trip, on or off for that trip, one list per
// trip, so the tabs a trip switched off stay hidden offline too.
this.version(16).stores({ tripAddons: 'tripId' });
}
}
@@ -702,11 +716,13 @@ export async function clearTripData(tripId: number): Promise<void> {
offlineDb.tourStationVisits,
offlineDb.tourDrafts,
offlineDb.tripTags,
offlineDb.tripAddons,
],
async () => {
await offlineDb.roadtripPreferences.delete(tripId);
await offlineDb.tourDrafts.delete(tripId);
await offlineDb.tripTags.delete(tripId);
await offlineDb.tripAddons.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();
+3 -2
View File
@@ -3,7 +3,7 @@ import { isServiceStopType } from '../components/Roadtrip/roadtripModel'
import { useState, useCallback, useRef, useEffect, useMemo } from 'react'
import { useTripStore } from '../store/tripStore'
import { useSettingsStore } from '../store/settingsStore'
import { useAddonStore } from '../store/addonStore'
import { useTripAddonEnabled } from '../store/tripAddonsStore'
import { calculateRouteWithRetries, type RouteProfileKey } from '../components/Map/routeRetry'
import { buildDayRouteRuns, hotelBookendOf, TRANSPORT_TYPES, type DayRouteInputs } from '../components/Map/dayRoutePlan'
import { dayViaLookup, foldViaLegs, threadVias, viaKeyOf, viasOnDayLeg } from '../utils/dayRouteVias'
@@ -36,7 +36,8 @@ export function useRouteCalculation(tripStore: Pick<TripStoreState, 'assignments
// Charging stops / rest areas a plugin route places on the drawn line.
const [routeVias, setRouteVias] = useState<RouteVia[]>([])
const mirrorServiceStops = useRoadtripSettings(s => s.roadtrip_service_stops_in_days !== false)
const toursEnabled = useAddonStore(s => s.isEnabled('tours'))
const activeTripId = useTripStore(s => s.trip?.id)
const toursEnabled = useTripAddonEnabled(activeTripId, 'tours')
const places = useTripStore(s => s.places)
const routeAbortRef = useRef<AbortController | null>(null)
const reservationsForSignature = useTripStore((s) => s.reservations)
+14
View File
@@ -0,0 +1,14 @@
import { useEffect } from 'react';
import { useAuthStore } from '../store/authStore';
import { watchTripAddons } from '../store/tripAddonsStore';
/**
* Keeps the trip addons of every trip the app looks at live while someone is
* signed in: the trip owner switching an addon reaches every member at once.
* Mounted once, by App.
*/
export function useTripAddonsSync(): void {
const userId = useAuthStore((s) => s.user?.id);
useEffect(() => (userId ? watchTripAddons() : undefined), [userId]);
}
-1
View File
@@ -14,7 +14,6 @@ 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="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)]"
className="m-safe-row 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>
+1 -1
View File
@@ -89,7 +89,7 @@ export function MSectionList({
* width on both screens.
*/
export const SECTION_SCREEN =
'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';
'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;
+5 -5
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-[max(var(--m-safe-top,12px),var(--m-corner-clear,0px))] bottom-[calc(var(--bottom-nav-h,84px)+12px)] justify-center',
card: 'inset-x-[14px] top-[var(--m-safe-top,12px)] 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-[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)]',
'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)]',
drawer: 'start-0 top-0 bottom-0 w-[78%] max-w-[320px]',
}
@@ -109,15 +109,15 @@ const WIDE_REGION: Record<MSheetWideAnchor, string> = {
// A form on a window as short as a phone on its side: a sheet the window's
// full height, over the dock, as wide as a form reads well and no wider.
const SHORT_FORM_REGION =
'short:inset-x-4 short:top-[max(env(safe-area-inset-top,0px),8px)] short:bottom-0 short:items-center short:justify-stretch'
'short:inset-x-4 short:top-[max(var(--m-safe-t,0px),8px)] short:bottom-0 short:items-center short:justify-stretch'
const SHORT_FORM_BOX = 'short:max-w-[640px] short:flex-1'
/** The region the sheet stands in, on a phone and on a wide window. */
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}`
// 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}` : ''}`
// m-safe-trail: on a wide window the sheet keeps off the trailing side's safe area (a Duo's status capsule).
return `${base} m-safe-trail ${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. */
@@ -1,8 +1,11 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { act, fireEvent, render, screen, waitFor } from '../../../tests/helpers/render';
import { ToastContainer } from '../../components/shared/Toast';
import { saveSharedLink, useSharedImportStore } from '../../native/sharedFiles';
import { tripAddonsRepo } from '../../repo/tripAddonsRepo';
import { tripRepo } from '../../repo/tripRepo';
import { useAddonStore } from '../../store/addonStore';
import { useTripAddonsStore } from '../../store/tripAddonsStore';
import NativeImportSheet from './NativeImportSheet';
const navigate = vi.hoisted(() => vi.fn());
@@ -21,6 +24,9 @@ beforeEach(() => {
navigate.mockReset();
useSharedImportStore.setState({ file: null, tripId: null, link: null });
useAddonStore.setState({ addons: [{ id: 'collab', enabled: true }] as never, loaded: true });
useTripAddonsStore.setState({ trips: {} });
// Every trip follows the instance switch unless a test says otherwise; answered at once, so no read outlives its test.
vi.spyOn(tripAddonsRepo, 'list').mockResolvedValue([]);
vi.mocked(saveSharedLink).mockReset().mockResolvedValue();
vi.spyOn(tripRepo, 'list').mockResolvedValue({
trips: [
@@ -33,6 +39,15 @@ beforeEach(() => {
const page = () => new File(['<html></html>'], 'hotel.html', { type: 'text/html' });
const bareLink = () => new File(['https://hotel.example/stay'], 'link.url', { type: 'text/uri-list' });
/** Trip 2's own Collab choice; trip 1 follows the instance. */
const collabOnlyFor2 = (enabled: boolean) =>
vi
.spyOn(tripAddonsRepo, 'list')
.mockImplementation(async (tripId: number) =>
tripId === 2
? [{ id: 'collab', name: 'Collab', icon: null, enabled, instanceEnabled: !enabled, overridden: true }]
: []
);
const link = (presetTripId: number | null = null) => ({
url: 'https://hotel.example/stay',
title: 'Hotel Kanra',
@@ -116,6 +131,33 @@ describe('NativeImportSheet', () => {
expect(useSharedImportStore.getState().file).not.toBeNull();
});
it('keeps a link in a trip that switched Collab on while the instance has it off, offering only that trip', async () => {
useAddonStore.setState({ addons: [], loaded: true });
collabOnlyFor2(true);
render(<NativeImportSheet />);
act(() => useSharedImportStore.getState().setFile(page(), link()));
fireEvent.click(await screen.findByRole('button', { name: /Save to the trip's links/ }));
expect(await screen.findByRole('button', { name: /Japan/ })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: /Past trip/ })).not.toBeInTheDocument();
});
it('leaves out a trip that switched Collab off, and shows why when the server refuses the link', async () => {
collabOnlyFor2(false);
vi.mocked(saveSharedLink).mockRejectedValue({ response: { data: { error: 'Collab addon is not enabled' } } });
render(
<>
<ToastContainer />
<NativeImportSheet />
</>
);
act(() => useSharedImportStore.getState().setFile(bareLink(), link(2)));
expect(await screen.findByText('Collab addon is not enabled')).toBeInTheDocument();
expect(await screen.findByRole('button', { name: /Past trip/ })).toBeInTheDocument();
await waitFor(() => expect(screen.queryByRole('button', { name: /Japan/ })).not.toBeInTheDocument());
});
it('stays closed with nothing shared', () => {
render(<NativeImportSheet />);
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
@@ -6,16 +6,21 @@
* A web page or a link is asked about first: kept among the trip's links
* (Collaboration, Links), or read as a booking. A bare link, whose page the phone
* could not read, can only be kept; with Collaboration off, a page can only be read.
* Collaboration counts per trip: a link goes only to a trip that has it on.
*/
import { ChevronRight, FileText, Link2, ScanText } from 'lucide-react';
import React, { useEffect, useEffectEvent, useRef, useState } from 'react';
import { useLocation, useNavigate } from 'react-router';
import { useShallow } from 'zustand/react/shallow';
import { useToast } from '../../components/shared/Toast';
import { useTranslation } from '../../i18n';
import { saveSharedLink, useSharedImportStore, type SharedLink } from '../../native/sharedFiles';
import { tripRepo } from '../../repo/tripRepo';
import { useAddonStore } from '../../store/addonStore';
import { tripAddonsEntry, useTripAddonsStore } from '../../store/tripAddonsStore';
import { getApiErrorMessage } from '../../utils/apiError';
import { offlineOr } from '../../utils/needsConnection';
import { tripAddonEnabled } from '../../utils/tripAddons';
import { TileHeader } from '../screens/trip/sheets/MTripSheetUi';
import MSheet from './MSheet';
@@ -83,6 +88,27 @@ function useTripRows(open: boolean): TripRow[] {
return trips;
}
/**
* The trips a shared link may go to: those with Collaboration on, each by its
* own list (the owner's choice, else the instance switch). The lists are read
* once the sheet opens for a link, so a trip that switched Collaboration on is
* offered while the instance has it off, and one that switched it off is not.
*/
function useCollabTrips(trips: TripRow[], active: boolean): TripRow[] {
const instanceOn = useAddonStore((s) => s.isEnabled('collab'));
const load = useTripAddonsStore((s) => s.load);
useEffect(() => {
if (!active) return;
trips.forEach((trip) => void load(trip.id));
}, [active, trips, load]);
const on = useTripAddonsStore(
useShallow((state) =>
trips.map((trip) => tripAddonEnabled(tripAddonsEntry(state, trip.id)?.addons, 'collab', instanceOn))
)
);
return trips.filter((_trip, i) => on[i]);
}
export default function NativeImportSheet(): React.ReactElement | null {
const { t } = useTranslation();
const toast = useToast();
@@ -93,7 +119,12 @@ export default function NativeImportSheet(): React.ReactElement | null {
const link = useSharedImportStore((s) => s.link);
const chooseTrip = useSharedImportStore((s) => s.chooseTrip);
const setFile = useSharedImportStore((s) => s.setFile);
const collabOn = useAddonStore((s) => s.isEnabled('collab'));
const instanceCollab = useAddonStore((s) => s.isEnabled('collab'));
const open = !!file && tripId == null;
const trips = useTripRows(open);
const collabTrips = useCollabTrips(trips, open && !!link);
// Before the trips are known the instance switch decides, as it always did.
const collabOn = trips.length === 0 ? instanceCollab : collabTrips.length > 0;
// Both belong to the item they were made for, so a newly shared one starts afresh.
const [pick, setPick] = useState<{ file: File; choice: LinkChoice } | null>(null);
const [failedFile, setFailedFile] = useState<File | null>(null);
@@ -107,8 +138,6 @@ export default function NativeImportSheet(): React.ReactElement | null {
picked,
presetFailed: failedFile != null && failedFile === file,
});
const open = !!file && tripId == null;
const trips = useTripRows(open);
// Once a trip is picked (here, or in the share sheet before the app opened), go to
// it; its planner opens the booking import with the file (MTripShell).
@@ -126,8 +155,9 @@ export default function NativeImportSheet(): React.ReactElement | null {
setFile(null);
void navigate(`/trips/${id}?tab=collab`);
},
() => {
toast.error(offlineOr(t, t('common.error')));
(err: unknown) => {
// The server says why, such as a trip that has Collaboration off.
toast.error(offlineOr(t, getApiErrorMessage(err, t('common.error'))));
savingRef.current = null;
setFailedFile(file);
}
@@ -164,7 +194,7 @@ export default function NativeImportSheet(): React.ReactElement | null {
{t('native.share.linkUnsupported')}
</p>
)}
{showTrips && <TripPicker trips={trips} onPick={pickTrip} />}
{showTrips && <TripPicker trips={choice === 'link' ? collabTrips : trips} onPick={pickTrip} />}
</div>
</MSheet>
);
-31
View File
@@ -1,31 +0,0 @@
/* ── 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);
}
+52 -72
View File
@@ -66,43 +66,26 @@
* publishSafeArea) is a floor under env(): where a release lays the web view
* out below the status bar, WebKit reports 0 while a camera in a corner still
* reaches into the page. In a browser the variables are unset: env() alone. */
--m-safe-t: max(env(safe-area-inset-top, 0px), var(--trek-native-safe-top, 0px));
--m-safe-l: max(env(safe-area-inset-left, 0px), var(--trek-native-safe-left, 0px));
--m-safe-r: max(env(safe-area-inset-right, 0px), var(--trek-native-safe-right, 0px));
--m-safe-top: calc(var(--m-safe-t) + 12px);
--m-raw-t: max(env(safe-area-inset-top, 0px), var(--trek-native-safe-top, 0px));
--m-raw-l: max(env(safe-area-inset-left, 0px), var(--trek-native-safe-left, 0px));
--m-raw-r: max(env(safe-area-inset-right, 0px), var(--trek-native-safe-right, 0px));
/* An element in a top corner of the screen, such as an iPhone Duo's status
* capsule, as the iOS app measures it (TrekBridgeViewController
* cornerElement): how far down it reaches and how wide it is on its side.
* The floating bars stand beside it; the page keeps the side's full width
* and starts below it, instead of giving up a strip of the whole height to
* an inset that only exists in the corner. 0 everywhere else. */
--m-corner-b: var(--trek-native-corner-bottom, 0px);
--m-bar-l: max(var(--m-safe-l), var(--trek-native-corner-left, 0px));
--m-bar-r: max(var(--m-safe-r), var(--trek-native-corner-right, 0px));
--m-page-l: max(0px, var(--m-safe-l) - var(--trek-native-corner-left, 0px));
--m-page-r: max(0px, var(--m-safe-r) - var(--trek-native-corner-right, 0px));
/* A bar's side inset plus a little air: next to a Duo's status capsule a
* bar that ends exactly at the inset reads as touching it. Without an inset
* cornerElement), counts as safe area like a notch, so every screen keeps
* clear of it without knowing it is there. Upright the top inset reaches
* below it and the sides keep their full width (iOS reports the element as
* a side inset too, which is taken back out); on a wide window its side is
* given up over the whole height instead (below), where a band across the
* top would cost a quarter of the height. 0 on every other device. */
--m-safe-t: max(var(--m-raw-t), var(--trek-native-corner-bottom, 0px));
--m-safe-l: max(0px, var(--m-raw-l) - var(--trek-native-corner-left, 0px));
--m-safe-r: max(0px, var(--m-raw-r) - var(--trek-native-corner-right, 0px));
--m-safe-top: calc(var(--m-safe-t) + 12px);
/* A side inset plus a little air, for a bar beside it: a bar that ends
* exactly at the inset reads as touching what is there. Without an inset
* 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);
--m-safe-l-gap: calc(var(--m-safe-l) + min(var(--m-safe-l), 8px));
--m-safe-r-gap: calc(var(--m-safe-r) + min(var(--m-safe-r), 8px));
/* 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;
@@ -115,21 +98,15 @@
* 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-bar-l) + 100px);
--m-rail-w: calc(var(--m-safe-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;
* as an iPhone on its side does for its camera, and keeps the top as it is. */
--m-safe-t: var(--m-raw-t);
--m-safe-l: max(var(--m-raw-l), var(--trek-native-corner-left, 0px));
--m-safe-r: max(var(--m-raw-r), var(--trek-native-corner-right, 0px));
}
html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-root {
--m-rail-w: calc(var(--m-bar-r) + 100px);
--m-corner-side-l: var(--m-corner-l-gap);
--m-corner-side-r: 0px;
--m-rail-w: calc(var(--m-safe-r) + 100px);
}
.dark .m-root {
@@ -649,40 +626,43 @@ html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-
html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) .m-span-x {
inset-inline-end: var(--m-safe-l-gap, 0px);
}
/* A control row or button a screen places by itself (m-safe-row: the trip's
top row, the map's controls, a viewer's close button, a dropdown) keeps
clear of the sides' safe area like the bars above: both sides on a phone,
the trailing side on a wide window, where the rail holds the leading one.
A layer that fills the window (m-safe-trail: a sheet, the assistant, the
trip's pane and map) does the same on a wide window only; on a phone its
own insets keep it off the sides. On an unfolded Duo that trailing side is
the status capsule's. */
html:not(:has(.m-shell[data-size='wide'], .m-shell[data-size='split'])) .m-safe-row {
margin-inline: var(--m-safe-l-gap, 0px) var(--m-safe-r-gap, 0px);
}
html[dir='rtl']:not(:has(.m-shell[data-size='wide'], .m-shell[data-size='split'])) .m-safe-row {
margin-inline: var(--m-safe-r-gap, 0px) var(--m-safe-l-gap, 0px);
}
html:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) :is(.m-safe-row, .m-safe-trail) {
margin-inline-end: var(--m-safe-r-gap, 0px);
}
html[dir='rtl']:has(.m-shell[data-size='wide'], .m-shell[data-size='split']) :is(.m-safe-row, .m-safe-trail) {
margin-inline-end: var(--m-safe-l-gap, 0px);
}
/* The page itself keeps clear of the sides' safe area, as iOS asks of every
app, and starts below an element in a top corner: on a Duo the status
capsule ran over the cards under the top bar (TestFlight feedback). The
padding lifts the content only by what the capsule reaches below the top
bar's row (about 70px under the top clearance), so with no corner element
it is 0. Margins, so the rail's wide:ps on the same element stays; fixed
layers are the window's and keep their own rules. The rail already takes
the leading inset on a wide window. */
app. Margins, so the rail's wide:ps on the same element stays; fixed layers
are the window's and keep their own rules. On a wide window the rail takes
the leading inset, so the page starts at the rail and ends before the
trailing inset. */
.m-page {
margin-inline: var(--m-page-l, 0px) var(--m-page-r, 0px);
padding-top: max(0px, calc(var(--m-corner-clear, 0px) + 2px - var(--m-safe-top, 12px) - 70px));
margin-inline: var(--m-safe-l, 0px) var(--m-safe-r, 0px);
}
html[dir='rtl'] .m-page {
margin-inline: var(--m-page-r, 0px) var(--m-page-l, 0px);
margin-inline: var(--m-safe-r, 0px) var(--m-safe-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));
margin-inline-end: var(--m-safe-r-gap, 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));
margin-inline-end: var(--m-safe-l-gap, 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
@@ -786,7 +766,7 @@ html:has(.m-shell) [data-desktop-navbar] {
html:has(.m-shell) [data-plugin-page] {
--plugin-page-h: calc(100dvh - var(--bottom-nav-h, 0px));
box-sizing: border-box;
padding-top: env(safe-area-inset-top, 0px);
padding-top: var(--m-safe-t, env(safe-area-inset-top, 0px));
padding-inline-start: var(--m-rail-w, 0px);
}
html:has(.m-shell) .leaflet-control-zoom {
+10 -4
View File
@@ -1,5 +1,4 @@
import MAdminSchoolHolidayCatalog from './MAdminSchoolHolidayCatalog'
import MAdminPaddleRegionsPanel from './MAdminPaddleRegionsPanel'
import { useState } from 'react'
import {
ArrowUp,
@@ -246,10 +245,17 @@ export default function MAdmin() {
onToggleBagTracking={toggleBagTracking}
collabFeatures={collabFeatures}
onToggleCollabFeature={toggleCollabFeature}
// Live flight status and the booking mail import are rows of the addon groups,
// and the paddle water data a row under Tours (desktop parity).
flightLive={{
on: admin.flightLive,
locked: admin.flightLiveLocked,
managed: !!managed,
onToggle: () =>
void admin.handleToggleAuthSetting('flight_live_enabled', !admin.flightLive, admin.setFlightLive),
}}
mailImport={!managed}
/>
{/* How the integrations reach the world (live flights, booking mails), beside the addons they serve. */}
<MAdminSettingsSection admin={admin} t={t} part="features" />
<MAdminPaddleRegionsPanel />
</div>
)}
{activeTab === 'plugins' && <MAdminPluginsPanel />}
@@ -3,7 +3,7 @@ import { useTranslation } from '../../../i18n'
import { useIsDark } from '../../../hooks/useIsDark'
import {
Puzzle, ListChecks, Wallet, FileText, CalendarDays, Globe, Briefcase, Image, Terminal, Link2, Compass, BookOpen,
Sparkles, Luggage, Plane, Bookmark, Users, Mountain, CarFront, Settings2, ChevronRight,
Sparkles, Luggage, Plane, Bookmark, Users, Mountain, CarFront, Radar,
} from 'lucide-react'
import DawarichIcon from '../../../components/shared/DawarichIcon'
import AirTrailIcon from '../../../components/shared/AirTrailIcon'
@@ -21,7 +21,10 @@ import AiSettingsDialog from '../../../components/Admin/addons/AiAdminConfig'
import { AI_ADDON_ICONS, type AiAddonId } from '../../../components/Admin/addons/aiAddons'
import { useAiAddonTile } from '../../../components/Admin/addons/useAiAddonTile'
import { ImmichIcon, SynologyIcon } from '../../../components/Admin/addons/PhotoProviderIcons'
import { MAdminCard } from './MAdminUi'
import { MAdminCard, MAdminOptionRow, MAdminSetupRow } from './MAdminUi'
import MAdminPaddleRegionsPanel from './MAdminPaddleRegionsPanel'
import MMailIngestAdminCard from './MMailIngestAdminCard'
import type { FlightLiveOption } from '../../../components/Admin/AddonManager'
import MHintLabel from '../../components/MHintLabel'
import WandererMark from '../../../components/Tours/wanderer/WandererMark'
import MSkeleton from '../../components/MSkeleton'
@@ -59,7 +62,16 @@ function AddonIcon({ name, size = 18, enabled = true }: AddonIconProps) {
return <Icon size={size} />
}
export default function MAdminAddonManager({ bagTrackingEnabled, onToggleBagTracking, collabFeatures, onToggleCollabFeature }: { bagTrackingEnabled?: boolean; onToggleBagTracking?: () => void; collabFeatures?: CollabFeatures; onToggleCollabFeature?: (key: string) => void }) {
export default function MAdminAddonManager({ bagTrackingEnabled, onToggleBagTracking, collabFeatures, onToggleCollabFeature, flightLive, mailImport = false }: {
bagTrackingEnabled?: boolean
onToggleBagTracking?: () => void
collabFeatures?: CollabFeatures
onToggleCollabFeature?: (key: string) => void
/** Live flight status, a row of the trip group (desktop parity). */
flightLive?: FlightLiveOption
/** Booking mail import, a row of the integration group with its setup sheet; off on a managed install. */
mailImport?: boolean
}) {
const { t } = useTranslation()
const dark = useIsDark()
const {
@@ -98,7 +110,7 @@ export default function MAdminAddonManager({ bagTrackingEnabled, onToggleBagTrac
) : (
<>
{/* Trip Addons */}
{tripAddons.length > 0 && (
{(tripAddons.length > 0 || flightLive) && (
<MAdminCard>
<MGroupHead icon={Briefcase} label={t('admin.addons.type.trip')} hint={t('admin.addons.tripHint')} />
{tripAddons.map((addon, i) => (
@@ -135,6 +147,7 @@ export default function MAdminAddonManager({ bagTrackingEnabled, onToggleBagTrac
onToggle={() => void toggle()}
/>
))}
<MAdminPaddleRegionsPanel />
</>
)}
{addon.id === 'collab' && addon.enabled && collabFeatures && onToggleCollabFeature && (
@@ -153,6 +166,7 @@ export default function MAdminAddonManager({ bagTrackingEnabled, onToggleBagTrac
)}
</div>
))}
{flightLive && <MFlightLiveRow option={flightLive} first={tripAddons.length === 0} />}
</MAdminCard>
)}
@@ -171,13 +185,14 @@ export default function MAdminAddonManager({ bagTrackingEnabled, onToggleBagTrac
)}
{/* Integration Addons, headed by the AI ones as one group, as on the desktop */}
{(integrationAddons.length > 0 || aiAddons.length > 0) && (
{(integrationAddons.length > 0 || aiAddons.length > 0 || mailImport) && (
<MAdminCard>
<MGroupHead icon={Link2} label={t('admin.addons.type.integration')} hint={t('admin.addons.integrationHint')} />
{aiAddons.length > 0 && <MAiAddons addons={aiAddons} onToggle={handleToggle} />}
{integrationAddons.map((addon, i) => (
<MAddonRow key={addon.id} addon={addon} onToggle={handleToggle} t={t} first={i === 0 && aiAddons.length === 0} />
))}
{mailImport && <MMailIngestAdminCard first={integrationAddons.length === 0 && aiAddons.length === 0} />}
</MAdminCard>
)}
</>
@@ -216,16 +231,28 @@ interface MAddonRowProps {
function MAddonRow({ addon, onToggle, t, first }: MAddonRowProps) {
const label = getAddonLabel(t, addon)
return (
<div className={`flex items-center gap-3 py-[11px] ${first ? '' : 'border-t border-[color:var(--m-rowbr)]'}`}>
{/* overflow-hidden so a brand mark that fills the slot keeps its rounded corners. */}
<span className="flex h-[38px] w-[38px] flex-none items-center justify-center overflow-hidden rounded-[11px] bg-[color:var(--m-ic)] text-m-ink">
<AddonIcon name={addon.icon} size={18} enabled={addon.enabled} />
</span>
<div className="min-w-0 flex-1">
<MHintLabel label={label.name} hint={label.description} />
</div>
<MToggle checked={addon.enabled} ariaLabel={label.name} onChange={() => onToggle(addon)} />
</div>
<MAdminOptionRow
icon={<AddonIcon name={addon.icon} size={18} enabled={addon.enabled} />}
title={label.name}
hint={label.description}
first={first}
trailing={<MToggle checked={addon.enabled} ariaLabel={label.name} onChange={() => onToggle(addon)} />}
/>
)
}
/** Live flight status as a trip row, locked with a word when the server environment holds it. */
function MFlightLiveRow({ option, first }: { option: FlightLiveOption; first: boolean }) {
const { t } = useTranslation()
const hint = option.managed ? t('flightLive.adminHintManaged') : t('flightLive.adminHint')
return (
<MAdminOptionRow
icon={<Radar size={18} />}
title={t('flightLive.adminTitle')}
hint={option.locked ? `${hint} ${t('flightLive.envLocked')}` : hint}
first={first}
trailing={<MToggle checked={option.on} ariaLabel={t('flightLive.adminToggle')} disabled={option.locked} onChange={option.onToggle} />}
/>
)
}
@@ -301,17 +328,7 @@ function MAiAddons({ addons, onToggle }: { addons: Addon[]; onToggle: (addon: Ad
/>
)
})}
{tile.canSetUp && (
<button
type="button"
onClick={tile.openDialog}
className="flex w-full items-center gap-3 border-t border-[color:var(--m-rowbr)] py-[11px] ps-[50px] text-start"
>
<Settings2 size={14} className="flex-none text-m-faint" />
<span className="min-w-0 flex-1 truncate text-[0.75rem] font-bold text-m-ink">{t('admin.addons.ai.setup')}</span>
<ChevronRight size={15} className="flex-none text-m-faint rtl:rotate-180" />
</button>
)}
{tile.canSetUp && <MAdminSetupRow label={t('admin.addons.ai.setup')} onOpen={tile.openDialog} />}
{tile.dialogOpen && <AiSettingsDialog addons={addons} onClose={tile.closeDialog} />}
</div>
)
@@ -15,6 +15,7 @@ import {
Waves,
WifiOff,
} from 'lucide-react';
import { useState } from 'react';
import {
AUTO_LOAD_MODES,
autoLoadSizes,
@@ -28,8 +29,9 @@ import { useTranslation } from '../../../i18n';
import { formatDisplayDate } from '../../../utils/dateFormat';
import MBadge from '../../components/MBadge';
import MChip from '../../components/MChip';
import MSheet from '../../components/MSheet';
import MConfirmSheet from '../settings/MConfirmSheet';
import { MAdminButton, MAdminCard, MAdminClampedText } from './MAdminUi';
import { MAdminButton, MAdminClampedText, MAdminSetupRow, MAdminSheetFrame } from './MAdminUi';
type Admin = ReturnType<typeof usePaddleRegionsAdmin>;
@@ -393,32 +395,49 @@ function Regions({ admin }: { admin: Admin }) {
/**
* PAD-05A/PAD-11C on the phone: the regions TREK reads paddle data for, how it
* loads a paddler's region by itself and the regions that wait for an admin.
* usePaddleRegionsAdmin is the desktop card's state; this is only the markup.
* loads a paddler's region by itself and the regions that wait for an admin, as
* a row under the Tours addon that opens them in a sheet. The row counts the
* open requests, else the regions. usePaddleRegionsAdmin is the desktop
* dialog's state; this is only the markup.
*/
export default function MAdminPaddleRegionsPanel() {
const { t } = useTranslation();
const admin = usePaddleRegionsAdmin();
const [open, setOpen] = useState(false);
if (!admin.toursOn) return null;
const title = t('admin.paddleRegions.title');
// A declined request no longer waits for anyone; only the open ones ask for a look.
const waiting = admin.requests.filter((r) => !r.declined).length;
const badge =
waiting > 0 ? (
<MBadge caps={false} tone="strong">
{waiting}
</MBadge>
) : admin.regions.length > 0 ? (
<MBadge caps={false}>{admin.regions.length}</MBadge>
) : undefined;
return (
<MAdminCard>
<div className="flex items-start gap-3">
<span className="flex h-[38px] w-[38px] flex-none items-center justify-center rounded-[11px] bg-[color:var(--m-ic)] text-m-ink">
<Waves size={18} />
</span>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="min-w-0 truncate text-[length:calc(14px*var(--fs-scale-body,1))] font-extrabold text-m-ink">
{t('admin.paddleRegions.title')}
</span>
{admin.regions.length > 0 && <MBadge caps={false}>{admin.regions.length}</MBadge>}
</div>
<MAdminClampedText className="mt-[2px] text-[length:calc(10px*var(--fs-scale-caption,1))]">
{t('admin.paddleRegions.hint')}
</MAdminClampedText>
</div>
</div>
<>
<MAdminSetupRow label={title} onOpen={() => setOpen(true)} badge={badge} />
{open && (
<MSheet open onClose={() => setOpen(false)} variant="bottom" material="glass" ariaLabel={title}>
<MAdminSheetFrame icon={<Waves size={19} strokeWidth={1.8} />} title={title} onClose={() => setOpen(false)}>
<p className="m-0 font-geist text-[length:calc(10px*var(--fs-scale-caption,1))] leading-relaxed text-m-muted">
{t('admin.paddleRegions.hint')}
</p>
<PanelBody admin={admin} />
</MAdminSheetFrame>
</MSheet>
)}
</>
);
}
/** What the sheet holds: the state of the list, the settings, the requests, the search and the regions. */
function PanelBody({ admin }: { admin: Admin }) {
const { t } = useTranslation();
return (
<>
{admin.offline && (
<p
role="status"
@@ -462,6 +481,6 @@ export default function MAdminPaddleRegionsPanel() {
danger
onConfirm={admin.confirmRemove}
/>
</MAdminCard>
</>
);
}
@@ -6,7 +6,6 @@ import type { useAdmin } from '../../../pages/admin/useAdmin'
import MToggle from '../../components/MToggle'
import { MBlockDisclosure, MProviderBlock, MTrekApiBlock } from './MApiProviderBlocks'
import MAdminOidcCard from './MAdminOidcCard'
import MMailIngestAdminCard from './MMailIngestAdminCard'
import MAdminGoogleDailyLimit from './MAdminGoogleDailyLimit'
import MAdminPlaceContrib from './MAdminPlaceContrib'
import MAdminServiceQuota from './MAdminServiceQuota'
@@ -27,41 +26,22 @@ interface MAdminSettingsSectionProps {
t: TranslationFn
/**
* Which section this renders, cut the way the desktop tabs are: who may sign
* in and what it takes (security), what the install talks to outside
* (services), and the setup of the features the addons switch on (features).
* in and what it takes (security) or what the install talks to outside
* (services). Live flight status and the booking mail import are rows of the
* addon groups (MAdminAddonManager).
*/
part: 'security' | 'services' | 'features'
part: 'security' | 'services'
}
type PartProps = Omit<MAdminSettingsSectionProps, 'part'>
// The admin's security, services and feature setup sections as phone cards,
// The admin's security and services sections as phone cards,
// one function each. All state and mutations come from useAdmin.
export default function MAdminSettingsSection({ admin, t, part }: MAdminSettingsSectionProps) {
if (part === 'features') return <FeaturesPart admin={admin} t={t} />
if (part === 'security') return <SecurityPart admin={admin} t={t} />
return <ServicesPart admin={admin} t={t} />
}
/** Live flights and booking mails: how the integrations of the addons tab reach the world. */
function FeaturesPart({ admin, t }: PartProps) {
const { managed, flightLive, setFlightLive, flightLiveLocked, handleToggleAuthSetting } = admin
return (
<div className="space-y-3">
{/* Live flight status: open ADS-B data, no key, on by default (desktop parity). */}
<FlightLiveCard
t={t}
managed={!!managed}
on={flightLive}
locked={flightLiveLocked}
onChange={(v) => void handleToggleAuthSetting('flight_live_enabled', v, setFlightLive)}
/>
{/* Booking mail import: self-hosted only, the operator runs the TREK Cloud relay (desktop parity). */}
{!managed && <MMailIngestAdminCard />}
</div>
)
}
/** Who may sign in and what it takes, with the one destructive action last. */
function SecurityPart({ admin, t }: PartProps) {
const {
@@ -482,23 +462,3 @@ function ServicesPart({ admin, t }: PartProps) {
</div>
)
}
/** The live flight status switch, locked with a word when the server environment holds it. */
function FlightLiveCard({ t, managed, on, locked, onChange }: {
t: TranslationFn
managed: boolean
on: boolean
locked: boolean
onChange: (on: boolean) => void
}) {
return (
<MAdminCard>
<MAdminCardHead title={t('flightLive.adminTitle')} hint={managed ? t('flightLive.adminHintManaged') : t('flightLive.adminHint')} />
<MAdminRow
title={t('flightLive.adminToggle')}
hint={locked ? t('flightLive.envLocked') : undefined}
trailing={<MToggle checked={on} ariaLabel={t('flightLive.adminToggle')} disabled={locked} onChange={onChange} />}
/>
</MAdminCard>
)
}
+53 -1
View File
@@ -1,5 +1,5 @@
import { InputHTMLAttributes, ReactNode, useState } from 'react'
import { ChevronDown, Eye, EyeOff, Loader2, X } from 'lucide-react'
import { ChevronDown, ChevronRight, Eye, EyeOff, Loader2, Settings2, X } from 'lucide-react'
import { useTranslation } from '../../../i18n'
import MIconBtn from '../../components/MIconBtn'
import MHintLabel from '../../components/MHintLabel'
@@ -61,6 +61,58 @@ export function MAdminRow({
)
}
/**
* A row of the addons screen: the icon tile, the name with its description
* behind the info mark, and the switch. Addons and the instance options that
* sit with them (live flight status, booking mails) share it.
*/
export function MAdminOptionRow({
icon,
title,
hint,
trailing,
first = false,
}: {
icon: ReactNode
title: string
hint?: string
trailing: ReactNode
first?: boolean
}) {
return (
<div className={`flex items-center gap-3 py-[11px] ${first ? '' : 'border-t border-[color:var(--m-rowbr)]'}`}>
{/* overflow-hidden so a brand mark that fills the slot keeps its rounded corners. */}
<span className="flex h-[38px] w-[38px] flex-none items-center justify-center overflow-hidden rounded-[11px] bg-[color:var(--m-ic)] text-m-ink">
{icon}
</span>
<div className="min-w-0 flex-1">
<MHintLabel label={title} hint={hint} />
</div>
{trailing}
</div>
)
}
/**
* The last row under an addon that opens its settings: a gear, what it sets up,
* an optional badge for what waits inside, and a chevron (AI, booking mails,
* paddle water data).
*/
export function MAdminSetupRow({ label, onOpen, badge }: { label: string; onOpen: () => void; badge?: ReactNode }) {
return (
<button
type="button"
onClick={onOpen}
className="flex w-full items-center gap-3 border-t border-[color:var(--m-rowbr)] py-[11px] ps-[50px] text-start"
>
<Settings2 size={14} className="flex-none text-m-faint" />
<span className="min-w-0 flex-1 truncate text-[length:calc(12px*var(--fs-scale-body,1))] font-bold text-m-ink">{label}</span>
{badge}
<ChevronRight size={15} className="flex-none text-m-faint rtl:rotate-180" />
</button>
)
}
/**
* A description that keeps to two lines until it is tapped. On a phone the long
* ones (a map provider's terms, how a loader decides) pushed every control off
@@ -1,4 +1,5 @@
import { Inbox, Upload, Webhook, type LucideIcon } from 'lucide-react';
import { Inbox, Mail, Upload, Webhook, type LucideIcon } from 'lucide-react';
import { useState } from 'react';
import {
TRANSPORTS,
problemText,
@@ -15,15 +16,16 @@ import { useTranslation } from '../../../i18n';
import type { TranslationFn } from '../../../types';
import { relativeTime } from '../../../utils/relativeTime';
import MSegmented from '../../components/MSegmented';
import MSheet from '../../components/MSheet';
import MToggle from '../../components/MToggle';
import {
MAdminButton,
MAdminCard,
MAdminCardHead,
MAdminField,
MAdminInput,
MAdminRow,
MAdminOptionRow,
MAdminSecretInput,
MAdminSetupRow,
MAdminSheetFrame,
} from './MAdminUi';
interface PartProps {
@@ -250,19 +252,23 @@ function Setup({ admin, form, t, locale }: PartProps & { locale: string }) {
}
/**
* The booking mail import in the phone's admin settings, the same card as on
* the desktop (useMailIngestAdmin): the switch, how mail arrives, the address
* template, the AI allowance, the test and the status. Self-hosted only.
* The booking mail import as a row of the phone's integration group, the same
* as on the desktop (useMailIngestAdmin): the switch, and while it is on a row
* to the sheet that sets it up (how mail arrives, the address template, the AI
* allowance, the test and the status). Self-hosted only.
*/
export default function MMailIngestAdminCard() {
export default function MMailIngestAdminCard({ first = false }: { first?: boolean }) {
const { t, locale } = useTranslation();
const admin = useMailIngestAdmin(true);
const [open, setOpen] = useState(false);
const setupLabel = t('mailAdmin.setup');
return (
<MAdminCard>
<MAdminCardHead title={t('mailAdmin.title')} hint={t('mailAdmin.hint')} />
<MAdminRow
title={t('mailAdmin.enabled')}
hint={t('mailAdmin.enabledHint')}
<>
<MAdminOptionRow
icon={<Mail size={18} />}
title={t('mailAdmin.title')}
hint={`${t('mailAdmin.hint')} ${t('mailAdmin.enabledHint')}`}
first={first}
trailing={
<MToggle
checked={admin.enabled}
@@ -272,7 +278,18 @@ export default function MMailIngestAdminCard() {
/>
}
/>
{admin.enabled && admin.form && <Setup admin={admin} form={admin.form} t={t} locale={locale} />}
</MAdminCard>
{admin.enabled && admin.form && <MAdminSetupRow label={setupLabel} onOpen={() => setOpen(true)} />}
{open && admin.enabled && admin.form && (
<MSheet open onClose={() => setOpen(false)} variant="bottom" material="glass" ariaLabel={setupLabel}>
<MAdminSheetFrame
icon={<Mail size={19} strokeWidth={1.8} />}
title={setupLabel}
onClose={() => setOpen(false)}
>
<Setup admin={admin} form={admin.form} t={t} locale={locale} />
</MAdminSheetFrame>
</MSheet>
)}
</>
);
}
+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 m-corner-own relative h-dvh overflow-hidden">
<div ref={rootRef} className="m-bleed 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

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