* feat(plugins): grow the frame bridge — fill pages, confirm, openExternal, live context

- page/trip-page hosts pass fill: the frame pins to 100% height and ignores
  trek:resize, so a kit plugin's auto height report no longer collapses a full
  page into a floating island with dead space below (widgets keep self-sizing)
- trek:confirm renders the native ConfirmDialog host-side (the sandbox has no
  allow-modals) and answers trek:confirm:result; one at a time
- trek:openExternal opens validated http(s) URLs in a noopener tab — the
  sandbox has no allow-popups, so plugins simply couldn't link out before
- trek:notify accepts an optional duration, clamped to 1.5-15s
- context gains dir (rtl/ltr) and is re-pushed when locale or format settings
  change, not just on appearance mutations
- core events for the trip in view are forwarded as trek:event — names only,
  never payloads, mirroring the server-side events surface

* fix(plugins): move trip warnings out of the content area

The warning pills overlaid the top of every planner tab at full width, sitting
on the map and its toolbar. Now a warning from a plugin that owns a trip-page
tab renders as a compact chip in the navbar centre (click jumps to the tab; the
navbar centre is free on trip pages), and everything else floats above the
content at the bottom instead. Mobile keeps all warnings in the bottom overlay
since the desktop navbar isn't there. The trip tab's frame also opts into the
new fill mode.

* feat(plugin-sdk): 1.4.0 — motion library + new bridge helpers in the kit

Mirrors the host's animation vocabulary 1:1 into TREK_UI_CSS (menu/popover/
modal/backdrop/toast enters, drawer variant under 640px, page-enter, stagger,
skeleton shimmer, chart reveals) including the reduced-motion degrade to a
gentle fade. window.trek grows confirm(), openExternal(), onEvent() and a
notify duration, and applyContext now stamps lang/dir on the document so RTL
hosts get RTL plugin UIs.

* feat(plugins): surface registry download counts in browse

The registry now aggregates GitHub release download counts per plugin
(TREK-Plugins#18) as an entry-level downloadCount. Project it through
browse/detail and show it as a compact stat on the browse cards and in the
detail meta grid. Counts are raw asset downloads (updates and CI included),
so the UI says downloads, not installs.

* docs(plugins): document the grown bridge surface and motion classes

* fix(plugins): harden the new bridge paths

Review pass over the bridge additions:

- keep the unstable useToast() object out of the effect deps (ref instead) —
  it re-created the effect on every parent render, and with the new live
  repost that meant a trek:context flood into the frame
- reset loads/height/confirm state and key the iframe when a host swaps
  pluginId in place (tab bar, /plugins/:id) — the new plugin's document was
  refused as a 'navigated' frame and every kit promise hung
- confirm dialogs always lead with the host-controlled plugin name so a
  plugin can't dress its dialog up as a TREK system prompt; answer/refuse
  moved out of setState updaters (StrictMode ran them twice)
- Number.isFinite on the notify duration (NaN parked a sticky toast)
- don't forward other plugins' namespaced broadcasts as trek:event; a
  plugin's own plugin:{id}:* broadcasts now reach its frame though
- teach the SDK dev preview the confirm/openExternal contract so
  trek.confirm() resolves in /preview
- 999,950 downloads formats as 1M, not 1000k

* fix(planner): let plugin warning chips grow wider before truncating

The nav-centre chip capped at 340px, so a longer warning (e.g. the TREK x
Japan weather prompt) was ellipsised almost immediately. Scale it with the
viewport up to 520px so most messages read in full while still yielding on
narrow desktops.

* feat(plugins): sort the plugin browser by download count

Discover now honours the sort dropdown (it was always alphabetical) and adds
a 'Most downloads' option that ranks the registry by downloadCount. The sort
keys are scoped per tab — updates-first stays with Installed, most-downloads
with Discover — and snap back to name when the tab can't offer them.

* feat(plugin-sdk): auto-upgrade native <select> to a host-styled dropdown

A sandboxed plugin can't reach the host's components, and a native <select>
draws its popup from the OS — so plugin dropdowns never matched TREK. The design
kit now enhances every <select> into a keyboard-accessible listbox that uses the
kit tokens, keeping the real element as the value/form source (it still fires
change). Authors write a plain <select> and get the host look for free; opt a
field out with data-trek-native. validate warns when a plugin ships a <select>
without inlining the kit.

* feat(plugins): add issue url link

* feat(plugins): reservations write + cross-trip reads

- db:write:reservations -> reservations.create/update/delete, gated exactly like
  the REST/MCP path (reservation_edit + trip membership, acting user host-bound,
  no impersonation) and delegating to ReservationsService so the accommodation,
  budget-sync, booking-notification and reservation:* broadcasts match the web
  app 1:1 — a booking/flight/import plugin can finally write a reservation
- trips.listMine / reservations.listMine: enumerate every trip and booking the
  acting user can access (membership baked into listTrips, never a raw
  cross-tenant SELECT) — dashboards/aggregates were impossible before
- audit: derive auditability from METHOD_PERMISSION so a new capability method
  can't be added un-audited by omission
- typed ctx.reservations.* / ctx.trips.listMine, perm label (en/de), wiki

* feat(plugins): read scopes for journal, atlas, vacay and day notes

- db:read:journal / db:read:atlas / db:read:vacay expose the acting user's OWN
  journals / visited countries+regions / vacation plan across all their trips
  (user-scoped like costs.listMine, each gated on its addon being enabled),
  reusing the addon's existing readers
- db:read:daynotes -> daynotes.list(tripId, dayId), trip-scoped and
  membership-checked like the other trip reads
- typed ctx.journal / atlas / vacay / daynotes, perm labels (en/de), wiki,
  audit resource labels, tests

* feat(plugins): day notes write scope

- db:write:daynotes -> daynotes.create/update/delete, gated under the app's
  'day_edit' permission (like days) with the day verified to belong to the trip;
  reuses dayNoteService and broadcasts the same dayNote:* events so open
  sessions update live
- typed ctx.daynotes.create/update/delete, perm label (en/de), wiki, tests

* feat(plugins): run declared background jobs on a schedule

- plugins already declared jobs {id, schedule} but the cron was never wired. The
  host now schedules them: host-entry reports each job's schedule, the supervisor
  starts the jobs (node-cron) when the plugin goes active and stops them on
  kill/deactivate so nothing leaks
- opt-in via a new jobs:run permission — scheduled work runs with NO acting user
  (its trip reads stay refused; it can only use ctx.db and declared egress), so
  background execution is a distinct, admin-granted capability. Invalid crons are
  skipped and a throwing job can't break the host
- extracted a small, unit-tested scheduler (plugin-jobs.ts); perm label (en/de),
  wiki, tests

* feat(plugins): read scope for saved-place collections

- db:read:collections -> collections.listMine() / collections.get(id): the acting
  user's own collections (user-scoped, gated on the Collections addon), reusing
  collectionsService
- typed ctx.collections, perm label (en/de), wiki, audit resource labels, tests

* fix(plugins): translate new permission labels to all locales + cover the new wiring

- add the 8 new admin.plugins.perm.* labels (reservations/day-notes writes, the
  journal/atlas/vacay/day-notes/collections reads and jobs:run) to the remaining
  20 locales so the strict i18n key-parity test passes again
- cover the create-rpc-host reservation / day-note / cross-trip / addon-read deps
  (the real side-effect wiring the mocked rpc-host tests don't exercise) so the
  src/nest 80% branch-coverage gate holds

* feat(plugins): dev-link — hot-reload a local plugin against real data

Answers a plugin developer's ask: today you either get `trek-plugin-sdk dev`
(fast hot-reload but MOCK/fixture data) or the full build->pack->upload->activate
cycle (real data, no watcher). Neither gives "local dir + hot-reload + real data".

- POST /admin/plugins/link registers a plugin from a LOCAL built directory by
  symlinking it into the plugins volume — the loader already forks the resolved
  real path, so ZERO loader change — and registering it INACTIVE as `local:link`.
  Validates the manifest + refuses native binaries exactly like a sideload.
- POST /admin/plugins/:id/reload re-forks a linked plugin via the existing
  deactivate->activate primitive (same grants, no re-consent unless the manifest
  widened perms). A best-effort fs.watch auto-reloads on rebuild.
- It runs through the UNCHANGED capability RPC host: real, membership-gated data,
  acting user host-bound, no impersonation — code origin never touches the gate.
- Gated behind TREK_PLUGINS_DEV_LINK on top of admin + kill-switch, because a
  linked plugin bypasses the install-time signature model and, under `npm run
  dev`, the OS jail is off. Off by default; never reachable in production.
- discovery follows a symlinked <root>/<id>; uninstall/link never delete the
  author's source (link-safe removal for POSIX symlinks and Windows junctions).

* docs(plugins): document the dev-link real-data hot-reload workflow

Adds a "Test against a real instance's data (dev-link)" subsection next to the
mock-data SDK preview: TREK_PLUGINS_DEV_LINK, POST /link with a local built dir,
activate + consent, hot-reload via the file-watch / POST /:id/reload / Restart,
and the dev-only security caveats.

* feat(plugins): dev-link admin UI

- surface devLink (TREK_PLUGINS_DEV_LINK) in GET /admin/plugins so the panel shows
  the link form only where dev-link is enabled
- AdminPluginsPanel: a "Link a local plugin" form (path -> POST /link), a Dev-Link
  badge for source_repo=local:link, and adminApi.pluginLink/pluginReload
- fix: the plugin menu treated any non-local:upload source_repo as a GitHub repo,
  so a dev-linked plugin rendered github.com/local:link links — exclude local:link
- labels for the 6 new dev-link UI strings across all 22 locales

* docs(plugins): document the dev-link admin UI

The dev-link section showed only the curl call — surface the Admin → Plugins
"Link a local plugin" field (the primary path) and the Dev-link badge, with curl
kept as the scripting alternative.

* feat(plugins): enrich core events with { entity, entityId }

Subscribed plugins now learn WHICH entity changed, not just the event name — a
reservation/place/day/... id derived host-side from an explicit per-family
whitelist. Threaded through the six event hops WITHOUT touching actingUserId: the
handler still runs with no user, so the id is not dereferenceable (a trip read is
still refused; the id says what to react to, not what it contains). A non-entity id
can never surface — budget:member-paid-updated yields the itemId, never the userId
— and bulk/reorder/sub-entity payloads carry no id. The mapper is pure, synchronous
and never throws into the core broadcast. No new permission (reuses
events:subscribe); backend-only.

* feat(plugins): packing write scope with #858 privacy-scoped broadcasts

- db:write:packing -> packing.create/update/delete, gated under the app's
  'packing_edit' permission (like the REST path) with the host-bound acting user
  as owner; reuses packingService
- replicates the packing privacy model 1:1 (the controller/service helpers aren't
  exported): create/delete fan out to the item's viewers only (owner + recipients,
  or the whole room for a Common item); update runs the four public<->private
  transitions, dropping a freshly-privatized item from the room BEFORE re-adding it
  owner-only so it never leaks. A stale write is BAD_PARAMS with no broadcast
- typed ctx.packing.create/update/delete, perm label (22 locales), wiki, tests
  (rpc-host gating + the four transitions + owner-scoped delete)

* feat(plugins): tableContributor hook — host-rendered view columns/actions (backend)

The registry backend for plugin-contributed columns/actions in the native planner
views (the tabular-reservations use case), mirroring placeDetailProvider:
- hook:table-contributor + the tableContributor hook (getContributions(view,
  tripId, ctx) -> TableContribution[]), double-gated (implement + grant) like the
  other provider hooks
- GET /api/view-contributions/:view/:tripId — view whitelist + membership gate +
  per-provider timeout/fail-safe, plus the hardening the older provider hooks lack:
  every field is String-coerced + length-capped, kind/tone/target enum-whitelisted,
  per-provider counts capped (<=20 columns / <=10 actions), and a column url must be
  http/https/mailto (a javascript:/data: url is click-XSS into the native DOM)
- typed pluginsApi.viewContributions + the ViewContribution union, perm label
  (22 locales), wiki, hardening tests

* feat(plugins): render tableContributor columns/actions in the reservations view

The frontend for the tableContributor hook: a reusable PluginContributions layer
(usePluginViewContributions + PluginColumns/PluginActions) that renders the
host-normalized column/action leaves NATIVELY — a column is text/badge/link, an
action is a button that calls the plugin route or opens its sandboxed frame in a
modal (plugin markup only ever runs inside the opaque-origin iframe). Wired into the
reservations cards (both ReservationCard and TransitJourneyCard) as a strictly-
additive footer keyed by reservation id: zero change to a card when no plugin
contributes. Fetched once per view, fail-safe.

* docs(plugins): bring the permissions wikis current with this cycle

Plugin-Permissions.md was missing every permission added this cycle — add rows for
the read scopes (journal/atlas/vacay/daynotes/collections), the write scopes
(reservations/daynotes/packing, packing noting the #858 owner-scoping), jobs:run
and hook:table-contributor, and correct the events:subscribe row for the new
{ entity, entityId } hint. Add the jobs:run row to Plugin-Development.md too.

* fix(maps): stop quick one-finger pans zooming the map on mobile (#1440)

The global drag-drop-touch polyfill installs document-level touch listeners
on phones. On every single-finger touchend it records a timestamp, and if the
next touch starts within 500ms it synthesises a dblclick on the target, which
the map's default double-click-zoom turns into a zoom-in. Two quick one-finger
pans therefore zoomed instead of panning.

The polyfill only bridges HTML5 drag-and-drop to touch for planner reordering,
which is already disabled on mobile (#1432), so gate its import to viewports
>=1024px (the lg breakpoint useIsMobile uses). Removes the phantom-dblclick
source on phones while keeping touch DnD on large viewports; fixes both the
Leaflet and GL renderers.

* fix(feeds): emit TZID + VTIMEZONE so subscribed calendars respect time zones (#1453)

exportICS emitted timed DTSTART/DTEND as bare floating times (no Z, no TZID),
which iOS/Google Calendar render in the subscriber's local zone instead of the
zone TREK shows. Resolve an IANA zone per timed event — transport endpoints use
their stored timezone (departure drives DTSTART, arrival drives DTEND), while
assignments and hotel/restaurant reservations derive it from place coordinates
via tz-lookup — and attach TZID backed by a VTIMEZONE component. The all-trips
feed now carries deduped VTIMEZONE blocks so TZID references still resolve.

* feat(plugins): render tableContributor contributions in the places + day views

Extends the tableContributor frontend to all three planner views: hoist the shared
PluginCardFooter into PluginContributions, wire the places sidebar (keyed by place
id, rendered as a sibling after each row so the drag/scroll row stays untouched)
and the day panel (keyed by day id, guarded for a null day). Strictly additive +
fail-safe like the reservations view — nothing renders when no plugin contributes.

* fix(vacay): source holiday subdivisions from ISO 3166-2 so all states show

The state/region picker for public-holiday calendars was built from the
union of each holiday's counties for the current year, so a subdivision
only appeared if some holiday that year was tagged with it. States with
no state-specific holiday (e.g. US-WA, and AR/FL/NV/WY in 2026) silently
vanished, blocking calendar creation (#1456).

Source the full, correctly-named subdivision list per country from
ISO 3166-2 instead, merged with any nager county code ISO lacks. Only
region-partitioned countries get a picker, so nationwide-only countries
keep allowing a country-level calendar. No server change needed —
selecting a state already yields federal holidays via applyHolidayCalendars.

* fix(costs): settlements honor custom per-member splits (#1458)

calculateSettlement read each member's custom split amount but its query
never selected budget_item_members.amount, so hasCustomSplit was always
false and every settlement fell back to the equal split. Select bm.amount
so custom amounts drive the balances.

Also blank the Overview 'Per Person' / 'Per Person·Day' columns and CSV
for custom-split items, where a single averaged figure is meaningless.

* feat(plugins): read-convenience + todos + packing bags + tags + roster

A wave of small, high-value capabilities:
- weather:read (ctx.weather.get) — the host's cached forecast, tenant-free
- db:read:categories (ctx.categories.list) — the global place-category list
- db:read:tags / db:write:tags (ctx.tags) — the acting user's own tags, ownership
  re-checked before each write
- trips.members (ctx.trips.members) — the trip roster (id + display fields),
  membership-checked
- db:read:todos / db:write:todos (ctx.todos) — a trip's to-dos, gated by the app's
  packing_edit like the REST path, broadcasts todo:*
- packing bags on ctx.packing (listBags/createBag/updateBag/deleteBag/setBagMembers)
  under db:write:packing — no privacy, plain room broadcasts
perm labels (22 locales), both wikis, rpc-host gating + create-rpc-host wiring tests

* fix(dashboard): render next-trip boarding pass stats on Safari (#1459)

The boarding-pass bar carved its ticket-stub notches with a two-layer
radial-gradient mask composited via mask-composite: intersect (and legacy
-webkit-mask-composite: source-in). Safari mis-composites that multi-layer
path to fully transparent, hiding the entire stats bar while Chrome renders
it fine.

Split .hero-pass into an outer wrapper (left notch) and a .hero-pass-inner
glass panel (right notch), each carrying a single-layer mask so the
mask-composite path is never exercised. Renders identically across engines
and degrades safely where mask-image is unsupported.

* feat(plugins): write scopes for atlas, vacay, journal and collections

The write half of the user-scoped addon reads:
- db:write:atlas -> ctx.atlas.markCountry/unmarkCountry/markRegion/unmarkRegion +
  bucket-list create/delete. Every row is the acting user's own (visited_countries/
  visited_regions/bucket) — no trip scoping, no cross-tenant surface. Unblocks
  AirTrail-style two-way sync (#214)
- db:write:vacay -> ctx.vacay.toggleEntry/toggleCompanyHoliday. The plan is
  resolved HOST-SIDE from the acting user's active plan — a plugin can never name
  another plan, and toggleEntry only toggles the acting user's own PTO day
- db:write:journal -> ctx.journal.createEntry/updateEntry/deleteEntry, self-gated
  by journeyService.canEdit (owner/contributor) against the acting user
- db:write:collections -> ctx.collections.create/update/savePlace/copyToTrip/
  deletePlace, schema-validated; the service's per-collection role checks
  (assertAccess 404 / assertCanEdit 403) map onto RESOURCE_FORBIDDEN
All addon-gated, userless contexts refused, audited. Perm labels (22 locales),
both wikis, gating + wiring tests.

* fix(admin): name the Costs add-on consistently in the catalog

The budget add-on catalog entry still resolved to 'Budget' while the
feature is labeled 'Costs' everywhere else (trip tab, navbar). Align
admin.addons.catalog.budget.name with each locale's trip.tabs.budget
label. Closes #1464

* feat(plugins): file attach, collab content and gated member-add

- db:write:files -> ctx.files.create/createLink/update/softDelete under the app's
  separate file_upload/file_edit/file_delete rights. Content arrives as bounded
  base64 (10MB decoded cap, well under the app's 50MB), the extension is validated
  against the central blocklist BEFORE anything touches disk, and link targets
  must live on the same trip (findForeignLinkTarget). Broadcasts file:*
- db:write:collab -> ctx.collab.createNote/createPoll/votePoll/createMessage
  under collab_edit + the Collab addon, emitting the same collab:* events as the
  app; service-reported errors surface as BAD_PARAMS
- db:write:members -> ctx.trips.addMember. Adding a member GRANTS TRIP ACCESS, so
  it is deliberately its own permission behind the app's member_manage right
  (default: trip owner only) and never bundled with a lower-risk write; the acting
  user is recorded as the inviter, target must exist, owner/duplicate adds no-op
Perm labels (22 locales), both wikis, gating + wiring tests.

* fix(maps): honor check-in/out times for hotel bookend legs (#1465)

The day route drew the accommodation as the day's start/end whenever the
edge stop was a place, ignoring the morningIsSleptHere/eveningIsOvernight
provenance already computed by getDayBookendHotels. On a check-in day an
airport placed before check-in got a spurious hotel -> airport leg, and on
a check-out day a later "home" stop still got a home -> hotel return leg.

Add time-aware shouldDrawMorningLeg/shouldDrawEveningLeg helpers: the
morning leg is the home-base default on a check-in day but is dropped when
the first place is timed before check-in; the evening return leg is off on
a check-out day unless the last place is timed at/before check-out. Wire
them into the map polyline, the sidebar hotel connectors, and the Google
Maps export so all three stay consistent.

* feat(plugins): host-mediated notifications and LLM access

Two host-owned integration primitives — the plugin supplies intent, the host
owns the sensitive part:

- notify:send -> ctx.notify.send({title, body, link?, scope, targetId}). Delegates
  to notificationService.send with a new plugin_notification event (raw title/body
  carried as passthrough params), so recipient resolution, channel fan-out
  (bell inbox + email/ntfy/webhook) and per-user preferences all match core 1:1.
  Recipients are FORCED to the acting user (scope 'user', targetId === uid) or a
  trip they belong to (scope 'trip'); scope 'admin' refused; the in-app link must
  be a relative /path (open-redirect-safe). No arbitrary recipient, no impersonation.
  Users can mute plugin notifications like any other event.
- ai:invoke -> ctx.ai.complete(prompt) / ctx.ai.extract(text, jsonSchema). Runs the
  admin/user-configured provider via resolveLlmConfig + the existing extraction
  client under the acting user; the host holds the (encrypted) key, the plugin
  never sees it. Refused when no provider is configured; 20k-char caps. Output is
  DATA (complete -> {text}, extract -> {results}) and never auto-written, so
  prompt-injection can't reach a write without the plugin's own gated call.

plugin_notification wired through the shared NotificationEventKey + all 22 locales
(inbox passthrough + external channels). Perm labels (22 locales), both wikis,
gating + wiring tests.

* fix(budget): offer every Frankfurter-supported currency (#1470)

The cost currency picker was gated by a hardcoded 47-code list, so
currencies the app can actually convert (OMR, CRC, UGX, MKD, ALL, and
~115 more) couldn't be selected. Replace CURRENCIES/SYMBOLS with the full
set the Frankfurter v2 FX API supports (archived BGN/HRK dropped), unify
the dashboard offline fallback onto it, and teach currencyDecimals about
the newly reachable zero- and three-decimal currencies. A currenciesWith
helper keeps a previously saved (now-archived) selection selectable so it
isn't silently wiped.

* feat(plugins): tableContributor into the costs, packing and files views

Extends the shipped tableContributor hook to three more native views — no new
permission, no new attack surface: the same host-normalized, length-capped,
url-allowlisted (http/https/mailto), enum-bounded, fail-safe pipeline, just more
render sites.

- server: add costs/packing/files to the view-contributions whitelist
- client: widen the ViewName union + the api view type; render PluginCardFooter
  keyed by entityId in the budget category table (a colSpan footer row per item),
  the packing category group (footer after each item row, drag untouched) and the
  files list (footer after each row)

A currency plugin can now drop a converted-amount column onto a cost row, a
receipts plugin a 'view receipt' action onto a file, etc. Controller test asserts
the three new views are accepted; both wikis updated.

* fix(pdf): repeat day header on overflowing itinerary export pages (#1471)

* feat(plugins): map-marker provider hook — plugins can overlay trip-map markers

New declarative provider hook `mapMarkerProvider` (#587 "show bookings on map",
the single most-requested contribution class, with zero contribution point until
now):

- hook:map-marker-provider permission + MapMarkerProvider/MapMarkerContribution SDK
  types + HOOK_PERMISSION wiring
- GET /api/map-markers/:tripId (MapMarkersController) mirrors the view-contributions
  hardening: membership-gated, providers invoked host->plugin on a 5s timeout,
  fail-safe. Every field normalized server-side — coordinates range-checked
  (-90..90 / -180..180), strings String-coerced + length-capped, icon/tone enum-
  whitelisted, popup url http/https/mailto only (a javascript:/data: url would be
  click-XSS), marker count capped at 200 per plugin
- client: PluginMapMarkers layer renders the markers as plain Leaflet Marker+Popup
  inside the trip map; plugin JS NEVER runs on the map canvas, every value is
  host-vetted data. Threaded tripId through MapView; fail-safe fetch

Declarative-only by design, mirroring placeDetailProvider/tableContributor. Perm
label (22 locales), controller hardening test, both wikis.

* feat(plugins): show page plugins in the mobile bottom nav

Page plugins were reachable from the desktop nav pill (Navbar) but not the mobile
tab bar — you had to type /plugins/:id. BottomNav now reads page plugins from the
plugin store and appends them the same way global addons are, mirroring Navbar.
One-file client nav wiring; no new capability surface.

* feat(plugins): per-user plugin settings form + ctx.settings runtime read

Users can now enter their own per-plugin config (an API key, a preference) —
the prerequisite for almost every real integration, previously unreachable
(scope:'user' settings were only listed read-only in the admin panel).

- migration: plugin_user_config (plugin_id, user_id, config JSON) — each user's
  own values, separate from the admin-owned instance plugins.config
- PluginsService.getUserConfig / updateUserConfig / getUserConfigDecrypted +
  readUserSettingDecrypted: secrets encrypted at rest (apiKeyCrypto), masked to
  the client, an unchanged secret (the mask) keeps its stored ciphertext, and only
  DECLARED scope:'user' keys are ever stored
- GET/POST /api/plugin-settings/:id (PluginUserSettingsController) — its own
  user-gated path (not the admin surface, not the /:id/* proxy), JwtAuthGuard only,
  scoped to the acting user
- runtime: ctx.settings.get(key) -> the acting user's decrypted value (unconditional
  RPC, not sensitive cross-tenant; userless job/onLoad gets undefined)
- client: a Plugins tab in Settings host-renders each active plugin's scope:'user'
  fields as an editable form (secrets write-only), reusing the declarative field
  shape — no plugin markup executes

i18n (22 locales), wiki, rpc-host + service + masking/encryption tests.

* fix(journey): keep skeleton suggestions in sync with linked trip places (#1473)

Journey skeleton suggestions mirror a linked trip's day-assigned places, but
sync relied on scattered per-event hooks that several assignment mutation paths
never called: unassign, move and time-change fired nothing, no remove-on-unassign
capability existed, and every MCP assignment tool synced nothing. Skeletons drifted
from the trip.

Add an idempotent reconcileTripSkeletons(tripId) that re-mirrors the trip's
day-assigned places onto every linked journey (add missing skeletons, refresh
date/time/location on move, remove skeletons for unassigned places; filled entries
are detached + noted, never destroyed). Call it from every REST assignment handler
and MCP assignment tool, and fire onPlaceDeleted on single MCP delete_place for
parity. Extract a shared insertSkeletonEntry helper.

* fix(memories): drop hidden Immich assets so Live Photo motion parts don't show a broken thumbnail (#1474)

* fix(transit): anchor arrive-by search time to the destination timezone (#1479)

* feat(plugins): host-brokered OAuth client + trustworthy inbound webhooks

Two integration primitives where the host owns the sensitive part.

Trustworthy webhooks:
- auth:false routes now receive req.headers, but ONLY an explicit, credential-free
  allowlist (the common provider signature/event headers — stripe-signature,
  x-hub-signature-256, svix-*, x-gitlab-event, …). Cookie/Authorization/X-Socket-Id
  and every session/forwarded-auth header are stripped; authenticated routes get {}.
  A plugin can finally verify a provider signature without any way to leak a session.

Host-brokered outbound OAuth (oauth:client):
- the HOST runs the whole flow — authorize -> callback -> token exchange -> refresh —
  with PKCE + single-use, user-bound, TTL'd state, and HOLDS the tokens. The client
  secret + refresh token never leave the host; the plugin only triggers connect and
  reads a short-lived access token via ctx.oauth.getAccessToken() for the acting user.
- provider config (authorize/token url + scopes + client id/secret) is the plugin's
  admin-owned instance settings; endpoints must be https (SSRF backstop, private/local
  hosts refused). Tokens per-user + encrypted at rest (apiKeyCrypto).
- GET/POST /api/plugin-oauth/:id/{status,connect,callback,disconnect} — JwtAuth-gated,
  the callback always redirects to an in-app /settings path (never leaks an error).
- Settings -> Plugins gains a Connect/Disconnect control per configured plugin.

migration: plugin_oauth_tokens + plugin_oauth_state. Perm labels + form strings
(22 locales), both wikis, service (PKCE/state/exchange/refresh/encrypt) + controller
+ proxy header-allowlist + rpc-host gating + create-rpc-host wiring tests.

* fix(navbar): re-measure sliding tab pill after font load and resize (#1481)

The active tab pill was measured once in a layout effect keyed only on activeTab, so on a hard reload it captured the active (bold) label's width against fallback-font metrics and never re-ran when the web font swapped in, leaving the pill slightly offset.

Re-measure after document.fonts.ready resolves and on ResizeObserver changes (container + active button), with an idempotent state update to avoid redundant renders.

* fix(collections): keep the Add-place button reachable after the first save

On a wide/desktop layout the collection toolbar (which hosts the Add
button) was gated on !mapOverlay, so it unmounted as soon as the list
gained its first place with coordinates — leaving only an easy-to-miss
"+" in the map overlay. Keep the toolbar rendered whenever the user can
add a place, and drop the now-redundant map-overlay Add button so there
is a single, predictable Add affordance in every state.

Fixes #1485

* feat(plugins): days + accommodations reads/writes, endpoints on the reservation write path

Community feedback on the 3.2.1 plugin surface: a plugin could write days but
never list them (no way to learn day ids), day_accommodations had no surface at
all, and trips.getReservations was the one reservation read that dropped the
endpoints/day_positions hydration.

- trips.getDays / trips.getAccommodations under db:read:trips (tripRead gate),
  wired to the same dayService lists the REST GETs use
- trips.getReservations now returns the hydrated REST-parity list (endpoints,
  day_positions, joins, normalized accommodation_id) - strict superset
- new db:write:accommodations scope: ctx.accommodations create/update/delete
  gated by day_edit like the accommodations REST path, with the partner-hotel
  reservation + delete cascade and broadcasts intact
- reservation create/update pin the endpoints shape up front (BadParams instead
  of a mid-transaction NOT-NULL or a silently dropped row)
- perm label in all 22 locales, consent PERM_KEYS, wiki tables

* feat(plugins): day-detail widget slot in the day panel

Widgets can now mount inside the trip planner's day panel
(capabilities.widget.slot: 'day-detail'), scoped to the open day via a dayId in
trek:context - the same pattern as the place-detail slot. Covers the requested
per-day plugin content (logistics, outfit planning, live flight status) without
a new plugin type. Day-detail widgets stay off the dashboard, the consent panel
labels the slot in all 22 locales.

* feat(plugins): let the frame CSP serve a plugin's own static assets

The sandboxed frame runs at an opaque origin, so script-src 'self' never
matched and a plugin's own <script src>/<link> files were blocked - authors had
to inline entire React builds into index.html. Add a scheme-less host-source
pinned to the plugin's own /plugin-frame/<id>/ path (charset-checked Host +
plugin id so a stray token can't widen the policy; malformed Host falls back to
inline-only). Multi-file client builds now load as-is; remote hosts stay
blocked, so script URLs remain useless as an egress channel.

* fix(plugin-sdk): catch the package up to the server capability surface

The npm SDK's validator still knew only the 3.2.1 permission set, so
'trek-plugin-sdk validate' (and pack/publish, which run it) hard-rejected any
manifest using the newer scopes - db:write:reservations, notify:send,
hook:map-marker-provider and 25 more. Sync KNOWN_PERMISSIONS with the server
envelope (48 entries), mirror the full PluginContext (reservations,
accommodations, notify/ai/oauth/settings, packing writes + bags, file writes,
collab, tags/todos/daynotes/collections/atlas/vacay/journal, weather,
categories), type the tableContributor/mapMarkerProvider hooks + the
entity/entityId event hint, accept the day-detail widget slot, and extend
createMockHost so plugin unit tests can exercise all of it.

* feat(plugins): grant-scoped entity snapshots on core events

An events:subscribe handler so far learned only WHICH entity changed - useful
for cache busting, useless for reacting to content, and the userless handler
can't refetch. Now the broadcast tap derives a whitelisted field snapshot of
the changed entity and the supervisor attaches it per plugin, only where the
granted set holds the family's matching db:read:* permission (trips family ->
db:read:trips, budget -> db:read:costs, packing -> db:read:packing, dayNote ->
db:read:daynotes, file -> db:read:files). No acting user is ever synthesized.

The whitelists are explicit per family, so user ids (owner/paid_by/uploaded_by/
participants/members), trips.feed_token and future migration columns never
travel; a private packing item (#858) yields no snapshot at all because its
core broadcast is owner-scoped; deletes/reorders/bulk ops carry none.

* feat(plugins): pdf-section, atlas-layer and journal-entry provider hooks

Three more declarative provider surfaces in the map-marker mould - plugins
return data specs, the host normalizes, caps and renders; a slow or failing
provider contributes nothing:

- hook:pdf-section-provider: sections (title + paragraphs + a simple table)
  appended to the trip PDF export, escaped into the same HTML/print pipeline
  as the core content
- hook:atlas-layer-provider: per-user country tint layers on the Atlas map
  (ISO 3166-1 alpha-2 codes only, tone-whitelisted, non-interactive pane so
  mark/unmark clicks keep working)
- hook:journal-entry-provider: extra rows on a journal entry card, gated by
  the same journey access check as the journal routes + the Journey addon

Permission labels in all 22 locales, consent PERM_KEYS, SDK types + manifest
validator in both SDK copies, wiki tables, per-controller hardening tests.

* feat(plugins): trip-page plugins can replace core planner tabs and pick their spot

A trip-page plugin that takes over a core surface (a transit planner
superseding Transports, a costs plugin superseding the budget tab) had to sit
awkwardly next to the tab it replaces. capabilities.tripPage now names the
core tabs to hide while the plugin is active - whitelisted (transports,
buchungen, listen, finanzplan, dateien, collab), 'plan' deliberately not
replaceable, and the tabs return the moment the plugin is deactivated - plus
an optional 0-based position for the plugin's own tab. The feed re-validates
the values out of the DB blob so a hand-edited row can't hide anything else,
the admin list chips a replacing plugin (all 22 locales), and a saved session
tab that got replaced falls back to the plan view.

Also fixes the plugins feed dropping the day-detail widget slot to 'sidebar',
which would have mounted a day-panel widget on the dashboard.

* fix(plugins): audit follow-ups — normalization, secret cleanup, cron leak, slot filter

Adversarial audit of the whole plugin PR surfaced 12 confirmed issues; this
addresses them:

- place-details provider was the ONE hook controller with no normalization: a
  plugin's href/label/value went to the client raw and unbounded. Now normalized
  like journal-entry-rows (safeUrl http/https/mailto, length + count caps).
- trip-warnings capped message length + per-provider count (was unbounded).
- uninstall(deleteData) now also purges plugin_user_config, plugin_oauth_tokens,
  plugin_oauth_state, plugin_meta_migrations and the capability audit — encrypted
  per-user API keys + OAuth refresh tokens no longer survive a 'delete all data'
  and get silently re-adopted on a same-id reinstall.
- supervisor: a crash-restart cycle leaked the dead child's node-cron tasks and
  re-scheduled fresh ones, so a job fired N+1 times per tick after N crashes.
  onExit now stops them, mirroring kill().
- dashboard sidebar no longer mounts place-detail/day-detail widgets (they belong
  in the planner panels).
- reservation endpoint validation relaxed to match the 3.2.1 service: a coord-less
  endpoint is accepted and dropped downstream instead of BadParams (no breaking
  change), while a bad role/non-string still rejects up front.
- a replaced core tab reached by programmatic nav now falls back to the plan view.
- trips.update caps title/description like the places path; plugin-db guard bans
  load_extension as defense-in-depth.
- wiki: event snapshots, string-typed context ids, dayId in the payload, the live
  provider hooks and the costs update/delete grant are now documented correctly.

* feat(plugins): phase-0 lifecycle hardening + per-plugin RPC rate limit

Operational-readiness fixes from the completeness audit:

- Re-activation after a failure worked again: a plugin left in 'error' state by
  a load-failure or crash-auto-disable stayed in the running map, so the admin's
  'enable' button was a silent no-op. activate() now replaces a dead entry.
- Per-plugin RPC rate limit at the dispatch boundary: every ctx.* call runs
  synchronously on the host thread, so a plugin in a tight loop could freeze the
  whole instance (and the reap sweep). A token bucket (generous burst) + an
  in-flight cap now throttle a runaway plugin with a retryable HOST_ERROR; a
  legitimate plugin never notices.
- plugin_error_log retention (500 rows/plugin) so a crash-looper can't grow
  trek.db without bound; the crash-timestamp array is trimmed to its window too.
- TREK_PLUGIN_PERMISSIONS=off now logs a loud one-time warning that the OS
  permission jail is disabled.

* feat(plugins): read symmetry + broker — collab/journal/atlas reads, file content, trip create, rates

The plugin API leaned write-heavy: collab and journal could be written but not
read, files listed but not read, and there was no way to create a trip or see
exchange rates. This closes those gaps in the established RPC+gate pattern (zero
architecture risk), and it's what unlocks the importer + finance plugin classes:

- collab reads: ctx.collab.listNotes/listPolls/listMessages under a new
  db:read:collab (membership + Collab addon, like the REST GETs)
- ctx.journal.getEntries(journeyId): a journey's entries, journey-access-checked,
  under the existing db:read:journal
- ctx.atlas.bucketList(): the acting user's bucket list, under db:read:atlas
- ctx.files.getContent(tripId, fileId): a file's bytes as base64 under a NEW
  db:read:files:content grant (reading a passport scan is more sensitive than its
  filename), size-capped at 10MB before it crosses the IPC pipe, trashed files
  refused
- ctx.trips.create(input): a new trip owned by the acting user, gated by the app's
  trip_create right + a bound user — the capability importers need
- ctx.rates.get(base): cached currency exchange rates, tenant-free like weather

Also caps trips.update title/description like the places path, and the plugin-db
guard now bans load_extension (defense-in-depth). SDK, mock-host, i18n (22
locales), consent labels and the wikis are all in lockstep.

* feat(plugins): deeper integration + user-facing activity transparency

Wave 2 of the completeness work — richer extension points, deeper metadata, and
the transparency that makes the broad read grants accountable:

- db:meta now attaches to reservations + accommodations too (not just
  trip/place/day), gated by reservation_edit / day_edit respectively — the
  natural home for an external-id mapping (AirTrail/calendar/booking-import sync)
  without forking the core schema.
- reservation-detail widget slot: a widget can mount on a booking card, scoped to
  the open reservation via reservationId in trek:context (the place-detail /
  day-detail pattern, third instance).
- tableContributor gains the transports + todos views, so a plugin can add
  host-rendered columns/actions there too.
- User activity log: GET /api/plugin-activity + a Settings → Plugins panel showing
  every host-mediated action a plugin took bound to the signed-in user, across all
  plugins, newest first — the user-facing half of the hash-chained audit. This is
  what legitimizes the deliberately broad read grants: not just the admin, the
  person whose data is read can see what was done in their name.
- DX: the local dev server now binds a default acting user, so the canonical
  ctx.trips.getPlaces(tripId) call works locally instead of failing RESOURCE_
  FORBIDDEN; the create scaffold drops the dead manifest routes[] / capabilities.nav
  fields the host ignores.

SDK, i18n (22 locales), consent labels and the wikis are all in lockstep.

* fix(memories): load Immich album photos on Immich v3

Immich v3 removed the `assets` property from AlbumResponseDto, so
`GET /api/albums/:id` no longer carries album contents. TREK read album
photos from that property, which now parses as undefined and degrades to
an empty array — hence "No photos yet" in the Journey gallery picker even
though the album header shows the right count (that count comes from
`GET /api/albums` -> assetCount, which v3 still returns).

Two call sites read the removed property. Besides getAlbumPhotos (the
reported bug), syncAlbumAssets failed silently on v3: it reported
`success: true, added: 0` while syncing nothing.

Fetch album contents via an `albumIds`-filtered `POST /api/search/metadata`
when `assets` is absent, and feature-detect rather than probe a version.
The two paths are not interchangeable: on v2, searchMetadata
unconditionally scopes results to `[self, ...partners]`
(`asset.ownerId = ANY(userIds)`), so an albumIds search against an album
shared by a non-partner returns nothing. v3 added an albumIds branch that
checks AlbumRead and skips that owner filter. v2 also hard-defaults
`visibility` to `timeline`, dropping archived assets. So v2 must keep
reading the album detail body, which this preserves exactly.

`withExif: true` is required on the search path: it has no default and
gates an inner join, so without it Immich omits `exifInfo` entirely and
every photo's city/country goes null.

The existing test mock returned an album detail body *with* `assets` — it
encoded the v2 assumption, which is why this shipped green. It now models
v3 by default, with explicit v2 coverage asserting no search call is made.

Fixes #1492

* feat(plugins): daily AI/notify budgets, runtime scheduler & reliable event redelivery

Per-plugin daily caps on ai.complete/ai.extract and notify.send (defaults
200 / 100, overridable via TREK_PLUGIN_AI_PER_DAY / TREK_PLUGIN_NOTIFY_PER_DAY),
seeded from the capability audit so a mid-day restart resumes the count instead
of resetting it. Surfaced at GET /plugins/:id/budget.

ctx.scheduler (at / in / every / cancel): persistent, userless timers that
survive restarts and fire a scheduled() handler, riding the existing jobs:run
grant so no new consent or admin setup is needed. Backed by
plugin_scheduled_tasks, swept every 30s, capped at 100 tasks/plugin with an 8 KB
payload and a 60s recurring floor; rows are removed on uninstall.

Core events that fire while a subscriber is mid-restart are now held in a
bounded in-memory buffer (200/plugin, 15 min TTL) and replayed once it goes
active again, with the events:subscribe grant and snapshot gating re-evaluated
at replay time so nothing leaks if a grant was revoked while the plugin was down.

* feat(plugins): GDPR data-subject rights — durable per-plugin erasure + export

New hook:user-data grant with two userless lifecycle handlers a plugin can put
on its definition: deleteUserData and exportUserData. Neither carries an acting
user — the plugin only learns the userId and touches its own db — so the grant
reads nothing from core data; it exists purely so a plugin can honour a GDPR
erasure or data-access request.

When a TREK account is deleted (admin or self-service), every installed plugin
holding the grant gets a row in a new durable erasure queue and its
deleteUserData runs on the next sweep, retried until it ACKs — so erasure
survives the plugin being offline or the server restarting. The core deletion
path notifies the runtime through a dependency-free relay (like the event sink),
keeping the auth/admin services decoupled from the plugins layer, and a plugin
bookkeeping error can never fail the account deletion.

Portability is served by GET /api/admin/plugins/user-data/:userId/export, which
fans exportUserData out to the active granted plugins and aggregates what each
holds about the user. Queue rows are purged on uninstall; the grant is labelled
in all 22 locales.

* feat(plugins): atomic ctx.db.tx for consistent multi-write on a plugin's own db

Plugins could already query/exec/migrate their own SQLite file, but a multi-step
write (move an item between tables, decrement one row and increment another) had
no way to be atomic. db.tx([{sql, args?}, …]) runs up to 100 statements in a
single transaction — all commit or all roll back — and reads within the batch see
its own earlier writes, so read-modify-write is safe. Each op is one statement:
a read returns { rows }, a write { changes }. The same guard (no ATTACH/PRAGMA/
RECURSIVE, size + row caps) applies to every statement in the batch.

* fix(memories): filter hidden Immich assets at the source, not just the picker

#1474 has the same root cause as #1492: the Immich v3 migration. On v2,
searchAssetBuilder hard-defaulted metadata search to `timeline` visibility
(`visibility = options.visibility ?? Timeline`), so hidden Live Photo
motion parts could never come back from a search. v3 defaults to any
visibility except `locked`, so they do — which is why the reporter is on
Immich 3.0.1 and why the bug never appeared before.

Ask for `visibility: 'timeline'` explicitly on the search path. That
restores v2 semantics on both versions and stops hidden assets crossing
the wire, which also fixes a pagination wart: a full page half-made of
motion parts previously rendered as a half-empty page, because hasMore
counts the raw page length while the filter shrinks the rendered set.

The client-side filter was display-only, applied in searchPhotos and
getAlbumPhotos — both picker-listing paths. Nothing guarded persistence
or rendering: getOrCreateTrekPhoto stores any id it is handed, pipeAsset
forwards Immich's 400/404 verbatim, and the photo grid is a plain <img>
with no onError. So syncAlbumAssets, which filtered `type === 'IMAGE'`
only, could persist a hidden IMAGE as a permanently broken tile. It now
applies the same guard, extracted as isVisibleAsset().

Albums keep their filter rather than requesting `timeline` visibility:
albums legitimately contain archived assets, and both the v2 album body
and the v3 album search return them.

Does not address tiles already persisted before this — those still render
broken and need a separate fix.

Refs #1474

* docs(memories): correct Immich version boundaries in the hidden-asset comments

Verified against the v1.120.0 → v3.0.0 OpenAPI specs and server source. The
previous comments said "Immich v2 hard-defaulted metadata search to timeline
visibility". That is true only for 1.133–1.144.

- `visibility` was added in 1.133.0. Before that, searchAssetBuilder applied
  `.$if(options.isVisible !== undefined, ...)` with no default, so pre-1.133
  servers returned hidden assets too. #1474 was therefore not purely a v3
  regression.
- Those servers strip the `visibility: 'timeline'` filter rather than
  rejecting it: Immich validates with `whitelist: true` and no
  `forbidNonWhitelisted`. So the request stays valid, the filter is a no-op,
  and isVisibleAsset() is the ONLY guard there. Say so, so it does not get
  removed later as redundant.
- `albumIds` only exists from 1.135.0. Because unknown properties are stripped,
  an albumIds search against an older server would silently drop the album
  filter and return the entire library as the album's contents. Feature
  detection on `assets` (present through 1.144.1, absent on v3) makes that
  unreachable; a version probe with a wrong boundary would not.

Also cite Immich's own enum, which documents AssetVisibility.Hidden as
"Video part of the LivePhotos and MotionPhotos".

Comments only — no behavior change.

* feat(plugins): dashboard trip-card badges + a mock-host driver for plugin tests

Two additions that round out the plugin platform's breadth and its authoring DX.

tripCardProvider hook (hook:trip-card-provider): a plugin returns small declarative
badges for the dashboard trip cards. The dashboard fetches all visible cards in one
call; the host access-checks every tripId for the acting user, bounds each field
(label/value length, enum tone, http/https/mailto-only url), caps the count and drops
any badge for a card that wasn't requested — plugin JS never runs on the dashboard.
Rendered as text chips under the card meta; labelled + gated in all 22 locales.

createMockHost now exposes run(def) — the other half of a plugin unit test. Where the
ctx recorders capture what a plugin read, run() fires its own entry points (route, job,
scheduled, event, plugin-event, deleteUserData, exportUserData, provider hooks) against
the same mock ctx, and host.scheduled surfaces the timers it armed. A handler the plugin
didn't declare throws a clear error instead of a silent no-op.

* feat(plugins): include plugin data + code in backups, applied on restart

A TREK backup archived travel.db + uploads + the encryption key, but each plugin's
own SQLite file — the ONLY copy of the user data it holds — and its installed code
lived in separate trees that were never captured, so a restore left the plugins rows
with no data or code behind them.

createBackup now adds plugins-data/ (each plugin's db + WAL sidecars, so SQLite
recovers a consistent snapshot) and plugins-code/ (skipping dev-links by realpath, so
an author's linked source is never bundled). Restore can't swap those live — the
runtime holds each plugin db open — so it STAGES the extracted trees beside the live
ones and the runtime swaps them in at the next boot, before it opens anything. Same
"applies on restart" model the bundled encryption key already uses: no plugin quiesce,
no swap under open handles, no new admin setup. Older archives without the trees restore
exactly as before.

* fix(plugins): audit — runtime robustness, security & data-lifecycle fixes

Fixes from an adversarial audit of the plugin system, host/runtime side:

Robustness:
- getPluginDataDb recreated a handle a terminal-failure dispose had closed but
  left cached, so a re-enabled plugin's db:own threw on every call — recreate
  when the cached handle is shut.
- ctx.ws.broadcast* now carry _inv, so the host can bind the acting user (the
  capability was silently refused, i.e. dead, without it).
- ctx.events.emit swallows a rejected emit instead of crashing the child into a
  terminal 'error'; an uncaught throw AFTER activation is treated as a crash
  (restart with backoff), not a load failure.
- A crash-respawned child gets the same activation deadline as a first activation
  and the buffered-event queue is cleared on the timeout path, so a hung onLoad
  after a crash can't peg a core and orphan events forever.
- Expired buffered events are pruned by the reaper, not only at flush; the
  scheduler + erasure sweeps scope their LIMIT window to ACTIVE plugins so a
  backlog for inactive plugins can't starve deliverable work.

Security / integrity:
- Unix-domain-socket / named-pipe connects are refused by default in the egress
  guard (a host-local pivot to docker.sock / DB sockets), under the same policy
  as private IPs.
- db.tx refuses transaction-control statements (a raw COMMIT would break its
  atomicity) and caps rows across the WHOLE batch, not per statement.
- plugin_capability_audit is retention-capped per plugin (chain-safe: retained
  rows stay self-verifying), so it can't grow unbounded in the shared db.
- A cap of 0 in TREK_PLUGIN_AI_PER_DAY / _NOTIFY_PER_DAY now disables the broker
  instead of falling back to the default.

GDPR data lifecycle:
- Account deletion now erases host-side per-user plugin tables (config, OAuth
  tokens/state) and enqueues the own-db erasure from the CORE path, so it works
  even when the runtime is disabled or pre-boot; guest deletion does the same.
- uninstall keeps a pending erasure when data is retained (deleteData=false);
  erasure delivery is no longer grant-re-checked (a queued erasure is a duty);
  export flags installed-but-inactive plugins as pending instead of omitting them.

Backup/restore:
- Plugin DBs are WAL-checkpointed before archiving (no torn/stale snapshots).
- Restore applies the staged trees immediately by quiescing the plugins (no
  unbounded gap where a later unrelated restart would revert diverged data);
  the swap is content-level (safe on a volume-mounted root) and preserves
  dev-links; the decompressed-size cap is operator-raisable.

* fix(plugins): audit — hook-output hardening, dashboard slot & mock-host parity

- Map-marker and atlas-layer tones were validated on String(tone) but emitted
  raw, so a non-string tone (an object with a matching toString) slipped through
  and crashed the client that renders it — check the raw value against the enum.
- View-contribution column/action caps are now PER ENTITY, not per view, so a
  plugin's columns no longer vanish from every table row past the first 20; the
  dashboard trip-card badge cap is per card (≥ one on every visible card).
- A reservation-detail widget no longer also renders as a context-free dashboard
  sidebar card (the inline filter was missing that slot).
- mock-host matches the real host: it ignores asUserId on trip reads (bind the
  acting user), throws on a wrong user-scope notify target instead of coercing,
  enforces the scheduler caps, and detects RETURNING as a read in db.tx — so a
  passing author test can't hide a production RESOURCE_FORBIDDEN.

* feat(plugins): full ctx parity in the dev server + fire jobs/events/hooks locally

The trek-plugin dev server injected only ~6 of the ~35 ctx areas, so any plugin
touching ctx.costs/packing/files/notify/ai/settings/scheduler/meta/oauth/db.tx/…
hit a TypeError in local dev while the same code passed mock-host tests and worked
installed. It also could only exercise routes.

Delegate every non-db-own capability to a grant-enforcing mock host (the same one
unit tests use) while keeping the real node:sqlite for db:own and dev-native ws
capture + logging — so the whole surface works in dev with the exact production
permission rules. dev-fixtures.json now takes the createMockHost options shape, so
you can seed the full surface. New GET /__dev/fire/<kind>[/<name>][/<fn>] fires a
job, scheduled timer, event subscription, GDPR handler or provider hook against the
dev ctx, closing the "can't test non-routes locally" gap.

* feat(plugins): wire the photoProvider + calendarSource hooks to real core consumers

Both hooks were declared, typed and documented but NO core code ever invoked them,
so an author could build, mock-test and install a photo or calendar plugin that
silently did nothing. Give each a real consumer that fans out to it, exactly like
the other eight provider hooks:

- GET /api/plugin-photos/search (+ /sources, /item) aggregates photoProvider results
  for the picker — {id, title?, thumbnailUrl, fullUrl, takenAt?}, thumbnail/full URLs
  http/https-only (they become <img src>), per-source count capped, failing source
  skipped.
- GET /api/plugin-calendar?start=&end= aggregates calendarSource events for the
  signed-in user — {id, title, start, end, allDay} ISO, count capped, failing source
  skipped, sensible default window.

Both run with the acting user bound. The SDK interfaces now pass ctx as the last arg
(so a source can reach ctx.settings/oauth/http for its backend), and the wiki marks
them live instead of "reserved — no core consumer".

* feat(plugins): close the create-heavy API asymmetries importers/sync hit

Core services implemented these but plugins had no path to them, so the flagship
importer/sync integrations hit real walls. Added, each reusing the EXISTING grant
(no new consent):

- ctx.trips.removeMember(tripId, userId) — reconcile DEPARTURES, not just additions
  (db:write:members + member_manage). Never removes the owner (that would orphan the
  trip); ownership transfer stays a separate deliberate action.
- ctx.journal.createJourney({title, subtitle?, trip_ids?}) / deleteJourney(journeyId)
  — an importer can now bootstrap the journal it fills with entries and clean it up
  (db:write:journal), instead of only appending to journals a human created first.

Wired end-to-end (envelope → rpc-host → create-rpc-host reusing tripService/
journeyService → both SDK copies → mock-host) and documented. (trips.delete needs its
own destructive permission + consent copy and collab edit/delete + collections.delete
remain — tracked as small follow-ups.)

* feat(plugins): strip emojis from plugin-rendered text so it matches TREK's lucide UI

Plugin authors (especially AI-generated ones) sprinkle emojis into the declarative
text TREK renders in its OWN chrome — hook contributions (badges, columns, warnings,
PDF sections, map-marker/atlas labels, journal rows, place details, trip-card badges,
calendar + photo titles) and notifications — which clashes with TREK's lucide-only icon
language.

A shared stripEmoji() removes emojis (incl. flag/ZWJ/variation-selector sequences) and
tidies the leftover whitespace, applied at the render boundary in every hook-contribution
normalizer and in notify.send — so no matter what a plugin returns, the text TREK draws
stays emoji-free. It does NOT touch a plugin's own sandboxed /ui frame (the author's to
design), and it leaves photo ids verbatim (they round-trip to getById). The validate CLI
warns when a manifest name/description contains emojis, nudging authors to the declarative
`icon` field (a lucide name) instead.

* fix(plugins): harden the restore-apply path — regressions from the backup/dev fix pass

A final audit of the fix pass caught three regressions clustered in the two newest
surfaces; the restore path could both crash the server and destroy data.

- CRITICAL: a restore quiesces plugins via supervisor.shutdownAll() AFTER closeDb(), but
  shutdownAll killed children without first marking them stopped, so each child 'exit'
  took the CRASH path and wrote crash-accounting rows into the now-closed core DB — the
  throw escaped an EventEmitter listener as an uncaughtException and killed the whole
  process mid-restore. shutdownAll now marks every entry stopped and drops it from
  `running` BEFORE the kills (so onExit early-returns), and the onStatus/onLog DB hooks
  are wrapped in try/catch (also covers the stderr→onLog path). This also stops a normal
  shutdown from logging phantom "crashed" rows.
- HIGH: swapContents cleared live entries then MOVED staged ones in, so a crash mid-move
  permanently deleted a plugin's only data copy (staging was already emptied, so a retry
  couldn't restore it). It now COPIES each staged entry over the live one and only deletes
  staging at the very end — `staged` stays the complete source of truth, making the whole
  operation crash-idempotent.
- HIGH: the dev server lost the actingUserId=1 default in the mock-host refactor, so a
  fresh scaffold refused every user-bound capability. Restored.

* fix(plugins): final-audit medium/low findings

- GDPR export flags an active plugin whose export errored/timed out as `pending`
  instead of silently omitting it (collectUserExport now returns a discriminated
  result), so a data-access export never reads complete while missing data.
- Account deletion also enqueues an erasure for plugins UNINSTALLED with retained
  data (an orphan data dir) — a same-id reinstall now honours the deletion instead
  of re-adopting the user's data forever.
- oauth.getToken returns null in a userless context (matching the SDK/mock contract)
  instead of throwing RESOURCE_FORBIDDEN a background caller can't handle.
- Crash-backoff restart is identity-guarded (+ the timer is tracked and cleared like
  the activation timer), so a disable + re-enable during the backoff window can no
  longer respawn a ghost child from the replaced entry.
- db.tx transaction-control guard strips leading comments first, so `/* */COMMIT`
  can't slip past the start-anchored check and break batch atomicity.
- createJournal inherits its cover only from a trip that was actually LINKED
  (access-checked), closing a cross-tenant cover-image read on plugin + REST paths.
- trip-warnings drops a null array element instead of losing ALL of that provider's
  warnings; plugin-activity floors a non-integer ?limit so it can't 500.
- The trek-plugin dev server binds loopback only and refuses cross-site requests to
  its side-effectful /__dev/fire endpoints (it serves real routes + no-auth dev
  actions).

* fix(plugins): clear no-misleading-character-class in the emoji stripper

The character class listed the ZWJ, variation selectors and combining keycap
marks as members, which eslint reads as an accidental combined grapheme and
rejected on CI. Pull the emoji glyphs out into Extended_Pictographic /
Regional_Indicator alternatives so only the joiner/selector code points stay in
the class, with a scoped disable where the rule still can't tell them apart.
While here, reset lastIndex before the /g regex is reused in hasEmoji() so a
second call can't resume mid-string and miss a leading emoji.

* fix(security): trip-scope note-file deletion and guard the LLM base URL

Two reported issues:

- deleteNoteFile only matched on the note id and file id, so a member of trip A
  could delete a file attached to a note in trip B by guessing its id. Thread the
  trip id through the service and controller and scope the delete to it, the way
  every other collab operation already does.

- The LLM extraction clients fetched the user-configured base URL directly, so a
  user could point it at the cloud-metadata endpoint (169.254.169.254) and read
  the echoed error body. Route both clients through a new safeFetchLlm() that
  blocks the link-local/metadata range while still allowing a local or LAN Ollama
  (loopback and private ranges stay reachable), pinned to the resolved IP so a
  hostname can't rebind to the metadata address after the check.

* fix(security): route every LLM client through the SSRF guard

The base-URL SSRF fix covered the openai-compatible and anthropic clients but
missed the native Ollama /api/chat client and the /api/tags + /api/pull model-
management calls, which fetched the same user/admin-configured URL raw. Route
them through safeFetchLlm too, and harden its link-local check: cover the whole
fe80::/10 range (not just the fe80: prefix), the IPv4-mapped/-compatible metadata
spellings, and the AWS IMDSv6 endpoint, while still allowing a loopback or LAN
model server.

* fix(plugins): narrow emoji stripping to real emoji + close two gaps

The stripper used \p{Extended_Pictographic}, which also swallowed legitimate text
symbols a plugin renders — (c), (r), tm, rating stars (a full row collapsed to the
empty ones). Narrow it to \p{Emoji_Presentation} (+ skin-tone modifiers, regional
indicators, and the ZWJ / variation-selector / keycap / tag glue) so only colour
emoji go and text symbols stay. The whitespace tidy-up now runs only when
something was actually removed and never collapses newlines, so plain text and
PDF paragraphs keep their exact spacing.

Also strip the trip-warning message — the one render boundary that slipped
through — and skip stray files (not just directories) when enqueuing orphan
plugin-data erasures.

* fix(plugins): harden the supervisor lifecycle + restore staging

- Restore staging is now atomic: the plugin trees are copied into a `.tmp` sibling
  and only a fully-copied tree is renamed to `.restore`. A copy that died partway
  (disk full, crash) previously left a PARTIAL `.restore`, and the next boot's swap
  deletes every live plugin dir missing from it — data loss, after the restore had
  reported success.
- A late `loaded` / `load-error` from a child that finished during the kill grace no
  longer resurrects a stopped/removed plugin or re-registers routes on an active one
  (which leaked node-cron tasks and double-fired jobs after a re-enable).
- The crash-backoff branch clears the stale activation deadline so it can't fire
  during the wait and cancel the scheduled retry.
- shutdownAll rejects in-flight activations (no more hung enable requests) and clears
  the buffered-event queue (no replaying pre-restore events); activate() self-handles
  the rejection so a caller that doesn't await can't crash the process.
- Erasure drains coalesce onto the one in flight instead of running concurrently and
  delivering an erasure to a plugin twice.

* fix(plugins): consistent plugin-db backups + close two restore/handle races

- Backups archive a VACUUM INTO snapshot of each plugin db instead of the live file.
  The archiver reads lazily while streaming, so a plugin writing during the backup
  could land a torn .db plus an out-of-sync -wal in the zip — the plugin's only data
  copy, silently corrupt. The snapshot is point-in-time consistent and drops the
  sidecars.
- The host data handle is resolved lazily per call rather than captured once, so a
  disable+re-enable within the kill grace can't have the old host's dispose() close
  the db out from under the freshly re-activated one.
- A restore quiesces the running plugins regardless of whether the archive carried
  plugin trees. An older archive (no trees) swaps in a different `plugins` table while
  the live children keep running with their pre-restore identity — ghosts, invisible
  in the restored UI and unstoppable short of a restart.

* fix(plugin-sdk): bring the mock host and dev runner to parity with the real host

A plugin developed against the local mock/dev runner must behave the same as in
production, or authors debug phantoms. Sixteen behaviour drifts closed:

- Userless handlers (jobs, scheduled tasks, events, GDPR erasure/export) run with a
  userless ctx like the real host, so membership-checked reads correctly refuse.
- member add/remove: member_manage gate, owner-guard, target-exists check.
- journal: addon gate + entry_date/title validation + access checks.
- notify: emoji stripping, title/body caps, in-app link check.
- scheduler dueAt must be finite and within a year.
- db.tx: TX_CONTROL / FORBIDDEN / op-cap in both the mock and the dev runner.
- ws/users: acting-user, membership, self-only and canSeeUser gates + field whitelist.
- dev db SQL guards + row cap; the dev request always carries headers; dev user is
  no longer implicitly an admin.
- core-write and small field validations mirrored from the shared schemas.
- addon toggles + a generic per-trip permission record; declaredEmits warning.
- /__dev/fire cross-site guard extended to cover the /api routes.

* fix(oauth): don't revoke active MCP sessions on a normal token refresh

refreshTokens() unconditionally revoked all MCP sessions for the
(user, client) pair on every successful refresh-token grant, not only
on replay/theft detection. Since MCP access tokens expire hourly, any
long-lived MCP client (Claude Code, Claude Desktop, etc.) silently
refreshing its token in the background would have its live session
killed roughly every hour, causing /mcp to return 404 "Session not
found" until the client was manually reconnected.

Session revocation now only happens on the replay-detection branch,
which is the actual security-relevant case; mcpHandler already
re-validates session.userId/clientId against the current token on
every request, so a legitimate rotation doesn't need to pre-emptively
kill the session.

Fixes #1475

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(atlas): match region names regardless of accent/dash formatting

The region layer's name-matching fallback (used when the geocoder's cached
region_code doesn't match the bundled admin-1 code) compared raw strings, so
a cached region_name with different accenting or dash style than the bundle
(e.g. "Ile-de-France" vs "Île-de-France") silently failed to highlight.
Added normalizeRegionName (diacritic-insensitive, dash-insensitive) and used
it everywhere region names are compared.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(atlas): connecting-flight layovers no longer mark the layover country visited

getStats' #1366 transport-only-country merge read every reservation_endpoints
row for a trip, including role='stop' (a connecting-flight layover). A plane
change through a country's airport now no longer marks it visited — only
real from/to legs do.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* feat(i18n): improve Simplified Chinese translations

* fix(i18n): correct Vietnamese locale translations (#1502)

* fix(pwa): self-host the leaflet stylesheet instead of loading it from unpkg (#1497)

The service worker's cdn-libs rule cached the unpkg leaflet.css as an
opaque response, which the browser then rejected for the CORS <link>
request — Atlas and trip maps stayed blank until users manually
unregistered the service worker. Bundling the stylesheet from the
leaflet package removes the cross-origin fetch (and the runtime CDN
dependency) entirely, so it is precached with the rest of the app
shell. The now-dead unpkg runtime-caching rule is dropped.

* fix(packing): select quantity on focus so typed number replaces it (#1513)

* fix(planner): sort transport and booking cards chronologically (#1507)

* fix(planner): keep leg distance visible across a car rental's middle days (#1504)

* fix(costs): restore the expenses CSV export lost in the Costs rework (#1500)

* fix(client): disable request timeout for cover image uploads (#1495)

* fix(planner): scope transit quick picks to the selected day (#1460)

* fix(atlas): restore the missing Spain bounding box so southern-Spain points stop resolving to Algeria (#1490)

* fix(mobile): dvh shell, safe-area padding in Plan/Places drawer, packing name overflow (#1505)

* fix(planner): persist typed booking addresses and add autocomplete (#1496)

* fix(security): enforce trip read scope and share flags server-side

get_trip_summary returned the trip's members (with emails), full itinerary
and accommodations to any valid MCP token regardless of its OAuth scopes.
Gate the core bucket on trips:read, keeping id + title so the tool still
works for navigation (GHSA-qvw8-w937-vcmq).

The public trip share ignored share_map: days, assignments, notes and the
place list (with coordinates) were always returned. Gate them on share_map
server-side, mirroring the journey share. Same class nearby: the journey
photo/asset proxies now honour share_gallery and the shared place-photo
proxy honours share_map.

* test(dashboard): pin the clock so trip-window fixtures don't rot

DashboardPage's tests seed a trip dated 2026-07-01..07-10 and assume it is
the current/spotlight trip. Once the wall clock passes that window the
past/upcoming split relocates the trip and 14 tests fail with "Paris
Adventure" no longer rendered. Freeze "now" to a date inside the window
(shouldAdvanceTime keeps userEvent/waitFor working) so the suite is
deterministic regardless of when it runs.

* fix(atlas): derive country boxes from admin0 and make country removal stick (#1490, #1486)

Removing a visited country in Atlas was a no-op, and 43 countries could not be
geocoded at all. Two independent defects behind one report.

The bounding boxes were a hand-maintained table that had drifted from the admin0
polygons we already ship: NG, BY, GL, KP, TD, SS and 37 others had no box, so
their coordinates fell into a *neighbour's* box as the sole candidate — Lagos
resolved to Benin, Minsk to Russia. getCountryFromCoords also short-circuited a
lone bbox candidate without checking the polygon, which is how a point in
southern Spain became Algeria. Derive the boxes from admin0 instead, one box per
geometry part so countries straddling the antimeridian (RU, US, FJ, KI) don't get
a globe-spanning box, and always validate against the polygon.

Removal never persisted because Atlas re-derives countries from places and
transport endpoints on every request: those have no visited_countries row, so the
DELETE hit nothing, the client hid the country optimistically, and the next
getStats brought it straight back. Tombstone the removal in a new
hidden_countries table and suppress it in the derived passes. Re-marking lifts
the tombstone; adding a real place there brings the country back on its own.

The same #1366 endpoint merge had been copy-pasted into authService.getTravelStats
without the role filter Atlas got, so the dashboard passport card still counted a
plane-change country as visited. Filter it there too, and honour the tombstones so
the card and the map agree.

CONTINENT_MAP had the mirror-image gap (ES missing, NG present) and bucketed the
newly-resolvable countries into 'Other'; fill it out to cover all 198.

* fix(ics): compute all-day DTEND without a local-timezone round-trip (#1453)

exportICS built all-day DTENDs as `new Date(date + 'T00:00:00')` → setDate(+1) →
toISOString(). The string carries no Z, so it parses as *server-local* midnight and
the toISOString() round-trip lands a day early on any positive UTC offset. DTEND is
exclusive, so every trip exported from a server east of Greenwich silently lost its
last day — and every per-day summary event lost its only day.

Reuse dayService.addDays(), which stays in Date.UTC throughout, for both blocks.

This shipped green because the all-day test asserted DTSTART and SUMMARY but never
DTEND, and TZ is pinned nowhere in the server test setup — so CI inherited UTC, one
of the few offsets where the bug is invisible. The new test pins TZ across
Europe/Berlin, Asia/Tokyo, Pacific/Kiritimati, America/New_York and UTC; it fails
against the old code in exactly the three positive-offset zones.

* fix(client): route every multipart upload through a timeout-free helper (#1495)

The shared axios instance carries timeout: 8000, and axios' timeout is a whole-request
deadline rather than an idle one — so any upload whose body takes more than 8s to push
is aborted mid-stream, which the server surfaces as a multer "Request aborted".

#1495 fixed this by hand-writing `timeout: 0` on the three cover uploads. That left the
identical bug live on 7 of the 15 multipart call sites, including the two that accept
500 MB: the documents addon (filesApi.upload) and backup restore. Avatar uploads — a
phone photo on a slow uplink, exactly the reported scenario — were also still on 8s.

Add postMultipart() and route all 15 sites through it, so opting out of the timeout is
the default instead of something each new endpoint has to remember. It also collapses
the three different hand-rolled Content-Type spellings; axios unsets the header for
FormData in the browser anyway so the platform can generate the boundary.

coverUpload.test.ts is superseded by uploadTimeout.test.ts, which pins all 13 endpoints
rather than just the three covers.

* fix(client): shared NumericInput so a typed digit replaces instead of appending (#1513)

Tapping a pre-populated numeric field parks the caret at the end, so the first digit
typed is appended rather than replacing: a packing quantity of 1 plus "6" committed 16.

#1513 fixed exactly one field — the packing quantity input. The weight field in the
very same row still appended, as did nine others, including Vacay's entitlement-days
which autoFocuses straight into the bug.

Extract the behaviour into components/shared/NumericInput and adopt it at all eleven
sites. It owns only the part that was uniformly broken — sanitizing and select-on-focus;
styling and commit semantics stay with each caller, since some save on every keystroke
and others on blur.

Two details worth keeping:

- The select() runs synchronously *and* on the next frame, because WebKit undoes a
  synchronous select() with its own post-focus caret placement. The deferred pass is
  guarded: if a keystroke lands inside that one-frame window, re-selecting would swallow
  it — "48.853" typed into a coordinate field came out as ".853" — so the first input
  cancels the pending select.
- The fields move from type=number to type=text + inputMode. Same keypad, minus the
  scroll-wheel-silently-changes-the-value and spinner-arrow footguns.

* fix(i18n): name Costs consistently across the app and in every locale (#1464)

The Budget addon was renamed to Costs, but the rename only ever landed on the trip tab
and — in English — the admin catalog. Two problems fell out of that.

The zh locale was self-contradicting: the admin add-on card read the English literal
'Costs' while the tab it configures read '费用'. That is the bug as reported.

Underneath it, the rename had been done in `en` and copy-pasted verbatim into the other
21 locales, so 16 of them showed an untranslated English "Costs" for the trip tab.
Meanwhile the surfaces the rename missed — the public shared-trip tab, its totals label,
the login feature list ("Budget Tracking") and the member-permission checkbox — were
still correctly translated as *Budget*. Every locale therefore called the same thing two
different things.

Translate "Costs" properly in all 22 locales and apply it to all six keys, so each
locale is internally consistent and none is left holding an English literal.

Note that i18n parity cannot catch this class of drift: it compares key and file sets,
never values, which is exactly why the zh mismatch shipped green.

* fix(i18n): call packing and todo categories "lists" (#1505)

#1505 asked for the "Add category" button to read "Add list". Renaming only the button
would have left it sitting next to "Delete Category" and "Change Category", and clicking
it would still open a field placeheld "Category name (e.g. Clothing)" — so the whole
user-facing vocabulary moves together, in all 22 locales.

Covers the button, the name placeholder and its inline variant, the delete and move menu
items, the delete-confirm dialog, and the todo sidebar heading, detail label and
no-category states.

The key names are unchanged, so i18n parity is unaffected — only values move.

The bulk-import hint is deliberately left alone: it documents the CSV column layout, and
the column really is `category` in the schema. Its strings have also drifted between
locales (several describe an entirely different format), which is worth a separate pass.

* fix(plugins): audit hardening — OAuth SSRF, demo upload guard, SDK perms, ICS tz

Follow-ups from the 3.2.2 audit, all additive and non-breaking:

- The host-side OAuth token exchange now runs through the SSRF guard
  (safeFetchLlm): a token_url that resolves to the cloud-metadata /
  link-local range is refused and the connection is pinned to the resolved
  IP, so a DNS name or IPv6 literal pointing at metadata can't be reached
  and can't rebind. Loopback and LAN stay reachable so a self-hosted
  internal IdP keeps working.
- Plugin files.create honours the demo-mode upload block the REST path
  enforces, so a demo user can't write files to a public demo instance
  through db:write:files.
- The SDK manifest validator learns hook:trip-card-provider and
  hook:user-data, which the host already accepts — it was hard-rejecting
  valid manifests that use them.
- ICS export validates a stored/plugin-provided timezone before it reaches
  Intl, so an invalid zone degrades to a floating local time instead of
  throwing a RangeError and crashing the calendar export / all-trips feed.

* fix(plugins): audit follow-ups — WAL backup, async read, dev-link gate, webhook raw body

More non-breaking hardening from the 3.2.2 audit:

- Backups copy a closed plugin.db's -wal/-shm sidecars. A plugin with no
  open handle has no writer, so the sidecars are a consistent set with the
  .db; without them an unclean shutdown's committed-but-uncheckpointed WAL
  rows would be missing from the backup. The open-handle path still captures
  a consistent VACUUM INTO snapshot and skips the sidecars.
- files.getContent reads off the event loop (fs.promises.readFile) instead
  of a synchronous up-to-10MB read + base64 that stalled every other plugin
  RPC and request for its duration.
- Plugin discovery only follows dev-link symlinks when TREK_PLUGINS_DEV_LINK
  is set, so a stale link left on the volume is not registered on a normal
  (non-dev) boot.
- Webhook (auth:false) proxy routes now receive req.rawBody, so a plugin can
  verify a provider's HMAC signature over the exact payload it was computed
  on. Enabled app-wide via Nest's rawBody option; authenticated routes never
  receive the raw bytes.

* fix(build): move tz-lookup to server production dependencies

tripService imports tz-lookup at runtime (ICS VTIMEZONE resolution, #1453)
but it was declared in devDependencies. Local dev worked because the
monorepo hoists devDependencies into the root node_modules, but the
production Docker stage installs with `npm ci --omit=dev`, so the image
shipped without tz-lookup and the server crash-looped with
MODULE_NOT_FOUND on boot. Move it to dependencies and sync the lockfile.

* fix(dashboard): round the boarding-pass wrapper so its mask layer isn't square

The #1459 Safari fix split the pass into an outer wrapper (left notch) and the
inner glass panel (right notch). The wrapper carries a mask + translateZ, which
promotes it to its own compositing layer whose bounds stayed square, showing a
square edge over the rounded inner panel. Give the wrapper the same 24px radius.

* fix(plugins): refresh the active-plugin store on admin changes

Activating/deactivating a plugin only updated the admin panel's own rows, not the
app-wide active-plugin store the dashboard reads. So a freshly enabled widget/hero
plugin (e.g. Koffi) only appeared after a full reload. refresh() now also reloads
the plugin store, so consumers pick the change up live.

* fix(trips): refresh the roster after a guest/member change

Adding an accountless guest (or any member change) only refreshed the members
modal's own list; the planner's tripMembers — which Costs participants, Collab,
etc. read from — was stale until a full reload. Expose refreshMembers from the
planner and let the members modal call it after each roster mutation.

* fix(security): hide co-members' private packing items in summary and share

getTripSummary built its packing section with listPackingItems(tripId) and no
viewer id, so the per-viewer #858 privacy filter never ran — the MCP
get_trip_summary tool then returned every other member's private/personal
packing items (name, category, owner) to any trip member or packing-scoped
token. Thread the acting user through so the filter applies. Separately, the
public trip share loaded packing with a raw SELECT * and published it when
share_packing was on; a public viewer is neither owner nor recipient, so only
Common (is_private = 0) items may surface.

* fix(plugins): forward webhook raw body as base64 and bound the ICS tz cache

The inbound webhook raw body was forwarded as a UTF-8 string, which corrupts a
non-UTF-8 signed payload (U+FFFD substitution) so a plugin can't reconstruct the
exact bytes for HMAC verification; forward base64 (rawBodyBase64) instead. Also
bound the ICS timezone-validity cache: its key is a free-form plugin/importer
zone string, so cap the distinct entries rather than growing for the process
lifetime.

* fix(atlas): resolve to a real neighbour polygon before a loose fallback box

A polygon-less micro-territory box (PS, XK) is far larger than the enclave it
represents and was winning the smallest-box tie-break over the sovereign whose
polygon actually contains the point, so cities inside a neighbouring country
resolved to the wrong territory. Only a tight box now auto-wins; a loose one
defers behind real polygons and is used only when no polygon contains the point.

* fix(feeds): include shared member trips in the all-trips calendar feed

buildUserIcs selected owned trips only, so a user's aggregate feed silently
dropped every trip shared with them as a member. Match the single-trip feed's
membership check.

* fix(plugins): tighten the OAuth pre-check and backup restore/snapshot

OAuth token-endpoint fast-fail now also rejects IPv6-literal loopback/metadata
hosts and .internal names (LAN stays reachable for a self-hosted IdP). Backup
restore enforces the decompressed-size cap by counting extracted bytes instead
of trusting the archive's declared sizes, and refuses a zip-slip path. A plugin
snapshot whose fold-in fails now keeps its -wal/-shm so no committed data is lost.

* fix(plugins): validate bag roster, reap orphaned erasures, harden brokers

A packing bag can only be assigned to a member of its trip. Queued user-erasures
for an uninstalled plugin are reaped instead of lingering forever. GDPR export
folds in host-side settings/oauth presence (best-effort). notify.send builds its
link by URL-parse so a backslash can't slip an off-site redirect through, and
dev-link discovery skips a Windows junction unless dev-link mode is on.

* fix(trips): refresh trip members only after a mutation, not on modal open

loadMembers notified the planner on every call, including the open effect, firing
a redundant refresh. Only mutation handlers notify now.

* docs(wiki): document the 3.3.0 plugin platform surface

Cover the plugin activity log, widget slots and tab takeover, the notify/ai/oauth
brokers, provider hooks, scheduler, GDPR hooks, the new plugin env vars, plugin
contributions on the map/atlas/PDF/journal pages, plugin runtime hardening, and
the Budget->Costs rename with multi-currency and CSV export.

---------

Co-authored-by: jubnl <jgunther021@gmail.com>
Co-authored-by: Dieter Blomme <dieterblomme@gmail.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: sld272 <zjrdmczh@outlook.com>
Co-authored-by: Nguyen Trong Binh <nguytb15@VN1N07HO1CD1015.local>
This commit is contained in:
Maurice
2026-07-11 19:02:34 +02:00
committed by GitHub
parent 3db2495bcd
commit a87b656b43
499 changed files with 20336 additions and 1842 deletions
-5
View File
@@ -23,11 +23,6 @@
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=MuseoModerno:wght@400;700;800&display=swap" rel="stylesheet" />
<!-- Leaflet -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY="
crossorigin="" />
</head>
<body>
<div id="root"></div>
+1
View File
@@ -34,6 +34,7 @@
"dexie": "^4.4.2",
"drag-drop-touch": "^1.3.1",
"heic-to": "^1.4.2",
"iso-3166-2": "^1.0.0",
"leaflet": "^1.9.4",
"lucide-react": "^0.344.0",
"mapbox-gl": "^3.22.0",
+1 -1
View File
@@ -88,7 +88,7 @@ function ProtectedRoute({ children, adminRequired = false, addonId }: ProtectedR
}
return (
<div className="flex flex-col h-screen md:block md:h-auto">
<div className="flex flex-col h-dvh md:block md:h-auto">
<div className="flex-1 overflow-y-auto md:overflow-visible">{children}</div>
<BottomNav />
</div>
+137 -34
View File
@@ -239,6 +239,40 @@ apiClient.interceptors.response.use(
}
)
/**
* POST a FormData body — the ONLY way this client should upload a file.
*
* The shared axios instance carries `timeout: 8000`, and axios' timeout is a whole-
* request deadline rather than an idle one. A file upload that takes longer than 8s to
* push its body — a phone photo on a slow uplink, a 500 MB document — is aborted
* mid-stream, which the server reports as a multer "Request aborted" (#1495).
*
* Every upload therefore has to opt out with `timeout: 0`. That opt-out used to be
* hand-written per call site, so it was forgotten on 7 of 15 — including the two 500 MB
* endpoints (documents, backup restore). Centralizing makes the correct behavior the
* default instead of something you have to remember.
*
* The Content-Type is set for clarity only: axios unsets it for FormData in the browser
* so the platform can generate the multipart boundary.
*/
export interface UploadOptions {
onUploadProgress?: (e: import('axios').AxiosProgressEvent) => void
idempotencyKey?: string
signal?: AbortSignal
}
export function postMultipart<T = any>(url: string, formData: FormData, opts?: UploadOptions): Promise<T> {
return apiClient.post(url, formData, {
headers: {
'Content-Type': 'multipart/form-data',
...(opts?.idempotencyKey ? { 'X-Idempotency-Key': opts.idempotencyKey } : {}),
},
timeout: 0,
onUploadProgress: opts?.onUploadProgress,
signal: opts?.signal,
}).then(r => r.data as T)
}
export const authApi = {
register: (data: RegisterRequest) => apiClient.post('/auth/register', data).then(r => r.data),
validateInvite: (token: string) => apiClient.get(`/auth/invite/${token}`).then(r => r.data),
@@ -253,7 +287,7 @@ export const authApi = {
updateSettings: (data: Record<string, unknown>) => apiClient.put('/auth/me/settings', data).then(r => r.data),
getSettings: () => apiClient.get('/auth/me/settings').then(r => r.data),
listUsers: () => apiClient.get('/auth/users').then(r => r.data),
uploadAvatar: (formData: FormData) => apiClient.post('/auth/avatar', formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(r => r.data),
uploadAvatar: (formData: FormData) => postMultipart('/auth/avatar', formData),
deleteAvatar: () => apiClient.delete('/auth/avatar').then(r => r.data),
getAppConfig: () => apiClient.get('/auth/app-config').then(r => r.data),
updateAppSettings: (data: Record<string, unknown>) => apiClient.put('/auth/app-settings', data).then(r => r.data),
@@ -334,7 +368,7 @@ export const tripsApi = {
get: (id: number | string) => apiClient.get(`/trips/${id}`).then(r => r.data),
update: (id: number | string, data: TripUpdateRequest) => apiClient.put(`/trips/${id}`, data).then(r => r.data),
delete: (id: number | string) => apiClient.delete(`/trips/${id}`).then(r => r.data),
uploadCover: (id: number | string, formData: FormData) => apiClient.post(`/trips/${id}/cover`, formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(r => r.data),
uploadCover: (id: number | string, formData: FormData) => postMultipart(`/trips/${id}/cover`, formData),
searchCoverImages: (query: string) => apiClient.get('/trips/cover-images/search', { params: { query } }).then(r => r.data),
archive: (id: number | string) => apiClient.put(`/trips/${id}`, { is_archived: true }).then(r => r.data),
unarchive: (id: number | string) => apiClient.put(`/trips/${id}`, { is_archived: false }).then(r => r.data),
@@ -370,14 +404,14 @@ export const placesApi = {
if (opts?.waypoints !== undefined) fd.append('importWaypoints', String(opts.waypoints))
if (opts?.routes !== undefined) fd.append('importRoutes', String(opts.routes))
if (opts?.tracks !== undefined) fd.append('importTracks', String(opts.tracks))
return apiClient.post(`/trips/${tripId}/places/import/gpx`, fd, { headers: { 'Content-Type': 'multipart/form-data' } }).then(r => r.data)
return postMultipart(`/trips/${tripId}/places/import/gpx`, fd)
},
importMapFile: (tripId: number | string, file: File, opts?: { points?: boolean; paths?: boolean }) => {
const fd = new FormData()
fd.append('file', file)
if (opts?.points !== undefined) fd.append('importPoints', String(opts.points))
if (opts?.paths !== undefined) fd.append('importPaths', String(opts.paths))
return apiClient.post(`/trips/${tripId}/places/import/map`, fd, { headers: { 'Content-Type': 'multipart/form-data' } }).then(r => r.data)
return postMultipart(`/trips/${tripId}/places/import/map`, fd)
},
importGoogleList: (tripId: number | string, url: string, enrich?: boolean) =>
apiClient.post(`/trips/${tripId}/places/import/google-list`, { url, enrich } satisfies PlaceImportListRequest).then(r => r.data),
@@ -470,7 +504,10 @@ export const adminApi = {
pluginUpdate: (id: string) => apiClient.post(`/admin/plugins/${id}/update`).then(r => r.data),
pluginUninstall: (id: string, deleteData: boolean) => apiClient.post(`/admin/plugins/${id}/uninstall`, { deleteData }).then(r => r.data),
pluginRescan: () => apiClient.post('/admin/plugins/rescan').then(r => r.data),
pluginUpload: (file: File) => { const fd = new FormData(); fd.append('file', file); return apiClient.post('/admin/plugins/upload', fd, { headers: { 'Content-Type': 'multipart/form-data' } }).then(r => r.data) },
pluginUpload: (file: File) => { const fd = new FormData(); fd.append('file', file); return postMultipart('/admin/plugins/upload', fd) },
// Dev-link (dev-only): register a plugin from a local built dir + hot-reload it.
pluginLink: (path: string) => apiClient.post('/admin/plugins/link', { path }).then(r => r.data),
pluginReload: (id: string) => apiClient.post(`/admin/plugins/${id}/reload`).then(r => r.data),
pluginErrors: (id: string) => apiClient.get(`/admin/plugins/${id}/errors`).then(r => r.data),
pluginAudit: (id: string) => apiClient.get(`/admin/plugins/${id}/audit`).then(r => r.data),
// Local LLM (Ollama) management for the AI-parsing addon.
@@ -555,6 +592,46 @@ export const addonsApi = {
enabled: () => apiClient.get('/addons').then(r => r.data),
}
/** A host-rendered column/action a plugin contributes into a native planner view
* (reservations/places/day) via the tableContributor hook. Every field is bounded +
* normalized server-side; a column url is guaranteed http/https/mailto. */
export type ViewContribution =
| { kind: 'column'; pluginId: string; entityId: number; id: string; label: string; value?: string; url?: string; icon?: string; tone: 'default' | 'success' | 'warn' | 'danger' }
| { kind: 'action'; pluginId: string; entityId: number; id: string; label: string; icon?: string; target: { kind: 'frame'; sub: string } | { kind: 'route'; method: 'GET' | 'POST'; sub: string } }
/** A badge a plugin adds to a dashboard trip card via the tripCardProvider hook.
* Bounded + normalized server-side; the url is guaranteed http/https/mailto. */
export interface TripCardBadge {
pluginId: string; tripId: number; id: string; label: string;
value?: string; icon?: string; tone: 'default' | 'success' | 'warn' | 'danger'; url?: string;
}
export interface PluginMapMarker {
pluginId: string; id: string; lat: number; lng: number;
label?: string; popupText?: string; url?: string; icon?: string;
tone: 'default' | 'success' | 'warn' | 'danger'
}
/** A text-only section a pdfSectionProvider plugin appends to the trip PDF export.
* Server-normalized: counts + lengths are capped, cells are plain strings. */
export interface PluginPdfSection {
pluginId: string; title: string; paragraphs: string[];
table?: { headers: string[]; rows: string[][] }
}
/** A country tint layer an atlasLayerProvider plugin draws over the Atlas map for
* the signed-in user. Codes are ISO alpha-2 (server-validated), tone enum-whitelisted. */
export interface PluginAtlasLayer {
pluginId: string; id: string; name?: string;
countries: Array<{ code: string; tone: 'default' | 'success' | 'warn' | 'danger'; label?: string }>
}
export interface PluginUserSettingField {
key: string; label?: string | null; input_type?: string; placeholder?: string | null;
hint?: string | null; required?: boolean; secret?: boolean;
options?: Array<{ value: string; label: string }>
}
export const pluginsApi = {
// Active plugins the client renders (page nav entries, dashboard widgets).
active: () => apiClient.get('/plugins').then(r => r.data),
@@ -565,6 +642,49 @@ export const pluginsApi = {
// Validation/warning contributions from warningProvider plugins (#1429). Fail-safe.
tripWarnings: (tripId: number) =>
apiClient.get(`/trip-warnings/${tripId}`).then(r => r.data as { warnings: Array<{ pluginId: string; level: 'info' | 'warning' | 'error'; message: string; dayId?: number; placeId?: number }> }),
// Host-rendered columns/actions plugins add into a native planner view via the
// tableContributor hook. Fetched once per view, keyed by entityId; fail-safe.
viewContributions: (view: 'reservations' | 'transports' | 'places' | 'day' | 'costs' | 'packing' | 'files' | 'todos', tripId: number | string) =>
apiClient.get(`/view-contributions/${view}/${tripId}`).then(r => r.data as { contributions: ViewContribution[] }),
// Bounded markers plugins overlay on the trip map via the mapMarkerProvider hook
// (#587). Host-normalized + range-checked; fail-safe (skips slow/failing providers).
mapMarkers: (tripId: number | string) =>
apiClient.get(`/map-markers/${tripId}`).then(r => r.data as { markers: PluginMapMarker[] }),
// Text-only sections plugins append to the trip PDF export via the
// pdfSectionProvider hook. Host-normalized (counts + lengths capped); fail-safe.
pdfSections: (tripId: number | string) =>
apiClient.get(`/pdf-sections/${tripId}`).then(r => r.data as { sections: PluginPdfSection[] }),
// Country tint layers plugins draw over the Atlas map for the signed-in user via
// the atlasLayerProvider hook. No tripId — user-scoped server-side; fail-safe.
atlasLayers: () =>
apiClient.get('/atlas-layers').then(r => r.data as { layers: PluginAtlasLayer[] }),
// Extra rows plugins add under a journal entry via the journalEntryProvider hook.
// Same shape + hardening as placeDetails (label/value/allowlisted url); fail-safe.
journalEntryRows: (entryId: number) =>
apiClient.get(`/journal-entry-rows/${entryId}`).then(r => r.data as { providers: Array<{ pluginId: string; items: Array<{ label: string; value?: string; url?: string }> }> }),
// Badges plugins add to the dashboard trip cards via the tripCardProvider hook.
// One call for all visible cards; host access-checks each tripId + bounds every
// field (label/value/tone/allowlisted url); fail-safe.
tripCardContributions: (tripIds: Array<number | string>) =>
apiClient.get(`/trip-card-contributions?tripIds=${tripIds.join(',')}`).then(r => r.data as { contributions: TripCardBadge[] }),
// The signed-in user's OWN plugin activity log — every host-mediated action a
// plugin took bound to them, across all plugins, newest first. The user-facing
// half of the capability audit; what makes the broad read grants accountable.
myActivity: (limit = 200) =>
apiClient.get(`/plugin-activity?limit=${limit}`).then(r => r.data as { activity: Array<{ ts: string; plugin_id: string; plugin_name: string | null; method: string; resource: string | null; code: string }> }),
// A user's OWN scope:'user' settings for a plugin (API key, prefs). Secrets are
// masked; the write only accepts declared user-scope keys.
userSettings: (id: string) =>
apiClient.get(`/plugin-settings/${id}`).then(r => r.data as { fields: PluginUserSettingField[]; config: Record<string, unknown> }),
saveUserSettings: (id: string, config: Record<string, unknown>) =>
apiClient.post(`/plugin-settings/${id}`, { config }).then(r => r.data as { config: Record<string, unknown> }),
// Host-brokered outbound OAuth (the host owns the tokens; the plugin only triggers).
oauthStatus: (id: string) =>
apiClient.get(`/plugin-oauth/${id}/status`).then(r => r.data as { configured: boolean; connected: boolean }),
oauthConnect: (id: string) =>
apiClient.post(`/plugin-oauth/${id}/connect`).then(r => r.data as { authorizeUrl: string }),
oauthDisconnect: (id: string) =>
apiClient.post(`/plugin-oauth/${id}/disconnect`).then(r => r.data as { connected: boolean }),
// Call one of a plugin's own declared routes through the host proxy. `sub` is
// supplied by untrusted plugin code (the trekBridge forwards it verbatim), so it
// MUST stay inside the plugin's own /plugins/:id/ namespace. We resolve it with
@@ -624,27 +744,12 @@ export const journeyApi = {
reorderEntries: (journeyId: number, orderedIds: number[]) => apiClient.put(`/journeys/${journeyId}/entries/reorder`, { orderedIds } satisfies JourneyReorderEntriesRequest).then(r => r.data),
// Photos
uploadPhotos: (entryId: number, formData: FormData, opts?: { onUploadProgress?: (e: import('axios').AxiosProgressEvent) => void; idempotencyKey?: string; signal?: AbortSignal }) =>
apiClient.post(`/journeys/entries/${entryId}/photos`, formData, {
headers: { 'Content-Type': undefined as any, ...(opts?.idempotencyKey ? { 'X-Idempotency-Key': opts.idempotencyKey } : {}) },
timeout: 0,
onUploadProgress: opts?.onUploadProgress,
signal: opts?.signal,
}).then(r => r.data),
uploadGalleryPhotos: (journeyId: number, formData: FormData, opts?: { onUploadProgress?: (e: import('axios').AxiosProgressEvent) => void; idempotencyKey?: string; signal?: AbortSignal }) =>
apiClient.post(`/journeys/${journeyId}/gallery/photos`, formData, {
headers: { 'Content-Type': undefined as any, ...(opts?.idempotencyKey ? { 'X-Idempotency-Key': opts.idempotencyKey } : {}) },
timeout: 0,
onUploadProgress: opts?.onUploadProgress,
signal: opts?.signal,
}).then(r => r.data),
uploadGalleryVideo: (journeyId: number, formData: FormData, opts?: { onUploadProgress?: (e: import('axios').AxiosProgressEvent) => void; idempotencyKey?: string; signal?: AbortSignal }) =>
apiClient.post(`/journeys/${journeyId}/gallery/video`, formData, {
headers: { 'Content-Type': undefined as any, ...(opts?.idempotencyKey ? { 'X-Idempotency-Key': opts.idempotencyKey } : {}) },
timeout: 0,
onUploadProgress: opts?.onUploadProgress,
signal: opts?.signal,
}).then(r => r.data),
uploadPhotos: (entryId: number, formData: FormData, opts?: UploadOptions) =>
postMultipart(`/journeys/entries/${entryId}/photos`, formData, opts),
uploadGalleryPhotos: (journeyId: number, formData: FormData, opts?: UploadOptions) =>
postMultipart(`/journeys/${journeyId}/gallery/photos`, formData, opts),
uploadGalleryVideo: (journeyId: number, formData: FormData, opts?: UploadOptions) =>
postMultipart(`/journeys/${journeyId}/gallery/video`, formData, opts),
addProviderPhotosToGallery: (journeyId: number, provider: string, assetIds: string[], passphrase?: string, mediaTypes?: string[]) => apiClient.post(`/journeys/${journeyId}/gallery/provider-photos`, { provider, asset_ids: assetIds, ...(passphrase ? { passphrase } : {}), ...(mediaTypes ? { media_types: mediaTypes } : {}) } satisfies JourneyProviderPhotosRequest).then(r => r.data),
addProviderPhoto: (entryId: number, provider: string, assetId: string, caption?: string, passphrase?: string) => apiClient.post(`/journeys/entries/${entryId}/provider-photos`, { provider, asset_id: assetId, caption, ...(passphrase ? { passphrase } : {}) }).then(r => r.data),
addProviderPhotos: (entryId: number, provider: string, assetIds: string[], caption?: string, passphrase?: string, mediaTypes?: string[]) => apiClient.post(`/journeys/entries/${entryId}/provider-photos`, { provider, asset_ids: assetIds, caption, ...(passphrase ? { passphrase } : {}), ...(mediaTypes ? { media_types: mediaTypes } : {}) }).then(r => r.data),
@@ -655,7 +760,7 @@ export const journeyApi = {
deletePhoto: (photoId: number) => apiClient.delete(`/journeys/photos/${photoId}`).then(r => r.data),
// Cover
uploadCover: (id: number, formData: FormData) => apiClient.post(`/journeys/${id}/cover`, formData, { headers: { 'Content-Type': undefined as any } }).then(r => r.data),
uploadCover: (id: number, formData: FormData) => postMultipart(`/journeys/${id}/cover`, formData),
// Contributors
addContributor: (id: number, userId: number, role: string) => apiClient.post(`/journeys/${id}/contributors`, { user_id: userId, role }).then(r => r.data),
@@ -711,9 +816,7 @@ export const budgetApi = {
export const filesApi = {
list: (tripId: number | string, trash?: boolean) => apiClient.get(`/trips/${tripId}/files`, { params: trash ? { trash: 'true' } : {} }).then(r => r.data),
upload: (tripId: number | string, formData: FormData) => apiClient.post(`/trips/${tripId}/files`, formData, {
headers: { 'Content-Type': 'multipart/form-data' }
}).then(r => r.data),
upload: (tripId: number | string, formData: FormData, opts?: UploadOptions) => postMultipart(`/trips/${tripId}/files`, formData, opts),
update: (tripId: number | string, id: number, data: FileUpdateRequest) => apiClient.put(`/trips/${tripId}/files/${id}`, data).then(r => r.data),
delete: (tripId: number | string, id: number) => apiClient.delete(`/trips/${tripId}/files/${id}`).then(r => r.data),
toggleStar: (tripId: number | string, id: number) => apiClient.patch(`/trips/${tripId}/files/${id}/star`).then(r => r.data),
@@ -738,7 +841,7 @@ export const reservationsApi = {
fd.append('mode', mode)
// No client-side timeout: kitinerary + LLM extraction routinely exceeds the
// global 8s default (a cold local model alone can take ~45s).
return apiClient.post(`/trips/${tripId}/reservations/import/booking`, fd, { headers: { 'Content-Type': 'multipart/form-data' }, timeout: 0 }).then(r => r.data)
return postMultipart(`/trips/${tripId}/reservations/import/booking`, fd)
},
importBookingConfirm: (tripId: number | string, items: BookingImportPreviewItem[]): Promise<BookingImportConfirmResponse> =>
apiClient.post(`/trips/${tripId}/reservations/import/booking/confirm`, { items }).then(r => r.data),
@@ -748,7 +851,7 @@ export const reservationsApi = {
const fd = new FormData()
for (const f of files) fd.append('files', f)
fd.append('mode', mode)
return apiClient.post(`/trips/${tripId}/reservations/import/booking/async`, fd, { headers: { 'Content-Type': 'multipart/form-data' }, timeout: 0 }).then(r => r.data)
return postMultipart(`/trips/${tripId}/reservations/import/booking/async`, fd)
},
// Poll a background job — recovery path when a WebSocket push was missed.
importJobStatus: (tripId: number | string, jobId: string): Promise<{ status: 'running' | 'done' | 'error'; done: number; total: number; result?: BookingImportPreviewResponse; error?: string }> =>
@@ -811,7 +914,7 @@ export const collabApi = {
createNote: (tripId: number | string, data: CollabNoteCreateRequest) => apiClient.post(`/trips/${tripId}/collab/notes`, data).then(r => r.data),
updateNote: (tripId: number | string, id: number, data: CollabNoteUpdateRequest) => apiClient.put(`/trips/${tripId}/collab/notes/${id}`, data).then(r => r.data),
deleteNote: (tripId: number | string, id: number) => apiClient.delete(`/trips/${tripId}/collab/notes/${id}`).then(r => r.data),
uploadNoteFile: (tripId: number | string, noteId: number, formData: FormData) => apiClient.post(`/trips/${tripId}/collab/notes/${noteId}/files`, formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(r => r.data),
uploadNoteFile: (tripId: number | string, noteId: number, formData: FormData) => postMultipart(`/trips/${tripId}/collab/notes/${noteId}/files`, formData),
deleteNoteFile: (tripId: number | string, noteId: number, fileId: number) => apiClient.delete(`/trips/${tripId}/collab/notes/${noteId}/files/${fileId}`).then(r => r.data),
getPolls: (tripId: number | string) => apiClient.get(`/trips/${tripId}/collab/polls`).then(r => r.data),
createPoll: (tripId: number | string, data: CollabPollCreateRequest) => apiClient.post(`/trips/${tripId}/collab/polls`, data).then(r => r.data),
@@ -846,7 +949,7 @@ export const backupApi = {
uploadRestore: (file: File) => {
const form = new FormData()
form.append('backup', file)
return apiClient.post('/backup/upload-restore', form, { headers: { 'Content-Type': 'multipart/form-data' } }).then(r => r.data)
return postMultipart('/backup/upload-restore', form)
},
getAutoSettings: () => apiClient.get('/backup/auto-settings').then(r => r.data),
setAutoSettings: (settings: Record<string, unknown>) => apiClient.put('/backup/auto-settings', settings).then(r => r.data),
+2 -2
View File
@@ -1,4 +1,4 @@
import apiClient from './client'
import apiClient, { postMultipart } from './client'
import type { AxiosResponse } from 'axios'
import type {
CollectionListResponse,
@@ -56,7 +56,7 @@ export const collectionsApi = {
update: (id: number, body: CollectionUpdateRequest): Promise<{ collection: Collection }> =>
ax.patch(`${base}/${id}`, body satisfies CollectionUpdateRequest).then((r: AxiosResponse) => r.data),
uploadCover: (id: number, formData: FormData): Promise<Collection> =>
ax.post(`${base}/${id}/cover`, formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then((r: AxiosResponse) => r.data),
postMultipart(`${base}/${id}/cover`, formData),
remove: (id: number): Promise<unknown> =>
ax.delete(`${base}/${id}`).then((r: AxiosResponse) => r.data),
reorder: (orderedIds: number[]): Promise<unknown> =>
+75
View File
@@ -0,0 +1,75 @@
// FE-API-UPLOAD-001 to FE-API-UPLOAD-013
//
// The shared axios instance carries timeout: 8000, and axios' timeout is a whole-request
// deadline — not an idle one. Any upload whose body takes longer than 8s to push is
// aborted mid-stream and the server reports a multer "Request aborted" (#1495).
//
// The original fix added `timeout: 0` to the three cover uploads by hand, which left the
// same bug live on 7 other endpoints — including the two that accept 500 MB (documents
// and backup restore). Every multipart call now goes through postMultipart(), so this
// suite pins ALL of them, not just the covers.
import { describe, it, expect, vi, afterEach } from 'vitest'
import {
apiClient,
authApi,
tripsApi,
placesApi,
adminApi,
journeyApi,
filesApi,
reservationsApi,
collabApi,
backupApi,
} from './client'
import { collectionsApi } from './collections'
describe('every multipart upload disables the global request timeout', () => {
afterEach(() => {
vi.restoreAllMocks()
})
function spyPost() {
return vi.spyOn(apiClient, 'post').mockResolvedValue({ data: {} } as any)
}
const fd = () => new FormData()
const file = () => new File(['x'], 'f.bin')
// [id, description, invoke, expected url]
const cases: [string, string, () => Promise<unknown>, string][] = [
['FE-API-UPLOAD-001', 'authApi.uploadAvatar (5 MB)', () => authApi.uploadAvatar(fd()), '/auth/avatar'],
['FE-API-UPLOAD-002', 'tripsApi.uploadCover (20 MB)', () => tripsApi.uploadCover(7, fd()), '/trips/7/cover'],
['FE-API-UPLOAD-003', 'placesApi.importGpx (10 MB)', () => placesApi.importGpx(7, file()), '/trips/7/places/import/gpx'],
['FE-API-UPLOAD-004', 'placesApi.importMapFile (10 MB)', () => placesApi.importMapFile(7, file()), '/trips/7/places/import/map'],
['FE-API-UPLOAD-005', 'adminApi.pluginUpload (50 MB)', () => adminApi.pluginUpload(file()), '/admin/plugins/upload'],
['FE-API-UPLOAD-006', 'journeyApi.uploadCover (20 MB)', () => journeyApi.uploadCover(7, fd()), '/journeys/7/cover'],
['FE-API-UPLOAD-007', 'journeyApi.uploadPhotos (20 MB)', () => journeyApi.uploadPhotos(7, fd()), '/journeys/entries/7/photos'],
['FE-API-UPLOAD-008', 'journeyApi.uploadGalleryVideo (500 MB)', () => journeyApi.uploadGalleryVideo(7, fd()), '/journeys/7/gallery/video'],
['FE-API-UPLOAD-009', 'filesApi.upload (500 MB)', () => filesApi.upload(7, fd()), '/trips/7/files'],
['FE-API-UPLOAD-010', 'collabApi.uploadNoteFile (50 MB)', () => collabApi.uploadNoteFile(7, 3, fd()), '/trips/7/collab/notes/3/files'],
['FE-API-UPLOAD-011', 'backupApi.uploadRestore (500 MB)', () => backupApi.uploadRestore(file()), '/backup/upload-restore'],
['FE-API-UPLOAD-012', 'collectionsApi.uploadCover (20 MB)', () => collectionsApi.uploadCover(7, fd()), '/addons/collections/7/cover'],
]
for (const [id, desc, invoke, url] of cases) {
it(`${id}: ${desc} posts with timeout 0`, async () => {
const post = spyPost()
await invoke()
expect(post).toHaveBeenCalledWith(
url,
expect.any(FormData),
expect.objectContaining({ timeout: 0 }),
)
})
}
it('FE-API-UPLOAD-013: reservationsApi booking import posts with timeout 0', async () => {
const post = spyPost()
await reservationsApi.importBookingPreview(7, [file()])
expect(post).toHaveBeenCalledWith(
'/trips/7/reservations/import/booking',
expect.any(FormData),
expect.objectContaining({ timeout: 0 }),
)
})
})
+125 -17
View File
@@ -1,12 +1,13 @@
import { useEffect, useMemo, useRef, useState, type DragEvent } from 'react'
import {
Blocks, AlertTriangle, PackageOpen, RefreshCw, Trash2, Download, Bug, X, ShieldCheck, UploadCloud,
ArrowUpCircle, Github, ExternalLink, ChevronDown, Check, Lock, Search,
ArrowUpCircle, Github, ExternalLink, ChevronDown, Check, Lock, Search, Link2,
SlidersHorizontal, ArrowUpDown, CircleDot, MoreHorizontal, RotateCw, ArrowRight, Database, Users, LayoutDashboard,
Radio, Luggage, Plane, Globe, Image, CalendarDays, Map, Bell, Cloud, Camera, Compass,
BookOpen, Wallet, Puzzle, MapPin, ListChecks, Pencil, Tag, FileText,
} from 'lucide-react'
import { adminApi } from '../../api/client'
import { usePluginStore } from '../../store/pluginStore'
import { useTranslation } from '../../i18n'
import { useToast } from '../shared/Toast'
import ConfirmDialog from '../shared/ConfirmDialog'
@@ -56,6 +57,7 @@ interface RegistryItem {
latest: string | null
minTrekVersion: string | null
reviewedAt: string | null
downloadCount?: number | null
screenshotUrl: string | null
requiredAddons?: string[]
pluginDependencies?: PluginDep[]
@@ -85,7 +87,7 @@ interface ActivateErr {
type T = (k: string, p?: Record<string, unknown>) => string
type TypeFilter = 'all' | 'widget' | 'page' | 'integration' | 'trip-page'
type StatusFilter = 'all' | 'on' | 'off' | 'update' | 'err'
type SortKey = 'name' | 'recent' | 'updates'
type SortKey = 'name' | 'recent' | 'updates' | 'downloads'
// Runtime health → dot colour on the icon tile.
const HEALTH: Record<string, string> = {
@@ -104,12 +106,19 @@ const ICON_MAP: Record<string, React.ComponentType<{ size?: number; className?:
// Known permissions → human-readable i18n key; unknown ones render as raw code.
const PERM_KEYS = [
'db:own', 'db:read:trips', 'db:read:users', 'db:read:costs', 'db:read:packing', 'db:read:files', 'db:write:costs',
'db:write:places', 'db:write:days', 'db:write:itinerary', 'db:write:trips',
'db:own', 'db:read:trips', 'db:read:users', 'db:read:costs', 'db:read:packing', 'db:read:files', 'db:read:files:content',
'db:read:collab', 'db:read:journal', 'db:read:atlas', 'db:read:vacay', 'db:read:daynotes', 'db:read:collections',
'db:read:categories', 'db:read:tags', 'db:read:todos', 'weather:read', 'rates:read', 'db:write:costs',
'db:write:places', 'db:write:days', 'db:write:itinerary', 'db:write:trips', 'db:write:reservations', 'db:write:accommodations', 'db:write:daynotes', 'db:write:packing',
'db:write:tags', 'db:write:todos', 'db:write:atlas', 'db:write:vacay', 'db:write:journal', 'db:write:collections',
'db:write:files', 'db:write:collab', 'db:write:members',
'db:create:trips',
'db:meta',
'events:subscribe',
'notify:send', 'ai:invoke', 'oauth:client',
'events:subscribe', 'jobs:run',
'ws:broadcast:trip', 'ws:broadcast:user',
'hook:photo-provider', 'hook:calendar-source', 'hook:place-detail-provider', 'hook:trip-warning-provider', 'http:outbound',
'hook:photo-provider', 'hook:calendar-source', 'hook:place-detail-provider', 'hook:trip-warning-provider', 'hook:table-contributor', 'hook:map-marker-provider',
'hook:pdf-section-provider', 'hook:atlas-layer-provider', 'hook:journal-entry-provider', 'hook:trip-card-provider', 'hook:user-data', 'http:outbound',
]
const KNOWN_TYPES = ['widget', 'page', 'integration', 'trip-page']
@@ -132,7 +141,7 @@ interface Cap { icon: React.ComponentType<{ size?: number; className?: string }>
// Turn a plugin's declared permissions + capabilities into the at-a-glance chips
// that make its real reach legible without opening the detail dialog.
function deriveCaps(perms: string[], caps: { widget?: { slot?: string } }, t: T): Cap[] {
function deriveCaps(perms: string[], caps: { widget?: { slot?: string }; tripPage?: { replaces?: string[] } }, t: T): Cap[] {
const out: Cap[] = []
if (perms.includes('db:read:trips')) out.push({ icon: Database, label: t('admin.plugins.cap.readsTrips') })
if (perms.includes('db:read:users')) out.push({ icon: Users, label: t('admin.plugins.cap.readsUsers') })
@@ -148,9 +157,13 @@ function deriveCaps(perms: string[], caps: { widget?: { slot?: string } }, t: T)
if (caps.widget) {
const slotKey = caps.widget.slot === 'hero' ? 'admin.plugins.cap.heroWidget'
: caps.widget.slot === 'place-detail' ? 'admin.plugins.cap.placeSlot'
: caps.widget.slot === 'day-detail' ? 'admin.plugins.cap.daySlot'
: caps.widget.slot === 'reservation-detail' ? 'admin.plugins.cap.reservationSlot'
: 'admin.plugins.cap.widget'
out.push({ icon: LayoutDashboard, label: t(slotKey as never) })
}
// Replacing planner tabs is the one capability that HIDES core UI — always chip it.
if (caps.tripPage?.replaces?.length) out.push({ icon: LayoutDashboard, label: t('admin.plugins.cap.replacesTabs') })
if (perms.some(p => p.startsWith('ws:broadcast'))) out.push({ icon: Radio, label: t('admin.plugins.cap.realtime') })
if (perms.includes('hook:photo-provider')) out.push({ icon: Image, label: t('admin.plugins.cap.photos') })
if (perms.includes('hook:calendar-source')) out.push({ icon: CalendarDays, label: t('admin.plugins.cap.calendar') })
@@ -204,6 +217,16 @@ function SideloadedBadge({ t }: { t: T }) {
)
}
/** Marks a dev-linked plugin: loaded from a local build dir + hot-reloaded (dev only). */
function DevLinkBadge({ t }: { t: T }) {
return (
<span className="inline-flex items-center gap-1 px-1.5 py-[2px] rounded-md text-[11px] font-medium bg-accent-soft text-accent border border-accent/25"
title={t('admin.plugins.devLinkHint')}>
<Link2 size={11} /> {t('admin.plugins.devLinkBadge')}
</span>
)
}
function TypeBadge({ type, t }: { type: string; t: T }) {
return (
<span className="inline-flex items-center px-2 py-0.5 rounded-md text-[10px] font-semibold uppercase tracking-wide bg-accent-subtle text-content-muted">
@@ -216,6 +239,8 @@ export default function AdminPluginsPanel() {
const { t, locale } = useTranslation()
const toast = useToast()
const [runtimeOn, setRuntimeOn] = useState(false)
const [devLink, setDevLink] = useState(false) // dev-link enabled server-side (TREK_PLUGINS_DEV_LINK)
const [linkPath, setLinkPath] = useState('')
const [plugins, setPlugins] = useState<PluginRow[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState(false)
@@ -239,15 +264,27 @@ export default function AdminPluginsPanel() {
const [statusFilter, setStatusFilter] = useState<StatusFilter>('all')
const [sort, setSort] = useState<SortKey>('name')
// 'updates' only ranks installed plugins, 'downloads' only the registry — snap
// the key back to name when switching tabs so the dropdown never carries a label
// for an option the active tab can't offer.
useEffect(() => {
if (view === 'discover' && sort === 'updates') setSort('name')
else if (view === 'installed' && sort === 'downloads') setSort('name')
}, [view, sort])
// Sideload upload: drag a plugin .zip onto the panel or use the toolbar button.
const [dragActive, setDragActive] = useState(false)
const uploadInputRef = useRef<HTMLInputElement>(null)
const dragDepth = useRef(0)
const refresh = () => {
// Keep the app-wide active-plugin store in sync so widget/hero/tab consumers
// (e.g. the dashboard) reflect an activate/deactivate without a full reload (F5).
void usePluginStore.getState().loadPlugins()
adminApi.plugins()
.then((d: { enabled: boolean; plugins: PluginRow[] }) => {
.then((d: { enabled: boolean; devLink?: boolean; plugins: PluginRow[] }) => {
setRuntimeOn(!!d.enabled)
setDevLink(!!d.devLink)
setPlugins(d.plugins || [])
if ((d.plugins || []).length) {
adminApi.pluginBrowse()
@@ -322,6 +359,23 @@ export default function AdminPluginsPanel() {
const updateAvailable = (p: PluginRow) => !!(p.version && latest[p.id] && isNewer(latest[p.id], p.version))
const install = (id: string) => act(id, () => adminApi.pluginInstall(id), t('admin.plugins.installed'))
const restart = (id: string) => act(id, async () => { await adminApi.pluginDeactivate(id); await adminApi.pluginActivate(id) }, t('admin.plugins.restarted'))
// Dev-link: register a plugin from a local built directory (dev only). Reuses the
// same busy/toast/refresh loop as uploadPlugin; the server gates it.
const linkLocal = async () => {
const p = linkPath.trim()
if (!p) return
setBusy('__link'); setMenu(null)
try {
const res = await adminApi.pluginLink(p)
setView('installed')
setLinkPath('')
toast.success(t('admin.plugins.devLinkLinked', { id: res.id }))
} catch (e) {
toast.error((e as { response?: { data?: { error?: string } } })?.response?.data?.error || t('admin.plugins.actionError'))
} finally {
setBusy(null); refresh()
}
}
const installedIds = new Set(plugins.map(p => p.id))
// Installed-but-disabled direct deps that enabling `p` will auto-enable first.
@@ -431,9 +485,13 @@ export default function AdminPluginsPanel() {
const matchesType = typeFilter === 'all' || r.type === typeFilter
return matchesText && matchesType
})
items = [...items].sort((a, b) => a.name.localeCompare(b.name))
items = [...items].sort((a, b) => {
if (sort === 'downloads') return (b.downloadCount ?? 0) - (a.downloadCount ?? 0) || a.name.localeCompare(b.name)
if (sort === 'recent') return (Date.parse(b.reviewedAt ?? '') || 0) - (Date.parse(a.reviewedAt ?? '') || 0) || a.name.localeCompare(b.name)
return a.name.localeCompare(b.name)
})
return items
}, [registry, q, typeFilter])
}, [registry, q, typeFilter, sort])
const anyFilter = q.trim() !== '' || typeFilter !== 'all' || statusFilter !== 'all'
@@ -478,6 +536,24 @@ export default function AdminPluginsPanel() {
</div>
)}
{/* Dev-link: register + hot-reload a plugin from a local build dir (dev only). */}
{devLink && runtimeOn && !loading && !error && (
<form onSubmit={(e) => { e.preventDefault(); void linkLocal() }}
className="mx-4 sm:mx-6 mt-4 p-3 rounded-xl border border-accent/30 bg-accent-soft flex flex-col sm:flex-row sm:items-center gap-2.5">
<div className="flex items-center gap-2 shrink-0 text-accent" title={t('admin.plugins.devLinkHint')}>
<Link2 size={15} />
<span className="text-xs font-semibold">{t('admin.plugins.devLinkTitle')}</span>
</div>
<input value={linkPath} onChange={(e) => setLinkPath(e.target.value)} spellCheck={false}
placeholder={t('admin.plugins.devLinkPathPlaceholder')}
className="flex-1 min-w-0 h-[34px] px-2.5 rounded-lg border border-edge bg-surface-card text-sm text-content placeholder:text-content-faint focus:outline-none focus:border-accent" />
<button type="submit" disabled={!linkPath.trim() || busy === '__link'}
className="h-[34px] px-3.5 shrink-0 inline-flex items-center justify-center gap-1.5 rounded-lg bg-accent text-white text-sm font-medium hover:bg-accent-hover disabled:opacity-50 transition-colors">
<Link2 size={14} /> {t('admin.plugins.devLinkButton')}
</button>
</form>
)}
{/* Toolbar — on mobile: tabs+rescan, then full-width search, then a
right-aligned filter row. On sm+ the wrappers collapse (sm:contents)
so everything sits in one wrapping row. */}
@@ -530,7 +606,9 @@ export default function AdminPluginsPanel() {
)}
<FilterMenu id="sort" label={t('admin.plugins.sortBy')} value={sort} menu={menu} setMenu={setMenu} icon={<ArrowUpDown size={14} />}
options={[['name', t('admin.plugins.sortName')], ['recent', t('admin.plugins.sortRecent')], ['updates', t('admin.plugins.sortUpdates')]]}
options={view === 'discover'
? [['name', t('admin.plugins.sortName')], ['recent', t('admin.plugins.sortRecent')], ['downloads', t('admin.plugins.sortDownloads')]]
: [['name', t('admin.plugins.sortName')], ['recent', t('admin.plugins.sortRecent')], ['updates', t('admin.plugins.sortUpdates')]]}
valueLabel={sortLabel(sort, t)}
onPick={v => setSort(v as SortKey)} />
@@ -654,7 +732,10 @@ function statusLabel(s: StatusFilter, t: T): string {
: s === 'off' ? t('admin.plugins.stateOff') : s === 'update' ? t('admin.plugins.filterUpdate') : t('admin.plugins.status.error')
}
function sortLabel(s: SortKey, t: T): string {
return s === 'name' ? t('admin.plugins.sortName') : s === 'recent' ? t('admin.plugins.sortRecent') : t('admin.plugins.sortUpdates')
return s === 'name' ? t('admin.plugins.sortName')
: s === 'recent' ? t('admin.plugins.sortRecent')
: s === 'downloads' ? t('admin.plugins.sortDownloads')
: t('admin.plugins.sortUpdates')
}
function SegBtn({ active, onClick, label, count }: { active: boolean; onClick: () => void; label: string; count?: number }) {
@@ -742,6 +823,7 @@ function InstalledRow({ p, t, busy, menu, setMenu, hasUpdate, latestVer, onToggl
{p.version && <span className="text-[11.5px] text-content-faint font-medium tabular-nums">v{p.version}</span>}
{p.reviewed_at && <ReviewedBadge t={t} compact />}
{p.source_repo === 'local:upload' && <SideloadedBadge t={t} />}
{p.source_repo === 'local:link' && <DevLinkBadge t={t} />}
</div>
{p.description && <p className="text-[12.5px] text-content-muted mt-0.5 truncate">{p.description}</p>}
{p.status === 'error' && p.last_error ? (
@@ -792,11 +874,17 @@ function InstalledRow({ p, t, busy, menu, setMenu, hasUpdate, latestVer, onToggl
<MenuItem icon={<RotateCw size={14} />} label={t('admin.plugins.restart')} onClick={onRestart} />
)}
<MenuItem icon={<Bug size={14} />} label={t('admin.plugins.viewErrors')} onClick={onErrors} />
{p.source_repo && p.source_repo !== 'local:upload' && (
<a href={`https://github.com/${p.source_repo}`} target="_blank" rel="noreferrer" onClick={() => setMenu(null)}
className="w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-[13px] text-content-secondary hover:bg-surface-tertiary transition-colors">
<Github size={14} /> {t('admin.plugins.sourceRepo')}
</a>
{p.source_repo && p.source_repo !== 'local:upload' && p.source_repo !== 'local:link' && (
<>
<a href={`https://github.com/${p.source_repo}`} target="_blank" rel="noreferrer" onClick={() => setMenu(null)}
className="w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-[13px] text-content-secondary hover:bg-surface-tertiary transition-colors">
<Github size={14} /> {t('admin.plugins.sourceRepo')}
</a>
<a href={`https://github.com/${p.source_repo}/issues`} target="_blank" rel="noreferrer" onClick={() => setMenu(null)}
className="w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-[13px] text-content-secondary hover:bg-surface-tertiary transition-colors">
<CircleDot size={14} /> {t('admin.plugins.reportIssue')}
</a>
</>
)}
<div className="my-1 border-t border-edge-secondary" />
<MenuItem icon={<Trash2 size={14} />} label={t('common.delete')} danger onClick={onUninstall} />
@@ -876,6 +964,11 @@ function RegistryGrid({ items, onInstall, onOpenDetail, busy, t, installedIds, f
<div className="flex items-center gap-2 mt-3">
<TypeBadge type={item.type} t={t} />
{item.latest && <span className="text-[10.5px] text-content-faint tabular-nums">v{item.latest}</span>}
{typeof item.downloadCount === 'number' && item.downloadCount > 0 && (
<span className="inline-flex items-center gap-1 text-[10.5px] text-content-faint tabular-nums" title={t('admin.plugins.downloads')}>
<Download size={11} /> {formatCompactCount(item.downloadCount)}
</span>
)}
<button onClick={e => { e.stopPropagation(); onInstall(item.id) }} disabled={busy === item.id || installed}
className="ml-auto text-xs font-semibold px-3.5 py-1.5 rounded-lg bg-accent text-accent-text hover:bg-accent-hover disabled:opacity-50 disabled:bg-surface-tertiary disabled:text-content-faint transition-colors">
{installed ? t('admin.plugins.installed') : t('admin.plugins.install')}
@@ -889,6 +982,14 @@ function RegistryGrid({ items, onInstall, onOpenDetail, busy, t, installedIds, f
)
}
// 1234 -> "1.2k" — GitHub-style compact download counts for the browse cards.
// The M threshold sits at the k-rounding boundary so 999 950 is "1M", not "1000k".
function formatCompactCount(n: number): string {
if (n >= 999_500) return `${Math.round(n / 100_000) / 10}M`
if (n >= 1000) return `${Math.round(n / 100) / 10}k`
return String(n)
}
// A permission rendered human-readable when known, else as its raw code.
function PermLabel({ perm, t }: { perm: string; t: T }) {
return PERM_KEYS.includes(perm)
@@ -1002,6 +1103,9 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
{sizeKb && <Meta k={t('admin.plugins.metaSize')} v={`${sizeKb} KB`} />}
{item.minTrekVersion && <Meta k={t('admin.plugins.metaRequires')} v={`TREK ${item.minTrekVersion}+`} />}
{item.reviewedAt && <Meta k={t('admin.plugins.metaReviewed')} v={new Date(item.reviewedAt).toLocaleDateString(locale)} />}
{typeof item.downloadCount === 'number' && item.downloadCount > 0 && (
<Meta k={t('admin.plugins.downloads')} v={item.downloadCount.toLocaleString(locale)} />
)}
</div>
</div>
</div>
@@ -1011,6 +1115,10 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
className="inline-flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded-lg border border-edge bg-surface-card text-content-secondary hover:text-content hover:border-content-faint transition-colors">
<Github size={13} /> {t('admin.plugins.sourceRepo')}
</a>
<a href={`${repoUrl}/issues`} target="_blank" rel="noreferrer"
className="inline-flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded-lg border border-edge bg-surface-card text-content-secondary hover:text-content hover:border-content-faint transition-colors">
<CircleDot size={13} /> {t('admin.plugins.reportIssue')}
</a>
{homepage && (
<a href={homepage} target="_blank" rel="noreferrer"
className="inline-flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded-lg border border-edge bg-surface-card text-content-secondary hover:text-content hover:border-content-faint transition-colors">
@@ -6,7 +6,7 @@ import { useToast } from '../shared/Toast'
import Section from '../Settings/Section'
import CustomSelect from '../shared/CustomSelect'
import { MapView } from '../Map/MapView'
import { CURRENCIES, SYMBOLS } from '../Budget/BudgetPanel.constants'
import { SYMBOLS, currenciesWith } from '../Budget/BudgetPanel.constants'
import type { DistanceUnit, Place } from '../../types'
import {
MAPBOX_DEFAULT_STYLE,
@@ -286,7 +286,7 @@ export default function DefaultUserSettingsTab(): React.ReactElement {
onChange={(value: string) => { if (value) save({ default_currency: value }) }}
placeholder={t('settings.currency')}
searchable
options={CURRENCIES.map(c => ({ value: c, label: SYMBOLS[c] ? `${c} ${SYMBOLS[c]}` : c }))}
options={currenciesWith(defaults.default_currency).map(c => ({ value: c, label: SYMBOLS[c] ? `${c} ${SYMBOLS[c]}` : c }))}
size="sm"
style={{ maxWidth: 240 }}
/>
@@ -1,23 +1,72 @@
// The full set of currencies the Frankfurter v2 FX API supports (archived codes
// excluded), so every selectable currency actually converts. Regenerate from
// `GET https://api.frankfurter.dev/v2/currencies?expand=providers` (iso_code +
// symbol) if the provider's list changes. See issue #1470.
export const CURRENCIES = [
'EUR', 'USD', 'GBP', 'JPY', 'CHF', 'CZK', 'PLN', 'SEK', 'NOK', 'DKK',
'TRY', 'THB', 'AUD', 'CAD', 'NZD', 'BRL', 'MXN', 'INR', 'IDR', 'MYR',
'PHP', 'SGD', 'KRW', 'CNY', 'HKD', 'TWD', 'ZAR', 'AED', 'SAR', 'ILS',
'EGP', 'MAD', 'HUF', 'RON', 'BGN', 'HRK', 'ISK', 'RUB', 'UAH', 'KGS',
'BDT', 'LKR', 'VND', 'CLP', 'COP', 'PEN', 'ARS',
'AED', 'AFN', 'ALL', 'AMD', 'ANG', 'AOA', 'ARS', 'AUD', 'AWG', 'AZN',
'BAM', 'BBD', 'BDT', 'BHD', 'BIF', 'BMD', 'BND', 'BOB', 'BRL', 'BSD',
'BTN', 'BWP', 'BYN', 'BZD', 'CAD', 'CDF', 'CHF', 'CLP', 'CNH', 'CNY',
'COP', 'CRC', 'CUP', 'CVE', 'CZK', 'DJF', 'DKK', 'DOP', 'DZD', 'EGP',
'ERN', 'ETB', 'EUR', 'FJD', 'FKP', 'GBP', 'GEL', 'GGP', 'GHS', 'GIP',
'GMD', 'GNF', 'GTQ', 'GYD', 'HKD', 'HNL', 'HTG', 'HUF', 'IDR', 'ILS',
'IMP', 'INR', 'IQD', 'IRR', 'ISK', 'JEP', 'JMD', 'JOD', 'JPY', 'KES',
'KGS', 'KHR', 'KMF', 'KPW', 'KRW', 'KWD', 'KYD', 'KZT', 'LAK', 'LBP',
'LKR', 'LRD', 'LSL', 'LYD', 'MAD', 'MDL', 'MGA', 'MKD', 'MMK', 'MNT',
'MOP', 'MRO', 'MRU', 'MUR', 'MVR', 'MWK', 'MXN', 'MYR', 'MZN', 'NAD',
'NGN', 'NIO', 'NOK', 'NPR', 'NZD', 'OMR', 'PAB', 'PEN', 'PGK', 'PHP',
'PKR', 'PLN', 'PYG', 'QAR', 'RON', 'RSD', 'RUB', 'RWF', 'SAR', 'SBD',
'SCR', 'SDG', 'SEK', 'SGD', 'SHP', 'SLE', 'SOS', 'SRD', 'SSP', 'STN',
'SVC', 'SYP', 'SZL', 'THB', 'TJS', 'TMT', 'TND', 'TOP', 'TRY', 'TTD',
'TWD', 'TZS', 'UAH', 'UGX', 'USD', 'UYU', 'UZS', 'VES', 'VND', 'VUV',
'WST', 'XAF', 'XAG', 'XAU', 'XCD', 'XCG', 'XDR', 'XOF', 'XPD', 'XPF',
'XPT', 'YER', 'ZAR', 'ZMW', 'ZWG',
]
export const SYMBOLS: Record<string, string> = {
EUR: '€', USD: '$', GBP: '£', JPY: '¥', CHF: 'CHF', CZK: 'Kč', PLN: 'zł',
SEK: 'kr', NOK: 'kr', DKK: 'kr', TRY: '₺', THB: '฿', AUD: 'A$', CAD: 'C$',
NZD: 'NZ$', BRL: 'R$', MXN: 'MX$', INR: '₹', IDR: 'Rp', MYR: 'RM',
PHP: '₱', SGD: 'S$', KRW: '₩', CNY: '¥', HKD: 'HK$', TWD: 'NT$',
ZAR: 'R', AED: 'د.إ', SAR: '﷼', ILS: '₪', EGP: 'E£', MAD: 'MAD',
HUF: 'Ft', RON: 'lei', BGN: 'лв', HRK: 'kn', ISK: 'kr', RUB: '₽',
UAH: '₴', KGS: 'сом', BDT: '৳', LKR: 'Rs', VND: '₫', CLP: 'CL$',
COP: 'CO$', PEN: 'S/.', ARS: 'AR$',
AED: 'د.إ', AFN: '؋', ALL: 'L', AMD: '֏', ANG: 'ƒ',
AOA: 'Kz', ARS: '$', AUD: '$', AWG: 'ƒ', AZN: '₼',
BAM: 'КМ', BBD: '$', BDT: '৳', BHD: 'د.ب', BIF: 'Fr',
BMD: '$', BND: '$', BOB: 'Bs.', BRL: 'R$', BSD: '$',
BTN: 'Nu.', BWP: 'P', BYN: 'Br', BZD: '$', CAD: '$',
CDF: 'Fr', CHF: 'CHF', CLP: '$', CNH: '¥', CNY: '¥',
COP: '$', CRC: '₡', CUP: '$', CVE: '$', CZK: 'Kč',
DJF: 'Fdj', DKK: 'kr.', DOP: '$', DZD: 'د.ج', EGP: 'ج.م',
ERN: 'Nfk', ETB: 'Br', EUR: '€', FJD: '$', FKP: '£',
GBP: '£', GEL: '₾', GGP: '£', GHS: '₵', GIP: '£',
GMD: 'D', GNF: 'Fr', GTQ: 'Q', GYD: '$', HKD: '$',
HNL: 'L', HTG: 'G', HUF: 'Ft', IDR: 'Rp', ILS: '₪',
IMP: '£', INR: '₹', IQD: 'ع.د', IRR: '﷼', ISK: 'kr.',
JEP: '£', JMD: '$', JOD: 'د.ا', JPY: '¥', KES: 'KSh',
KGS: 'som', KHR: '៛', KMF: 'Fr', KPW: '₩', KRW: '₩',
KWD: 'د.ك', KYD: '$', KZT: '₸', LAK: '₭', LBP: 'ل.ل',
LKR: '₨', LRD: '$', LSL: 'L', LYD: 'ل.د', MAD: 'د.م.',
MDL: 'L', MGA: 'Ar', MKD: 'ден', MMK: 'K', MNT: '₮',
MOP: 'P', MRO: 'UM', MRU: 'UM', MUR: '₨', MVR: 'MVR',
MWK: 'MK', MXN: '$', MYR: 'RM', MZN: 'MTn', NAD: '$',
NGN: '₦', NIO: 'C$', NOK: 'kr', NPR: 'Rs.', NZD: '$',
OMR: 'ر.ع.', PAB: 'B/.', PEN: 'S/', PGK: 'K', PHP: '₱',
PKR: '₨', PLN: 'zł', PYG: '₲', QAR: 'ر.ق', RON: 'Lei',
RSD: 'RSD', RUB: '₽', RWF: 'FRw', SAR: 'ر.س', SBD: '$',
SCR: '₨', SDG: '£', SEK: 'kr', SGD: '$', SHP: '£',
SLE: 'Le', SOS: 'Sh', SRD: '$', SSP: '£', STN: 'Db',
SVC: '₡', SYP: '£S', SZL: 'E', THB: '฿', TJS: 'ЅМ',
TMT: 'm', TND: 'د.ت', TOP: 'T$', TRY: '₺', TTD: '$',
TWD: '$', TZS: 'Sh', UAH: '₴', UGX: 'USh', USD: '$',
UYU: '$U', UZS: 'so\'m', VES: 'Bs', VND: '₫', VUV: 'Vt',
WST: 'T', XAF: 'CFA', XAG: 'oz t', XAU: 'oz t', XCD: '$',
XCG: 'Cg', XDR: 'SDR', XOF: 'Fr', XPD: 'oz t', XPF: 'Fr',
XPT: 'oz t', YER: '﷼', ZAR: 'R', ZMW: 'K', ZWG: 'ZiG',
}
export const PIE_COLORS = ['#6366f1', '#ec4899', '#f59e0b', '#10b981', '#3b82f6', '#8b5cf6', '#ef4444', '#14b8a6', '#f97316', '#06b6d4', '#84cc16', '#a855f7']
// Keep a currency the user already saved selectable even after it leaves the
// supported set (e.g. archived BGN/HRK), so opening an existing item or settings
// row doesn't silently blank the field and wipe the value on the next save.
export function currenciesWith(current?: string | null): readonly string[] {
const cur = (current || '').toUpperCase()
return cur && !CURRENCIES.includes(cur) ? [...CURRENCIES, cur] : CURRENCIES
}
export const PIE_COLORS =['#6366f1', '#ec4899', '#f59e0b', '#10b981', '#3b82f6', '#8b5cf6', '#ef4444', '#14b8a6', '#f97316', '#06b6d4', '#84cc16', '#a855f7']
export const SPLIT_COLORS = [
{ solid: '#6366f1', gradient: 'linear-gradient(135deg, #6366f1, #8b5cf6)' },
@@ -0,0 +1,28 @@
import { describe, it, expect } from 'vitest'
import { calcPP, hasCustomMemberSplit } from './BudgetPanel.helpers'
describe('BudgetPanel.helpers', () => {
describe('hasCustomMemberSplit (#1458)', () => {
it('is false when no members', () => {
expect(hasCustomMemberSplit({})).toBe(false)
expect(hasCustomMemberSplit({ members: [] })).toBe(false)
})
it('is false for an equal split (members carry no amount)', () => {
expect(hasCustomMemberSplit({ members: [{ amount: null }, { amount: null }] })).toBe(false)
expect(hasCustomMemberSplit({ members: [{}, {}] })).toBe(false)
})
it('is true as soon as any member has a custom amount', () => {
expect(hasCustomMemberSplit({ members: [{ amount: 90 }, { amount: 10 }] })).toBe(true)
expect(hasCustomMemberSplit({ members: [{ amount: null }, { amount: 10 }] })).toBe(true)
expect(hasCustomMemberSplit({ members: [{ amount: 0 }] })).toBe(true)
})
})
it('calcPP still averages the total for equal splits', () => {
expect(calcPP(100, 2)).toBe(50)
expect(calcPP(100, 0)).toBeNull()
expect(calcPP(100, null)).toBeNull()
})
})
@@ -64,6 +64,12 @@ export const calcPP = (p: NumOrNull, n: NumOrNull) => (n! > 0 ? (p as number) /
export const calcPD = (p: NumOrNull, d: NumOrNull) => (d! > 0 ? (p as number) / (d as number) : null)
export const calcPPD = (p: NumOrNull, n: NumOrNull, d: NumOrNull) => (n! > 0 && d! > 0 ? (p as number) / ((n as number) * (d as number)) : null)
// A custom (uneven) split has no single "per person" figure — one member's share
// differs from another's — so the averaged per-person columns are meaningless for it
// (the per-member amounts are shown via the member chips instead). #1458
export const hasCustomMemberSplit = (item: { members?: { amount?: number | null }[] }) =>
(item.members || []).some(m => m.amount != null)
export function splitColorFor(userId: number, order: number) {
return SPLIT_COLORS[order % SPLIT_COLORS.length]
}
+2 -2
View File
@@ -1,6 +1,6 @@
import { Plus, Calculator, Download } from 'lucide-react'
import CustomSelect from '../shared/CustomSelect'
import { CURRENCIES, SYMBOLS } from './BudgetPanel.constants'
import { currenciesWith, SYMBOLS } from './BudgetPanel.constants'
import { useBudgetPanel } from './useBudgetPanel'
import type { TripMember } from './BudgetPanelMemberChips'
import BudgetCategoryTable from './BudgetPanelCategoryTable'
@@ -74,7 +74,7 @@ export default function BudgetPanel({ tripId, tripMembers = [] }: BudgetPanelPro
value={currency}
onChange={setCurrency}
disabled={!canEdit}
options={CURRENCIES.map(c => ({ value: c, label: `${c} (${SYMBOLS[c] || c})` }))}
options={currenciesWith(currency).map(c => ({ value: c, label: `${c} (${SYMBOLS[c] || c})` }))}
searchable
/>
</div>
@@ -1,9 +1,10 @@
import type { CSSProperties, Dispatch, SetStateAction } from 'react'
import { Fragment, type CSSProperties, type Dispatch, type SetStateAction } from 'react'
import { Trash2, Pencil, GripVertical } from 'lucide-react'
import type { BudgetItem } from '../../types'
import { usePluginViewContributions, PluginCardFooter } from '../Plugins/PluginContributions'
import { currencyDecimals } from '../../utils/formatters'
import { CustomDatePicker } from '../shared/CustomDateTimePicker'
import { calcPP, calcPD, calcPPD } from './BudgetPanel.helpers'
import { calcPP, calcPD, calcPPD, hasCustomMemberSplit } from './BudgetPanel.helpers'
import InlineEditCell from './BudgetPanelInlineEditCell'
import AddItemRow from './BudgetPanelAddItemRow'
import BudgetMemberChips, { type TripMember } from './BudgetPanelMemberChips'
@@ -53,6 +54,7 @@ export default function BudgetCategoryTable({ cat, grouped, categoryColor, canEd
handleRenameCategory, handleDeleteCategory, handleDeleteItem, handleUpdateField, handleAddItem,
tripId, currency, locale, t, fmt, hasMultipleMembers, tripMembers, setBudgetItemMembers, toggleBudgetMemberPaid, th, td }: BudgetCategoryTableProps) {
const items = grouped.get(cat) || []
const contribFor = usePluginViewContributions('costs', tripId)
const subtotal = items.reduce((s, x) => s + (x.total_price || 0), 0)
const color = categoryColor(cat)
return (
@@ -149,12 +151,17 @@ export default function BudgetCategoryTable({ cat, grouped, categoryColor, canEd
</thead>
<tbody>
{items.map(item => {
const pp = calcPP(item.total_price, item.persons)
// A custom (uneven) split has no single per-person figure — the per-member
// amounts are shown via the member chips — so blank those columns (#1458).
const customSplit = hasCustomMemberSplit(item)
const pp = customSplit ? null : calcPP(item.total_price, item.persons)
const pd = calcPD(item.total_price, item.days)
const ppd = calcPPD(item.total_price, item.persons, item.days)
const ppd = customSplit ? null : calcPPD(item.total_price, item.persons, item.days)
const hasMembers = (item.members?.length ?? 0) > 0
const contributions = contribFor(item.id)
return (
<tr key={item.id}
<Fragment key={item.id}>
<tr
style={{
transition: 'background 0.1s, opacity 0.15s',
opacity: dragItem === item.id ? 0.4 : 1,
@@ -247,6 +254,14 @@ export default function BudgetCategoryTable({ cat, grouped, categoryColor, canEd
)}
</td>
</tr>
{contributions.length > 0 && (
<tr>
<td colSpan={10} style={{ padding: '0 8px 6px 20px' }}>
<PluginCardFooter items={contributions} tripId={tripId} />
</td>
</tr>
)}
</Fragment>
)
})}
{canEdit && <AddItemRow onAdd={data => handleAddItem(cat, data)} t={t} />}
@@ -222,6 +222,34 @@ describe('CostsPanel — settlements in the ledger', () => {
expect(posted!.payers).toEqual([])
})
it('exports the expenses as a CSV download (#1500)', async () => {
// Display in the trip's own currency so FX conversion is an identity.
seedStore(useSettingsStore, { settings: { ...useSettingsStore.getState().settings, default_currency: 'EUR' } })
let exported: Blob | null = null
const createObjURL = vi.spyOn(URL, 'createObjectURL').mockImplementation(b => { exported = b as Blob; return 'blob:mock' })
const revokeObjURL = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {})
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
const item = { ...buildBudgetItem({ trip_id: 1, category: 'food', name: 'Dinner; tapas' }), total_price: 90, expense_date: '2025-06-15' }
server.use(
http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [item] })),
http.get('/api/trips/1/budget/settlement', () => HttpResponse.json({ balances: [], flows: [], settlements: [] })),
)
const { default: userEvent } = await import('@testing-library/user-event')
const user = userEvent.setup()
render(<CostsPanel tripId={1} tripMembers={tripMembers} />)
await screen.findByText('Dinner; tapas')
await user.click(screen.getByTitle('Export CSV'))
expect(exported).toBeTruthy()
const text = await exported!.text()
expect(text).toContain('Date;Name;Category;Amount;Currency;Amount (EUR);Note')
expect(text).toContain('"Dinner; tapas"') // separator inside the name gets quoted
expect(text).toContain('Food & drink') // category label, not the raw key
expect(text).toContain('90.00;EUR')
createObjURL.mockRestore(); revokeObjURL.mockRestore(); clickSpy.mockRestore()
})
it('supports itemized receipt ticket manual entry and split assignment', async () => {
let posted: Record<string, unknown> | null = null
server.use(
+55 -10
View File
@@ -1,6 +1,6 @@
import { useState, useEffect, useMemo, useCallback } from 'react'
import { useSearchParams } from 'react-router-dom'
import { ArrowDown, ArrowUp, BarChart3, Plus, Search, ArrowRight, ArrowLeftRight, Check, RotateCcw, Pencil, Trash2, AlertCircle } from 'lucide-react'
import { ArrowDown, ArrowUp, BarChart3, Plus, Search, ArrowRight, ArrowLeftRight, Check, RotateCcw, Pencil, Trash2, AlertCircle, Download } from 'lucide-react'
import { useTripStore } from '../../store/tripStore'
import { useAuthStore } from '../../store/authStore'
import { useSettingsStore } from '../../store/settingsStore'
@@ -14,11 +14,12 @@ import { formatMoney, currencyDecimals, currencyLocale } from '../../utils/forma
import Modal from '../shared/Modal'
import CustomSelect from '../shared/CustomSelect'
import { CustomDatePicker } from '../shared/CustomDateTimePicker'
import { SYMBOLS, CURRENCIES, SPLIT_COLORS } from './BudgetPanel.constants'
import { SYMBOLS, currenciesWith, SPLIT_COLORS } from './BudgetPanel.constants'
import { COST_CATEGORY_LIST, catMeta } from './costsCategories'
import type { BudgetItem } from '../../types'
import type { TripMember } from './BudgetPanelMemberChips'
import GuestBadge from '../shared/GuestBadge'
import { NumericInput } from '../shared/NumericInput'
export function splitEqualShares(total: number, members: { user_id: number }[], itemId: number): Record<number, number> {
const n = members.length
@@ -289,6 +290,39 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
try { await deleteBudgetItem(tripId, id); loadSettlement() } catch { toast.error(t('common.unknownError')) }
}
// CSV export of all expenses — the wiki-documented export that got lost in the
// Costs rework (#1500). One row per expense, oldest first.
const handleExportCsv = () => {
const sep = ';'
const esc = (v: unknown) => { const s = String(v ?? ''); return s.includes(sep) || s.includes('"') || s.includes('\n') ? '"' + s.replace(/"/g, '""') + '"' : s }
const fmtDate = (iso: string) => { if (!iso) return ''; try { return new Date(iso + 'T00:00:00Z').toLocaleDateString(locale, { day: '2-digit', month: '2-digit', year: 'numeric', timeZone: 'UTC' }) } catch { return iso } }
const header = ['Date', 'Name', 'Category', 'Amount', 'Currency', 'Amount (' + base + ')', 'Note']
const rows = [header.join(sep)]
const items = budgetItems.slice().sort((a, b) => (a.expense_date || '').localeCompare(b.expense_date || ''))
for (const e of items) {
const cur = curOf(e)
// Ticket notes carry the itemized-receipt JSON, not a human note.
const note = e.note && !e.note.startsWith('TICKETJSON:') ? e.note : ''
rows.push([
esc(fmtDate(e.expense_date || '')), esc(e.name), esc(t(catMeta(e.category).labelKey)),
(e.total_price || 0).toFixed(currencyDecimals(cur)), cur,
baseTotal(e).toFixed(currencyDecimals(base)),
esc(note),
].join(sep))
}
const bom = ''
const blob = new Blob([bom + rows.join('\r\n')], { type: 'text/csv;charset=utf-8;' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
const safeName = (trip?.title || 'trip').replace(/[^a-zA-Z0-9À-ɏ _-]/g, '').trim()
a.download = `costs-${safeName}.csv`
a.click()
URL.revokeObjectURL(url)
}
// ── small presentational helpers ────────────────────────────────────────
const Avatar = ({ id, size = 24 }: { id: number; size?: number }) => {
const url = personById(id)?.avatar_url
@@ -419,6 +453,11 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
</button>
))}
</div>
<button onClick={handleExportCsv} title={t('budget.exportCsv')} disabled={!budgetItems.length}
className="bg-surface-input border border-edge text-content-muted disabled:opacity-40"
style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 34, height: 34, borderRadius: 10, cursor: 'pointer', fontFamily: 'inherit', flexShrink: 0 }}>
<Download size={15} />
</button>
</div>
</div>
@@ -618,7 +657,14 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
{/* Expenses */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<div className="text-content" style={{ fontSize: 'calc(19px * var(--fs-scale-subtitle, 1))', fontWeight: 700, letterSpacing: '-0.02em' }}>{t('costs.expenses')}</div>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
<div className="text-content" style={{ fontSize: 'calc(19px * var(--fs-scale-subtitle, 1))', fontWeight: 700, letterSpacing: '-0.02em' }}>{t('costs.expenses')}</div>
<button onClick={handleExportCsv} title={t('budget.exportCsv')} disabled={!budgetItems.length}
className="bg-surface-card border border-edge text-content-muted disabled:opacity-40"
style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: 34, height: 34, borderRadius: 10, cursor: 'pointer', fontFamily: 'inherit', flexShrink: 0 }}>
<Download size={15} />
</button>
</div>
<div className="bg-surface-card border border-edge" style={{ display: 'flex', alignItems: 'center', gap: 8, borderRadius: 12, padding: '0 12px', height: 42 }}>
<Search size={16} className="text-content-faint" />
<input value={search} onChange={e => setSearch(e.target.value)} placeholder={t('costs.searchPlaceholder')} className="text-content" style={{ border: 0, background: 'none', outline: 'none', fontSize: 'calc(14px * var(--fs-scale-body, 1))', width: '100%', fontFamily: 'inherit' }} />
@@ -1151,8 +1197,8 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
<label className={labelCls}>{t('costs.totalAmount')}</label>
<div className="bg-surface-input border border-edge" style={{ height: FIELD_H, boxSizing: 'border-box', display: 'flex', alignItems: 'center', borderRadius: 10, padding: '0 12px', opacity: isTicketMode ? 0.6 : 1 }}>
<span className="text-content-faint" style={{ fontSize: 'calc(15px * var(--fs-scale-subtitle, 1))' }}>{sym(currency)}</span>
<input type="text" inputMode="decimal" placeholder="0.00" value={isTicketMode ? ticketInfo.total.toFixed(2) : total}
onChange={e => onTotalChange(e.target.value)}
<NumericInput mode="decimal" placeholder="0.00" value={isTicketMode ? ticketInfo.total.toFixed(2) : total}
onValueChange={onTotalChange}
disabled={isTicketMode}
className="text-content" style={{ flex: 1, border: 0, background: 'none', outline: 'none', fontSize: 'calc(15px * var(--fs-scale-subtitle, 1))', fontWeight: 600, paddingLeft: 6, width: '100%' }} />
</div>
@@ -1161,7 +1207,7 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
<div style={{ minWidth: 0 }}>
<label className={labelCls}>{t('costs.currency')}</label>
<CustomSelect value={currency} onChange={v => setCurrency(String(v))} searchable
options={CURRENCIES.map(c => ({ value: c, label: SYMBOLS[c] ? `${c} ${SYMBOLS[c]}` : c }))}
options={currenciesWith(currency).map(c => ({ value: c, label: SYMBOLS[c] ? `${c} ${SYMBOLS[c]}` : c }))}
style={{ width: '100%' }} />
</div>
<div style={{ minWidth: 0 }}>
@@ -1244,12 +1290,11 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
/>
<div className="bg-surface-input border border-edge" style={{ flex: 1, display: 'flex', alignItems: 'center', padding: '0 8px', borderRadius: 8 }}>
<span className="text-content-faint" style={{ fontSize: 12 }}>{sym(currency)}</span>
<input
type="text"
inputMode="decimal"
<NumericInput
mode="decimal"
placeholder="0.00"
value={item.price}
onChange={e => handleUpdateItemPrice(item.id, e.target.value)}
onValueChange={v => handleUpdateItemPrice(item.id, v)}
className="text-content"
style={{ width: '100%', border: 0, background: 'none', outline: 'none', fontSize: 13, fontWeight: 600, textAlign: 'right', padding: '6px 0' }}
/>
@@ -7,7 +7,7 @@ import { useTranslation } from '../../i18n'
import { budgetApi } from '../../api/client'
import type { BudgetItem } from '../../types'
import { currencyDecimals } from '../../utils/formatters'
import { widgetTheme, fmtNum, calcPP, calcPD, calcPPD } from './BudgetPanel.helpers'
import { widgetTheme, fmtNum, calcPP, calcPD, calcPPD, hasCustomMemberSplit } from './BudgetPanel.helpers'
import { PIE_COLORS } from './BudgetPanel.constants'
import type { TripMember } from './BudgetPanelMemberChips'
@@ -167,9 +167,11 @@ export function useBudgetPanel(tripId: number, tripMembers: TripMember[]) {
for (const cat of categoryNames) {
for (const item of (grouped.get(cat) || [])) {
const pp = calcPP(item.total_price, item.persons)
// A custom (uneven) split has no single per-person figure, so leave those columns blank (#1458).
const customSplit = hasCustomMemberSplit(item)
const pp = customSplit ? null : calcPP(item.total_price, item.persons)
const pd = calcPD(item.total_price, item.days)
const ppd = calcPPD(item.total_price, item.persons, item.days)
const ppd = customSplit ? null : calcPPD(item.total_price, item.persons, item.days)
rows.push([
esc(item.category), esc(item.name), esc(fmtDate(item.expense_date || '')),
fmtPrice(item.total_price), item.persons ?? '', item.days ?? '',
@@ -1,5 +1,5 @@
import React from 'react'
import { PanelLeftClose, PanelLeftOpen, Search, Plus } from 'lucide-react'
import { PanelLeftClose, PanelLeftOpen, Search } from 'lucide-react'
import type { CollectionPlace } from '@trek/shared'
import type { TranslationFn } from '../../types'
import CollectionMap from './CollectionMap'
@@ -15,9 +15,6 @@ interface CollectionMapPanelProps {
/** 'list' = split (map can be expanded); 'map' = full (list collapsed). */
view: 'list' | 'map'
onToggleView: () => void
/** Show a "+" to add a place to the current list (real lists only). */
canAddPlace: boolean
onAddPlace: () => void
search: string
onSearch: (v: string) => void
t: TranslationFn
@@ -30,7 +27,7 @@ interface CollectionMapPanelProps {
*/
export default function CollectionMapPanel({
places, selectedPlaceId, onSelect, onDeselect, dark, overlay, view, onToggleView,
canAddPlace, onAddPlace, search, onSearch, t,
search, onSearch, t,
}: CollectionMapPanelProps): React.ReactElement {
return (
<div className="col-map-shell">
@@ -55,11 +52,6 @@ export default function CollectionMapPanel({
</button>
</div>
<div className="col-map-group right">
{canAddPlace && (
<button type="button" onClick={onAddPlace} className="col-map-btn" aria-label={t('collections.addPlace')} title={t('collections.addPlace')}>
<Plus size={17} />
</button>
)}
<div className="col-map-search">
<Search size={15} />
<input value={search} onChange={e => onSearch(e.target.value)} placeholder={t('collections.search')} />
@@ -1,12 +1,15 @@
import { Fragment } from 'react'
import { Upload, FileText, Star } from 'lucide-react'
import type { FileManagerState } from './useFileManager'
import { FileRow } from './FileManagerRow'
import { usePluginViewContributions, PluginCardFooter } from '../Plugins/PluginContributions'
export function FilesView(S: FileManagerState) {
const {
can, trip, getRootProps, getInputProps, isDragActive, uploading, t, allowedFileTypes,
files, filterType, setFilterType, filteredFiles,
} = S
const contribFor = usePluginViewContributions('files', S.tripId)
return (
<>
{/* Upload zone */}
@@ -70,7 +73,15 @@ export function FilesView(S: FileManagerState) {
</div>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{filteredFiles.map(file => <FileRow key={file.id} {...S} file={file} />)}
{filteredFiles.map(file => {
const contributions = contribFor(file.id)
return (
<Fragment key={file.id}>
<FileRow {...S} file={file} />
{contributions.length > 0 && <div style={{ padding: '0 4px' }}><PluginCardFooter items={contributions} tripId={S.tripId} /></div>}
</Fragment>
)
})}
</div>
)}
</div>
@@ -1,8 +1,10 @@
import { useState, useRef } from 'react'
import { useState, useRef, useEffect } from 'react'
import { createPortal } from 'react-dom'
import { MapPin, Clock, MoreHorizontal, Pencil, Trash2 } from 'lucide-react'
import { formatLocationName } from '../../utils/formatters'
import { useTranslation } from '../../i18n'
import { pluginsApi } from '../../api/client'
import { usePluginStore } from '../../store/pluginStore'
import type { JourneyEntry, JourneyPhoto } from '../../store/journeyStore'
import { MOOD_CONFIG, WEATHER_CONFIG } from '../../pages/journeyDetail/JourneyDetailPage.constants'
import { photoUrl } from '../../pages/journeyDetail/JourneyDetailPage.helpers'
@@ -21,6 +23,19 @@ export function EntryCard({ entry, readOnly, onEdit, onDelete, onPhotoClick }: {
const { t } = useTranslation()
const [menuOpen, setMenuOpen] = useState(false)
const menuBtnRef = useRef<HTMLButtonElement>(null)
// Extra rows contributed by journalEntryProvider plugins — same pattern as the
// PlaceInspector provider details: fetched only when plugins are active at all,
// fail-safe (the server drops slow/failing providers), only ever additive.
const hasPlugins = usePluginStore((s) => s.plugins.length > 0)
const [providerRows, setProviderRows] = useState<Array<{ pluginId: string; items: Array<{ label: string; value?: string; url?: string }> }>>([])
useEffect(() => {
if (!hasPlugins) { setProviderRows([]); return }
let cancelled = false
pluginsApi.journalEntryRows(entry.id)
.then((d) => { if (!cancelled) setProviderRows((d.providers || []).filter((p) => Array.isArray(p.items) && p.items.length > 0)) })
.catch(() => { if (!cancelled) setProviderRows([]) })
return () => { cancelled = true }
}, [entry.id, hasPlugins])
const photos = entry.photos || []
const mood = entry.mood ? MOOD_CONFIG[entry.mood] : null
const weather = entry.weather ? WEATHER_CONFIG[entry.weather] : null
@@ -146,6 +161,20 @@ export function EntryCard({ entry, readOnly, onEdit, onDelete, onPhotoClick }: {
</div>
</div>
)}
{/* Plugin provider rows — host-vetted label/value/url, plain text only */}
{providerRows.length > 0 && (
<div className="pt-3 mt-3 border-t border-zinc-100 dark:border-zinc-800 space-y-1.5">
{providerRows.flatMap((p) => p.items.map((it, i) => (
<div key={`${p.pluginId}-${i}`} className="flex items-baseline justify-between gap-2 text-[12px]">
<span className="font-medium text-zinc-500 dark:text-zinc-400 flex-shrink-0">{it.label}</span>
{it.url
? <a href={it.url} target="_blank" rel="noreferrer noopener" className="text-indigo-600 dark:text-indigo-400 truncate text-right">{it.value ?? it.url}</a>
: <span className="text-zinc-600 dark:text-zinc-300 truncate text-right">{it.value}</span>}
</div>
)))}
</div>
)}
</div>
</div>
)
+6 -1
View File
@@ -1,8 +1,9 @@
import { useNavigate, useLocation, useMatch } from 'react-router-dom'
import { useAddonStore } from '../../store/addonStore'
import { usePluginStore } from '../../store/pluginStore'
import { useSettingsStore } from '../../store/settingsStore'
import { useTranslation } from '../../i18n'
import { LayoutGrid, CalendarDays, Globe, Compass, Bookmark, Plus } from 'lucide-react'
import { LayoutGrid, CalendarDays, Globe, Compass, Bookmark, Plus, Blocks } from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
const ADDON_NAV: Record<string, { icon: LucideIcon; labelKey: string }> = {
@@ -52,6 +53,9 @@ export default function BottomNav() {
const dark = darkMode === true || darkMode === 'dark' || (darkMode === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches)
const addons = useAddonStore(s => s.addons)
const globalAddons = addons.filter(a => a.type === 'global' && a.enabled)
// Page plugins are reachable from the mobile tab bar too, mirroring the desktop
// nav pill (Navbar) — otherwise they were only reachable by typing /plugins/:id.
const pagePlugins = usePluginStore(s => s.plugins).filter(p => p.type === 'page')
const location = useLocation()
const create = useCreateAction()
@@ -61,6 +65,7 @@ export default function BottomNav() {
const nav = ADDON_NAV[addon.id]
return nav ? [{ to: `/${addon.id}`, label: t(nav.labelKey), icon: nav.icon }] : []
}),
...pagePlugins.map(p => ({ to: `/plugins/${p.id}`, label: p.name, icon: Blocks })),
]
// Split the items so the raised "+" sits dead centre.
const splitAt = Math.ceil(items.length / 2)
+15
View File
@@ -172,6 +172,21 @@ export default function Navbar({ tripTitle, tripId, onBack, showBack, onShare }:
</div>
)}
{/* Centre slot for page-scoped notices (plugin trip warnings portal into it).
Only mounted on trip pages, where the tab pill above is absent, so the two
never fight over the centre. Zero-size while empty; pointer events stay off
on the wrapper so an empty slot can't swallow clicks. */}
{tripTitle && (
<div
id="trek-nav-center-slot"
style={{
position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%, -50%)',
display: 'flex', alignItems: 'center', gap: 6, maxWidth: '42%',
overflow: 'hidden', pointerEvents: 'none',
}}
/>
)}
{/* Spacer */}
<div className="flex-1" />
@@ -0,0 +1,75 @@
import { useEffect, useMemo, useState } from 'react'
import { Marker, Popup } from 'react-leaflet'
import L from 'leaflet'
import { pluginsApi, type PluginMapMarker } from '../../api/client'
/**
* Host-rendered overlay for the `mapMarkerProvider` plugin hook (#587). A plugin
* returns bounded marker specs (coordinates + plain text + an allowlisted url); the
* server range-checks + normalizes them, and this layer draws them as plain Leaflet
* markers. Plugin JS NEVER runs on the map canvas — every value here is host-vetted
* data, and the popup renders it as text (the url is already http/https/mailto-only).
*
* Mounted inside the trip map's <MapContainer>; fail-safe — a fetch error just yields
* no extra markers, the core map is untouched.
*/
const TONE_COLORS: Record<PluginMapMarker['tone'], string> = {
default: '#4F46E5',
success: '#10b981',
warn: '#f59e0b',
danger: '#ef4444',
}
function markerIcon(tone: PluginMapMarker['tone']): L.DivIcon {
const color = TONE_COLORS[tone] ?? TONE_COLORS.default
return L.divIcon({
className: 'plugin-map-marker',
html: `<span style="display:block;width:16px;height:16px;border-radius:50%;background:${color};border:2px solid #fff;box-shadow:0 1px 4px rgba(0,0,0,0.4)"></span>`,
iconSize: [16, 16],
iconAnchor: [8, 8],
popupAnchor: [0, -8],
})
}
export function PluginMapMarkers({ tripId }: { tripId?: number | string }) {
const [markers, setMarkers] = useState<PluginMapMarker[]>([])
useEffect(() => {
if (tripId == null) { setMarkers([]); return }
let alive = true
pluginsApi.mapMarkers(tripId)
.then(r => { if (alive) setMarkers(r.markers || []) })
.catch(() => { if (alive) setMarkers([]) }) // fail-safe: no extra markers
return () => { alive = false }
}, [tripId])
const icons = useMemo(() => {
const m = new Map<PluginMapMarker['tone'], L.DivIcon>()
for (const tone of ['default', 'success', 'warn', 'danger'] as const) m.set(tone, markerIcon(tone))
return m
}, [])
if (markers.length === 0) return null
return (
<>
{markers.map(mk => (
<Marker key={`${mk.pluginId}:${mk.id}`} position={[mk.lat, mk.lng]} icon={icons.get(mk.tone)!}>
{(mk.label || mk.popupText || mk.url) && (
<Popup>
<div style={{ minWidth: 120, fontSize: 13 }}>
{mk.label && <div style={{ fontWeight: 600, marginBottom: mk.popupText ? 4 : 0 }}>{mk.label}</div>}
{mk.popupText && <div style={{ color: '#4b5563' }}>{mk.popupText}</div>}
{mk.url && (
<a href={mk.url} target="_blank" rel="noreferrer noopener" style={{ display: 'inline-block', marginTop: 6, color: TONE_COLORS.default }}>
{mk.url}
</a>
)}
</div>
</Popup>
)}
</Marker>
))}
</>
)
}
+3
View File
@@ -9,6 +9,7 @@ import 'leaflet.markercluster/dist/MarkerCluster.Default.css'
import { mapsApi } from '../../api/client'
import { getCategoryIcon, CATEGORY_ICON_MAP } from '../shared/categoryIcons'
import ReservationOverlay from './ReservationOverlay'
import { PluginMapMarkers } from './MapPluginMarkers'
import { useTransportRoutes } from '../../hooks/useTransportRoutes'
import type { Reservation } from '../../types'
import { POI_CATEGORY_BY_KEY, type Poi } from './poiCategories'
@@ -451,6 +452,7 @@ export const MapView = memo(function MapView({
pois = [] as Poi[],
onPoiClick,
onViewportChange,
tripId,
}: any) {
const poiMarkers = useMemo(() => (pois as Poi[]).map((poi: Poi) => (
<Marker
@@ -719,6 +721,7 @@ export const MapView = memo(function MapView({
/>
{poiMarkers}
<PluginMapMarkers tripId={tripId} />
</MapContainer>
{isMobile && <LocationButton
mode={trackingMode}
+50
View File
@@ -47,6 +47,9 @@ beforeEach(() => {
http.get('/api/maps/place-photo/:placeId', () =>
HttpResponse.json({ photoUrl: null })
),
http.get('/api/pdf-sections/:tripId', () =>
HttpResponse.json({ sections: [] })
),
)
})
@@ -151,6 +154,22 @@ describe('downloadTripPDF', () => {
expect(iframe!.srcdoc).toContain('Day One')
})
it('FE-COMP-TRIPPDF-005b: day is a table with a thead header that repeats on overflow pages (#1471)', async () => {
await downloadTripPDF(richArgs)
const iframe = getIframe()
const srcdoc = iframe!.srcdoc
// The day is a real <table> whose <thead> is repeated by the browser's print
// engine on every page an overflowing day spills onto.
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"')
// Day content still renders inside the new structure.
expect(srcdoc).toContain('Rome Day')
expect(srcdoc).toContain('Colosseum')
})
it('FE-COMP-TRIPPDF-006: escHtml prevents XSS in trip title', async () => {
const args = {
...minimalArgs,
@@ -356,4 +375,35 @@ describe('downloadTripPDF', () => {
// The empty-day div should appear (contains the translation key for empty day)
expect(iframe!.srcdoc).toContain('dayplan.emptyDay')
})
it('FE-COMP-TRIPPDF-021: appends plugin pdf sections after the days, escaped', async () => {
server.use(
http.get('/api/pdf-sections/:tripId', () =>
HttpResponse.json({
sections: [{
pluginId: 'weather',
title: 'Weather <b>Forecast</b>',
paragraphs: ['Sunny all week'],
table: { headers: ['Day', 'Temp'], rows: [['Mon', '24°C']] },
}],
})
),
)
await downloadTripPDF(richArgs)
const srcdoc = getIframe()!.srcdoc
expect(srcdoc).toContain('class="plugin-section"')
// Plugin text is escHtml'd like the core content — no markup passes through.
expect(srcdoc).not.toContain('<b>Forecast</b>')
expect(srcdoc).toContain('Weather &lt;b&gt;Forecast&lt;/b&gt;')
expect(srcdoc).toContain('Sunny all week')
expect(srcdoc).toContain('24°C')
// Sections come after the last day section.
expect(srcdoc.indexOf('class="plugin-sections')).toBeGreaterThan(srcdoc.lastIndexOf('class="day-section'))
})
it('FE-COMP-TRIPPDF-022: renders no plugin block when the sections fetch fails (fail-safe)', async () => {
server.use(http.get('/api/pdf-sections/:tripId', () => HttpResponse.error()))
await expect(downloadTripPDF(minimalArgs)).resolves.not.toThrow()
expect(getIframe()!.srcdoc).not.toContain('class="plugin-sections')
})
})
+51 -12
View File
@@ -2,7 +2,7 @@
import { createElement } from 'react'
import { getCategoryIcon } from '../shared/categoryIcons'
import { FileText, Info, Clock, MapPin, Navigation, Train, Plane, Bus, Car, Ship, Sailboat, Bike, CarTaxiFront, Route, Coffee, Ticket, Star, Heart, Camera, Flag, Lightbulb, AlertTriangle, ShoppingBag, Bookmark, Hotel, LogIn, LogOut, KeyRound, BedDouble, Utensils, Users, LucideIcon } from 'lucide-react'
import { accommodationsApi, mapsApi } from '../../api/client'
import { accommodationsApi, mapsApi, pluginsApi } from '../../api/client'
import type { Trip, Day, Place, Category, AssignmentsMap, DayNote } from '../../types'
import { isDayInAccommodationRange, getDayOrder } from '../../utils/dayOrder'
import { splitReservationDateTime } from '../../utils/formatters'
@@ -149,6 +149,11 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor
//retrieve accommodations for the trip to display on the day sections and prefetch their photos if needed
const accommodations = await accommodationsApi.list(trip.id);
// Sections contributed by pdfSectionProvider plugins — server-normalized plain
// text (counts + lengths capped), appended after the days. Fail-safe: an error
// just means no extra sections, the core export is untouched.
const pluginSections = await pluginsApi.pdfSections(trip.id).then(r => r.sections || []).catch(() => [])
// Pre-fetch place photos (Google, OSM and coords-only places)
const photoMap = await fetchPlacePhotos(assignments, places)
@@ -375,18 +380,41 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor
</div>`
: ''
// A real <table> so the browser repeats the <thead> day header at the top of
// every page an overflowing day spills onto (#1471). CSS `table-header-group`
// on a <div> is NOT repeated by Chromium's print engine — only real thead is.
return `
<div class="day-section${di > 0 ? ' page-break' : ''}">
<div class="day-header">
<span class="day-tag">${escHtml(tr('dayplan.dayN', { n: day.day_number })).toUpperCase()}</span>
<span class="day-title">${escHtml(day.title || tr('dayplan.dayN', { n: day.day_number }))}</span>
${day.date ? `<span class="day-date">${shortDate(day.date, loc)}</span>` : ''}
${cost ? `<span class="day-cost">${cost}</span>` : ''}
</div>
<div class="day-body">${accommodationsHtml}${itemsHtml}</div>
</div>`
<table class="day-section${di > 0 ? ' page-break' : ''}">
<thead class="day-header"><tr><td>
<div class="day-header-bar">
<span class="day-tag">${escHtml(tr('dayplan.dayN', { n: day.day_number })).toUpperCase()}</span>
<span class="day-title">${escHtml(day.title || tr('dayplan.dayN', { n: day.day_number }))}</span>
${day.date ? `<span class="day-date">${shortDate(day.date, loc)}</span>` : ''}
${cost ? `<span class="day-cost">${cost}</span>` : ''}
</div>
</td></tr></thead>
<tbody class="day-body-group"><tr><td>
<div class="day-body">${accommodationsHtml}${itemsHtml}</div>
</td></tr></tbody>
</table>`
}).join('')
// Plugin sections after the days — every value is host-vetted plain text and
// still escHtml'd here (same treatment as the core content above).
const pluginSectionsHtml = pluginSections.length === 0 ? '' : `
<div class="plugin-sections page-break">
${pluginSections.map(s => `
<div class="plugin-section">
<div class="plugin-section-title">${escHtml(s.title)}</div>
${(s.paragraphs || []).map(p => `<p class="plugin-section-text">${escHtml(p)}</p>`).join('')}
${s.table ? `
<table class="plugin-section-table">
<thead><tr>${s.table.headers.map(h => `<th>${escHtml(h)}</th>`).join('')}</tr></thead>
<tbody>${s.table.rows.map(row => `<tr>${row.map(cell => `<td>${escHtml(cell)}</td>`).join('')}</tr>`).join('')}</tbody>
</table>` : ''}
</div>`).join('')}
</div>`
const html = `<!DOCTYPE html>
<html lang="${loc.split('-')[0]}">
<head>
@@ -456,8 +484,10 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor
.cover-stat-lbl { font-size: 9px; font-weight: 500; color: rgba(255,255,255,0.4); letter-spacing: 1px; margin-top: 4px; text-transform: uppercase; }
/* ── Day ───────────────────────────────────────── */
/* .day-section is a real <table>; its <thead> day header repeats on overflow pages. */
.page-break { page-break-before: always; }
.day-header {
.day-section { width: 100%; border-collapse: collapse; table-layout: fixed; }
.day-header-bar {
background: #0f172a; padding: 11px 28px;
display: flex; align-items: center; gap: 8px;
}
@@ -538,6 +568,15 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor
.empty-day { font-size: 9.5px; color: #cbd5e1; font-style: italic; text-align: center; padding: 14px 0; }
/* ── Plugin sections ───────────────────────────── */
.plugin-sections { padding: 16px 28px 6px; }
.plugin-section { margin-bottom: 16px; page-break-inside: avoid; }
.plugin-section-title { font-size: 12px; font-weight: 600; color: #1e293b; margin-bottom: 6px; padding-bottom: 4px; border-bottom: 1px solid #e2e8f0; }
.plugin-section-text { font-size: 9.5px; color: #334155; line-height: 1.55; margin-bottom: 5px; }
.plugin-section-table { width: 100%; border-collapse: collapse; margin-top: 6px; }
.plugin-section-table th { font-size: 8px; font-weight: 600; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; text-align: left; padding: 4px 8px; border-bottom: 1px solid #e2e8f0; }
.plugin-section-table td { font-size: 9px; color: #334155; padding: 4px 8px; border-bottom: 1px solid #f1f5f9; }
/* ── Print ─────────────────────────────────────── */
@media print {
body { margin: 0; }
@@ -591,7 +630,7 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor
<!-- Days -->
${daysHtml}
${pluginSectionsHtml}
</body></html>`
// Open in modal with srcdoc iframe (no URL loading = no X-Frame-Options issue)
@@ -159,17 +159,17 @@ describe('PackingListPanel', () => {
expect(screen.getByText('Documents')).toBeInTheDocument();
});
it('FE-COMP-PACKING-014: Add category button is shown', () => {
it('FE-COMP-PACKING-014: Add list button is shown', () => {
render(<PackingListPanel tripId={1} items={[]} />);
// The "Add category" button should be present in the toolbar
expect(screen.getByText('Add category')).toBeInTheDocument();
// The "Add list" button should be present in the toolbar
expect(screen.getByText('Add list')).toBeInTheDocument();
});
it('FE-COMP-PACKING-015: clicking Add Category shows the category name input', async () => {
const user = userEvent.setup();
render(<PackingListPanel tripId={1} items={[]} />);
await user.click(screen.getByText('Add category'));
await screen.findByPlaceholderText('Category name (e.g. Clothing)');
await user.click(screen.getByText('Add list'));
await screen.findByPlaceholderText('List name (e.g. Clothing)');
});
it('FE-COMP-PACKING-016: delete item button exists and triggers API call', async () => {
@@ -340,8 +340,8 @@ describe('PackingListPanel', () => {
);
render(<PackingListPanel tripId={1} items={[]} />);
await user.click(screen.getByText('Add category'));
const input = await screen.findByPlaceholderText('Category name (e.g. Clothing)');
await user.click(screen.getByText('Add list'));
const input = await screen.findByPlaceholderText('List name (e.g. Clothing)');
await user.type(input, 'Valuables');
await user.keyboard('{Enter}');
@@ -496,7 +496,7 @@ describe('PackingListPanel', () => {
// Click "Rename" in the menu
await user.click(await screen.findByText('Rename'));
// Category name input appears — type new name and save
// List name input appears — type new name and save
const catInput = screen.getByDisplayValue('Clothing');
await user.clear(catInput);
await user.type(catInput, 'Apparel');
@@ -858,8 +858,8 @@ describe('PackingListPanel', () => {
// It's rendered inside the action buttons group (sm:opacity-0 sm:group-hover:opacity-100)
// In jsdom, CSS classes don't apply so the buttons are accessible
// The dot button has a circle span inside with category color
// Find all buttons with the 'Change Category' title
const catChangeBtn = screen.getAllByTitle('Change Category');
// Find all buttons with the 'Move to List' title
const catChangeBtn = screen.getAllByTitle('Move to List');
expect(catChangeBtn.length).toBeGreaterThan(0);
await user.click(catChangeBtn[0]);
@@ -999,10 +999,10 @@ describe('PackingListPanel', () => {
);
const { container } = render(<PackingListPanel tripId={1} items={[item1, item2]} />);
// Open context menu and click Delete Category
// Open context menu and click Delete List
const moreBtn = container.querySelector('svg.lucide-more-horizontal')?.closest('button');
await user.click(moreBtn!);
await user.click(await screen.findByText('Delete Category'));
await user.click(await screen.findByText('Delete List'));
await waitFor(() => {
expect(deletedIds).toContain(100);
@@ -1059,7 +1059,7 @@ describe('PackingListPanel', () => {
render(<PackingListPanel tripId={1} items={[itemA, itemB]} />);
// Use fireEvent (no pointer events) to open the category picker — avoids mouseLeave closing picker
const catChangeBtns = screen.getAllByTitle('Change Category');
const catChangeBtns = screen.getAllByTitle('Move to List');
fireEvent.click(catChangeBtns[0]);
// Picker shows available categories — find and click the 'Documents' button (role=button, text=Documents)
@@ -10,6 +10,7 @@ import type { PackingItem, PackingBag } from '../../types'
import { katColor } from './packingListPanel.helpers'
import type { TripMember, CategoryAssignee } from './usePackingListPanel'
import { ArtikelZeile } from './PackingListPanelItemRow'
import { usePluginViewContributions, PluginCardFooter } from '../Plugins/PluginContributions'
import GuestBadge from '../shared/GuestBadge'
interface KategorieGruppeProps {
@@ -44,6 +45,7 @@ export function KategorieGruppe({ kategorie, items, tripId, allCategories, onRen
const [offen, setOffen] = useState(true)
const [dragId, setDragId] = useState<number | null>(null)
const [overId, setOverId] = useState<number | null>(null)
const contribFor = usePluginViewContributions('packing', tripId)
const handleReorderDrop = (targetId: number) => {
const from = dragId
@@ -265,18 +267,24 @@ export function KategorieGruppe({ kategorie, items, tripId, allCategories, onRen
{offen && (
<div style={{ padding: '4px 4px 6px' }}>
{items.map(item => (
<ArtikelZeile key={item.id} item={item} tripId={tripId} categories={allCategories} onCategoryChange={() => {}} onDelete={onDeleteItem} bagTrackingEnabled={bagTrackingEnabled} bags={bags} onCreateBag={onCreateBag} canEdit={canEdit}
tripMembers={tripMembers} currentUserId={currentUserId} onSetSharing={onSetSharing} onClone={onClone} onJoin={onJoin} onLeave={onLeave}
drag={canEdit ? {
isDragging: dragId === item.id,
isOver: overId === item.id && dragId !== null && dragId !== item.id,
onStart: (id) => { setDragId(id); setOverId(null) },
onOver: (id) => setOverId(id),
onEnd: () => { setDragId(null); setOverId(null) },
onDrop: handleReorderDrop,
} : undefined} />
))}
{items.map(item => {
const contributions = contribFor(item.id)
return (
<React.Fragment key={item.id}>
<ArtikelZeile item={item} tripId={tripId} categories={allCategories} onCategoryChange={() => {}} onDelete={onDeleteItem} bagTrackingEnabled={bagTrackingEnabled} bags={bags} onCreateBag={onCreateBag} canEdit={canEdit}
tripMembers={tripMembers} currentUserId={currentUserId} onSetSharing={onSetSharing} onClone={onClone} onJoin={onJoin} onLeave={onLeave}
drag={canEdit ? {
isDragging: dragId === item.id,
isOver: overId === item.id && dragId !== null && dragId !== item.id,
onStart: (id) => { setDragId(id); setOverId(null) },
onOver: (id) => setOverId(id),
onEnd: () => { setDragId(null); setOverId(null) },
onDrop: handleReorderDrop,
} : undefined} />
{contributions.length > 0 && <div style={{ padding: '0 8px 2px' }}><PluginCardFooter items={contributions} tripId={tripId} /></div>}
</React.Fragment>
)
})}
{/* Inline add item */}
{canEdit && (showAddItem ? (
<div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '4px 8px' }}>
@@ -11,6 +11,7 @@ import { PACKING_PLACEHOLDER_NAME } from './packingListPanel.constants'
import { QuantityInput } from './PackingListPanelQuantityInput'
import PackingShareControl from './PackingShareControl'
import type { TripMember } from './usePackingListPanel'
import { NumericInput } from '../shared/NumericInput'
interface ArtikelZeileProps {
item: PackingItem
@@ -141,13 +142,14 @@ export function ArtikelZeile({ item, tripId, categories, onCategoryChange, onDel
onChange={e => setEditName(e.target.value)}
onBlur={handleSaveName}
onKeyDown={e => { if (e.key === 'Enter') handleSaveName(); if (e.key === 'Escape') { setEditing(false); setEditName(isPlaceholder ? '' : item.name) } }}
style={{ flex: 1, fontSize: 'calc(13.5px * var(--fs-scale-body, 1))', padding: '2px 8px', borderRadius: 6, border: '1px solid var(--border-primary)', outline: 'none', fontFamily: 'inherit' }}
style={{ flex: 1, minWidth: 0, fontSize: 'calc(13.5px * var(--fs-scale-body, 1))', padding: '2px 8px', borderRadius: 6, border: '1px solid var(--border-primary)', outline: 'none', fontFamily: 'inherit' }}
/>
) : (
<span
onClick={() => canEdit && !item.checked && setEditing(true)}
style={{
flex: 1, fontSize: 'calc(13.5px * var(--fs-scale-body, 1))',
flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
fontSize: 'calc(13.5px * var(--fs-scale-body, 1))',
cursor: !canEdit || item.checked ? 'default' : 'text',
color: isPlaceholder ? 'var(--text-faint)' : (item.checked ? 'var(--text-faint)' : 'var(--text-primary)'),
transition: 'color 200ms cubic-bezier(0.23,1,0.32,1)',
@@ -185,13 +187,11 @@ export function ArtikelZeile({ item, tripId, categories, onCategoryChange, onDel
{bagTrackingEnabled && (
<div style={{ display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 2, border: '1px solid var(--border-primary)', borderRadius: 8, padding: '3px 6px', background: 'transparent' }}>
<input
type="text" inputMode="numeric"
<NumericInput
value={item.weight_grams ?? ''}
readOnly={!canEdit}
onChange={async e => {
onValueChange={async raw => {
if (!canEdit) return
const raw = e.target.value.replace(/[^0-9]/g, '')
const v = raw === '' ? null : parseInt(raw)
try { await updatePackingItem(tripId, item.id, { weight_grams: v }) } catch { toast.error(t('packing.toast.saveError')) }
}}
@@ -0,0 +1,47 @@
// FE-COMP-PACKING-082 to FE-COMP-PACKING-083
import { vi } from 'vitest';
import { render, screen, waitFor, fireEvent } from '../../../tests/helpers/render';
import { QuantityInput } from './PackingListPanelQuantityInput';
describe('QuantityInput', () => {
it('FE-COMP-PACKING-082: selects the current value on focus so typing replaces it', async () => {
render(<QuantityInput value={1} onSave={() => {}} />);
const input = screen.getByRole('textbox') as HTMLInputElement;
fireEvent.focus(input);
await waitFor(() => {
expect(input.selectionStart).toBe(0);
expect(input.selectionEnd).toBe(1);
});
});
it('FE-COMP-PACKING-083: commits the typed quantity on blur', async () => {
const onSave = vi.fn();
render(<QuantityInput value={1} onSave={onSave} />);
const input = screen.getByRole('textbox') as HTMLInputElement;
fireEvent.change(input, { target: { value: '6' } });
fireEvent.blur(input);
await waitFor(() => expect(onSave).toHaveBeenCalledWith(6));
});
it('FE-COMP-PACKING-084: #1513 focus-then-type replaces the value instead of appending to it', async () => {
// The end-to-end shape of the bug: with the caret parked at the end, typing 6 over a
// quantity of 1 committed 16. Selecting on focus makes the keystroke overwrite.
const onSave = vi.fn();
render(<QuantityInput value={1} onSave={onSave} />);
const input = screen.getByRole('textbox') as HTMLInputElement;
fireEvent.focus(input);
await waitFor(() => expect(input.selectionEnd).toBe(1));
// A selected value means the browser replaces it — simulate the resulting input event.
fireEvent.change(input, { target: { value: '6' } });
fireEvent.blur(input);
await waitFor(() => expect(onSave).toHaveBeenCalledWith(6));
expect(onSave).not.toHaveBeenCalledWith(16);
});
});
@@ -1,4 +1,5 @@
import { useState, useEffect } from 'react'
import { NumericInput } from '../shared/NumericInput'
export function QuantityInput({ value, onSave }: { value: number; onSave: (qty: number) => void }) {
const [local, setLocal] = useState(String(value))
@@ -12,10 +13,9 @@ export function QuantityInput({ value, onSave }: { value: number; onSave: (qty:
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 2, border: '1px solid var(--border-primary)', borderRadius: 8, padding: '3px 6px', background: 'transparent', flexShrink: 0 }}>
<input
type="text" inputMode="numeric"
<NumericInput
value={local}
onChange={e => setLocal(e.target.value.replace(/\D/g, ''))}
onValueChange={setLocal}
onBlur={commit}
onKeyDown={e => { if (e.key === 'Enter') { commit(); (e.target as HTMLInputElement).blur() } }}
style={{ width: 24, border: 'none', outline: 'none', background: 'transparent', fontSize: 'calc(12px * var(--fs-scale-body, 1))', textAlign: 'right', fontFamily: 'inherit', color: 'var(--text-secondary)', padding: 0 }}
@@ -0,0 +1,114 @@
import { useEffect, useRef, useState } from 'react'
import { MapPin } from 'lucide-react'
import { mapsApi } from '../../api/client'
import { useTranslation } from '../../i18n'
interface Props {
value: string
onChange: (value: string) => void
placeholder?: string
className?: string
}
// Free-text address input with location autocomplete, backed by the same maps
// search as LocationSelect. Unlike LocationSelect the typed text is
// authoritative: every keystroke reaches the parent so a hand-written address
// is never lost, and picking a suggestion just replaces the text (#1496).
export default function AddressInput({ value, onChange, placeholder, className }: Props) {
const { t, locale } = useTranslation()
const [open, setOpen] = useState(false)
const [results, setResults] = useState<any[]>([])
const [highlight, setHighlight] = useState(-1)
const [loading, setLoading] = useState(false)
const wrapRef = useRef<HTMLDivElement>(null)
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
useEffect(() => {
const handler = (e: MouseEvent) => {
if (!wrapRef.current?.contains(e.target as Node)) setOpen(false)
}
if (open) document.addEventListener('mousedown', handler)
return () => document.removeEventListener('mousedown', handler)
}, [open])
useEffect(() => () => { if (debounceRef.current) clearTimeout(debounceRef.current) }, [])
// Search on typing only (not on focus or external value changes), so opening
// a modal with a saved address doesn't fire a request.
const search = (text: string) => {
if (debounceRef.current) clearTimeout(debounceRef.current)
const trimmed = text.trim()
if (trimmed.length < 3) { setResults([]); setLoading(false); return }
debounceRef.current = setTimeout(async () => {
setLoading(true)
try {
const data = await mapsApi.search(trimmed, locale)
setResults(data.places || [])
setHighlight(-1)
} catch {
setResults([])
} finally {
setLoading(false)
}
}, 320)
}
const pick = (r: any) => {
if (debounceRef.current) clearTimeout(debounceRef.current)
onChange(r.address || r.name || '')
setOpen(false)
setResults([])
setLoading(false)
}
const onKey = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (!open || results.length === 0) return
if (e.key === 'ArrowDown') { e.preventDefault(); setHighlight(h => Math.min(h + 1, results.length - 1)) }
else if (e.key === 'ArrowUp') { e.preventDefault(); setHighlight(h => Math.max(h - 1, 0)) }
else if (e.key === 'Enter' && highlight >= 0) { e.preventDefault(); pick(results[highlight]) }
else if (e.key === 'Escape') setOpen(false)
}
return (
<div ref={wrapRef} style={{ position: 'relative' }}>
<input
type="text"
value={value}
placeholder={placeholder}
onChange={e => { onChange(e.target.value); setOpen(true); search(e.target.value) }}
onFocus={() => setOpen(true)}
onKeyDown={onKey}
className={className}
/>
{open && (loading || results.length > 0) && (
<div className="bg-surface-card" style={{ position: 'absolute', top: 'calc(100% + 4px)', left: 0, right: 0, border: '1px solid var(--border-primary)', borderRadius: 10, boxShadow: '0 8px 24px rgba(0,0,0,0.18)', maxHeight: 260, overflowY: 'auto', zIndex: 1000 }}>
{loading && results.length === 0 && (
<div className="text-content-faint" style={{ padding: 10, fontSize: 'calc(12px * var(--fs-scale-body, 1))' }}>{t('common.loading')}</div>
)}
{results.map((r, i) => (
<button
key={`${r.osm_id || r.google_place_id || i}`}
type="button"
onClick={() => pick(r)}
onMouseEnter={() => setHighlight(i)}
className={`text-content ${i === highlight ? 'bg-surface-hover' : 'bg-transparent'}`}
style={{
display: 'flex', alignItems: 'flex-start', gap: 8, width: '100%',
padding: '8px 12px', border: 'none', cursor: 'pointer', textAlign: 'left',
fontFamily: 'inherit',
}}
>
<MapPin size={12} className="text-content-faint" style={{ marginTop: 2, flexShrink: 0 }} />
<span style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.name || r.address}</div>
{r.address && r.name !== r.address && (
<div className="text-content-faint" style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.address}</div>
)}
</span>
</button>
))}
</div>
)}
</div>
)
}
@@ -5,6 +5,9 @@ import { X, Sun, Cloud, CloudRain, CloudSnow, CloudDrizzle, CloudLightning, Wind
const RES_TYPE_ICONS = { flight: Plane, hotel: Hotel, restaurant: Utensils, train: Train, car: Car, cruise: Ship, transit: TramFront, event: Ticket, tour: Users, other: FileText }
const RES_TYPE_COLORS = { flight: '#3b82f6', hotel: '#8b5cf6', restaurant: '#ef4444', train: '#06b6d4', car: '#6b7280', cruise: '#0ea5e9', transit: '#7c3aed', event: '#f59e0b', tour: '#10b981', other: '#6b7280' }
import { weatherApi, accommodationsApi } from '../../api/client'
import { usePluginViewContributions, PluginCardFooter } from '../Plugins/PluginContributions'
import { usePluginStore } from '../../store/pluginStore'
import PluginFrame from '../Plugins/PluginFrame'
import { useCanDo } from '../../store/permissionsStore'
import { useTripStore } from '../../store/tripStore'
import CustomSelect from '../shared/CustomSelect'
@@ -103,6 +106,12 @@ export default function DayDetailPanel({ day, days, places, categories = [], tri
hotelForm, setHotelForm, handleSelectPlace, handleSaveAccommodation,
updateAccommodationField, handleRemoveAccommodation,
} = useDayDetail(day, days, tripId, lat, lng, language, onAccommodationChange)
// Plugin-contributed columns/actions for the day view, keyed by day id (#plugins).
// day can be null (panel closed) and hooks must run before the early return, so guard it.
const dayContributions = usePluginViewContributions('day', tripId)(day?.id ?? -1)
// Plugins that declared a day-detail slot mount at the bottom of this panel,
// scoped to the open day. Inline-filter like the place-detail site.
const dayDetailPlugins = usePluginStore((s) => s.plugins).filter((p) => p.type === 'widget' && p.slot === 'day-detail')
// Publish the panel's live height as a root CSS var so the map's mobile GPS
// button can sit just above the panel instead of being hidden behind it (#1348).
@@ -274,6 +283,7 @@ export default function DayDetailPanel({ day, days, places, categories = [], tri
)}
{/* ── Reservations for this day's assignments ── */}
{dayContributions.length > 0 && <PluginCardFooter items={dayContributions} tripId={tripId} />}
{(() => {
const dayAssignments = assignments[String(day.id)] || []
const dayReservations = reservations.filter(r => {
@@ -336,6 +346,17 @@ export default function DayDetailPanel({ day, days, places, categories = [], tri
setDayAccommodations={setDayAccommodations} setAccommodation={setAccommodation}
handleSaveAccommodation={handleSaveAccommodation} onAccommodationChange={onAccommodationChange} />
</div>
{/* Day-detail plugin slots: sandboxed, scoped to this day. */}
{dayDetailPlugins.length > 0 && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 12 }}>
{dayDetailPlugins.map((p) => (
<div key={p.id} className="bg-surface-hover" style={{ borderRadius: 10, overflow: 'hidden' }}>
<PluginFrame pluginId={p.id} tripId={String(tripId)} dayId={String(day.id)} title={p.name} />
</div>
))}
</div>
)}
</div>
</div>
<style>{`@keyframes spin { to { transform: rotate(360deg) } }`}</style>
@@ -1924,4 +1924,41 @@ describe('DayPlanSidebar', () => {
expect(await screen.findByText('1000 m')).toBeInTheDocument()
expect(await screen.findByText('2000 m')).toBeInTheDocument()
})
it('FE-PLANNER-DAYPLAN-106: leg distance survives a car rental on its middle days (#1504)', async () => {
const user = userEvent.setup()
const { calculateRouteWithLegs } = await import('../Map/RouteCalculator')
vi.mocked(calculateRouteWithLegs as any).mockImplementation((wp: any) => Promise.resolve({
distanceText: '2 km', durationText: '10 min',
legs: Array.from({ length: Math.max(0, (wp?.length ?? 0) - 1) }, () => ({
distanceText: '2 km', durationText: '10 min', drivingText: '10 min', walkingText: '25 min',
})),
}))
// A rental spanning days 10–12: on day 11 (middle) its row is not rendered in
// the timeline, so the through-leg between the places around it must stay keyed
// to the place — re-keying it to the hidden car row would drop the distance.
const car = {
...buildReservation({ id: 400, type: 'car', title: 'Rental car', day_id: 10 }),
end_day_id: 12,
day_positions: { 11: 0.5 },
}
const days = [
buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' }),
buildDay({ id: 11, date: '2025-06-02', title: 'Day 2' }),
buildDay({ id: 12, date: '2025-06-03', title: 'Day 3' }),
]
const assigns = {
'11': [
buildAssignment({ id: 1, day_id: 11, order_index: 0, place: buildPlace({ id: 1, name: 'A', lat: 48.85, lng: 2.35 }) }),
buildAssignment({ id: 2, day_id: 11, order_index: 1, place: buildPlace({ id: 2, name: 'B', lat: 48.86, lng: 2.36 }) }),
],
}
render(<DayPlanSidebar {...makeDefaultProps({
days, places: [], assignments: assigns, reservations: [car as any],
selectedDayId: null, showRouteToolsWhenExpanded: true,
})} />)
// Only day 2 has places, so it renders the sole Route toggle.
await user.click(screen.getByRole('button', { name: 'Route' }))
expect(await screen.findByText('2 km')).toBeInTheDocument()
})
})
@@ -22,7 +22,7 @@ import { useAddonStore } from '../../store/addonStore'
import { useSaveToCollectionStore } from '../../store/saveToCollectionStore'
import { placeToSaveTarget } from '../Collections/saveTarget'
import { useTranslation } from '../../i18n'
import { isDayInAccommodationRange, getAccommodationAnchors, getDayBookendHotels } from '../../utils/dayOrder'
import { isDayInAccommodationRange, getAccommodationAnchors, getDayBookendHotels, shouldDrawMorningLeg, shouldDrawEveningLeg } from '../../utils/dayOrder'
import {
TRANSPORT_TYPES, parseTimeToMinutes, getSpanPhase, getDisplayTimeForDay, getTransportRouteEndpoints,
getTransportForDay as _getTransportForDay, getMergedItems as _getMergedItems,
@@ -455,9 +455,11 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
cur = []
curHasPlace = false
if (to) cur.push({ id: r.id, lat: to.lat, lng: to.lng })
} else if (cur.length > 0) {
} else if (cur.length > 0 && !(r.type === 'car' && getSpanPhase(r, dayId) === 'middle')) {
// No location: ignore for routing, but attribute the through-leg to the
// booking so its distance/duration shows under it (purely cosmetic).
// Not for a car rental's middle days though — that row isn't rendered
// in the timeline, so re-keying would drop the leg entirely (#1504).
cur[cur.length - 1] = { ...cur[cur.length - 1], id: r.id }
}
}
@@ -475,22 +477,23 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
const endHotel = bookends?.evening
// Waypoints include transport endpoints (a car return, a taxi/train arrival), so the hotel
// legs connect even when the day starts or ends with a booking rather than a place. Track
// whether each is a place so we can skip a hotel↔transport leg that isn't real: on a day-1
// arrival the check-in hotel never drove to the departure airport (#1321).
const wayPts: { lat: number; lng: number; isPlace: boolean }[] = []
// whether each is a place and its time so the bookend decision can drop a leg that isn't
// real: a check-in hotel never drove to a departure airport (#1321), and a place timed before
// check-in / after check-out means you weren't at the hotel then (#1465).
const wayPts: { lat: number; lng: number; isPlace: boolean; time: string | null }[] = []
for (const it of merged) {
if (it.type === 'place' && it.data.place?.lat && it.data.place?.lng) {
wayPts.push({ lat: it.data.place.lat, lng: it.data.place.lng, isPlace: true })
wayPts.push({ lat: it.data.place.lat, lng: it.data.place.lng, isPlace: true, time: it.data.place?.place_time ?? null })
} else if (it.type === 'transport') {
const { from, to } = getTransportRouteEndpoints(it.data, dayId)
if (from) wayPts.push({ lat: from.lat, lng: from.lng, isPlace: false })
if (to) wayPts.push({ lat: to.lat, lng: to.lng, isPlace: false })
if (from) wayPts.push({ lat: from.lat, lng: from.lng, isPlace: false, time: null })
if (to) wayPts.push({ lat: to.lat, lng: to.lng, isPlace: false, time: null })
}
}
const firstWay = wayPts[0]
const lastWay = wayPts[wayPts.length - 1]
const wantTop = !!(startHotel && firstWay && (firstWay.isPlace || bookends?.morningIsSleptHere))
const wantBottom = !!(endHotel && lastWay && (lastWay.isPlace || bookends?.eveningIsOvernight))
const wantTop = !!(startHotel && firstWay && bookends && day && shouldDrawMorningLeg(bookends, day, firstWay))
const wantBottom = !!(endHotel && lastWay && bookends && day && shouldDrawEveningLeg(bookends, day, lastWay))
return { runs, startHotel, endHotel, firstWay, lastWay, wantTop, wantBottom }
}
@@ -2358,11 +2361,19 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
// Bookend the Google Maps route with the day's accommodation the
// same way the drawn map route does (routeBookends is null when
// "optimize from accommodation" is off), so hotels aren't dropped
// from the exported route (#1372).
const stops = getDayAssignments(day.id).map(a => a.place).filter(p => p?.lat != null && p?.lng != null) as { lat: number; lng: number }[]
const morning = routeBookends?.morning?.place_lat != null && routeBookends?.morning?.place_lng != null
// from the exported route (#1372) — but only when the leg is real:
// no hotel prepended before an early check-in-day stop, none appended
// after a post-check-out stop (#1465).
const dayStops = getDayAssignments(day.id).filter(a => a.place?.lat != null && a.place?.lng != null)
const stops = dayStops.map(a => ({ lat: a.place!.lat!, lng: a.place!.lng! }))
const firstStop = dayStops[0] ? { isPlace: true, time: dayStops[0].place?.place_time ?? null } : undefined
const lastAssignment = dayStops[dayStops.length - 1]
const lastStop = lastAssignment ? { isPlace: true, time: lastAssignment.place?.place_time ?? null } : undefined
const drawMorning = !!routeBookends && shouldDrawMorningLeg(routeBookends, day, firstStop)
const drawEvening = !!routeBookends && shouldDrawEveningLeg(routeBookends, day, lastStop)
const morning = drawMorning && routeBookends?.morning?.place_lat != null && routeBookends?.morning?.place_lng != null
? { lat: routeBookends.morning.place_lat, lng: routeBookends.morning.place_lng } : null
const evening = routeBookends?.evening?.place_lat != null && routeBookends?.evening?.place_lng != null
const evening = drawEvening && routeBookends?.evening?.place_lat != null && routeBookends?.evening?.place_lng != null
? { lat: routeBookends.evening.place_lat, lng: routeBookends.evening.place_lng } : null
const url = generateGoogleMapsUrl([...(morning ? [morning] : []), ...stops, ...(evening ? [evening] : [])])
if (url) window.open(url, '_blank', 'noopener,noreferrer')
@@ -14,6 +14,7 @@ import CustomTimePicker from '../shared/CustomTimePicker'
import { DEFAULT_FORM, isGoogleMapsUrl, type PlaceFormData } from './PlaceFormModal.helpers'
import { getApiErrorMessage } from '../../utils/apiError'
import type { Place, Category, Assignment } from '../../types'
import { NumericInput } from '../shared/NumericInput'
// The submit payload mirrors the form, but lat/lng are parsed to numbers and
// category_id is normalised, plus any files chosen before the place existed.
@@ -698,11 +699,10 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
className="form-input"
/>
<div className="grid grid-cols-2 gap-2 mt-2">
<input
type="number"
step="any"
<NumericInput
mode="signed"
value={form.lat}
onChange={e => handleChange('lat', e.target.value)}
onValueChange={v => handleChange('lat', v)}
onPaste={e => {
const text = e.clipboardData.getData('text').trim()
const match = text.match(/^(-?\d+\.?\d*)\s*[,;\s]\s*(-?\d+\.?\d*)$/)
@@ -715,11 +715,10 @@ export default function PlaceFormModal(props: PlaceFormModalProps) {
placeholder={t('places.formLat')}
className="form-input"
/>
<input
type="number"
step="any"
<NumericInput
mode="signed"
value={form.lng}
onChange={e => handleChange('lng', e.target.value)}
onValueChange={v => handleChange('lng', v)}
placeholder={t('places.formLng')}
className="form-input"
/>
@@ -1,12 +1,16 @@
import { Fragment } from 'react'
import { MemoPlaceRow } from './PlacesSidebarRow'
import type { SidebarState } from './usePlacesSidebar'
import { usePluginViewContributions, PluginCardFooter } from '../Plugins/PluginContributions'
export function PlacesList(S: SidebarState) {
const {
filtered, scrollContainerRef, onScrollTopChange, filter, t, canEditPlaces, onAddPlace,
categories, selectedPlaceId, plannedIds, inDaySet, selectedIds, selectMode, selectedDayId,
isMobile, onPlaceClick, openContextMenu, onAssignToDay, toggleSelected, setDayPickerPlace, registerPlaceRow,
isMobile, onPlaceClick, openContextMenu, onAssignToDay, toggleSelected, setDayPickerPlace, registerPlaceRow, tripId,
} = S
// Plugin-contributed columns/actions for the places view, keyed by place id (#plugins).
const contribFor = usePluginViewContributions('places', tripId)
return (
<div className="trek-stagger" style={{ flex: 1, overflowY: 'auto', minHeight: 0 }} ref={scrollContainerRef} onScroll={(e) => onScrollTopChange?.((e.currentTarget as HTMLElement).scrollTop)}>
{filtered.length === 0 ? (
@@ -25,27 +29,32 @@ export function PlacesList(S: SidebarState) {
const isPlanned = plannedIds.has(place.id)
const inDay = inDaySet.has(place.id)
const isChecked = selectedIds.has(place.id)
const contributions = contribFor(place.id)
return (
<MemoPlaceRow
key={place.id}
place={place}
category={cat}
isSelected={isSelected}
isPlanned={isPlanned}
inDay={inDay}
isChecked={isChecked}
selectMode={selectMode}
selectedDayId={selectedDayId}
canEditPlaces={canEditPlaces}
isMobile={isMobile}
t={t}
onPlaceClick={onPlaceClick}
onContextMenu={openContextMenu}
onAssignToDay={onAssignToDay}
toggleSelected={toggleSelected}
setDayPickerPlace={setDayPickerPlace}
registerPlaceRow={registerPlaceRow}
/>
<Fragment key={place.id}>
<MemoPlaceRow
place={place}
category={cat}
isSelected={isSelected}
isPlanned={isPlanned}
inDay={inDay}
isChecked={isChecked}
selectMode={selectMode}
selectedDayId={selectedDayId}
canEditPlaces={canEditPlaces}
isMobile={isMobile}
t={t}
onPlaceClick={onPlaceClick}
onContextMenu={openContextMenu}
onAssignToDay={onAssignToDay}
toggleSelected={toggleSelected}
setDayPickerPlace={setDayPickerPlace}
registerPlaceRow={registerPlaceRow}
/>
{contributions.length > 0 && (
<div style={{ padding: '0 14px 8px 16px' }}><PluginCardFooter items={contributions} tripId={tripId} /></div>
)}
</Fragment>
)
})
)}
@@ -782,4 +782,62 @@ describe('ReservationModal', () => {
await waitFor(() => expect(onSave).toHaveBeenCalled());
expect(onSave.mock.calls[0][0].assignment_id).toBeNull();
});
// ── Hotel address persistence (issue #1496) ─────────────────────────────────
it('FE-PLANNER-RESMODAL-053: editing a hotel address sends the typed value even with a place linked', async () => {
const onSave = vi.fn().mockResolvedValue(undefined);
const place = buildPlace({ id: 5, name: 'Grand Hotel', address: 'Old Street 1' });
const days = [
buildDay({ id: 1, trip_id: 1, date: '2026-05-01', day_number: 1 }),
buildDay({ id: 2, trip_id: 1, date: '2026-05-02', day_number: 2 }),
];
const res = buildReservation({
id: 3, title: 'Grand Hotel', type: 'hotel', accommodation_id: 8,
} as any);
const acc = { id: 8, trip_id: 1, place_id: 5, start_day_id: 1, end_day_id: 2 } as any;
render(
<ReservationModal
{...defaultProps}
onSave={onSave}
reservation={res}
days={days}
places={[place]}
accommodations={[acc]}
/>
);
// Address field is pre-filled from the linked place
const addressInput = screen.getByPlaceholderText(/Address, Airport/i);
expect(addressInput).toHaveValue('Old Street 1');
await userEvent.clear(addressInput);
await userEvent.type(addressInput, 'New Street 2');
await userEvent.click(screen.getByRole('button', { name: /^Update$/i }));
await waitFor(() => expect(onSave).toHaveBeenCalled());
const saved = onSave.mock.calls[0][0];
// The typed address must reach the save handler — before #1496 it was
// dropped whenever a place was linked and the old address reappeared.
expect(saved.location).toBe('New Street 2');
expect(saved.create_accommodation?.address).toBe('New Street 2');
expect(saved.create_accommodation?.place_id).toBe(5);
});
it('FE-PLANNER-RESMODAL-054: hotel address is kept in location when no days or place are set', async () => {
const onSave = vi.fn().mockResolvedValue(undefined);
render(<ReservationModal {...defaultProps} onSave={onSave} />);
await userEvent.click(screen.getByRole('button', { name: /^Accommodation$/i }));
await userEvent.type(screen.getByPlaceholderText(/e\.g\. Lufthansa/i), 'Hotel Test');
await userEvent.type(screen.getByPlaceholderText(/Address, Airport/i), 'Main Road 3');
await userEvent.click(screen.getByRole('button', { name: /^Add$/i }));
await waitFor(() => expect(onSave).toHaveBeenCalled());
const saved = onSave.mock.calls[0][0];
// No day range → no accommodation, but the address must not be lost
expect(saved.create_accommodation).toBeUndefined();
expect(saved.location).toBe('Main Road 3');
});
});
@@ -5,6 +5,7 @@ import { useTripStore } from '../../store/tripStore'
import { useAddonStore } from '../../store/addonStore'
import Modal from '../shared/Modal'
import CustomSelect from '../shared/CustomSelect'
import AddressInput from './AddressInput'
import { Hotel, Utensils, Ticket, FileText, Users, Paperclip, X, ExternalLink, Link2 } from 'lucide-react'
import { useToast } from '../shared/Toast'
import { useTranslation } from '../../i18n'
@@ -147,7 +148,9 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
hotel_place_id: editAcc?.place_id || '',
hotel_start_day: editAcc?.start_day_id || '',
hotel_end_day: editAcc?.end_day_id || '',
hotel_address: places.find(p => p.id == editAcc?.place_id)?.address || '',
// The linked place carries the address; reservations saved without a
// place (or before the accommodation existed) keep it in location.
hotel_address: places.find(p => p.id == editAcc?.place_id)?.address || reservation.location || '',
})
} else if (prefill) {
// Review-before-save: populate from a parsed import item, stay in create mode.
@@ -202,9 +205,10 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
if (!acc) return
setForm(prev => {
if (prev.hotel_place_id !== '' || prev.hotel_start_day !== '' || prev.hotel_end_day !== '') return prev
return { ...prev, hotel_place_id: acc.place_id, hotel_start_day: acc.start_day_id, hotel_end_day: acc.end_day_id }
const accPlace = places.find(p => p.id == acc.place_id)
return { ...prev, hotel_place_id: acc.place_id, hotel_start_day: acc.start_day_id, hotel_end_day: acc.end_day_id, hotel_address: accPlace?.address || prev.hotel_address }
})
}, [accommodations, isOpen, reservation])
}, [accommodations, isOpen, reservation, places])
const set = (field, value) => setForm(prev => ({ ...prev, [field]: value }))
@@ -240,7 +244,10 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
title: form.title, type: form.type, status: form.status,
reservation_time: form.type === 'hotel' ? null : (form.reservation_time || null),
reservation_end_time: form.type === 'hotel' ? null : (combinedEndTime || null),
location: form.location, confirmation_number: form.confirmation_number,
// Hotels show the address field instead of location — persist it on the
// reservation itself so it survives even without days/place (#1496).
location: form.type === 'hotel' ? form.hotel_address : form.location,
confirmation_number: form.confirmation_number,
notes: form.notes,
url: form.url,
assignment_id: (form.type === 'hotel' && !form.accommodation_id) ? null : (form.assignment_id || null),
@@ -260,6 +267,9 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
venue: (!form.hotel_place_id && (form.hotel_address || form.title))
? { name: form.title, address: form.hotel_address || null }
: null,
// The typed address, so the save handler can write it through to a
// linked place — an edited address used to be silently dropped (#1496).
address: form.hotel_address || null,
// Tolerate a single resolved end of the range (a one-night stay or a date
// that only matched one trip day) so the accommodation is still created.
start_day_id: form.hotel_start_day || form.hotel_end_day,
@@ -504,7 +514,7 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
{form.type !== 'hotel' && (
<div>
<label className={labelClass}>{t('reservations.locationAddress')}</label>
<input type="text" value={form.location} onChange={e => set('location', e.target.value)}
<AddressInput value={form.location} onChange={v => set('location', v)}
placeholder={t('reservations.locationPlaceholder')} className={inputClass} />
</div>
)}
@@ -542,11 +552,11 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
const p = places.find(pl => pl.id === value)
setForm(prev => {
const next = { ...prev, hotel_place_id: value }
if (!value) {
next.location = ''
} else if (p) {
if (value && p) {
if (!prev.title) next.title = p.name
if (!prev.location && p.address) next.location = p.address
// Show the picked hotel's address; keep a hand-typed one
// if the place has none.
next.hotel_address = p.address || prev.hotel_address
}
return next
})
@@ -609,7 +619,7 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p
</div>
<div>
<label className={labelClass}>{t('reservations.locationAddress')}</label>
<input type="text" value={form.hotel_address} onChange={e => set('hotel_address', e.target.value)}
<AddressInput value={form.hotel_address} onChange={v => set('hotel_address', v)}
placeholder={t('reservations.locationPlaceholder')} className={inputClass} />
</div>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
@@ -436,4 +436,30 @@ describe('ReservationsPanel', () => {
expect(screen.queryByText(/Invalid Date/)).not.toBeInTheDocument();
expect(screen.getByText(/08:30/)).toBeInTheDocument();
});
// ── Chronological sorting (#1507) ───────────────────────────────────────────
it('FE-PLANNER-RESP-044: cards are ordered chronologically, day-linked entries by their day date', () => {
const day1 = buildDay({ id: 201, date: '2025-06-02', day_number: 2 } as any);
const day2 = buildDay({ id: 202, date: '2025-06-04', day_number: 4 } as any);
const dated = buildReservation({ title: 'Dated flight', type: 'flight', status: 'pending', reservation_time: '2025-06-03T09:00', created_at: '2025-05-01T00:00:00.000Z' });
const dayOnly = buildReservation({ title: 'Day-only train', type: 'train', status: 'pending', reservation_time: 'T10:00', day_id: 201, created_at: '2025-05-02T00:00:00.000Z' } as any);
const late = buildReservation({ title: 'Late bus', type: 'bus', status: 'pending', reservation_time: null, day_id: 202, created_at: '2025-05-03T00:00:00.000Z' } as any);
const undated = buildReservation({ title: 'Undated taxi', type: 'taxi', status: 'pending', created_at: '2025-04-01T00:00:00.000Z' });
render(<ReservationsPanel {...defaultProps} reservations={[undated, late, dayOnly, dated]} days={[day1, day2]} />);
const text = document.body.textContent || '';
const order = ['Day-only train', 'Dated flight', 'Late bus', 'Undated taxi'].map(t => text.indexOf(t));
expect(order.every(i => i >= 0)).toBe(true);
expect([...order].sort((a, b) => a - b)).toEqual(order);
});
it('FE-PLANNER-RESP-045: hotel sorts by its accommodation start day, not a stale day_id', () => {
const day1 = buildDay({ id: 301, date: '2025-06-01', day_number: 1 } as any);
const day2 = buildDay({ id: 302, date: '2025-06-05', day_number: 5 } as any);
const hotel = buildReservation({ title: 'Hotel stay', type: 'hotel', status: 'pending', day_id: 301, accommodation_start_day_id: 302 } as any);
const flight = buildReservation({ title: 'Mid flight', type: 'flight', status: 'pending', reservation_time: '2025-06-03T12:00' });
render(<ReservationsPanel {...defaultProps} reservations={[hotel, flight]} days={[day1, day2]} />);
const text = document.body.textContent || '';
expect(text.indexOf('Mid flight')).toBeLessThan(text.indexOf('Hotel stay'));
});
});
@@ -17,6 +17,10 @@ import Markdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import remarkBreaks from 'remark-breaks'
import type { Reservation, Day, TripFile, AssignmentsMap } from '../../types'
import type { ViewContribution } from '../../api/client'
import { usePluginViewContributions, PluginCardFooter } from '../Plugins/PluginContributions'
import { usePluginStore, type ActivePlugin } from '../../store/pluginStore'
import PluginFrame from '../Plugins/PluginFrame'
import { splitReservationDateTime, formatTime } from '../../utils/formatters'
interface AssignmentLookupEntry {
@@ -76,9 +80,12 @@ interface ReservationCardProps {
assignmentLookup: Record<number, AssignmentLookupEntry>
canEdit: boolean
days?: Day[]
contributions?: ViewContribution[]
/** Plugins that declared a reservation-detail slot — mounted at the card's foot, scoped to this reservation. */
detailPlugins?: ActivePlugin[]
}
function ReservationCard({ r, tripId, onEdit, onDelete, files = [], onNavigateToFiles, assignmentLookup, canEdit, days = [] }: ReservationCardProps) {
function ReservationCard({ r, tripId, onEdit, onDelete, files = [], onNavigateToFiles, assignmentLookup, canEdit, days = [], contributions = [], detailPlugins = [] }: ReservationCardProps) {
const { toggleReservationStatus } = useTripStore()
const toast = useToast()
const { t, locale } = useTranslation()
@@ -407,6 +414,19 @@ function ReservationCard({ r, tripId, onEdit, onDelete, files = [], onNavigateTo
)}
</div>
<PluginCardFooter items={contributions} tripId={tripId} />
{/* Reservation-detail plugin slots: sandboxed, scoped to this reservation. */}
{detailPlugins.length > 0 && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, padding: '0 14px 14px' }}>
{detailPlugins.map(p => (
<div key={p.id} className="bg-surface-hover" style={{ borderRadius: 10, overflow: 'hidden' }}>
<PluginFrame pluginId={p.id} tripId={String(tripId)} reservationId={String(r.id)} title={p.name} />
</div>
))}
</div>
)}
{/* Delete confirmation */}
{showDeleteConfirm && ReactDOM.createPortal(
<div className="bg-[rgba(0,0,0,0.3)]" style={{
@@ -498,12 +518,15 @@ function Section({ title, count, children, defaultOpen = true, accent, storageKe
* A transit journey's own card (#1065) — leg chips + journey stats instead of
* the generic booking layout. Clicking anywhere opens the journey view.
*/
function TransitJourneyCard({ r, days, onOpen, onDelete, canEdit }: {
function TransitJourneyCard({ r, days, onOpen, onDelete, canEdit, tripId, contributions = [], detailPlugins = [] }: {
r: Reservation
days: Day[]
onOpen: (r: Reservation) => void
onDelete: (id: number) => void
canEdit: boolean
tripId: number
contributions?: ViewContribution[]
detailPlugins?: ActivePlugin[]
}) {
const { t, locale } = useTranslation()
const timeFormat = useSettingsStore(st => st.settings.time_format) || '24h'
@@ -566,6 +589,18 @@ function TransitJourneyCard({ r, days, onOpen, onDelete, canEdit }: {
</span>
</div>
)}
<PluginCardFooter items={contributions} tripId={tripId} />
{/* Reservation-detail plugin slots: sandboxed, scoped to this journey. The
card itself is clickable, so keep frame interactions from opening it. */}
{detailPlugins.length > 0 && (
<div onClick={e => e.stopPropagation()} style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{detailPlugins.map(p => (
<div key={p.id} className="bg-surface-hover" style={{ borderRadius: 10, overflow: 'hidden' }}>
<PluginFrame pluginId={p.id} tripId={String(tripId)} reservationId={String(r.id)} title={p.name} />
</div>
))}
</div>
)}
{confirmOpen && ReactDOM.createPortal(
<div className="bg-[rgba(0,0,0,0.35)]" style={{ position: 'fixed', inset: 0, zIndex: 3000, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={e => { e.stopPropagation(); setConfirmOpen(false) }}>
<div className="bg-surface-card" style={{ borderRadius: 14, padding: 20, width: 340, boxShadow: '0 16px 48px rgba(0,0,0,0.22)' }} onClick={e => e.stopPropagation()}>
@@ -599,9 +634,12 @@ interface ReservationsPanelProps {
onNavigateToFiles: () => void
titleKey?: string
addManualKey?: string
/** Which plugin view this panel represents — the transports tab is its own
* contribution view, the bookings tab stays 'reservations'. */
contributionView?: 'reservations' | 'transports'
}
export default function ReservationsPanel({ tripId, reservations, days, assignments, files = [], onAdd, onImport, bookingImportAvailable, onAirTrailImport, airTrailAvailable, onEdit, onDelete, onNavigateToFiles, titleKey = 'reservations.title', addManualKey = 'reservations.addManual' }: ReservationsPanelProps) {
export default function ReservationsPanel({ tripId, reservations, days, assignments, files = [], onAdd, onImport, bookingImportAvailable, onAirTrailImport, airTrailAvailable, onEdit, onDelete, onNavigateToFiles, titleKey = 'reservations.title', addManualKey = 'reservations.addManual', contributionView = 'reservations' }: ReservationsPanelProps) {
const { t, locale } = useTranslation()
const can = useCanDo()
const trip = useTripStore((s) => s.trip)
@@ -609,6 +647,12 @@ export default function ReservationsPanel({ tripId, reservations, days, assignme
const [showHint, setShowHint] = useState(() => !localStorage.getItem('hideReservationHint'))
const storageKey = `trek-reservation-filters-${tripId}`
// Plugin-contributed columns/actions for this view, keyed by reservation id (#plugins).
// The bookings and transports tabs share this panel but are distinct plugin views.
const contribFor = usePluginViewContributions(contributionView, tripId)
// Plugins that declared a reservation-detail slot mount at the foot of each card,
// scoped to that reservation. Filtered inline like the place-/day-detail sites.
const reservationDetailPlugins = usePluginStore((s) => s.plugins).filter((p) => p.type === 'widget' && p.slot === 'reservation-detail')
const [typeFilters, setTypeFilters] = useState<Set<string>>(() => {
try {
const saved = sessionStorage.getItem(storageKey)
@@ -631,10 +675,37 @@ export default function ReservationsPanel({ tripId, reservations, days, assignme
typeFilters.size === 0 ? reservations : reservations.filter(r => typeFilters.has(r.type)),
[reservations, typeFilters])
// Chronological order (#1507): day-linked transports often carry no date in
// reservation_time, so resolve each entry to an effective departure datetime —
// the stamped date when there is one, else the linked day's date (the
// accommodation start day for hotels, matching the card label). Entries
// without any resolvable date sink to the bottom; creation order breaks ties.
const sorted = useMemo(() => {
const dayDates = new Map(days.map(d => [d.id, d.date]))
const sortKey = (r: Reservation): string | null => {
const { date, time } = splitReservationDateTime(r.reservation_time)
const dayId = r.type === 'hotel' ? (r.accommodation_start_day_id ?? r.day_id) : r.day_id
const effectiveDate = date ?? (dayId != null ? dayDates.get(dayId) : null)
if (!effectiveDate) return null
return `${effectiveDate}T${time ?? '00:00'}`
}
return filtered
.map(r => ({ r, key: sortKey(r) }))
.sort((a, b) => {
if (a.key !== b.key) {
if (a.key === null) return 1
if (b.key === null) return -1
return a.key < b.key ? -1 : 1
}
return (a.r.created_at ?? '').localeCompare(b.r.created_at ?? '')
})
.map(({ r }) => r)
}, [filtered, days])
// Automated public transit (#1065) gets its own section — journeys planned via
// the transit search live alongside manual transports without mixing in.
const transitEntries = filtered.filter(r => r.type === 'transit')
const nonTransit = filtered.filter(r => r.type !== 'transit')
const transitEntries = sorted.filter(r => r.type === 'transit')
const nonTransit = sorted.filter(r => r.type !== 'transit')
const allPending = nonTransit.filter(r => r.status !== 'confirmed')
const allConfirmed = nonTransit.filter(r => r.status === 'confirmed')
const total = filtered.length
@@ -776,17 +847,17 @@ export default function ReservationsPanel({ tripId, reservations, days, assignme
<>
{transitEntries.length > 0 && (
<Section title={t('transit.sectionTitle')} count={transitEntries.length} accent="gray" storageKey={`trek:bookings-transit-open:${tripId}`}>
{transitEntries.map(r => <TransitJourneyCard key={r.id} r={r} days={days} onOpen={onEdit} onDelete={onDelete} canEdit={canEdit} />)}
{transitEntries.map(r => <TransitJourneyCard key={r.id} r={r} days={days} onOpen={onEdit} onDelete={onDelete} canEdit={canEdit} tripId={tripId} contributions={contribFor(r.id)} detailPlugins={reservationDetailPlugins} />)}
</Section>
)}
{allPending.length > 0 && (
<Section title={t('reservations.pending')} count={allPending.length} accent="gray" storageKey={`trek:bookings-pending-open:${tripId}`}>
{allPending.map(r => <ReservationCard key={r.id} r={r} tripId={tripId} onEdit={onEdit} onDelete={onDelete} files={files} onNavigateToFiles={onNavigateToFiles} assignmentLookup={assignmentLookup} canEdit={canEdit} days={days} />)}
{allPending.map(r => <ReservationCard key={r.id} r={r} tripId={tripId} onEdit={onEdit} onDelete={onDelete} files={files} onNavigateToFiles={onNavigateToFiles} assignmentLookup={assignmentLookup} canEdit={canEdit} days={days} contributions={contribFor(r.id)} detailPlugins={reservationDetailPlugins} />)}
</Section>
)}
{allConfirmed.length > 0 && (
<Section title={t('reservations.confirmed')} count={allConfirmed.length} accent="green" storageKey={`trek:bookings-confirmed-open:${tripId}`}>
{allConfirmed.map(r => <ReservationCard key={r.id} r={r} tripId={tripId} onEdit={onEdit} onDelete={onDelete} files={files} onNavigateToFiles={onNavigateToFiles} assignmentLookup={assignmentLookup} canEdit={canEdit} days={days} />)}
{allConfirmed.map(r => <ReservationCard key={r.id} r={r} tripId={tripId} onEdit={onEdit} onDelete={onDelete} files={files} onNavigateToFiles={onNavigateToFiles} assignmentLookup={assignmentLookup} canEdit={canEdit} days={days} contributions={contribFor(r.id)} detailPlugins={reservationDetailPlugins} />)}
</Section>
)}
</>
@@ -135,6 +135,43 @@ describe('TransitSearchPanel', () => {
expect(cards[0].textContent).toContain('08:40')
})
// Cross-timezone route (#1479): origin Europe/Berlin (UTC+2 in June),
// destination Europe/London (UTC+1). Same wall-clock 09:00 resolves to a
// different UTC instant depending on which end the user anchors to.
async function pickFromAndLondon(user: ReturnType<typeof userEvent.setup>) {
const [fromInput, toInput] = screen.getAllByPlaceholderText('Search stop or station…')
await user.click(fromInput)
await user.click(await screen.findByText('Fernsehturm'))
transitApiMock.geocode.mockResolvedValueOnce({ results: [{ name: 'London Victoria', lat: 51.5074, lng: -0.1278, type: 'STOP', area: 'England' }] })
await user.click(toInput)
await user.type(toInput, 'Lon')
await user.click(await screen.findByText(/London Victoria/))
}
it('FE-PLANNER-TRANSIT-007: depart-by anchors the entered time to the origin timezone', async () => {
const user = userEvent.setup()
transitApiMock.plan.mockResolvedValueOnce({ itineraries: [] })
render(<TransitSearchPanel {...makeProps()} />)
await pickFromAndLondon(user)
await user.click(screen.getByRole('button', { name: /^Search$/ }))
await waitFor(() => expect(transitApiMock.plan).toHaveBeenCalled())
// Default 09:00 in Berlin (UTC+2) → 07:00Z.
expect(transitApiMock.plan.mock.calls[0][0]).toMatchObject({ arriveBy: false, time: '2025-06-01T07:00:00.000Z' })
})
it('FE-PLANNER-TRANSIT-008: arrive-by anchors the entered time to the destination timezone', async () => {
const user = userEvent.setup()
transitApiMock.plan.mockResolvedValueOnce({ itineraries: [] })
render(<TransitSearchPanel {...makeProps()} />)
await pickFromAndLondon(user)
await user.click(screen.getByRole('button', { name: 'Arrive' }))
await user.click(screen.getByRole('button', { name: /^Search$/ }))
await waitFor(() => expect(transitApiMock.plan).toHaveBeenCalled())
// 09:00 arrival in London (UTC+1) → 08:00Z, not 07:00Z.
expect(transitApiMock.plan.mock.calls[0][0]).toMatchObject({ arriveBy: true, time: '2025-06-01T08:00:00.000Z' })
})
it('FE-PLANNER-TRANSIT-006: swap exchanges from and to', async () => {
const user = userEvent.setup()
render(<TransitSearchPanel {...makeProps()} />)
@@ -368,7 +368,10 @@ export default function TransitSearchPanel({ day, days, places, accommodations =
setExpandedIdx(null)
try {
const tzFrom = tzAt(from.lat, from.lng)
const timeIso = localToUtcIso(day.date, time, tzFrom)
const tzTo = tzAt(to.lat, to.lng)
// Depart-by anchors the entered time at the origin; arrive-by anchors it at
// the destination (#1479), so each mode must convert with the matching zone.
const timeIso = localToUtcIso(day.date, time, arriveBy ? tzTo : tzFrom)
const allModes = activeModes.size === MODE_GROUPS.length
const modes = allModes ? undefined : MODE_GROUPS.filter(m => activeModes.has(m.key)).map(m => m.modes).join(',')
const d = await transitApi.plan({ from: `${from.lat},${from.lng}`, to: `${to.lat},${to.lng}`, time: timeIso, arriveBy, modes })
@@ -11,6 +11,8 @@ import {
buildUser,
buildTrip,
buildDay,
buildPlace,
buildAssignment,
buildReservation,
buildTripFile,
} from '../../../tests/helpers/factories';
@@ -391,6 +393,25 @@ describe('TransportModal', () => {
expect(screen.getAllByPlaceholderText('Search stop or station…')).toHaveLength(2);
});
it('FE-PLANNER-TRANSMODAL-028: automated quick picks only offer the chosen day\'s places (#1460)', async () => {
const days = [
buildDay({ id: 10, date: '2025-06-01' }),
buildDay({ id: 11, date: '2025-06-02' }),
];
const louvre = buildPlace({ id: 1, name: 'Louvre' });
const eiffel = buildPlace({ id: 2, name: 'Eiffel Tower' });
const assignments = {
'10': [buildAssignment({ day_id: 10, place_id: louvre.id, place: louvre })],
'11': [buildAssignment({ day_id: 11, place_id: eiffel.id, place: eiffel })],
};
render(<TransportModal {...defaultProps} days={days} selectedDayId={10} initialAutomated places={[louvre, eiffel]} assignments={assignments} accommodations={[]} />);
// Focusing the "from" field opens the quick picks — day 1's place only.
const [fromInput] = screen.getAllByPlaceholderText('Search stop or station…');
await userEvent.click(fromInput);
expect(screen.getByText('Louvre')).toBeInTheDocument();
expect(screen.queryByText('Eiffel Tower')).not.toBeInTheDocument();
});
it('FE-PLANNER-TRANSMODAL-024: editing shows no Manual/Automated switch', () => {
const res = buildReservation({ title: 'My Train', type: 'train' });
render(<TransportModal {...defaultProps} reservation={res} />);
@@ -13,7 +13,7 @@ import { useAddonStore } from '../../store/addonStore'
import { formatDate, splitReservationDateTime, resolveDayId } from '../../utils/formatters'
import { openFile } from '../../utils/fileDownload'
import apiClient from '../../api/client'
import type { Day, Place, Accommodation, Reservation, ReservationEndpoint, TripFile, BudgetItem } from '../../types'
import type { Day, Place, Accommodation, Reservation, ReservationEndpoint, TripFile, BudgetItem, AssignmentsMap } from '../../types'
import { parseReservationMetadata, orderedEndpoints } from '../../utils/flightLegs'
import { BookingCostsSection } from './BookingCostsSection'
import type { BookingExpenseRequest } from './BookingCostsSection.types'
@@ -151,6 +151,8 @@ interface TransportModalProps {
prefill?: BookingReviewDraft | null
/** Data for the Automated (public transit) mode's quick picks. */
places?: Place[]
/** Day→assignments map, used to scope the quick picks to the chosen day (#1460). */
assignments?: AssignmentsMap
accommodations?: Accommodation[]
/** Open directly in the Automated public-transit mode (day-header tram button, "change route"). */
initialAutomated?: boolean
@@ -158,7 +160,7 @@ interface TransportModalProps {
transitPrefill?: { from?: PickedPlace | null; to?: PickedPlace | null } | null
}
export function TransportModal({ isOpen, onClose, onSave, reservation, days, selectedDayId, files = [], onFileUpload, onFileDelete, onOpenExpense, prefill = null, places = [], accommodations = [], initialAutomated = false, transitPrefill = null }: TransportModalProps) {
export function TransportModal({ isOpen, onClose, onSave, reservation, days, selectedDayId, files = [], onFileUpload, onFileDelete, onOpenExpense, prefill = null, places = [], assignments = {}, accommodations = [], initialAutomated = false, transitPrefill = null }: TransportModalProps) {
const { t, locale } = useTranslation()
const toast = useToast()
const isBudgetEnabled = useAddonStore(s => s.isEnabled('budget'))
@@ -639,11 +641,16 @@ export function TransportModal({ isOpen, onClose, onSave, reservation, days, sel
{(() => {
const transitDay = days.find(d => d.id === Number(form.start_day_id))
if (!transitDay) return <div className="text-content-faint" style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))', padding: '4px 2px 12px' }}>{t('transit.pickDay')}</div>
// Quick picks offer the chosen day's itinerary, not the whole trip (#1460).
const dayPlaces = (assignments[String(transitDay.id)] || [])
.slice().sort((a, b) => a.order_index - b.order_index)
.map(a => places.find(p => p.id === a.place_id))
.filter((p): p is Place => p != null)
return (
<TransitSearchPanel
day={transitDay}
days={days}
places={places}
places={dayPlaces}
accommodations={accommodations}
onAdd={(payload) => onSave(payload as Record<string, any> & { title: string })}
initialFrom={transitPrefill?.from ?? null}
@@ -1,11 +1,18 @@
import { useEffect, useState } from 'react'
import { createPortal } from 'react-dom'
import { AlertTriangle, Info, AlertCircle } from 'lucide-react'
import { pluginsApi } from '../../api/client'
import { usePluginStore } from '../../store/pluginStore'
/**
* Shows validation/warning contributions from `warningProvider` plugins (#1429).
* Self-contained + fail-safe: the server skips any slow/failing provider, so this
* only ever adds rows; it renders nothing (and takes no space) when there are none.
*
* Placement: a warning from a plugin that owns a trip-page tab in this planner
* renders as a compact chip in the navbar centre (click jumps to that tab); all
* other warnings float above the content at the BOTTOM of the planner, so neither
* kind ever covers the map toolbar or displaces the working area up top.
*/
type Warning = { pluginId: string; level: 'info' | 'warning' | 'error'; message: string }
@@ -15,8 +22,14 @@ const STYLE = {
error: { Icon: AlertCircle, color: 'var(--danger)', bg: 'var(--danger-soft)' },
} as const
export default function TripWarningsBanner({ tripId }: { tripId: number }) {
export default function TripWarningsBanner({ tripId, onOpenPluginTab }: { tripId: number; onOpenPluginTab?: (pluginId: string) => void }) {
const [warnings, setWarnings] = useState<Warning[]>([])
const [navSlot, setNavSlot] = useState<HTMLElement | null>(null)
const [isDesktop, setIsDesktop] = useState(
() => typeof window !== 'undefined' && (window.matchMedia?.('(min-width: 768px)')?.matches ?? true)
)
const plugins = usePluginStore((s) => s.plugins)
useEffect(() => {
if (!Number.isFinite(tripId)) { setWarnings([]); return }
let cancelled = false
@@ -26,21 +39,62 @@ export default function TripWarningsBanner({ tripId }: { tripId: number }) {
return () => { cancelled = true }
}, [tripId])
// The navbar renders in the same commit as the planner, so the slot exists by
// the time effects run; it is display:none'd with the navbar below md.
useEffect(() => { setNavSlot(document.getElementById('trek-nav-center-slot')) }, [])
useEffect(() => {
const mq = window.matchMedia?.('(min-width: 768px)')
if (!mq) return
const handler = (e: MediaQueryListEvent) => setIsDesktop(e.matches)
mq.addEventListener('change', handler)
return () => mq.removeEventListener('change', handler)
}, [])
if (warnings.length === 0) return null
// A non-blocking overlay pinned to the top of the (fixed) planner content region:
// the wrapper ignores pointer events so it never covers the map/panels, and only
// the warning pills themselves are interactive.
const tripPageIds = new Set(plugins.filter((p) => p.type === 'trip-page').map((p) => p.id))
const chips = navSlot && isDesktop ? warnings.filter((w) => tripPageIds.has(w.pluginId)) : []
const floating = warnings.filter((w) => !chips.includes(w))
return (
<div style={{ position: 'absolute', top: 0, left: 0, right: 0, zIndex: 6, pointerEvents: 'none', display: 'flex', flexDirection: 'column', gap: 6, padding: '8px 16px' }}>
{warnings.map((w, i) => {
const s = STYLE[w.level] ?? STYLE.warning
return (
<div key={`${w.pluginId}-${i}`} style={{ pointerEvents: 'auto', display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px', borderRadius: 10, background: s.bg, color: s.color, fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 500, boxShadow: 'var(--shadow-card)' }}>
<s.Icon size={15} style={{ flexShrink: 0 }} />
<span>{w.message}</span>
</div>
)
})}
</div>
<>
{navSlot && chips.length > 0 && createPortal(
chips.map((w, i) => {
const s = STYLE[w.level] ?? STYLE.warning
return (
<button
key={`${w.pluginId}-${i}`}
type="button"
onClick={onOpenPluginTab ? () => onOpenPluginTab(w.pluginId) : undefined}
title={w.message}
style={{
pointerEvents: 'auto', display: 'flex', alignItems: 'center', gap: 6,
padding: '4px 10px', borderRadius: 999, border: 'none',
background: s.bg, color: s.color, cursor: onOpenPluginTab ? 'pointer' : 'default',
fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 500,
maxWidth: 'min(44vw, 520px)', minWidth: 0,
}}
>
<s.Icon size={13} style={{ flexShrink: 0 }} />
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{w.message}</span>
</button>
)
}),
navSlot
)}
{floating.length > 0 && (
<div style={{ position: 'absolute', bottom: 'calc(var(--bottom-nav-h, 0px) + 8px)', left: 0, right: 0, zIndex: 6, pointerEvents: 'none', display: 'flex', flexDirection: 'column', gap: 6, padding: '0 16px' }}>
{floating.map((w, i) => {
const s = STYLE[w.level] ?? STYLE.warning
return (
<div key={`${w.pluginId}-${i}`} style={{ pointerEvents: 'auto', display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px', borderRadius: 10, background: s.bg, color: s.color, fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 500, boxShadow: 'var(--shadow-card)' }}>
<s.Icon size={15} style={{ flexShrink: 0 }} />
<span>{w.message}</span>
</div>
)
})}
</div>
)}
</>
)
}
@@ -0,0 +1,125 @@
import { useCallback, useEffect, useState } from 'react'
import { X } from 'lucide-react'
import { pluginsApi, type ViewContribution } from '../../api/client'
import { useToast } from '../shared/Toast'
import PluginFrame from './PluginFrame'
/**
* Host-rendered plugin contributions in a native planner view (#plugins,
* tableContributor hook). The server has already normalized + bounded every field
* (label/value length, http/https/mailto-only urls, enum tone/target), so this only
* renders trusted primitives — a column is text/link, an action is a labelled button
* that opens the plugin's sandboxed frame or calls one of its routes. Plugin-authored
* markup NEVER runs inline; it only ever runs inside the opaque-origin PluginFrame.
*/
export type ViewName = 'reservations' | 'transports' | 'places' | 'day' | 'costs' | 'packing' | 'files' | 'todos'
type Column = Extract<ViewContribution, { kind: 'column' }>
type Action = Extract<ViewContribution, { kind: 'action' }>
const EMPTY: ViewContribution[] = []
/** Fetch a view's contributions once (keyed on tripId) and bucket them by entityId.
* Fail-safe: any error yields an empty lookup, so a plugin can never block or break
* the native view — it can only ADD cells/buttons. */
export function usePluginViewContributions(view: ViewName, tripId: string | number | null | undefined) {
const [byEntity, setByEntity] = useState<Map<number, ViewContribution[]>>(new Map())
useEffect(() => {
if (tripId == null) { setByEntity(new Map()); return }
let cancelled = false
pluginsApi.viewContributions(view, tripId)
.then(({ contributions }) => {
if (cancelled) return
const m = new Map<number, ViewContribution[]>()
for (const c of contributions || []) {
const arr = m.get(c.entityId)
if (arr) arr.push(c); else m.set(c.entityId, [c])
}
setByEntity(m)
})
.catch(() => { if (!cancelled) setByEntity(new Map()) })
return () => { cancelled = true }
}, [view, tripId])
return useCallback((entityId: number): ViewContribution[] => byEntity.get(entityId) ?? EMPTY, [byEntity])
}
const TONE_CLASS: Record<Column['tone'], string> = {
default: 'text-content-muted',
success: 'text-success',
warn: 'text-warning',
danger: 'text-danger',
}
/** Extra read-only cells (label + value/link) for one entity, in the card/row body. */
export function PluginColumns({ items }: { items: ViewContribution[] }) {
const cols = items.filter((c): c is Column => c.kind === 'column')
if (!cols.length) return null
return (
<div className="flex flex-col gap-1">
{cols.map((c) => (
<div key={c.pluginId + c.id} className="flex items-baseline justify-between gap-2 text-xs">
<span className="text-content-secondary font-medium shrink-0">{c.label}</span>
{c.url
? <a href={c.url} target="_blank" rel="noreferrer noopener" className="text-accent truncate text-right" onClick={(e) => e.stopPropagation()}>{c.value ?? '↗'}</a>
: <span className={`${TONE_CLASS[c.tone] ?? TONE_CLASS.default} text-right truncate`}>{c.value}</span>}
</div>
))}
</div>
)
}
/** The plugin-contributed columns + actions strip appended to the bottom of an
* entity row/card. Renders nothing (zero change) when no plugin contributes. */
export function PluginCardFooter({ items, tripId }: { items: ViewContribution[]; tripId: number }) {
if (!items.length) return null
return (
<div className="border-t border-edge" style={{ marginTop: 8, paddingTop: 8, display: 'flex', flexDirection: 'column', gap: 6 }}>
<PluginColumns items={items} />
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}><PluginActions items={items} tripId={tripId} /></div>
</div>
)
}
/** Labelled action buttons for one entity — a route action calls the plugin route;
* a frame action opens the plugin's sandboxed UI in a modal. */
export function PluginActions({ items, tripId, className }: { items: ViewContribution[]; tripId: string | number | null; className?: string }) {
const actions = items.filter((c): c is Action => c.kind === 'action')
const [frame, setFrame] = useState<{ pluginId: string; label: string } | null>(null)
const toast = useToast()
if (!actions.length) return null
const run = (a: Action, e: React.MouseEvent) => {
e.stopPropagation()
if (a.target.kind === 'frame') { setFrame({ pluginId: a.pluginId, label: a.label }); return }
void pluginsApi.invoke(a.pluginId, a.target.sub, { method: a.target.method })
.then(() => toast.success(a.label))
.catch(() => toast.error(a.label))
}
return (
<>
{actions.map((a) => (
<button
key={a.pluginId + a.id}
onClick={(e) => run(a, e)}
title={a.label}
className={className ?? 'px-2 h-7 inline-flex items-center rounded-lg border border-edge bg-surface-card text-xs text-content-muted hover:text-content hover:border-content-faint transition-colors'}
>
{a.label}
</button>
))}
{frame && (
<div className="fixed inset-0 z-[4000] flex items-center justify-center bg-black/50 p-4" onClick={() => setFrame(null)}>
<div className="bg-surface-card rounded-xl shadow-xl w-full max-w-lg h-[70vh] flex flex-col overflow-hidden" onClick={(e) => e.stopPropagation()}>
<div className="flex items-center justify-between px-4 py-2.5 border-b border-edge shrink-0">
<span className="text-sm font-medium text-content truncate">{frame.label}</span>
<button onClick={() => setFrame(null)} className="text-content-muted hover:text-content"><X size={16} /></button>
</div>
<div className="flex-1 min-h-0">
<PluginFrame pluginId={frame.pluginId} tripId={tripId != null ? String(tripId) : null} title={frame.label} fill />
</div>
</div>
</div>
)}
</>
)
}
@@ -1,17 +1,22 @@
// FE-PLUGINS-FRAME-001 to 004
import { render, cleanup, waitFor } from '@testing-library/react';
// FE-PLUGINS-FRAME-001 to 012
import { render, cleanup, waitFor, fireEvent, screen, act } from '@testing-library/react';
import PluginFrame from './PluginFrame';
const navigate = vi.fn();
const toast = { info: vi.fn(), success: vi.fn(), warning: vi.fn(), error: vi.fn() };
const invoke = vi.fn((..._args: unknown[]) => Promise.resolve({ ok: true }));
const wsListeners = new Set<(ev: Record<string, unknown>) => void>();
vi.mock('react-router-dom', () => ({ useNavigate: () => navigate }));
vi.mock('../shared/Toast', () => ({ useToast: () => toast }));
vi.mock('../../i18n', () => ({ useTranslation: () => ({ locale: 'en' }) }));
vi.mock('../../i18n', () => ({ useTranslation: () => ({ locale: 'en', t: (k: string) => k }) }));
vi.mock('../../store/authStore', () => ({ useAuthStore: (sel: (s: unknown) => unknown) => sel({ user: { id: 7, username: 'ada', avatar_url: null, role: 'admin' } }) }));
vi.mock('../../store/settingsStore', () => ({ useSettingsStore: (sel: (s: unknown) => unknown) => sel({ settings: { default_currency: 'EUR', time_format: '24h', distance_unit: 'metric', temperature_unit: 'celsius' } }) }));
vi.mock('../../api/client', () => ({ pluginsApi: { invoke: (id: string, sub: string, init?: unknown) => invoke(id, sub, init) } }));
vi.mock('../../api/websocket', () => ({
addListener: (fn: (ev: Record<string, unknown>) => void) => wsListeners.add(fn),
removeListener: (fn: (ev: Record<string, unknown>) => void) => wsListeners.delete(fn),
}));
function fromFrame(frame: HTMLIFrameElement, data: unknown) {
window.dispatchEvent(new MessageEvent('message', { source: frame.contentWindow, data } as MessageEventInit));
@@ -22,6 +27,7 @@ afterEach(() => {
navigate.mockClear();
Object.values(toast).forEach((f) => f.mockClear());
invoke.mockClear();
wsListeners.clear();
});
describe('PluginFrame', () => {
@@ -83,6 +89,37 @@ describe('PluginFrame', () => {
expect(JSON.stringify(ctx)).not.toContain('@'); // no email leaked
});
it('FE-PLUGINS-FRAME-008: a day-detail host passes the open day (and place stays null)', () => {
const { container } = render(<PluginFrame pluginId="demo" tripId="1" dayId="12" />);
const iframe = container.querySelector('iframe')!;
const posted: Array<Record<string, unknown>> = [];
(iframe.contentWindow as unknown as { postMessage: (m: unknown) => void }).postMessage = (m: unknown) => posted.push(m as Record<string, unknown>);
fromFrame(iframe, { type: 'trek:context:request' });
const ctx = posted.find((m) => m.type === 'trek:context') as Record<string, unknown> | undefined;
expect(ctx).toBeTruthy();
expect(ctx!.tripId).toBe('1');
expect(ctx!.dayId).toBe('12');
expect(ctx!.placeId).toBeNull();
});
it('FE-PLUGINS-FRAME-014: a reservation-detail host passes the open reservation (and day/place stay null)', () => {
const { container } = render(<PluginFrame pluginId="demo" tripId="1" reservationId="88" />);
const iframe = container.querySelector('iframe')!;
const posted: Array<Record<string, unknown>> = [];
(iframe.contentWindow as unknown as { postMessage: (m: unknown) => void }).postMessage = (m: unknown) => posted.push(m as Record<string, unknown>);
fromFrame(iframe, { type: 'trek:context:request' });
const ctx = posted.find((m) => m.type === 'trek:context') as Record<string, unknown> | undefined;
expect(ctx).toBeTruthy();
expect(ctx!.tripId).toBe('1');
expect(ctx!.reservationId).toBe('88');
expect(ctx!.dayId).toBeNull();
expect(ctx!.placeId).toBeNull();
});
it('FE-PLUGINS-FRAME-006: context mirrors the host appearance state (scheme/density/flags)', () => {
const { container } = render(<PluginFrame pluginId="demo" />);
const iframe = container.querySelector('iframe')!;
@@ -101,4 +138,89 @@ describe('PluginFrame', () => {
reducedMotion: false,
});
});
it('FE-PLUGINS-FRAME-007: fill mode pins the frame to 100% height and ignores trek:resize', () => {
const { container } = render(<PluginFrame pluginId="demo" fill />);
const iframe = container.querySelector('iframe')!;
act(() => { fromFrame(iframe, { type: 'trek:resize', height: 480 }); });
expect(iframe.style.height).toBe('100%');
});
it('FE-PLUGINS-FRAME-008: without fill, trek:resize drives the frame height (widget self-sizing)', () => {
const { container } = render(<PluginFrame pluginId="demo" />);
const iframe = container.querySelector('iframe')!;
act(() => { fromFrame(iframe, { type: 'trek:resize', height: 480 }); });
expect(iframe.style.height).toBe('480px');
});
it('FE-PLUGINS-FRAME-009: trek:confirm renders the native dialog and answers over the bridge', async () => {
const { container } = render(<PluginFrame pluginId="demo" />);
const iframe = container.querySelector('iframe')!;
const posted: Array<Record<string, unknown>> = [];
(iframe.contentWindow as unknown as { postMessage: (m: unknown) => void }).postMessage = (m: unknown) => posted.push(m as Record<string, unknown>);
fromFrame(iframe, { type: 'trek:confirm', requestId: 'c1', message: 'Delete everything?', confirmLabel: 'Yes, wipe it' });
const confirmBtn = await screen.findByText('Yes, wipe it');
fireEvent.click(confirmBtn);
const result = posted.find((m) => m.type === 'trek:confirm:result') as Record<string, unknown> | undefined;
expect(result).toMatchObject({ requestId: 'c1', confirmed: true });
});
it('FE-PLUGINS-FRAME-010: trek:openExternal opens only real web URLs in a noopener tab', () => {
const open = vi.spyOn(window, 'open').mockReturnValue(null);
const { container } = render(<PluginFrame pluginId="demo" />);
const iframe = container.querySelector('iframe')!;
fromFrame(iframe, { type: 'trek:openExternal', url: 'javascript:alert(1)' });
fromFrame(iframe, { type: 'trek:openExternal', url: 'not a url' });
expect(open).not.toHaveBeenCalled();
fromFrame(iframe, { type: 'trek:openExternal', url: 'https://example.com/docs' });
expect(open).toHaveBeenCalledWith('https://example.com/docs', '_blank', 'noopener,noreferrer');
open.mockRestore();
});
it('FE-PLUGINS-FRAME-011: forwards core-event names for the trip in view, payload-free', () => {
const { container } = render(<PluginFrame pluginId="demo" tripId="42" />);
const iframe = container.querySelector('iframe')!;
const posted: Array<Record<string, unknown>> = [];
(iframe.contentWindow as unknown as { postMessage: (m: unknown) => void }).postMessage = (m: unknown) => posted.push(m as Record<string, unknown>);
// The bridge only forwards to the original document (first load).
fireEvent.load(iframe);
expect(wsListeners.size).toBe(1);
const emit = [...wsListeners][0];
emit({ type: 'place_created', tripId: 99, place: { secret: true } }); // other trip -> dropped
emit({ type: 'place_created', tripId: 42, place: { secret: true } });
const events = posted.filter((m) => m.type === 'trek:event');
expect(events).toHaveLength(1);
expect(events[0]).toMatchObject({ event: 'place_created', tripId: '42' });
expect(JSON.stringify(events[0])).not.toContain('secret'); // names only, never payloads
});
it('FE-PLUGINS-FRAME-012: trek:notify clamps a plugin-supplied duration', () => {
const { container } = render(<PluginFrame pluginId="demo" />);
const iframe = container.querySelector('iframe')!;
fromFrame(iframe, { type: 'trek:notify', level: 'info', message: 'hi', duration: 999999 });
expect(toast.info).toHaveBeenCalledWith('hi', 15000);
// NaN must not slip through the clamp as a sticky toast.
fromFrame(iframe, { type: 'trek:notify', level: 'info', message: 'ho', duration: NaN });
expect(toast.info).toHaveBeenLastCalledWith('ho');
});
it('FE-PLUGINS-FRAME-013: swapping pluginId in place restarts the bridge for the new plugin', () => {
const { container, rerender } = render(<PluginFrame pluginId="alpha" />);
fireEvent.load(container.querySelector('iframe')!);
rerender(<PluginFrame pluginId="beta" />);
const next = container.querySelector('iframe')!; // keyed by pluginId -> fresh element
expect(next.getAttribute('src')).toBe('/plugin-frame/beta/index.html');
act(() => { fireEvent.load(next); });
// Without the per-plugin reset this would be refused as a "navigated" frame.
fromFrame(next, { type: 'trek:navigate', to: '/dashboard' });
expect(navigate).toHaveBeenCalledWith('/dashboard');
});
});
+161 -21
View File
@@ -4,7 +4,9 @@ import { useTranslation } from '../../i18n'
import { useAuthStore } from '../../store/authStore'
import { useSettingsStore } from '../../store/settingsStore'
import { useToast } from '../shared/Toast'
import ConfirmDialog from '../shared/ConfirmDialog'
import { pluginsApi } from '../../api/client'
import { addListener, removeListener } from '../../api/websocket'
// The design-token contract handed to plugins (#4 richer context): non-secret CSS
// values, resolved for the CURRENT theme, so a plugin can match TREK exactly (and
@@ -81,6 +83,17 @@ interface PluginFrameProps {
tripId?: string | null
/** The place in view — set for a place-detail slot so the plugin can scope to it. */
placeId?: string | null
/** The day in view — set for a day-detail slot so the plugin can scope to it. */
dayId?: string | null
/** The reservation in view — set for a reservation-detail slot so the plugin can scope to it. */
reservationId?: string | null
/**
* Full-page hosts (trip tab, /plugins/:id) set this so the frame always fills
* its container. Without it a kit-based plugin auto-reports its content height
* (trek:resize) and the page collapses to a floating island with dead space
* below — right for dashboard widgets, wrong for a page.
*/
fill?: boolean
className?: string
title?: string
}
@@ -89,11 +102,22 @@ type Inbound =
| { type: 'trek:ready' }
| { type: 'trek:context:request' }
| { type: 'trek:navigate'; to: string }
| { type: 'trek:notify'; level?: 'info' | 'success' | 'warning' | 'error'; message?: string }
| { type: 'trek:notify'; level?: 'info' | 'success' | 'warning' | 'error'; message?: string; duration?: number }
| { type: 'trek:resize'; height?: number }
| { type: 'trek:invoke'; requestId: string; sub: string; method?: string; body?: unknown }
| { type: 'trek:confirm'; requestId: string; title?: string; message?: string; confirmLabel?: string; cancelLabel?: string; danger?: boolean }
| { type: 'trek:openExternal'; url?: string }
export default function PluginFrame({ pluginId, tripId = null, placeId = null, className, title }: PluginFrameProps) {
interface ConfirmRequest {
requestId: string
title?: string
message?: string
confirmLabel?: string
cancelLabel?: string
danger: boolean
}
export default function PluginFrame({ pluginId, tripId = null, placeId = null, dayId = null, reservationId = null, fill = false, className, title }: PluginFrameProps) {
const frameRef = useRef<HTMLIFrameElement | null>(null)
// A sandboxed frame may navigate ITSELF (connect-src can't stop that), and its
// window identity keeps matching our iframe afterwards. Track loads and refuse
@@ -107,12 +131,24 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, c
const { locale } = useTranslation()
const navigate = useNavigate()
const toast = useToast()
// useToast returns a fresh object every render; keep it out of the effect deps
// (via this ref) or the bridge effect would tear down and re-post the context on
// EVERY parent re-render instead of only when the context inputs change.
const toastRef = useRef(toast)
toastRef.current = toast
const userId = useAuthStore((s) => s.user?.id)
const userName = useAuthStore((s) => s.user?.username ?? null)
const userAvatar = useAuthStore((s) => s.user?.avatar_url ?? null)
const isAdmin = useAuthStore((s) => s.user?.role === 'admin')
const settings = useSettingsStore((s) => s.settings)
const [height, setHeight] = useState<number | null>(null)
// A host-rendered ConfirmDialog on the plugin's behalf: sandboxed frames have no
// allow-modals and can't overlay the host, so destructive plugin actions get the
// same native confirm every TREK feature uses. One at a time; extras are refused.
// The ref mirrors the state so the message handler can gate + answer without
// side effects inside a setState updater (StrictMode runs updaters twice).
const [confirmReq, setConfirmReq] = useState<ConfirmRequest | null>(null)
const confirmReqRef = useRef<ConfirmRequest | null>(null)
// opaque frame -> targetOrigin must be '*'. Hoisted so the iframe's onLoad can
// deliver the context too: the trek:ready handshake alone is racy — if the frame
@@ -123,9 +159,14 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, c
type: 'trek:context',
tripId,
placeId,
dayId,
reservationId,
userId: userId != null ? String(userId) : null,
theme: document.documentElement.classList.contains('dark') ? 'dark' : 'light',
locale,
// Mirror of what TranslationProvider stamps on <html> — an RTL host (Arabic)
// wants RTL plugin UIs too, and the frame can't read our DOM to find out.
dir: (document.documentElement.getAttribute('dir') === 'rtl' ? 'rtl' : 'ltr') as 'rtl' | 'ltr',
hostOrigin: window.location.origin,
// #4 richer context — non-secret display data so plugins render natively:
// who the user is (name/avatar/isAdmin — never email/role beyond a boolean),
@@ -143,7 +184,7 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, c
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
},
tokens: readThemeTokens(),
}), [tripId, placeId, userId, locale, userName, userAvatar, isAdmin, settings])
}), [tripId, placeId, dayId, reservationId, userId, locale, userName, userAvatar, isAdmin, settings])
useEffect(() => {
const frame = frameRef.current
@@ -175,11 +216,47 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, c
case 'trek:notify': {
const text = String(msg.message ?? '').slice(0, 200)
const level = msg.level ?? 'info'
if (text) (toast[level] ?? toast.info)(text)
if (!text) break
const t = toastRef.current
const show = t[level] ?? t.info
// Optional duration, clamped so a plugin can neither flash nor park a
// toast (isFinite: NaN would slip through the clamp as duration 0 = sticky).
if (Number.isFinite(msg.duration)) show(text, Math.min(Math.max(msg.duration as number, 1500), 15000))
else show(text)
break
}
case 'trek:confirm': {
if (typeof msg.requestId !== 'string' || !msg.requestId) break
if (confirmReqRef.current) {
// One dialog at a time — answer the newcomer 'not confirmed' right away.
post({ type: 'trek:confirm:result', requestId: msg.requestId, confirmed: false })
break
}
const req: ConfirmRequest = {
requestId: msg.requestId,
title: typeof msg.title === 'string' ? msg.title.slice(0, 120) : undefined,
message: typeof msg.message === 'string' ? msg.message.slice(0, 500) : undefined,
confirmLabel: typeof msg.confirmLabel === 'string' ? msg.confirmLabel.slice(0, 40) : undefined,
cancelLabel: typeof msg.cancelLabel === 'string' ? msg.cancelLabel.slice(0, 40) : undefined,
danger: msg.danger !== false,
}
confirmReqRef.current = req
setConfirmReq(req)
break
}
case 'trek:openExternal': {
// The sandbox has no allow-popups, so the HOST opens the link — but only
// real web URLs, never javascript:/data:/file: or anything else.
try {
const u = new URL(String(msg.url ?? ''))
if (u.protocol === 'https:' || u.protocol === 'http:') {
window.open(u.href, '_blank', 'noopener,noreferrer')
}
} catch { /* not a URL — ignore */ }
break
}
case 'trek:resize':
if (typeof msg.height === 'number' && msg.height > 0) setHeight(Math.min(msg.height, 2000))
if (!fill && typeof msg.height === 'number' && msg.height > 0) setHeight(Math.min(msg.height, 2000))
break
case 'trek:invoke': {
// The plugin's own route, called host-side with the user's session.
@@ -197,6 +274,29 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, c
window.addEventListener('message', onMessage)
// Live locale/format sync: this effect re-runs whenever buildContext's inputs
// (locale, settings, trip/place) change, so a loaded frame gets the fresh
// context pushed instead of staying stale until reload. First delivery is
// handled by onLoad; navigated frames (loads > 1) are never re-bridged.
if (loadsRef.current === 1) post(context())
// Forward event *names* for the trip in view, mirroring the server-side events
// surface: only { event, tripId }, never payloads — the frame's user is already
// looking at this trip. Core events plus the plugin's OWN namespaced broadcasts
// (plugin:{id}:*) pass; other plugins' broadcasts don't. Trip events only reach
// the socket while a planner has the trip joined, so this is a planner-side
// refresh signal — dashboard widgets still poll.
let wsForward: ((ev: Record<string, unknown>) => void) | null = null
if (tripId) {
wsForward = (ev) => {
if (loadsRef.current !== 1) return
if (!ev || typeof ev.type !== 'string' || ev.tripId == null || String(ev.tripId) !== tripId) return
if (ev.type.startsWith('plugin:') && !ev.type.startsWith(`plugin:${pluginId}:`)) return
post({ type: 'trek:event', event: ev.type, tripId })
}
addListener(wsForward)
}
// The frame is opaque-origin and can't read our DOM, and we otherwise send the
// context (incl. theme + tokens) only once on trek:ready — so a plugin can't
// follow an in-app appearance change. Watch the <html> element for anything
@@ -229,23 +329,63 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, c
attributeFilter: ['class', 'style', 'data-scheme', 'data-density', 'data-no-transparency', 'data-reduce-motion'],
})
return () => { window.removeEventListener('message', onMessage); themeObserver.disconnect() }
}, [pluginId, navigate, toast, postFrame, buildContext])
return () => {
window.removeEventListener('message', onMessage)
themeObserver.disconnect()
if (wsForward) removeListener(wsForward)
}
}, [pluginId, tripId, fill, navigate, postFrame, buildContext])
// Hosts swap pluginId in place (tab bar, /plugins/:id route) — the iframe below
// is keyed so the document is a fresh first load, and the per-plugin bridge
// state must start over with it or the new plugin would be refused as a
// "navigated" frame (loads > 1) and an open confirm would leak across plugins.
useEffect(() => {
loadsRef.current = 0
setHeight(null)
confirmReqRef.current = null
setConfirmReq(null)
}, [pluginId])
const answerConfirm = (confirmed: boolean) => {
const req = confirmReqRef.current
if (req) postFrame({ type: 'trek:confirm:result', requestId: req.requestId, confirmed })
confirmReqRef.current = null
setConfirmReq(null)
}
// The dialog title always leads with the host-controlled plugin name, so a
// plugin cannot dress its confirm up as a TREK system dialog.
const pluginLabel = title || pluginId
const confirmTitle = confirmReq?.title ? `${pluginLabel} — ${confirmReq.title}` : pluginLabel
return (
<iframe
ref={frameRef}
src={`/plugin-frame/${pluginId}/index.html`}
// Deliver the context as soon as the document is parsed (the plugin sets up its
// message listener during parse), closing the trek:ready race so the theme is
// right on first paint. A 2nd load is a self-navigation — don't bridge to it.
onLoad={() => { loadsRef.current += 1; if (loadsRef.current === 1) postFrame(buildContext()) }}
sandbox="allow-scripts allow-forms"
referrerPolicy="no-referrer"
loading="lazy"
title={title || pluginId}
className={className}
style={{ width: '100%', height: height ?? '100%', border: 0 }}
/>
<>
<iframe
key={pluginId}
ref={frameRef}
src={`/plugin-frame/${pluginId}/index.html`}
// Deliver the context as soon as the document is parsed (the plugin sets up its
// message listener during parse), closing the trek:ready race so the theme is
// right on first paint. A 2nd load is a self-navigation — don't bridge to it.
onLoad={() => { loadsRef.current += 1; if (loadsRef.current === 1) postFrame(buildContext()) }}
sandbox="allow-scripts allow-forms"
referrerPolicy="no-referrer"
loading="lazy"
title={title || pluginId}
className={className}
style={{ width: '100%', height: fill ? '100%' : height ?? '100%', border: 0 }}
/>
<ConfirmDialog
isOpen={confirmReq != null}
onClose={() => answerConfirm(false)}
onConfirm={() => answerConfirm(true)}
title={confirmTitle}
message={confirmReq?.message}
confirmLabel={confirmReq?.confirmLabel}
cancelLabel={confirmReq?.cancelLabel}
danger={confirmReq?.danger}
/>
</>
)
}
@@ -0,0 +1,59 @@
import { useCallback, useEffect, useState } from 'react'
import { pluginsApi, type TripCardBadge } from '../../api/client'
/**
* Host-rendered plugin badges on the dashboard trip cards (#plugins, tripCardProvider
* hook). The server has already access-checked every tripId for the user and bounded
* every field (label/value length, enum tone, http/https/mailto-only url), so this
* renders trusted primitives only — a badge is a small text chip or link. Plugin JS
* never runs here; it only ever runs inside the opaque-origin PluginFrame. Fail-safe:
* any error yields an empty lookup, so a plugin can only ADD chips, never break a card.
*/
const EMPTY: TripCardBadge[] = []
/** Fetch badges for all visible cards in ONE call (the server fans out per plugin over
* the whole id list) and bucket them by tripId. `enabled` gates the call so a dashboard
* with no active plugins never hits the endpoint. */
export function useTripCardBadges(tripIds: number[], enabled: boolean) {
const [byTrip, setByTrip] = useState<Map<number, TripCardBadge[]>>(new Map())
const key = tripIds.join(',')
useEffect(() => {
if (!enabled || tripIds.length === 0) { setByTrip(new Map()); return }
let cancelled = false
pluginsApi.tripCardContributions(tripIds)
.then(({ contributions }) => {
if (cancelled) return
const m = new Map<number, TripCardBadge[]>()
for (const c of contributions || []) {
const arr = m.get(c.tripId)
if (arr) arr.push(c); else m.set(c.tripId, [c])
}
setByTrip(m)
})
.catch(() => { if (!cancelled) setByTrip(new Map()) })
return () => { cancelled = true }
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [key, enabled])
return useCallback((tripId: number): TripCardBadge[] => byTrip.get(tripId) ?? EMPTY, [byTrip])
}
/** The plugin badge strip on a trip card. Renders nothing when no plugin contributes. */
export function TripCardBadges({ items }: { items: TripCardBadge[] }) {
if (!items.length) return null
return (
<div className="trip-plugin-badges">
{items.map((b) => {
const inner = (
<>
<span className="badge-label">{b.label}</span>
{b.value != null && b.value !== '' && <span className="badge-value">{b.value}</span>}
</>
)
const cls = `trip-plugin-badge tone-${b.tone}`
return b.url
? <a key={b.pluginId + b.id} href={b.url} target="_blank" rel="noreferrer noopener" className={cls} onClick={(e) => e.stopPropagation()}>{inner}</a>
: <span key={b.pluginId + b.id} className={cls}>{inner}</span>
})}
</div>
)
}
@@ -4,7 +4,7 @@ import { SUPPORTED_LANGUAGES, useTranslation } from '../../i18n'
import { useSettingsStore } from '../../store/settingsStore'
import { useToast } from '../shared/Toast'
import CustomSelect from '../shared/CustomSelect'
import { CURRENCIES, SYMBOLS } from '../Budget/BudgetPanel.constants'
import { SYMBOLS, currenciesWith } from '../Budget/BudgetPanel.constants'
import Section from './Section'
import type { DistanceUnit } from '../../types'
@@ -46,7 +46,7 @@ export default function DisplaySettingsTab(): React.ReactElement {
try { await updateSetting('default_currency', String(v)) }
catch (e: unknown) { toast.error(e instanceof Error ? e.message : t('common.error')) }
}}
options={CURRENCIES.map(c => ({ value: c, label: `${c} — ${SYMBOLS[c] || c}` }))}
options={currenciesWith(settings.default_currency).map(c => ({ value: c, label: `${c} — ${SYMBOLS[c] || c}` }))}
searchable
/>
<p className="text-xs text-content-faint mt-2">{t('settings.currencyHint')}</p>
@@ -9,6 +9,7 @@ import GlMapPreview from './MapboxPreview'
import Section from './Section'
import ToggleSwitch from './ToggleSwitch'
import type { Place } from '../../types'
import { NumericInput } from '../shared/NumericInput'
import {
MAPBOX_DEFAULT_STYLE,
defaultStyleForProvider,
@@ -405,21 +406,19 @@ export default function MapSettingsTab(): React.ReactElement {
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-sm font-medium text-slate-700 mb-1.5">{t('settings.latitude')}</label>
<input
type="number"
step="any"
<NumericInput
mode="signed"
value={defaultLat}
onChange={(e) => setDefaultLat(e.target.value)}
onValueChange={setDefaultLat}
className="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm focus:ring-2 focus:ring-slate-400 focus:border-transparent"
/>
</div>
<div>
<label className="block text-sm font-medium text-slate-700 mb-1.5">{t('settings.longitude')}</label>
<input
type="number"
step="any"
<NumericInput
mode="signed"
value={defaultLng}
onChange={(e) => setDefaultLng(e.target.value)}
onValueChange={setDefaultLng}
className="w-full px-3 py-2 border border-slate-300 rounded-lg text-sm focus:ring-2 focus:ring-slate-400 focus:border-transparent"
/>
</div>
@@ -0,0 +1,112 @@
import { useEffect, useState } from 'react'
import { History, RefreshCw } from 'lucide-react'
import { pluginsApi } from '../../api/client'
import { useTranslation } from '../../i18n'
interface ActivityRow {
ts: string
plugin_id: string
plugin_name: string | null
method: string
resource: string | null
code: string
}
/**
* Tailwind classes for a result-code pill. "ok" stays neutral; an access denial
* reads as danger, anything else non-ok as a softer warning. Kept subtle — this
* is meant to be a quiet log, not an alert wall.
*/
function codeTone(code: string): string {
if (code === 'ok') return 'bg-surface-hover text-content-secondary'
if (/FORBIDDEN|DENIED|UNAUTHORIZED/i.test(code)) return 'bg-danger-soft text-danger'
return 'bg-warning-soft text-warning'
}
/**
* The signed-in user's own plugin activity log — every host-mediated action a
* plugin took while bound to them, newest first. The user-facing half of the
* capability audit; it's what keeps the deliberately broad read grants
* accountable to the person whose data was read. Fail-safe: a failed load just
* shows the empty state, never a crash.
*/
export default function PluginActivityPanel() {
const { t, locale } = useTranslation()
const [rows, setRows] = useState<ActivityRow[]>([])
const [loading, setLoading] = useState(true)
const load = () => {
setLoading(true)
pluginsApi.myActivity()
.then(r => setRows(r.activity))
.catch(() => setRows([]))
.finally(() => setLoading(false))
}
useEffect(() => { load() }, [])
const fmtWhen = (ts: string): string => {
const d = new Date(ts)
return Number.isNaN(d.getTime()) ? ts : d.toLocaleString(locale)
}
return (
<div className="rounded-xl border border-edge bg-surface-card overflow-hidden">
<div className="px-5 py-4 border-b border-edge-secondary flex items-center gap-3">
<History className="w-4 h-4 flex-shrink-0 text-content-secondary" />
<div className="flex-1 min-w-0">
<h3 className="text-sm font-semibold text-content">{t('settings.pluginActivity.title')}</h3>
<p className="text-xs text-content-muted mt-0.5">{t('settings.pluginActivity.description')}</p>
</div>
<button
type="button"
onClick={load}
disabled={loading}
className="inline-flex items-center gap-1.5 rounded-lg border border-edge px-2.5 py-1.5 text-xs font-medium text-content-secondary hover:text-content disabled:opacity-60"
>
<RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} />
{t('settings.pluginActivity.refresh')}
</button>
</div>
{rows.length === 0 ? (
<p className="px-5 py-6 text-sm text-content-muted">
{loading ? t('common.loading') : t('settings.pluginActivity.empty')}
</p>
) : (
<div className="overflow-x-auto">
<table className="w-full text-sm border-collapse">
<thead>
<tr className="text-left text-xs uppercase tracking-wide text-content-faint border-b border-edge-secondary">
<th className="font-medium px-5 py-2">{t('settings.pluginActivity.columns.plugin')}</th>
<th className="font-medium px-3 py-2">{t('settings.pluginActivity.columns.action')}</th>
<th className="font-medium px-3 py-2">{t('settings.pluginActivity.columns.resource')}</th>
<th className="font-medium px-3 py-2 whitespace-nowrap">{t('settings.pluginActivity.columns.when')}</th>
<th className="font-medium px-5 py-2 text-right">{t('settings.pluginActivity.columns.status')}</th>
</tr>
</thead>
<tbody>
{rows.map((r, i) => (
<tr key={i} className="border-b border-edge-secondary last:border-b-0">
<td className="px-5 py-2.5 text-content align-top">{r.plugin_name || r.plugin_id}</td>
<td className="px-3 py-2.5 align-top">
<span className="font-mono text-xs text-content-secondary">{r.method}</span>
</td>
<td className="px-3 py-2.5 align-top">
<span className="font-mono text-xs text-content-muted">{r.resource || '—'}</span>
</td>
<td className="px-3 py-2.5 align-top whitespace-nowrap text-content-muted">{fmtWhen(r.ts)}</td>
<td className="px-5 py-2.5 align-top text-right">
<span className={`inline-block rounded-full px-2 py-0.5 text-[11px] font-medium ${codeTone(r.code)}`}>
{r.code}
</span>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
)
}
@@ -0,0 +1,188 @@
import { useEffect, useState } from 'react'
import { Blocks, Save, Loader2, Link2, Unlink, CheckCircle } from 'lucide-react'
import { pluginsApi, type PluginUserSettingField } from '../../api/client'
import { usePluginStore } from '../../store/pluginStore'
import { useToast } from '../shared/Toast'
import { useTranslation } from '../../i18n'
import PluginActivityPanel from './PluginActivityPanel'
/** Host-brokered OAuth: a Connect/Disconnect control. The host runs the whole flow +
* holds the tokens; this only triggers connect (redirect to the provider) / disconnect. */
function PluginOAuthSection({ id, state, setState }: {
id: string
state: { configured: boolean; connected: boolean } | null
setState: (s: { configured: boolean; connected: boolean }) => void
}) {
const { t } = useTranslation()
const toast = useToast()
const [busy, setBusy] = useState(false)
if (!state?.configured) return null
const connect = async () => {
setBusy(true)
try {
const { authorizeUrl } = await pluginsApi.oauthConnect(id)
window.location.href = authorizeUrl // hand off to the provider; returns to /settings
} catch {
toast.error(t('common.error')); setBusy(false)
}
}
const disconnect = async () => {
setBusy(true)
try { await pluginsApi.oauthDisconnect(id); setState({ ...state, connected: false }) }
catch { toast.error(t('common.error')) }
finally { setBusy(false) }
}
return (
<div className="mt-4 flex items-center justify-between rounded-lg border border-border bg-surface-secondary px-3 py-2">
<span className="flex items-center gap-2 text-sm text-content-secondary">
{state.connected
? <><CheckCircle className="w-4 h-4 text-success" /> {t('settings.plugins.oauth.connected')}</>
: <>{t('settings.plugins.oauth.notConnected')}</>}
</span>
{state.connected
? <button onClick={disconnect} disabled={busy} className="inline-flex items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-sm font-semibold text-content disabled:opacity-60"><Unlink className="w-4 h-4" />{t('settings.plugins.oauth.disconnect')}</button>
: <button onClick={connect} disabled={busy} className="inline-flex items-center gap-1.5 rounded-lg bg-accent px-3 py-1.5 text-sm font-semibold text-white disabled:opacity-60">{busy ? <Loader2 className="w-4 h-4 animate-spin" /> : <Link2 className="w-4 h-4" />}{t('settings.plugins.oauth.connect')}</button>}
</div>
)
}
const SECRET_MASK = '••••••••'
/**
* A user's own per-plugin settings (#plugins). The host renders the plugin's
* declared `scope:'user'` fields as an editable form — a plugin never ships markup
* here; the field list is trusted, validated manifest data. Secrets stay write-only
* (masked, never echoed back). One form per active plugin that declares user fields.
*/
function PluginSettingsForm({ id, name }: { id: string; name: string }) {
const { t } = useTranslation()
const toast = useToast()
const [fields, setFields] = useState<PluginUserSettingField[] | null>(null)
const [values, setValues] = useState<Record<string, string | boolean>>({})
const [saving, setSaving] = useState(false)
const [oauth, setOauth] = useState<{ configured: boolean; connected: boolean } | null>(null)
useEffect(() => {
let alive = true
pluginsApi.userSettings(id)
.then(r => {
if (!alive) return
setFields(r.fields)
const init: Record<string, string | boolean> = {}
for (const f of r.fields) {
const v = r.config[f.key]
init[f.key] = f.input_type === 'checkbox' ? v === true : (v == null ? '' : String(v))
}
setValues(init)
})
.catch(() => { if (alive) setFields([]) })
pluginsApi.oauthStatus(id).then(s => { if (alive) setOauth(s) }).catch(() => { if (alive) setOauth(null) })
return () => { alive = false }
}, [id])
const hasFields = (fields?.length ?? 0) > 0
// Show the card if the plugin has user fields OR an OAuth connection to offer.
if (fields === null || (!hasFields && !oauth?.configured)) return null
const save = async () => {
setSaving(true)
try {
// Skip an untouched secret (still shows the mask) so we never overwrite it with the mask.
const patch: Record<string, unknown> = {}
for (const f of fields) {
const v = values[f.key]
if (f.secret && v === SECRET_MASK) continue
patch[f.key] = v
}
const r = await pluginsApi.saveUserSettings(id, patch)
const next: Record<string, string | boolean> = {}
for (const f of fields) {
const v = r.config[f.key]
next[f.key] = f.input_type === 'checkbox' ? v === true : (v == null ? '' : String(v))
}
setValues(next)
toast.success(t('settings.plugins.saved'))
} catch {
toast.error(t('common.error'))
} finally {
setSaving(false)
}
}
return (
<div className="rounded-xl border border-border bg-surface p-5">
<div className="flex items-center gap-2 mb-4">
<Blocks className="w-4 h-4 text-content-secondary" />
<h3 className="text-sm font-semibold text-content">{name}</h3>
</div>
<div className="space-y-4">
{(fields ?? []).map(f => (
<label key={f.key} className="block">
<span className="block text-sm font-medium text-content-secondary mb-1">
{f.label || f.key}{f.required && <span className="text-danger"> *</span>}
</span>
{f.input_type === 'checkbox' ? (
<input
type="checkbox"
checked={values[f.key] === true}
onChange={e => setValues(v => ({ ...v, [f.key]: e.target.checked }))}
className="h-4 w-4 rounded border-border"
/>
) : f.input_type === 'select' && f.options ? (
<select
value={String(values[f.key] ?? '')}
onChange={e => setValues(v => ({ ...v, [f.key]: e.target.value }))}
className="w-full rounded-lg border border-border bg-surface-secondary px-3 py-2 text-sm text-content"
>
<option value="">—</option>
{f.options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
</select>
) : (
<input
type={f.secret ? 'password' : (f.input_type === 'number' ? 'number' : 'text')}
value={String(values[f.key] ?? '')}
placeholder={f.placeholder || ''}
autoComplete={f.secret ? 'new-password' : 'off'}
onChange={e => setValues(v => ({ ...v, [f.key]: e.target.value }))}
className="w-full rounded-lg border border-border bg-surface-secondary px-3 py-2 text-sm text-content"
/>
)}
{f.hint && <span className="block text-xs text-content-muted mt-1">{f.hint}</span>}
</label>
))}
</div>
{hasFields && (
<button
onClick={save}
disabled={saving}
className="mt-4 inline-flex items-center gap-2 rounded-lg bg-accent px-4 py-2 text-sm font-semibold text-white disabled:opacity-60"
>
{saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
{t('common.save')}
</button>
)}
<PluginOAuthSection id={id} state={oauth} setState={setOauth} />
</div>
)
}
export default function PluginSettingsTab() {
const { t } = useTranslation()
const plugins = usePluginStore(s => s.plugins)
return (
<div className="space-y-4">
<div>
<h2 className="text-lg font-semibold text-content">{t('settings.plugins.title')}</h2>
<p className="text-sm text-content-muted">{t('settings.plugins.subtitle')}</p>
</div>
{plugins.length === 0
? <p className="text-sm text-content-muted">{t('settings.plugins.empty')}</p>
: plugins.map(p => <PluginSettingsForm key={p.id} id={p.id} name={p.name} />)}
<PluginActivityPanel />
</div>
)
}
@@ -338,23 +338,23 @@ describe('TodoListPanel', () => {
}
});
it('FE-COMP-TODO-025: New category input appears when clicking "Add category" button', async () => {
it('FE-COMP-TODO-025: New list input appears when clicking "Add list" button', async () => {
const user = userEvent.setup();
render(<TodoListPanel tripId={1} items={[]} />);
// Find and click the "Add category" button
// Find and click the "Add list" button
const addCatBtn = screen.getAllByRole('button').find(
b => b.textContent?.includes('Add category') || b.getAttribute('title') === 'Add category'
b => b.textContent?.includes('Add list') || b.getAttribute('title') === 'Add list'
);
expect(addCatBtn).toBeTruthy();
await user.click(addCatBtn!);
// A text input for category name should appear
await waitFor(() => {
const input = screen.getByPlaceholderText('Category name');
const input = screen.getByPlaceholderText('List name');
expect(input).toBeInTheDocument();
});
});
it('FE-COMP-TODO-026: Adding a new category creates a filter button for it', async () => {
it('FE-COMP-TODO-026: Adding a new list creates a filter button for it', async () => {
const user = userEvent.setup();
server.use(
http.post('/api/trips/1/todo', () =>
@@ -363,10 +363,10 @@ describe('TodoListPanel', () => {
);
render(<TodoListPanel tripId={1} items={[]} />);
const addCatBtn = screen.getAllByRole('button').find(
b => b.textContent?.includes('Add category') || b.getAttribute('title') === 'Add category'
b => b.textContent?.includes('Add list') || b.getAttribute('title') === 'Add list'
);
await user.click(addCatBtn!);
const categoryInput = await screen.findByPlaceholderText('Category name');
const categoryInput = await screen.findByPlaceholderText('List name');
await user.type(categoryInput, 'Errands');
await user.keyboard('{Enter}');
// The Errands filter button should appear after the API call
+34 -23
View File
@@ -1,4 +1,4 @@
import { useState, useMemo, useEffect, useRef } from 'react'
import { Fragment, useState, useMemo, useEffect, useRef } from 'react'
import { avatarSrc } from '../../utils/avatarSrc'
import ReactDOM from 'react-dom'
import { useTripStore } from '../../store/tripStore'
@@ -19,6 +19,7 @@ import type { TodoItem } from '../../types'
import { KAT_COLORS, PRIO_CONFIG, katColor, type FilterType, type Member } from './todoListModel'
import { useTodoList } from './useTodoList'
import TodoRow from './TodoRow'
import { usePluginViewContributions, PluginCardFooter } from '../Plugins/PluginContributions'
export default function TodoListPanel({ tripId, items, addItemSignal = 0 }: { tripId: number; items: TodoItem[]; addItemSignal?: number }) {
// Layout component: state/effects/derived/handlers live in useTodoList.
@@ -32,6 +33,9 @@ export default function TodoListPanel({ tripId, items, addItemSignal = 0 }: { tr
addCategory, catCount,
} = useTodoList(tripId, items, addItemSignal)
// Plugin-contributed columns/actions for the todo view, keyed by task id (#plugins).
const contribFor = usePluginViewContributions('todos', tripId)
// Drag-to-reorder (#969). Manual ordering only makes sense when the list isn't
// sorted by priority; a drag within the filtered view is mapped back onto the
// full item order so unfiltered tasks keep their place.
@@ -203,28 +207,35 @@ export default function TodoListPanel({ tripId, items, addItemSignal = 0 }: { tr
{/* Task list */}
<div style={{ flex: 1, overflowY: 'auto', padding: '4px 0' }}>
{filtered.length === 0 ? null : (
filtered.map(item => (
<TodoRow
key={item.id}
item={item}
members={members}
categories={categories}
today={today}
isSelected={selectedId === item.id}
canEdit={canEdit}
formatDate={formatDate}
onSelect={(id) => { setSelectedId(id); setIsAddingNew(false) }}
onToggle={(id, checked) => toggleTodoItem(tripId, id, checked)}
drag={canReorder ? {
isDragging: dragId === item.id,
isOver: overId === item.id && dragId !== null && dragId !== item.id,
onStart: (id) => { setDragId(id); setOverId(null) },
onOver: (id) => setOverId(id),
onEnd: () => { setDragId(null); setOverId(null) },
onDrop: handleReorderDrop,
} : undefined}
/>
))
filtered.map(item => {
const contributions = contribFor(item.id)
return (
<Fragment key={item.id}>
<TodoRow
item={item}
members={members}
categories={categories}
today={today}
isSelected={selectedId === item.id}
canEdit={canEdit}
formatDate={formatDate}
onSelect={(id) => { setSelectedId(id); setIsAddingNew(false) }}
onToggle={(id, checked) => toggleTodoItem(tripId, id, checked)}
drag={canReorder ? {
isDragging: dragId === item.id,
isOver: overId === item.id && dragId !== null && dragId !== item.id,
onStart: (id) => { setDragId(id); setOverId(null) },
onOver: (id) => setOverId(id),
onEnd: () => { setDragId(null); setOverId(null) },
onDrop: handleReorderDrop,
} : undefined}
/>
{contributions.length > 0 && (
<div style={{ padding: '0 20px 8px' }}><PluginCardFooter items={contributions} tripId={tripId} /></div>
)}
</Fragment>
)
})
)}
</div>
</div>
@@ -11,6 +11,7 @@ import { CustomDatePicker } from '../shared/CustomDateTimePicker'
import { normalizeImageFile } from '../../utils/convertHeic'
import { getApiErrorMessage, type Trip } from '../../types'
import type { TripCreateRequest } from '@trek/shared'
import { NumericInput } from '../shared/NumericInput'
interface TripFormModalProps {
isOpen: boolean
@@ -436,9 +437,8 @@ export default function TripFormModal({ isOpen, onClose, onSave, trip, onCoverUp
<label className="block text-sm font-medium text-slate-700 mb-1.5">
{t('dashboard.dayCount')}
</label>
<input type="number" min={1} max={365} value={formData.day_count}
onChange={e => {
const raw = e.target.value
<NumericInput min={1} max={365} value={formData.day_count}
onValueChange={raw => {
if (raw === '') { update('day_count', ''); return }
const n = Math.floor(Number(raw))
if (Number.isFinite(n)) update('day_count', Math.min(365, Math.max(1, n)))
@@ -489,9 +489,9 @@ export default function TripFormModal({ isOpen, onClose, onSave, trip, onCoverUp
</div>
{customReminder && (
<div className="flex items-center gap-2 mt-2">
<input type="number" min={1} max={30}
<NumericInput min={1} max={30}
value={formData.reminder_days}
onChange={e => update('reminder_days', Math.max(1, Math.min(30, Number(e.target.value) || 1)))}
onValueChange={raw => update('reminder_days', Math.max(1, Math.min(30, Number(raw) || 1)))}
className="w-20 px-3 py-1.5 border border-slate-200 rounded-lg text-sm text-slate-900 focus:outline-none focus:ring-2 focus:ring-slate-300" />
<span className="text-xs text-slate-500">{t('trips.reminderDaysBefore')}</span>
</div>
@@ -268,9 +268,12 @@ interface TripMembersModalProps {
onClose: () => void
tripId: number
tripTitle: string
/** Called after the roster changes (guest/member added, renamed or removed) so the
* planner can refresh its members for Costs participants, Collab, etc. */
onMembersChanged?: () => void
}
export default function TripMembersModal({ isOpen, onClose, tripId, tripTitle }: TripMembersModalProps) {
export default function TripMembersModal({ isOpen, onClose, tripId, tripTitle, onMembersChanged }: TripMembersModalProps) {
const [data, setData] = useState(null)
const [allUsers, setAllUsers] = useState([])
const [loading, setLoading] = useState(false)
@@ -297,11 +300,14 @@ export default function TripMembersModal({ isOpen, onClose, tripId, tripTitle }:
}
}, [isOpen, tripId])
const loadMembers = async () => {
const loadMembers = async (notify = false) => {
setLoading(true)
try {
const d = await tripsApi.getMembers(tripId)
setData(d)
// Notify the planner to re-sync (Costs participants etc.) only after an actual
// roster mutation — not on the initial open load, which would be a redundant fetch.
if (notify) onMembersChanged?.()
} catch {
toast.error(t('members.loadError'))
} finally {
@@ -323,7 +329,7 @@ export default function TripMembersModal({ isOpen, onClose, tripId, tripTitle }:
const target = allUsers.find(u => String(u.id) === String(selectedUserId))
await tripsApi.addMember(tripId, target.username)
setSelectedUserId('')
await loadMembers()
await loadMembers(true)
toast.success(`${target.username} ${t('members.added')}`)
} catch (err: unknown) {
toast.error(getApiErrorMessage(err, t('members.addError')))
@@ -354,7 +360,7 @@ export default function TripMembersModal({ isOpen, onClose, tripId, tripTitle }:
try {
await tripsApi.createGuest(tripId, name)
setNewGuestName('')
await loadMembers()
await loadMembers(true)
toast.success(t('members.guestAdded'))
} catch (err: unknown) {
toast.error(getApiErrorMessage(err, t('members.guestAddError')))
@@ -369,7 +375,7 @@ export default function TripMembersModal({ isOpen, onClose, tripId, tripTitle }:
try {
await tripsApi.renameGuest(tripId, userId, name)
setRenamingGuestId(null)
await loadMembers()
await loadMembers(true)
} catch (err: unknown) {
toast.error(getApiErrorMessage(err, t('members.guestRenameError')))
}
@@ -380,7 +386,7 @@ export default function TripMembersModal({ isOpen, onClose, tripId, tripTitle }:
setRemovingId(userId)
try {
await tripsApi.deleteGuest(tripId, userId)
await loadMembers()
await loadMembers(true)
toast.success(t('members.guestRemoved'))
} catch {
toast.error(t('members.removeError'))
@@ -398,7 +404,7 @@ export default function TripMembersModal({ isOpen, onClose, tripId, tripTitle }:
try {
await tripsApi.removeMember(tripId, userId)
if (isSelf) { onClose(); window.location.reload() }
else { await loadMembers(); toast.success(t('members.removed')) }
else { await loadMembers(true); toast.success(t('members.removed')) }
} catch {
toast.error(t('members.removeError'))
} finally {
@@ -7,6 +7,7 @@ import { server } from '../../../tests/helpers/msw/server'
import { http, HttpResponse } from 'msw'
import { useVacayStore } from '../../store/vacayStore'
import VacaySettings from './VacaySettings'
import { fetchRegionOptions } from './holidayRegions'
const basePlan = {
id: 1,
@@ -414,6 +415,40 @@ describe('VacaySettings', () => {
expect(updatePlan).toHaveBeenCalledWith({ company_holidays_enabled: true })
})
it('FE-COMP-VACAYSETTINGS-019: fetchRegionOptions lists the full ISO subdivision set incl. states with no holiday (regression #1456: US-WA)', async () => {
// US 2026 nager data tags some states but NOT Washington — it must still appear.
server.use(
http.get('/api/addons/vacay/holidays/:year/:country', () =>
HttpResponse.json([
{ date: '2026-01-01', global: true, counties: null },
{ date: '2026-04-25', global: false, counties: ['US-CA', 'US-VT', 'US-WI'] },
])
),
)
const opts = await fetchRegionOptions('US')
// Washington is present with its proper name, and options are sorted by label.
expect(opts).toContainEqual({ value: 'US-WA', label: 'Washington' })
const labels = opts.map(o => o.label)
expect(labels).toEqual([...labels].sort((a, b) => a.localeCompare(b)))
// Other previously-missing states surface too.
expect(opts.map(o => o.value)).toEqual(expect.arrayContaining(['US-AR', 'US-FL', 'US-NV', 'US-WY']))
})
it('FE-COMP-VACAYSETTINGS-020: fetchRegionOptions returns [] for a nationwide-only country (no region picker forced)', async () => {
server.use(
http.get('/api/addons/vacay/holidays/:year/:country', () =>
HttpResponse.json([
{ date: '2026-01-01', global: true, counties: null },
{ date: '2026-12-25', global: true, counties: null },
])
),
)
expect(await fetchRegionOptions('JP')).toEqual([])
})
it('FE-COMP-VACAYSETTINGS-018: adding weekend day calls updatePlan with day added', async () => {
const user = userEvent.setup()
const updatePlan = vi.fn().mockResolvedValue(undefined)
+1 -24
View File
@@ -5,6 +5,7 @@ import { getIntlLanguage, useTranslation } from '../../i18n'
import { useToast } from '../shared/Toast'
import CustomSelect from '../shared/CustomSelect'
import apiClient from '../../api/client'
import { fetchRegionOptions } from './holidayRegions'
import type { VacayHolidayCalendar } from '../../types'
interface VacaySettingsProps {
@@ -255,30 +256,6 @@ function SettingToggle({ icon: Icon, label, hint, value, onChange }: SettingTogg
)
}
// ── shared region-loading helper ─────────────────────────────────────────────
async function fetchRegionOptions(country: string): Promise<{ value: string; label: string }[]> {
try {
const year = new Date().getFullYear()
const r = await apiClient.get(`/addons/vacay/holidays/${year}/${country}`)
const allCounties = new Set<string>()
r.data.forEach(h => { if (h.counties) h.counties.forEach(c => allCounties.add(c)) })
if (allCounties.size === 0) return []
return [...allCounties].sort().map(c => {
let label = c.split('-')[1] || c
if (c.startsWith('DE-')) {
const m: Record<string, string> = { BW:'Baden-Württemberg',BY:'Bayern',BE:'Berlin',BB:'Brandenburg',HB:'Bremen',HH:'Hamburg',HE:'Hessen',MV:'Mecklenburg-Vorpommern',NI:'Niedersachsen',NW:'Nordrhein-Westfalen',RP:'Rheinland-Pfalz',SL:'Saarland',SN:'Sachsen',ST:'Sachsen-Anhalt',SH:'Schleswig-Holstein',TH:'Thüringen' }
label = m[c.split('-')[1]] || label
} else if (c.startsWith('CH-')) {
const m: Record<string, string> = { AG:'Aargau',AI:'Appenzell Innerrhoden',AR:'Appenzell Ausserrhoden',BE:'Bern',BL:'Basel-Landschaft',BS:'Basel-Stadt',FR:'Freiburg',GE:'Genf',GL:'Glarus',GR:'Graubünden',JU:'Jura',LU:'Luzern',NE:'Neuenburg',NW:'Nidwalden',OW:'Obwalden',SG:'St. Gallen',SH:'Schaffhausen',SO:'Solothurn',SZ:'Schwyz',TG:'Thurgau',TI:'Tessin',UR:'Uri',VD:'Waadt',VS:'Wallis',ZG:'Zug',ZH:'Zürich' }
label = m[c.split('-')[1]] || label
}
return { value: c, label }
})
} catch {
return []
}
}
// ── Existing calendar row (inline edit) ──────────────────────────────────────
function CalendarRow({ cal, countries, onUpdate, onDelete }: {
cal: VacayHolidayCalendar
@@ -95,7 +95,7 @@ describe('VacayStats', () => {
render(<VacayStats />)
// The vacation_days tile shows "25" as a standalone div; click it to trigger edit
await user.click(screen.getByText('25'))
expect(screen.getByRole('spinbutton')).toBeInTheDocument()
expect(screen.getByRole('textbox')).toBeInTheDocument()
})
it('FE-COMP-VACAYSTATS-009: Pressing Enter in editor calls updateVacationDays', async () => {
@@ -104,7 +104,7 @@ describe('VacayStats', () => {
seedStore(useVacayStore, { stats: [buildStat({ user_id: 1 })] })
render(<VacayStats />)
await user.click(screen.getByText('25'))
const input = screen.getByRole('spinbutton')
const input = screen.getByRole('textbox')
await user.clear(input)
await user.type(input, '30')
await user.keyboard('{Enter}')
@@ -117,11 +117,11 @@ describe('VacayStats', () => {
seedStore(useVacayStore, { stats: [buildStat({ user_id: 1 })] })
render(<VacayStats />)
await user.click(screen.getByText('25'))
const input = screen.getByRole('spinbutton')
const input = screen.getByRole('textbox')
await user.clear(input)
await user.type(input, '99')
await user.keyboard('{Escape}')
expect(screen.queryByRole('spinbutton')).not.toBeInTheDocument()
expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
expect(mockUpdateVacationDays).not.toHaveBeenCalled()
})
@@ -146,6 +146,6 @@ describe('VacayStats', () => {
})
render(<VacayStats />)
await user.click(screen.getByText('25'))
expect(screen.getByRole('spinbutton')).toBeInTheDocument()
expect(screen.getByRole('textbox')).toBeInTheDocument()
})
})
+3 -3
View File
@@ -4,6 +4,7 @@ import { useVacayStore } from '../../store/vacayStore'
import { useAuthStore } from '../../store/authStore'
import { useTranslation } from '../../i18n'
import type { VacayStat, TranslationFn } from '../../types'
import { NumericInput } from '../shared/NumericInput'
export default function VacayStats() {
@@ -101,10 +102,9 @@ function StatCard({ stat: s, isMe, canEdit, selectedYear, onSave, t }: StatCardP
{t('vacay.entitlementDays')} {canEdit && !editing && <Pencil size={9} className="inline opacity-0 group-hover/days:opacity-100 transition-opacity text-content-faint" style={{ verticalAlign: 'middle' }} />}
</div>
{editing ? (
<input
type="number"
<NumericInput
value={localDays}
onChange={e => setLocalDays(e.target.value)}
onValueChange={setLocalDays}
onBlur={handleSave}
onKeyDown={e => { if (e.key === 'Enter') handleSave(); if (e.key === 'Escape') { setEditing(false); setLocalDays(s.vacation_days) } }}
autoFocus
@@ -0,0 +1,34 @@
import apiClient from '../../api/client'
import iso31662 from 'iso-3166-2'
// Loads the subdivision (state/region) options for a holiday-calendar country.
//
// The subdivision list is sourced from ISO 3166-2 (proper names, complete per country)
// rather than inferred from which subdivisions happen to have a holiday this year — the
// latter silently dropped states with no state-specific holiday (e.g. US-WA, issue #1456).
// We only surface a list for countries that are actually region-partitioned, so countries
// with only nationwide holidays keep showing no region picker (and allow a country-level
// calendar, matching the server's applyHolidayCalendars behaviour).
export async function fetchRegionOptions(country: string): Promise<{ value: string; label: string }[]> {
try {
const year = new Date().getFullYear()
const r = await apiClient.get(`/addons/vacay/holidays/${year}/${country}`)
const hasRegions = r.data.some(h => h.counties && h.counties.length > 0)
if (!hasRegions) return []
const opts = new Map<string, string>() // ISO code -> display name
const sub = iso31662.country(country)?.sub || {}
for (const [code, info] of Object.entries(sub)) opts.set(code, info.name)
// Fall back to any nager county code ISO doesn't know about, so nothing regresses.
r.data.forEach(h => h.counties?.forEach(c => {
if (!opts.has(c)) opts.set(c, iso31662.subdivision(c)?.name || c.split('-')[1] || c)
}))
return [...opts]
.map(([value, label]) => ({ value, label }))
.sort((a, b) => a.label.localeCompare(b.label))
} catch {
return []
}
}
@@ -0,0 +1,133 @@
// FE-COMP-NUMINPUT-001 to FE-COMP-NUMINPUT-008
//
// #1513: tapping a pre-populated numeric field put the caret at the end, so the first
// digit typed was appended rather than replacing the value — quantity 1 + "6" = "16".
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { useState } from 'react'
import { NumericInput, type NumericMode } from './NumericInput'
// select() is deferred a frame on purpose (see the component); run rAF synchronously.
beforeEach(() => {
vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => {
cb(0)
return 0
})
})
afterEach(() => vi.unstubAllGlobals())
function Harness({ initial, mode }: { initial: string; mode?: NumericMode }) {
const [v, setV] = useState(initial)
return <NumericInput value={v} onValueChange={setV} mode={mode} aria-label="field" />
}
describe('NumericInput', () => {
it('FE-COMP-NUMINPUT-001: selects the existing value on focus so a typed digit replaces it', () => {
render(<Harness initial="1" />)
const input = screen.getByLabelText('field') as HTMLInputElement
fireEvent.focus(input)
expect(input.selectionStart).toBe(0)
expect(input.selectionEnd).toBe(1)
})
it('FE-COMP-NUMINPUT-002: selects a multi-digit value in full', () => {
render(<Harness initial="250" />)
const input = screen.getByLabelText('field') as HTMLInputElement
fireEvent.focus(input)
expect(input.selectionStart).toBe(0)
expect(input.selectionEnd).toBe(3)
})
it('FE-COMP-NUMINPUT-003: is a text input with a numeric keypad, not type=number', () => {
// type=number silently mutates the value on scroll-wheel and ships spinner arrows.
render(<Harness initial="1" />)
const input = screen.getByLabelText('field') as HTMLInputElement
expect(input.type).toBe('text')
expect(input.inputMode).toBe('numeric')
})
it('FE-COMP-NUMINPUT-004: integer mode strips non-digits', () => {
render(<Harness initial="" />)
const input = screen.getByLabelText('field') as HTMLInputElement
fireEvent.change(input, { target: { value: '1a2-b3' } })
expect(input.value).toBe('123')
})
it('FE-COMP-NUMINPUT-005: decimal mode keeps a dot and a comma (callers normalize the comma)', () => {
render(<Harness initial="" mode="decimal" />)
const input = screen.getByLabelText('field') as HTMLInputElement
fireEvent.change(input, { target: { value: '12.50' } })
expect(input.value).toBe('12.50')
fireEvent.change(input, { target: { value: '12,50' } })
expect(input.value).toBe('12,50')
fireEvent.change(input, { target: { value: '1x2.5eur' } })
expect(input.value).toBe('12.5')
})
it('FE-COMP-NUMINPUT-006: decimal mode uses the decimal keypad', () => {
render(<Harness initial="" mode="decimal" />)
expect((screen.getByLabelText('field') as HTMLInputElement).inputMode).toBe('decimal')
})
it('FE-COMP-NUMINPUT-007: signed mode keeps a leading minus (coordinates)', () => {
render(<Harness initial="" mode="signed" />)
const input = screen.getByLabelText('field') as HTMLInputElement
fireEvent.change(input, { target: { value: '-4.4215' } })
expect(input.value).toBe('-4.4215')
// A minus anywhere but the front is not a sign.
fireEvent.change(input, { target: { value: '36.72' } })
expect(input.value).toBe('36.72')
})
it('FE-COMP-NUMINPUT-009: typing inside the one-frame window is not swallowed by the deferred select', async () => {
// The deferred select() exists for WebKit, but it must not fire *after* the user has
// started typing: it would select the half-typed value and the next character would
// replace it, turning "48.853" into ".853". Any input cancels the pending select.
vi.unstubAllGlobals()
const frames: FrameRequestCallback[] = []
vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => {
frames.push(cb)
return 0
})
render(<Harness initial="" mode="signed" />)
const input = screen.getByLabelText('field') as HTMLInputElement
fireEvent.focus(input)
// User types before the queued frame runs.
fireEvent.change(input, { target: { value: '4' } })
fireEvent.change(input, { target: { value: '48' } })
// Frame finally runs — must be a no-op now.
frames.forEach(cb => cb(0))
fireEvent.change(input, { target: { value: '48.853' } })
expect(input.value).toBe('48.853')
})
it('FE-COMP-NUMINPUT-008: a caller-supplied onFocus still runs alongside the select', () => {
const onFocus = vi.fn()
render(
<NumericInput value="7" onValueChange={() => {}} onFocus={onFocus} aria-label="field" />,
)
const input = screen.getByLabelText('field') as HTMLInputElement
fireEvent.focus(input)
expect(onFocus).toHaveBeenCalledTimes(1)
expect(input.selectionEnd).toBe(1)
})
})
@@ -0,0 +1,87 @@
import { forwardRef, useRef, type InputHTMLAttributes } from 'react'
export type NumericMode = 'integer' | 'decimal' | 'signed'
const SANITIZERS: Record<NumericMode, (raw: string) => string> = {
// Digits only — quantities, weights, day counts.
integer: raw => raw.replace(/[^0-9]/g, ''),
// Digits plus a decimal separator. Both '.' and ',' pass through; callers already
// normalize the comma (see CostsPanel.onTotalChange) so a European keypad still works.
decimal: raw => raw.replace(/[^0-9.,]/g, ''),
// Signed decimal — coordinates. Keeps a leading '-'.
signed: raw => {
const negative = raw.trimStart().startsWith('-')
const digits = raw.replace(/[^0-9.]/g, '')
return negative ? `-${digits}` : digits
},
}
type Props = Omit<InputHTMLAttributes<HTMLInputElement>, 'type' | 'onChange' | 'value'> & {
value: string | number | null | undefined
/** Receives the sanitized raw string. Callers keep their own state and commit logic. */
onValueChange: (value: string) => void
mode?: NumericMode
/** Escape hatch for a field that must not steal the caret (none today). */
selectOnFocus?: boolean
}
/**
* A numeric text input that replaces its contents when you type into it.
*
* Two things every numeric field in the app needs, and most were getting wrong (#1513):
*
* 1. **Select-on-focus.** Tapping a pre-populated field puts the caret at the end, so
* the first digit you type is *appended*: a quantity of 1 becomes 16 instead of 6.
* Selecting the value on focus makes the first keystroke replace it.
*
* We select twice: synchronously (works everywhere) and again on the next frame,
* because WebKit undoes a synchronous select() with its own post-focus caret
* placement — without the deferred pass, iOS silently keeps appending.
*
* The deferred pass is guarded. If a keystroke lands inside that one-frame window,
* re-selecting would swallow what was just typed: type "4" then "8", the frame
* fires and selects "48", and the next character *replaces* both — "48.853" comes
* out as ".853". So the first input cancels the pending select and we leave the
* caret alone.
*
* 2. **type="text" + inputMode**, not type="number". They render the same keypad, but
* type="number" also silently mutates the value on scroll-wheel over the field and
* ships spinner arrows. (setSelectionRange() also throws InvalidStateError on a
* number input — select() happens to be allowed, but the whole class is a trap.)
*
* Styling and commit semantics stay with the caller: some fields save on every keystroke,
* others on blur. This owns only the part that was uniformly broken.
*/
export const NumericInput = forwardRef<HTMLInputElement, Props>(function NumericInput(
{ value, onValueChange, mode = 'integer', selectOnFocus = true, onFocus, inputMode, ...rest },
ref,
) {
// Set while a deferred select() is queued; any input in that window cancels it.
const selectPending = useRef(false)
return (
<input
{...rest}
ref={ref}
type="text"
inputMode={inputMode ?? (mode === 'integer' ? 'numeric' : 'decimal')}
value={value ?? ''}
onChange={e => {
selectPending.current = false
onValueChange(SANITIZERS[mode](e.target.value))
}}
onFocus={e => {
if (selectOnFocus) {
const el = e.currentTarget
el.select()
selectPending.current = true
requestAnimationFrame(() => {
if (selectPending.current && document.activeElement === el) el.select()
selectPending.current = false
})
}
onFocus?.(e)
}}
/>
)
})
@@ -0,0 +1,108 @@
import { render, waitFor, act } from '../../../tests/helpers/render';
import SlidingTabs from './SlidingTabs';
const TABS = [
{ id: 'a', label: 'Alpha' },
{ id: 'b', label: 'Bravo' },
] as const;
// Query the absolutely-positioned pill (rendered with aria-hidden).
function pill(): HTMLElement | null {
return document.querySelector('[aria-hidden="true"]');
}
describe('SlidingTabs', () => {
const onChange = vi.fn();
let rectSpy: ReturnType<typeof vi.spyOn>;
// Mutable geometry so we can simulate the active label reflowing (e.g. after a font swap).
let activeButtonRect: { left: number; width: number };
let capturedResizeCallbacks: ResizeObserverCallback[];
let resolveFonts: () => void;
beforeEach(() => {
onChange.mockClear();
activeButtonRect = { left: 20, width: 100 };
capturedResizeCallbacks = [];
// jsdom has no real layout — stub geometry. Container sits at left 0; buttons report
// the mutable rect (only the active button is ever measured).
rectSpy = vi
.spyOn(HTMLElement.prototype, 'getBoundingClientRect')
.mockImplementation(function (this: HTMLElement) {
const base = { top: 0, right: 0, bottom: 0, x: 0, y: 0, toJSON: () => ({}) };
if (this.tagName === 'BUTTON') {
return { ...base, left: activeButtonRect.left, width: activeButtonRect.width } as DOMRect;
}
return { ...base, left: 0, width: 300 } as DOMRect;
});
// Capturing ResizeObserver so tests can drive the resize path (global mock is a no-op).
class CapturingResizeObserver {
constructor(cb: ResizeObserverCallback) {
capturedResizeCallbacks.push(cb);
}
observe() {}
unobserve() {}
disconnect() {}
}
vi.stubGlobal('ResizeObserver', CapturingResizeObserver);
// Controllable document.fonts.ready.
Object.defineProperty(document, 'fonts', {
configurable: true,
value: {
ready: new Promise<void>(resolve => {
resolveFonts = resolve;
}),
},
});
});
afterEach(() => {
rectSpy.mockRestore();
vi.unstubAllGlobals();
// @ts-expect-error — remove the stub so it doesn't leak into other suites.
delete document.fonts;
});
it('FE-COMP-TABS-001: positions the pill from the initial measurement', () => {
render(<SlidingTabs tabs={TABS} activeTab="a" onChange={onChange} />);
const el = pill();
expect(el).toBeTruthy();
// left = activeRect.left(20) - containerRect.left(0) + scrollLeft(0)
expect(el!.style.left).toBe('20px');
expect(el!.style.width).toBe('100px');
});
it('FE-COMP-TABS-002: re-measures after document.fonts.ready resolves (reload font swap)', async () => {
render(<SlidingTabs tabs={TABS} activeTab="a" onChange={onChange} />);
expect(pill()!.style.width).toBe('100px');
// Font settles → active (bold) label reflows wider and recentres.
activeButtonRect = { left: 12, width: 130 };
await act(async () => {
resolveFonts();
await Promise.resolve();
});
await waitFor(() => {
expect(pill()!.style.left).toBe('12px');
expect(pill()!.style.width).toBe('130px');
});
});
it('FE-COMP-TABS-003: re-measures when the ResizeObserver fires (window/container resize)', () => {
render(<SlidingTabs tabs={TABS} activeTab="a" onChange={onChange} />);
expect(pill()!.style.width).toBe('100px');
activeButtonRect = { left: 40, width: 90 };
act(() => {
capturedResizeCallbacks.forEach(cb =>
cb([] as unknown as ResizeObserverEntry[], {} as ResizeObserver),
);
});
expect(pill()!.style.left).toBe('40px');
expect(pill()!.style.width).toBe('90px');
});
});
+36 -9
View File
@@ -30,16 +30,43 @@ export function SlidingTabs<T extends string>({
const [indicator, setIndicator] = useState<{ left: number; width: number; ready: boolean }>({ left: 0, width: 0, ready: false })
useLayoutEffect(() => {
const active = tabRefs.current.get(activeTab)
const container = containerRef.current
if (!active || !container) return
const containerRect = container.getBoundingClientRect()
const activeRect = active.getBoundingClientRect()
setIndicator({
left: activeRect.left - containerRect.left + container.scrollLeft,
width: activeRect.width,
ready: true,
const measure = (): void => {
const active = tabRefs.current.get(activeTab)
const container = containerRef.current
if (!active || !container) return
const containerRect = container.getBoundingClientRect()
const activeRect = active.getBoundingClientRect()
const left = activeRect.left - containerRect.left + container.scrollLeft
const width = activeRect.width
setIndicator(prev =>
prev.ready && prev.left === left && prev.width === width
? prev
: { left, width, ready: true },
)
}
measure()
// Re-measure once web fonts settle — on a reload the first measure runs against
// fallback-font metrics, so the (bold) active label reflows and the pill drifts.
let cancelled = false
document.fonts?.ready?.then(() => {
if (!cancelled) measure()
})
// Re-measure on layout/size changes: container (window resize) + active label reflow.
let ro: ResizeObserver | undefined
if (typeof ResizeObserver !== 'undefined') {
ro = new ResizeObserver(() => measure())
if (containerRef.current) ro.observe(containerRef.current)
const active = tabRefs.current.get(activeTab)
if (active) ro.observe(active)
}
return () => {
cancelled = true
ro?.disconnect()
}
}, [activeTab, tabs.length])
const padding = size === 'sm' ? '5px 12px' : '6px 14px'
+13 -11
View File
@@ -3,7 +3,7 @@ import { useTripStore } from '../store/tripStore'
import { useSettingsStore } from '../store/settingsStore'
import { calculateRouteWithLegs, withHotelBookends } from '../components/Map/RouteCalculator'
import { getTransportRouteEndpoints } from '../utils/dayMerge'
import { getDayBookendHotels } from '../utils/dayOrder'
import { getDayBookendHotels, shouldDrawMorningLeg, shouldDrawEveningLeg } from '../utils/dayOrder'
import type { TripStoreState } from '../store/tripStore'
import type { RouteSegment, RouteResult, Accommodation } from '../types'
@@ -66,11 +66,11 @@ export function useRouteCalculation(tripStore: TripStoreState, selectedDayId: nu
// Build a unified list of places + transports sorted by effective position.
type Entry =
| { kind: 'place'; lat: number; lng: number; pos: number }
| { kind: 'place'; lat: number; lng: number; pos: number; time: string | null }
| { kind: 'transport'; from: { lat: number; lng: number } | null; to: { lat: number; lng: number } | null; pos: number }
const entries: Entry[] = [
...da.filter(a => a.place?.lat && a.place?.lng).map(a => ({
kind: 'place' as const, lat: a.place.lat!, lng: a.place.lng!, pos: a.order_index,
kind: 'place' as const, lat: a.place.lat!, lng: a.place.lng!, pos: a.order_index, time: a.place?.place_time ?? null,
})),
...dayTransports.map(r => {
const { from, to } = getTransportRouteEndpoints(r, dayId)
@@ -125,17 +125,19 @@ export function useRouteCalculation(tripStore: TripStoreState, selectedDayId: nu
}
const hotelPt = (a?: Accommodation) =>
a && a.place_lat != null && a.place_lng != null ? { lat: a.place_lat, lng: a.place_lng } : null
// Only draw a hotel bookend when the leg is real. A hotel → first-stop leg holds
// if the first stop is a place, or if you actually slept in that hotel last night;
// on a day-1 arrival the morning hotel is just a check-in fallback and the first
// waypoint is the transport's departure point, so [hotel → departure] is dropped
// (#1321). Symmetrically, [last-stop → hotel] is dropped when you leave on a transport
// in the evening and don't sleep in that hotel tonight.
// Only draw a hotel bookend when the leg is a real drive. You start/end the day at a hotel
// when you slept there / sleep there tonight; on the hotel's own check-in or check-out day
// the leg holds only when the edge stop is a PLACE timed after check-in / before check-out
// (you dropped bags first, or swung back before checking out). A place before check-in (an
// airport you reach first, #1465), a later "home" stop on the checkout day (#1465), or a
// transport endpoint on an arrival/departure day (#1321, S7) all draw no bookend.
const contributes = (e: Entry) => e.kind === 'place' || !!e.from || !!e.to
const firstStop = entries.find(contributes)
const lastStop = [...entries].reverse().find(contributes)
const drawMorning = firstStop?.kind === 'place' || !!bookends?.morningIsSleptHere
const drawEvening = lastStop?.kind === 'place' || !!bookends?.eveningIsOvernight
const edgeInfo = (e?: Entry) =>
e ? { isPlace: e.kind === 'place', time: e.kind === 'place' ? e.time : null } : undefined
const drawMorning = !!bookends && !!day && shouldDrawMorningLeg(bookends, day, edgeInfo(firstStop))
const drawEvening = !!bookends && !!day && shouldDrawEveningLeg(bookends, day, edgeInfo(lastStop))
const runsWithHotel = withHotelBookends(
runs,
flatPts[0],
+32
View File
@@ -0,0 +1,32 @@
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { describe, it, expect } from 'vitest'
// Leaflet's stylesheet must be bundled, not loaded from unpkg: the service
// worker cached the CDN response as opaque and the browser then rejected it,
// leaving the Atlas and trip maps blank (#1497). These checks keep the CDN
// reference from sneaking back in.
describe('leaflet css self-hosting (#1497)', () => {
// Vitest runs with the client package as its root, so cwd is stable here.
const read = (rel: string) => readFileSync(resolve(process.cwd(), rel), 'utf8')
it('index.html no longer references unpkg', () => {
const html = read('index.html')
expect(html).not.toMatch(/unpkg\.com/i)
expect(html).not.toMatch(/leaflet/i)
})
it('main.tsx imports the bundled leaflet css before the app styles', () => {
const main = read('src/main.tsx')
const leafletAt = main.indexOf("import 'leaflet/dist/leaflet.css'")
const indexAt = main.indexOf("import './index.css'")
expect(leafletAt).toBeGreaterThan(-1)
expect(indexAt).toBeGreaterThan(-1)
// index.css overrides .leaflet-* styles, so order matters.
expect(leafletAt).toBeLessThan(indexAt)
})
it('the service worker has no runtime-caching rule for unpkg', () => {
expect(read('vite.config.js')).not.toMatch(/unpkg/i)
})
})
+13 -4
View File
@@ -13,15 +13,24 @@ import '@fontsource/poppins/700.css'
import '@fontsource/geist-sans/400.css'
import '@fontsource/geist-sans/500.css'
import '@fontsource/geist-sans/600.css'
// Leaflet CSS bundled from node_modules instead of unpkg: the service worker
// cached the CDN stylesheet as an opaque response, which the browser then
// rejected, breaking the Atlas/trip maps (#1497). Bundling keeps it same-origin
// and precached with the app shell. Must stay above index.css, which overrides
// several .leaflet-* styles.
import 'leaflet/dist/leaflet.css'
import './index.css'
// Native HTML5 drag-and-drop never fires on touch input, so the planner's place /
// day reordering was dead on Android and iOS. This polyfill synthesises the standard
// drag events from touch gestures over draggable elements — it only hooks touch, so
// desktop mouse dragging is untouched (#1265).
import 'drag-drop-touch'
// day reordering was dead on Android and iOS. The `drag-drop-touch` polyfill synthesises
// the standard drag events from touch gestures over draggable elements (#1265). It is
// loaded only on non-mobile viewports: reorder DnD is disabled on mobile (#1432), where
// the polyfill's synthetic click/dblclick otherwise turned quick one-finger map pans into
// double-tap zooms (#1440). See utils/touchDragPolyfill.ts.
import { maybeInstallTouchDragPolyfill } from './utils/touchDragPolyfill'
import { startConnectivityProbe } from './sync/connectivity'
import { requestPersistentStorage } from './sync/persistentStorage'
maybeInstallTouchDragPolyfill()
startConnectivityProbe()
// Keep offline data (map tiles, file blobs, IndexedDB) exempt from eviction.
requestPersistentStorage()
+123
View File
@@ -0,0 +1,123 @@
// Regression coverage for issue #1485 — the "Add place" button vanished once a
// collection held its first mappable place on a wide/desktop layout, because the
// whole toolbar (which hosts the button) was gated on `!mapOverlay`. These tests
// render the page against a mocked useCollections hook (per the Page pattern) and
// assert the Add affordance stays reachable — and that there is exactly one of it.
import { describe, it, expect, vi } from 'vitest'
import React from 'react'
import { render, screen } from '../../tests/helpers/render'
import CollectionsPage from './CollectionsPage'
// Stub every child so the test isolates CollectionsPage's own toolbar/branch JSX
// (the Add button is rendered by the page itself, not by any child). This also
// keeps the Leaflet/Mapbox map out of jsdom.
vi.mock('../components/Layout/Navbar', () => ({ default: () => <nav /> }))
vi.mock('../components/Collections/ListsRail', () => ({ default: () => <div /> }))
vi.mock('../components/Collections/ListEditorModal', () => ({ default: () => null }))
vi.mock('../components/Collections/CollectionHero', () => ({ default: () => <div /> }))
vi.mock('../components/Collections/CollectionList', () => ({ default: () => <div data-testid="list" /> }))
vi.mock('../components/Collections/CollectionFilterBar', () => ({ default: () => <div /> }))
vi.mock('../components/Collections/CollectionMapPanel', () => ({ default: () => <div data-testid="map" /> }))
vi.mock('../components/Collections/CopyToTripModal', () => ({ default: () => null }))
vi.mock('../components/Collections/MoveToListModal', () => ({ default: () => null }))
vi.mock('../components/Collections/ShareCollectionModal', () => ({ default: () => null }))
vi.mock('../components/Collections/AddPlaceToCollectionModal', () => ({ default: () => null }))
vi.mock('../components/Collections/CollectionPlaceDetail', () => ({ default: () => null }))
vi.mock('../components/Collections/LabelManager', () => ({ default: () => null }))
vi.mock('../components/Collections/BulkAssignLabelModal', () => ({ default: () => null }))
vi.mock('../components/shared/Modal', () => ({ default: () => null }))
const mockUseCollections = vi.fn()
vi.mock('./collections/useCollections', () => ({
useCollections: () => mockUseCollections(),
}))
// A complete-enough hook return; individual tests override the fields that matter.
function makeHook(overrides: Record<string, unknown> = {}) {
const noop = vi.fn()
return {
t: (k: string) => k,
language: 'en',
dark: false,
navigate: noop,
isWide: true,
heroRef: { current: null },
heroHeight: 0,
listColRef: { current: null },
listColRect: null,
categories: [],
collections: [{ id: 1, name: 'Test', is_owner: true }],
ownedLists: [{ id: 1, name: 'Test', is_owner: true }],
sharedLists: [],
activeCollection: { id: 1, name: 'Test', is_owner: true, color: '#6366f1' },
isAllSaved: false,
isOwner: true,
myRole: 'owner',
canEdit: true,
canDelete: true,
canShare: true,
shareMemberCount: 0,
activeId: 1,
places: [{ id: 10 }],
visiblePlaces: [{ id: 10 }],
mappable: [{ id: 10 }],
members: [],
incomingInvites: [],
counts: { all: 1, idea: 0, want: 1, visited: 0 },
view: 'list',
statusFilter: 'all',
categoryFilter: 'all',
categoryOptions: [],
search: '',
selectedPlaceId: null,
selectMode: false,
selectedIds: [],
labels: [],
labelFilter: [],
labelOptions: [],
loading: false,
placesLoading: false,
setView: noop, setStatusFilter: noop, setCategoryFilter: noop, setLabelFilter: noop,
setSearch: noop, setSelectedPlaceId: noop, setSelectMode: noop, toggleSelect: noop,
updatePlace: noop,
showLabelManager: false, setShowLabelManager: noop, labelPickerOpen: false, setLabelPickerOpen: noop,
handleCreateLabel: noop, handleUpdateLabel: noop, handleDeleteLabel: noop, handleBulkAssignLabels: noop, handleAssignPlaceLabels: noop,
editorTarget: null, setEditorTarget: noop, handleEditorCreated: noop,
showAddPlace: false, setShowAddPlace: noop, handlePlaceAdded: noop,
confirmDeleteList: null, setConfirmDeleteList: noop,
mobileRailOpen: false, setMobileRailOpen: noop,
showShare: false, setShowShare: noop, handleAfterLeave: noop,
selectedPlace: null, detailPlace: null, detailCategories: [], handleCloseDetail: noop,
handleDetailStatus: noop, handleDetailRemove: noop,
copyIds: null, openCopyForSelectedPlace: noop, openCopyForSelection: noop, closeCopy: noop, handleCopyToTrip: noop,
handleSelectList: noop, handleDeleteList: noop,
handleStatusChange: noop, handleDeletePlace: noop, handleDeleteSelected: noop,
handleAcceptInvite: noop, handleDeclineInvite: noop,
allVisibleSelected: false, handleSelectAll: noop,
listPickerMode: null, setListPickerMode: noop, handleMoveToList: noop, handleDuplicateToList: noop,
...overrides,
}
}
describe('CollectionsPage — Add place button reachability (#1485)', () => {
it('keeps the Add button visible on a wide desktop once the list has a mappable place', () => {
// The exact bug: wide layout + one place with coordinates + editable list.
mockUseCollections.mockReturnValue(makeHook())
render(<CollectionsPage />)
const addButtons = screen.getAllByLabelText('collections.addPlace')
// Present, and exactly one — no duplicate map-overlay "+" alongside it.
expect(addButtons).toHaveLength(1)
})
it('does not show the Add button for a viewer who cannot edit', () => {
mockUseCollections.mockReturnValue(makeHook({ canEdit: false, isOwner: false, myRole: 'viewer' }))
render(<CollectionsPage />)
expect(screen.queryByLabelText('collections.addPlace')).toBeNull()
})
it('shows the Add button on an empty collection', () => {
mockUseCollections.mockReturnValue(makeHook({ places: [], visiblePlaces: [], mappable: [] }))
render(<CollectionsPage />)
expect(screen.getAllByLabelText('collections.addPlace')).toHaveLength(1)
})
})
+1 -3
View File
@@ -91,8 +91,6 @@ export default function CollectionsPage(): React.ReactElement {
overlay={overlay}
view={c.view}
onToggleView={toggleView}
canAddPlace={canAddPlace}
onAddPlace={() => c.setShowAddPlace(true)}
search={c.search}
onSearch={c.setSearch}
t={t}
@@ -202,7 +200,7 @@ export default function CollectionsPage(): React.ReactElement {
/>
</div>
{!mapOverlay && (
{(!mapOverlay || canAddPlace) && (
<div className="col-toolbar">
<button type="button" className="col-rail-toggle" onClick={() => c.setMobileRailOpen(true)}>
<Bookmark size={15} /> {t('collections.title')}
+12 -1
View File
@@ -1,4 +1,4 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { render, screen, waitFor } from '../../tests/helpers/render';
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
@@ -12,6 +12,13 @@ import DashboardPage from './DashboardPage';
beforeEach(() => {
vi.clearAllMocks();
// Pin "now" to a date inside the fixtures' trip window (Paris Adventure runs
// 2026-07-01..07-10) so the dashboard's past/upcoming/spotlight split is stable
// regardless of the wall clock — otherwise these tests break once the date
// rolls past the hardcoded fixture window. shouldAdvanceTime keeps userEvent
// and async waitFor working under fake timers.
vi.useFakeTimers({ shouldAdvanceTime: true });
vi.setSystemTime(new Date('2026-07-05T12:00:00Z'));
resetAllStores();
// Seed auth with authenticated user
seedStore(useAuthStore, { isAuthenticated: true, user: buildUser() });
@@ -30,6 +37,10 @@ beforeEach(() => {
);
});
afterEach(() => {
vi.useRealTimers();
});
describe('DashboardPage', () => {
describe('FE-PAGE-DASH-001: Unauthenticated user is redirected', () => {
it('does not render dashboard content when not authenticated', () => {
+19 -7
View File
@@ -22,8 +22,11 @@ import { IcsSubscribeModal } from '../components/Planner/IcsSubscribeModal'
import CollectionsWidget from '../components/Dashboard/CollectionsWidget'
import PluginWidgets from '../components/Plugins/PluginWidgets'
import PluginFrame from '../components/Plugins/PluginFrame'
import { TripCardBadges, useTripCardBadges } from '../components/Plugins/TripCardBadges'
import type { TripCardBadge } from '../api/client'
import { usePluginStore } from '../store/pluginStore'
import { formatTime, splitReservationDateTime } from '../utils/formatters'
import { CURRENCIES } from '../components/Budget/BudgetPanel.constants'
import { convertDistance, getDistanceUnitLabel } from '../utils/units'
import { useSettingsStore } from '../store/settingsStore'
import { useAddonStore } from '../store/addonStore'
@@ -128,9 +131,16 @@ export default function DashboardPage(): React.ReactElement {
const isAddonEnabled = useAddonStore(s => s.isEnabled)
const showCollections = isAddonEnabled('collections') && sideWidgets.collections
// Desktop has a master toggle for the whole right column; off → centered layout.
const widgetPlugins = usePluginStore(s => s.plugins).filter(p => p.type === 'widget' && p.slot !== 'hero')
// Only true dashboard widgets belong here — hero mounts on the boarding pass, and
// place-detail/day-detail widgets live inside the planner panels, not the sidebar.
const widgetPlugins = usePluginStore(s => s.plugins).filter(p => p.type === 'widget' && p.slot !== 'hero' && p.slot !== 'place-detail' && p.slot !== 'day-detail' && p.slot !== 'reservation-detail')
const sidebarVisible = (isMobile || dashCfg.desktop.sidebar) && (showCurrency || showCollections || showTimezones || showUpcoming || widgetPlugins.length > 0)
// Plugin-contributed badges on the trip cards (tripCardProvider hook). One fetch for
// all visible cards; only runs when at least one plugin is active. Fail-safe.
const anyPluginActive = usePluginStore(s => s.plugins).length > 0
const badgesFor = useTripCardBadges(gridTrips.map(t => t.id), anyPluginActive)
return (
<>
{/* Navbar lives outside .trek-dash so it keeps the app-wide font + button
@@ -212,6 +222,7 @@ export default function DashboardPage(): React.ReactElement {
key={trip.id}
trip={trip}
locale={locale}
badges={badgesFor(trip.id)}
onOpen={() => navigate(`/trips/${trip.id}`)}
onEdit={() => { setEditingTrip(trip); setShowForm(true) }}
onCopy={() => setCopyTrip(trip)}
@@ -418,7 +429,9 @@ function BoardingPassHero({ trip, bundle, locale, onOpen, onEdit, onCopy, onArch
))}
</div>
)}
<div className="hero-pass" onClick={(e) => { e.stopPropagation(); onOpen() }}>{passCells}</div>
<div className="hero-pass" onClick={(e) => { e.stopPropagation(); onOpen() }}>
<div className="hero-pass-inner">{passCells}</div>
</div>
</div>
)}
</div>
@@ -526,8 +539,8 @@ function AtlasStats({ stats }: { stats: TravelStats | null }): React.ReactElemen
}
// ── Trip card ────────────────────────────────────────────────────────────────
function TripCard({ trip, locale, onOpen, onEdit, onCopy, onArchive, onDelete }: {
trip: DashboardTrip; locale: string; onOpen: () => void
function TripCard({ trip, locale, badges, onOpen, onEdit, onCopy, onArchive, onDelete }: {
trip: DashboardTrip; locale: string; badges?: TripCardBadge[]; onOpen: () => void
onEdit: () => void; onCopy: () => void; onArchive: () => void; onDelete: () => void
}): React.ReactElement {
const { t } = useTranslation()
@@ -578,14 +591,13 @@ function TripCard({ trip, locale, onOpen, onEdit, onCopy, onArchive, onDelete }:
<div><span className="n mono">{trip.place_count ?? 0}</span><span className="k">{t('dashboard.places')}</span></div>
<div><span className="n mono">{trip.shared_count ?? 0}</span><span className="k">{trip.shared_count === 1 ? t('dashboard.card.buddyOne') : t('dashboard.members')}</span></div>
</div>
<TripCardBadges items={badges ?? []} />
</div>
</article>
)
}
// ── Currency tool (self-contained, mirrors the design's fx widget) ───────────
const FX_FALLBACK = ['EUR', 'USD', 'GBP', 'CHF', 'JPY', 'CAD', 'AUD', 'CNY', 'SEK', 'NOK', 'DKK', 'PLN', 'CZK', 'HUF', 'TRY', 'THB', 'INR', 'BRL', 'MXN', 'ZAR']
function CurrencyTool(): React.ReactElement {
const { t } = useTranslation()
const isLoaded = useSettingsStore(s => s.isLoaded)
@@ -629,7 +641,7 @@ function CurrencyTool(): React.ReactElement {
}).catch(() => { /* keep localStorage; retry on next load */ })
}, [isLoaded, updateSetting])
const currencies = rates ? Object.keys(rates).sort() : FX_FALLBACK
const currencies = rates ? Object.keys(rates).sort() : CURRENCIES
const ccyOptions = currencies.map(c => ({ value: c, label: c }))
const rate = rates?.[to] ?? null
const converted = rate != null ? (parseFloat(amount.replace(',', '.')) || 0) * rate : null
+1 -1
View File
@@ -27,7 +27,7 @@ export default function PluginPage(): React.ReactElement {
return (
<PageShell background="var(--bg-secondary)" navOffset="var(--nav-h, 56px)">
<div style={{ height: 'calc(100vh - var(--nav-h, 56px))' }}>
<PluginFrame pluginId={pluginId} title={plugin?.name} className="w-full h-full" />
<PluginFrame pluginId={pluginId} title={plugin?.name} fill className="w-full h-full" />
</div>
</PageShell>
)
+8 -1
View File
@@ -1,5 +1,5 @@
import React from 'react'
import { Settings, SlidersHorizontal, Paintbrush, Map, Bell, Plug, CloudOff, User, Info } from 'lucide-react'
import { Settings, SlidersHorizontal, Paintbrush, Map, Bell, Plug, CloudOff, User, Info, Blocks } from 'lucide-react'
import { useTranslation } from '../i18n'
import PageShell from '../components/Layout/PageShell'
import PageSidebar, { type PageSidebarTab } from '../components/Layout/PageSidebar'
@@ -11,12 +11,15 @@ import IntegrationsTab from '../components/Settings/IntegrationsTab'
import AccountTab from '../components/Settings/AccountTab'
import AboutTab from '../components/Settings/AboutTab'
import OfflineTab from '../components/Settings/OfflineTab'
import PluginSettingsTab from '../components/Settings/PluginSettingsTab'
import { usePluginStore } from '../store/pluginStore'
import { useSettings } from './settings/useSettings'
export default function SettingsPage(): React.ReactElement {
const { t } = useTranslation()
// Page = wiring container: addon/version loading + active-tab state in the hook.
const { hasIntegrations, appVersion, activeTab, setActiveTab } = useSettings()
const hasPlugins = usePluginStore(s => s.plugins.length > 0)
const tabs: PageSidebarTab[] = [
{ id: 'display', label: t('settings.tabs.display'), icon: SlidersHorizontal },
@@ -26,6 +29,9 @@ export default function SettingsPage(): React.ReactElement {
...(hasIntegrations
? [{ id: 'integrations', label: t('settings.tabs.integrations'), icon: Plug }]
: []),
...(hasPlugins
? [{ id: 'plugins', label: t('settings.tabs.plugins'), icon: Blocks }]
: []),
{ id: 'offline', label: t('settings.tabs.offline'), icon: CloudOff },
{ id: 'account', label: t('settings.tabs.account'), icon: User },
...(appVersion
@@ -60,6 +66,7 @@ export default function SettingsPage(): React.ReactElement {
{activeTab === 'map' && <MapSettingsTab />}
{activeTab === 'notifications' && <NotificationsTab />}
{activeTab === 'integrations' && hasIntegrations && <IntegrationsTab />}
{activeTab === 'plugins' && hasPlugins && <PluginSettingsTab />}
{activeTab === 'offline' && <OfflineTab />}
{activeTab === 'account' && <AccountTab />}
{activeTab === 'about' && appVersion && <AboutTab appVersion={appVersion} />}
+3 -3
View File
@@ -235,7 +235,7 @@ describe('SharedTripPage', () => {
expect(screen.getByText('Shared Paris Trip')).toBeInTheDocument();
});
const budgetTab = screen.getByRole('button', { name: /budget/i });
const budgetTab = screen.getByRole('button', { name: /costs/i });
expect(budgetTab).toBeInTheDocument();
fireEvent.click(budgetTab);
@@ -532,7 +532,7 @@ describe('SharedTripPage', () => {
renderSharedTrip('cad-token');
await waitFor(() => expect(screen.getByText('Shared Paris Trip')).toBeInTheDocument());
fireEvent.click(screen.getByRole('button', { name: /budget/i }));
fireEvent.click(screen.getByRole('button', { name: /costs/i }));
await waitFor(() => expect(screen.getByText('Hotel')).toBeInTheDocument());
// Total + per-row labelled CAD; never the EUR fallback.
@@ -565,7 +565,7 @@ describe('SharedTripPage', () => {
renderSharedTrip('mixed-token');
await waitFor(() => expect(screen.getByText('Shared Paris Trip')).toBeInTheDocument());
fireEvent.click(screen.getByRole('button', { name: /budget/i }));
fireEvent.click(screen.getByRole('button', { name: /costs/i }));
await waitFor(() => expect(screen.getByText('Dinner')).toBeInTheDocument());
// 100 EUR / 0.8 = 125.00 NZD once the rate resolves.
+1 -1
View File
@@ -143,7 +143,7 @@ export default function SharedTripPage() {
{/* Tabs */}
<div style={{ display: 'flex', gap: 6, marginBottom: 20, overflowX: 'auto', padding: '2px 0' }}>
{[
{ id: 'plan', label: t('shared.tabPlan'), Icon: Map },
...(permissions?.share_map !== false ? [{ id: 'plan', label: t('shared.tabPlan'), Icon: Map }] : []),
...(permissions?.share_bookings ? [{ id: 'bookings', label: t('shared.tabBookings'), Icon: Ticket }] : []),
...(permissions?.share_packing ? [{ id: 'packing', label: t('shared.tabPacking'), Icon: Luggage }] : []),
...(permissions?.share_budget ? [{ id: 'budget', label: t('shared.tabBudget'), Icon: Wallet }] : []),
+38
View File
@@ -6,6 +6,7 @@ import { resetAllStores, seedStore } from '../../tests/helpers/store';
import { buildUser, buildTrip, buildDay, buildPlace, buildAssignment } from '../../tests/helpers/factories';
import { useAuthStore } from '../store/authStore';
import { useTripStore } from '../store/tripStore';
import { usePluginStore } from '../store/pluginStore';
import TripPlannerPage from './TripPlannerPage';
import { server } from '../../tests/helpers/msw/server';
import { http, HttpResponse } from 'msw';
@@ -1336,6 +1337,43 @@ describe('TripPlannerPage', () => {
});
});
describe('FE-PAGE-PLANNER-048: trip-page plugins can replace core tabs and pick a position', () => {
afterEach(() => usePluginStore.setState({ plugins: [], loaded: false }));
it('hides the replaced core tab and splices the plugin tab at its position', async () => {
usePluginStore.setState({
plugins: [{ id: 'transit-pro', name: 'Transit Pro', type: 'trip-page', icon: null, tripPage: { replaces: ['transports'], position: 1 } }],
loaded: true,
});
seedTripStore({ id: 42 });
renderPlannerPage(42);
// the plugin tab is present, the replaced Transports tab is not (the splash
// screen holds the page for 1.5s, so give the query room)
const pluginTab = await screen.findByTitle('Transit Pro', {}, { timeout: 4000 });
expect(pluginTab).toBeInTheDocument();
expect(screen.queryByTitle('Transports')).not.toBeInTheDocument();
// an unreplaced core tab stays reachable
expect(screen.getByTitle('Bookings')).toBeInTheDocument();
});
it('a saved session tab that a plugin replaced resets to plan once plugins load', async () => {
sessionStorage.setItem('trip-tab-42', 'transports');
usePluginStore.setState({
plugins: [{ id: 'transit-pro', name: 'Transit Pro', type: 'trip-page', icon: null, tripPage: { replaces: ['transports'] } }],
loaded: true,
});
seedTripStore({ id: 42 });
renderPlannerPage(42);
await waitFor(() => {
expect(sessionStorage.getItem('trip-tab-42')).toBe('plan');
});
});
});
describe('FE-PAGE-PLANNER-047: Desktop PlaceInspector onEdit with selectedAssignment', () => {
it('calls onEdit on desktop PlaceInspector with selectedAssignmentId to cover if-branch', async () => {
vi.useFakeTimers();
+10 -7
View File
@@ -183,7 +183,7 @@ export default function TripPlannerPage(): React.ReactElement | null {
selectedDayId, isLoading, tripActions, can, canUploadFiles,
pushUndo, undo, canUndo, lastActionLabel, handleUndo,
enabledAddons, collabFeatures, tripAccommodations, setTripAccommodations,
allowedFileTypes, tripMembers, setTripMembers, loadAccommodations,
allowedFileTypes, tripMembers, setTripMembers, refreshMembers, loadAccommodations,
TRANSPORT_TYPES, TRIP_TABS, activeTab, setActiveTab, handleTabChange,
leftWidth, rightWidth, leftCollapsed, rightCollapsed, setLeftCollapsed, setRightCollapsed, startResizeLeft, startResizeRight,
selectedPlaceId, selectedAssignmentId, setSelectedPlaceId, selectAssignment,
@@ -300,12 +300,14 @@ export default function TripPlannerPage(): React.ReactElement | null {
{/* Offset by navbar + tab bar (44px) */}
<div style={{ position: 'fixed', top: 'calc(var(--nav-h) + 44px)', left: 0, right: 0, bottom: 0, overflow: 'hidden', overscrollBehavior: 'contain' }}>
{/* Plugin validation/warning contributions (#1429) — non-blocking overlay. */}
<TripWarningsBanner tripId={tripId} />
{/* Plugin validation/warning contributions (#1429) — navbar chips for
plugins with a tab here, floating bottom overlay for the rest. */}
<TripWarningsBanner tripId={tripId} onOpenPluginTab={(pid) => handleTabChange(`plugin:${pid}`)} />
{activeTab === 'plan' && (
<div style={{ position: 'absolute', inset: 0 }}>
<MapView
tripId={tripId}
places={mapPlaces}
dayPlaces={dayPlaces}
route={route}
@@ -628,7 +630,7 @@ export default function TripPlannerPage(): React.ReactElement | null {
<X size={14} />
</button>
</div>
<div style={{ flex: 1, overflow: 'auto' }}>
<div style={{ flex: 1, overflow: 'auto', paddingBottom: 'env(safe-area-inset-bottom, 0px)' }}>
{mobileSidebarOpen === 'left'
? <DayPlanSidebar tripId={tripId} trip={trip} days={days} places={places} categories={categories} assignments={assignments} selectedDayId={selectedDayId} selectedPlaceId={selectedPlaceId} selectedAssignmentId={selectedAssignmentId} onSelectDay={(id) => { handleSelectDay(id); setMobileSidebarOpen(null) }} onPlaceClick={(placeId, assignmentId) => { handlePlaceClick(placeId, assignmentId) }} onReorder={handleReorder} onReorderDays={handleReorderDays} onAddDay={handleAddDay} onUpdateDayTitle={handleUpdateDayTitle} onAssignToDay={handleAssignToDay} onRouteCalculated={(r) => { if (r) { setRoute([r.coordinates]); setRouteInfo(r) } }} reservations={reservations} visibleConnectionIds={visibleConnections} onToggleConnection={toggleConnection} onAddReservation={(dayId) => { setEditingReservation(null); tripActions.setSelectedDay(dayId); setShowReservationModal(true); setMobileSidebarOpen(null) }} onAddTransport={can('day_edit', trip) ? (dayId) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill(null); setTransportModalAutomated(false); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onOpenTransit={(r) => { setTransitJourney(r); setMobileSidebarOpen(null) }} onPlanTransit={can('day_edit', trip) ? (dayId) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill(null); setTransportModalAutomated(true); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onAddPlace={() => { setEditingPlace(null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onDayDetail={(day) => { setShowDayDetail(day); setSelectedPlaceId(null); selectAssignment(null) }} onRemoveAssignment={handleRemoveAssignment} onEditPlace={(place, assignmentId) => { setEditingPlace(place); setEditingAssignmentId(assignmentId || null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onDeletePlace={(placeId) => handleDeletePlace(placeId)} accommodations={tripAccommodations} routeShown={routeShown} routeProfile={routeProfile} onToggleRoute={() => setRouteShown(v => !v)} onSetRouteProfile={setRouteProfile} onNavigateToFiles={() => { setMobileSidebarOpen(null); handleTabChange('dateien') }} onExpandedDaysChange={setExpandedDayIds} pushUndo={pushUndo} canUndo={canUndo} lastActionLabel={lastActionLabel} onUndo={handleUndo} onEditTransport={can('day_edit', trip) ? (reservation) => { setEditingTransport(reservation); setTransportModalDayId(reservation.day_id ?? null); setShowTransportModal(true); setMobileSidebarOpen(null) } : undefined} onEditReservation={can('reservation_edit', trip) ? (r) => { setEditingReservation(r); setShowReservationModal(true); setMobileSidebarOpen(null) } : undefined} initialScrollTop={mobilePlanScrollTopRef.current} onScrollTopChange={(top) => { mobilePlanScrollTopRef.current = top }} showRouteToolsWhenExpanded isMobile />
: <PlacesSidebar tripId={tripId} places={places} categories={categories} assignments={assignments} selectedDayId={selectedDayId} selectedPlaceId={selectedPlaceId} onPlaceClick={(placeId) => { handlePlaceClick(placeId); setMobileSidebarOpen(null) }} onAddPlace={() => { setEditingPlace(null); setShowPlaceForm(true); setMobileSidebarOpen(null) }} onAssignToDay={handleAssignToDay} onEditPlace={(place) => { openPlaceEditor(place); setMobileSidebarOpen(null) }} onDeletePlace={(placeId) => handleDeletePlace(placeId)} onBulkDeletePlaces={(ids) => setDeletePlaceIds(ids)} onBulkDeleteConfirm={(ids) => confirmDeletePlaces(ids)} onBulkChangeCategory={(ids, catId) => confirmChangeCategory(ids, catId)} days={days} isMobile onCategoryFilterChange={setMapCategoryFilter} onPlacesFilterChange={setMapPlacesFilter} pushUndo={pushUndo} initialScrollTop={mobilePlacesScrollTopRef.current} onScrollTopChange={(top) => { mobilePlacesScrollTopRef.current = top }} />
@@ -659,6 +661,7 @@ export default function TripPlannerPage(): React.ReactElement | null {
onNavigateToFiles={() => handleTabChange('dateien')}
titleKey="transport.title"
addManualKey="transport.addManual"
contributionView="transports"
/>
</div>
)}
@@ -718,7 +721,7 @@ export default function TripPlannerPage(): React.ReactElement | null {
{activeTab.startsWith('plugin:') && (
<div style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 'var(--bottom-nav-h)', overflow: 'hidden' }}>
<PluginFrame pluginId={activeTab.slice('plugin:'.length)} tripId={String(tripId)} className="w-full h-full" />
<PluginFrame pluginId={activeTab.slice('plugin:'.length)} tripId={String(tripId)} fill className="w-full h-full" />
</div>
)}
</div>
@@ -731,9 +734,9 @@ export default function TripPlannerPage(): React.ReactElement | null {
trip={trip}
onCoverUpdate={(_, coverUrl) => useTripStore.setState(state => ({ trip: state.trip ? { ...state.trip, cover_image: coverUrl } : state.trip }))}
/>
<TripMembersModal isOpen={showMembersModal} onClose={() => setShowMembersModal(false)} tripId={tripId} tripTitle={trip?.title} />
<TripMembersModal isOpen={showMembersModal} onClose={() => setShowMembersModal(false)} tripId={tripId} tripTitle={trip?.title} onMembersChanged={refreshMembers} />
<ReservationModal isOpen={showReservationModal} onClose={() => { if (importReviewActive) { advanceImportReview() } else { setShowReservationModal(false); setEditingReservation(null); setBookingForAssignmentId(null) } }} onSave={async (data) => { const r = await handleSaveReservation(data); if (importReviewActive && r) advanceImportReview(); return r }} reservation={editingReservation} prefill={reservationPrefill} days={days} places={places} assignments={assignments} selectedDayId={selectedDayId} files={files} onFileUpload={canUploadFiles ? (fd) => tripActions.addFile(tripId, fd) : undefined} onFileDelete={(id) => tripActions.deleteFile(tripId, id)} accommodations={tripAccommodations} defaultAssignmentId={bookingForAssignmentId} onOpenExpense={openBookingExpense} />
{showTransportModal && <TransportModal isOpen={showTransportModal} onClose={() => { if (importReviewActive) { advanceImportReview() } else { setShowTransportModal(false); setEditingTransport(null); setTransportModalDayId(null); setTransportModalAutomated(false); setTransitPrefill(null) } }} onSave={async (data) => { const r = await handleSaveTransport(data); if (importReviewActive && r) advanceImportReview(); return r }} reservation={editingTransport} prefill={transportPrefill} days={days} selectedDayId={transportModalDayId} files={files} onFileUpload={canUploadFiles ? (fd) => tripActions.addFile(tripId, fd) : undefined} onFileDelete={(id) => tripActions.deleteFile(tripId, id)} onOpenExpense={openBookingExpense} places={places} accommodations={tripAccommodations} initialAutomated={transportModalAutomated} transitPrefill={transitPrefill} />}
{showTransportModal && <TransportModal isOpen={showTransportModal} onClose={() => { if (importReviewActive) { advanceImportReview() } else { setShowTransportModal(false); setEditingTransport(null); setTransportModalDayId(null); setTransportModalAutomated(false); setTransitPrefill(null) } }} onSave={async (data) => { const r = await handleSaveTransport(data); if (importReviewActive && r) advanceImportReview(); return r }} reservation={editingTransport} prefill={transportPrefill} days={days} selectedDayId={transportModalDayId} files={files} onFileUpload={canUploadFiles ? (fd) => tripActions.addFile(tripId, fd) : undefined} onFileDelete={(id) => tripActions.deleteFile(tripId, id)} onOpenExpense={openBookingExpense} places={places} assignments={assignments} accommodations={tripAccommodations} initialAutomated={transportModalAutomated} transitPrefill={transitPrefill} />}
{/* Journey view for a saved public-transit entry (#1065) */}
{transitJourney && (
<TransitJourneyModal
+20
View File
@@ -0,0 +1,20 @@
import { describe, it, expect } from 'vitest';
import { normalizeRegionName } from './atlasModel';
describe('normalizeRegionName', () => {
it('matches names that only differ by diacritics (Ile-de-France vs Île-de-France)', () => {
expect(normalizeRegionName('Ile-de-France')).toBe(normalizeRegionName('Île-de-France'));
});
it('matches names that only differ by dash style and surrounding spaces', () => {
expect(normalizeRegionName('Bourgogne – Franche-Comté')).toBe(normalizeRegionName('Bourgogne-Franche-Comté'));
});
it('is case-insensitive', () => {
expect(normalizeRegionName('PROVENCE')).toBe(normalizeRegionName('provence'));
});
it('still distinguishes genuinely different names', () => {
expect(normalizeRegionName('Bretagne')).not.toBe(normalizeRegionName('Brittany'));
});
});
+14
View File
@@ -50,6 +50,20 @@ export interface BucketItem {
target_date: string | null
}
// Normalize a region name for matching: strip diacritics (the geocoder and the
// bundled boundaries don't always agree on accenting, e.g. "Ile-de-France" vs
// "Île-de-France") and fold dash variants (en/em dash vs hyphen) to a plain
// hyphen, then lowercase. Used to compare a place's cached region_name against
// the admin-1 GeoJSON's name/name_en when the region code itself doesn't match.
export function normalizeRegionName(name: string): string {
return name
.normalize('NFD').replace(/[̀-ͯ]/g, '') // strip combining diacritics
.replace(/[‐-―]/g, '-') // fold hyphen/dash variants to "-"
.replace(/\s*-\s*/g, '-') // collapse spaced dashes ("A – B" vs "A-B")
.toLowerCase()
.trim()
}
// Convert country code to flag emoji
export function countryCodeToFlag(code: string): string {
if (!code || code.length !== 2) return ''
+65 -9
View File
@@ -2,10 +2,10 @@ import React, { useEffect, useMemo, useState, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { getIntlLanguage, getLocaleForLanguage, useTranslation } from '../../i18n'
import { useSettingsStore } from '../../store/settingsStore'
import apiClient, { mapsApi } from '../../api/client'
import apiClient, { mapsApi, pluginsApi, type PluginAtlasLayer } from '../../api/client'
import L from 'leaflet'
import type { GeoJsonFeatureCollection } from '../../types'
import { A2_TO_A3, type AtlasData, type CountryDetail, type BucketItem } from './atlasModel'
import { A2_TO_A3, normalizeRegionName, type AtlasData, type CountryDetail, type BucketItem } from './atlasModel'
import { continentForCountry } from '@trek/shared'
function useCountryNames(language: string): (code: string) => string {
@@ -68,6 +68,8 @@ export function useAtlas() {
const [countryDetail, setCountryDetail] = useState<CountryDetail | null>(null)
const [geoData, setGeoData] = useState<GeoJsonFeatureCollection | null>(null)
const [visitedRegions, setVisitedRegions] = useState<Record<string, { code: string; name: string; placeCount: number; manuallyMarked?: boolean }[]>>({})
const [pluginLayers, setPluginLayers] = useState<PluginAtlasLayer[]>([])
const pluginLayerRef = useRef<L.GeoJSON | null>(null)
const regionLayerRef = useRef<L.GeoJSON | null>(null)
const regionGeoCache = useRef<Record<string, GeoJsonFeatureCollection>>({})
const [showRegions, setShowRegions] = useState(false)
@@ -165,6 +167,14 @@ export function useAtlas() {
.catch(() => {})
}, [])
// Load plugin tint layers (atlasLayerProvider hook) — once on mount. Fail-safe:
// an error just means no plugin overlay, the core map is untouched.
useEffect(() => {
pluginsApi.atlasLayers()
.then(r => setPluginLayers(r.layers || []))
.catch(() => setPluginLayers([]))
}, [])
// Load admin-1 GeoJSON for countries visible in the current viewport
const loadRegionsForViewportRef = useRef<() => void>(() => {})
const loadRegionsForViewport = (): void => {
@@ -388,6 +398,49 @@ export function useAtlas() {
mapInstance.current.setView(currentCenter, currentZoom, { animate: false })
}, [geoData, data, dark])
// Render plugin tint layers (atlasLayerProvider hook) — a dashed wash over the
// countries a plugin flagged, in its own non-interactive pane above the country
// fills. pointer-events stay off so clicks/hovers fall through to the country
// layer and the mark/unmark flows are untouched.
useEffect(() => {
if (!mapInstance.current) return
if (pluginLayerRef.current) {
mapInstance.current.removeLayer(pluginLayerRef.current)
pluginLayerRef.current = null
}
if (!geoData || pluginLayers.length === 0) return
// Same tone palette as the plugin map markers; the last layer naming a country wins.
const TONE_COLORS: Record<string, string> = { default: '#4F46E5', success: '#10b981', warn: '#f59e0b', danger: '#ef4444' }
const toneByA3: Record<string, string> = {}
for (const layer of pluginLayers) {
for (const c of layer.countries) {
const a3 = A2_TO_A3[c.code]
if (a3) toneByA3[a3] = c.tone || 'default'
}
}
const featureA3 = (f: any) => f?.properties?.ADM0_A3 || f?.properties?.ISO_A3 || f?.properties?.['ISO3166-1-Alpha-3'] || f?.id
const features = ((geoData as any).features || []).filter((f: any) => toneByA3[featureA3(f)] !== undefined)
if (features.length === 0) return
if (!mapInstance.current.getPane('atlasPluginPane')) {
mapInstance.current.createPane('atlasPluginPane')
const pane = mapInstance.current.getPane('atlasPluginPane')!
pane.style.zIndex = '402'
pane.style.pointerEvents = 'none'
}
pluginLayerRef.current = L.geoJSON({ type: 'FeatureCollection', features } as any, {
pane: 'atlasPluginPane',
interactive: false,
style: (feature) => {
const color = TONE_COLORS[toneByA3[featureA3(feature)]] || TONE_COLORS.default
return { fillColor: color, fillOpacity: 0.18, color, weight: 1.4, dashArray: '4 3' }
},
} as L.GeoJSONOptions).addTo(mapInstance.current)
// `loading` is a dep because the map itself is created once loading flips —
// layers fetched before that would otherwise never get drawn.
}, [geoData, pluginLayers, dark, loading])
// Render sub-national region layer (zoom >= 5)
useEffect(() => {
if (!mapInstance.current) return
@@ -408,22 +461,25 @@ export function useAtlas() {
const names = new Set<string>()
for (const r of regions) {
visitedRegionCodes.add(r.code)
names.add(r.name.toLowerCase())
names.add(normalizeRegionName(r.name))
regionPlaceCounts[r.code] = r.placeCount
regionPlaceCounts[`${countryCode}:${r.name.toLowerCase()}`] = r.placeCount
regionPlaceCounts[`${countryCode}:${normalizeRegionName(r.name)}`] = r.placeCount
}
visitedRegionNamesByCountry.set(countryCode, names)
}
// Match feature by ISO code OR region name scoped to the feature's country
// Match feature by ISO code OR region name scoped to the feature's country. Names are
// normalized (diacritics/dash variants folded) since the geocoder's cached region_name
// and the bundled boundaries' name don't always agree on accenting (e.g. a cached
// "Ile-de-France" must still match the bundle's "Île-de-France") (#atlas-region-match).
const isVisitedFeature = (f: any) => {
if (visitedRegionCodes.has(f.properties?.iso_3166_2)) return true
const countryA2 = (f.properties?.iso_a2 || '').toUpperCase()
const countryNames = visitedRegionNamesByCountry.get(countryA2)
if (!countryNames) return false
const name = (f.properties?.name || '').toLowerCase()
const name = normalizeRegionName(f.properties?.name || '')
if (countryNames.has(name)) return true
const nameEn = (f.properties?.name_en || '').toLowerCase()
const nameEn = normalizeRegionName(f.properties?.name_en || '')
if (nameEn && countryNames.has(nameEn)) return true
return false
}
@@ -476,11 +532,11 @@ export function useAtlas() {
const regionCode = feature?.properties?.iso_3166_2 || ''
const countryA2 = (feature?.properties?.iso_a2 || '').toUpperCase()
const visited = isVisitedFeature(feature)
const count = regionPlaceCounts[regionCode] || regionPlaceCounts[`${countryA2}:${regionName.toLowerCase()}`] || regionPlaceCounts[`${countryA2}:${regionNameEn.toLowerCase()}`] || 0
const count = regionPlaceCounts[regionCode] || regionPlaceCounts[`${countryA2}:${normalizeRegionName(regionName)}`] || regionPlaceCounts[`${countryA2}:${normalizeRegionName(regionNameEn)}`] || 0
layer.on('click', () => {
if (!countryA2) return
if (visited) {
const regionEntry = visitedRegions[countryA2]?.find(r => r.code === regionCode || r.name.toLowerCase() === regionNameEn.toLowerCase())
const regionEntry = visitedRegions[countryA2]?.find(r => r.code === regionCode || normalizeRegionName(r.name) === normalizeRegionName(regionNameEn))
if (regionEntry?.manuallyMarked) {
setConfirmActionRef.current({
type: 'unmark-region',
@@ -25,6 +25,20 @@ export function useSharedTrip() {
shareApi.getSharedTrip(token).then(setData).catch(() => setError(true))
}, [token])
// The server now withholds the whole itinerary when the owner disabled the map
// (share_map=false), so the Plan tab has nothing to show — land on the first
// section the owner actually shared instead of an empty map.
useEffect(() => {
if (!data) return
const p = data.permissions || {}
if (p.share_map === false && activeTab === 'plan') {
setActiveTab(
p.share_bookings ? 'bookings' : p.share_packing ? 'packing' : p.share_budget ? 'budget' : p.share_collab ? 'collab' : 'plan'
)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [data])
// Budget display currency = what the share owner sees in Costs (embedded in the
// payload as baseCurrency), falling back to the trip's own currency, then EUR.
// Convert every expense into it via live FX, mirroring CostsPanel — a public
+38 -8
View File
@@ -77,6 +77,16 @@ export function useTripPlanner() {
const [allowedFileTypes, setAllowedFileTypes] = useState<string | null>(null)
const [tripMembers, setTripMembers] = useState<TripMember[]>([])
// Re-fetch the trip roster so consumers (Costs participants, Collab, …) pick up a
// just-added guest or member without a full page reload.
const refreshMembers = useCallback(() => {
if (!tripId || isEffectivelyOffline()) return
tripsApi.getMembers(tripId).then(d => {
const all = [d.owner, ...(d.members || [])].filter(Boolean)
setTripMembers(all)
}).catch(() => {})
}, [tripId])
const loadAccommodations = useCallback(() => {
if (tripId) {
accommodationRepo.list(tripId).then(d => setTripAccommodations(d.accommodations || [])).catch(() => {})
@@ -101,6 +111,9 @@ export function useTripPlanner() {
const tripPagePlugins = allPlugins.filter(p => p.type === 'trip-page')
const tripPluginIds = tripPagePlugins.map(p => p.id).join(',')
// A trip-page plugin may replace core tabs while it's active (its manifest names
// them; 'plan' is never replaceable) and may pick where its own tab sits.
const replacedTabs = new Set(tripPagePlugins.flatMap(p => p.tripPage?.replaces ?? []))
const TRIP_TABS = [
{ id: 'plan', label: t('trip.tabs.plan'), icon: Map },
{ id: 'transports', label: t('trip.tabs.transports'), icon: Train },
@@ -109,8 +122,12 @@ export function useTripPlanner() {
...(enabledAddons.budget ? [{ id: 'finanzplan', label: t('trip.tabs.budget'), icon: Wallet }] : []),
...(enabledAddons.documents ? [{ id: 'dateien', label: t('trip.tabs.files'), icon: FolderOpen }] : []),
...(enabledAddons.collab ? [{ id: 'collab', label: t('admin.addons.catalog.collab.name'), icon: Users }] : []),
...tripPagePlugins.map(p => ({ id: `plugin:${p.id}`, label: p.name, icon: Blocks })),
]
].filter(tab => tab.id === 'plan' || !replacedTabs.has(tab.id))
// Positioned plugin tabs splice in ascending order so two positions stay stable;
// the rest append, exactly as before this capability existed.
const positioned = tripPagePlugins.filter(p => p.tripPage?.position != null).sort((a, b) => (a.tripPage!.position! - b.tripPage!.position!))
for (const p of positioned) TRIP_TABS.splice(Math.min(p.tripPage!.position!, TRIP_TABS.length), 0, { id: `plugin:${p.id}`, label: p.name, icon: Blocks })
for (const p of tripPagePlugins.filter(p => p.tripPage?.position == null)) TRIP_TABS.push({ id: `plugin:${p.id}`, label: p.name, icon: Blocks })
const [activeTab, setActiveTab] = useState<string>(() => {
const saved = sessionStorage.getItem(`trip-tab-${tripId}`)
@@ -127,7 +144,11 @@ export function useTripPlanner() {
}
}, [enabledAddons, tripPluginIds, pluginsLoaded])
const handleTabChange = (tabId: string): void => {
const handleTabChange = (rawTabId: string): void => {
// A core tab a plugin replaced is gone from the bar, but a programmatic jump
// (e.g. onNavigateToFiles) could still target it and render a dead panel with
// no active pill — fall back to the plan view like the invalid-tab guard does.
const tabId = replacedTabs.has(rawTabId) ? 'plan' : rawTabId
setActiveTab(tabId)
sessionStorage.setItem(`trip-tab-${tripId}`, tabId)
if (tabId === 'finanzplan') tripActions.loadBudgetItems?.(tripId)
@@ -275,10 +296,7 @@ export function useTripPlanner() {
.then(rows => setTripMembers(rows))
.catch(() => {})
} else {
tripsApi.getMembers(tripId).then(d => {
const all = [d.owner, ...(d.members || [])].filter(Boolean)
setTripMembers(all)
}).catch(() => {})
refreshMembers()
}
}
}, [tripId])
@@ -652,6 +670,18 @@ export function useTripPlanner() {
acc.place_id = (await resolveImportedPlace(acc.venue)) ?? undefined
delete acc.venue
}
// A hotel's address lives on the linked place. Write an edited address
// through to it, otherwise the typed value was silently dropped and the
// old one reappeared on the next open (#1496).
if (data.type === 'hotel' && acc && typeof acc.address === 'string') {
const address = acc.address.trim()
const linkedPlace = acc.place_id ? places.find(p => p.id === Number(acc.place_id)) : undefined
if (address && linkedPlace && (linkedPlace.address || '') !== address) {
try { await tripActions.updatePlace(tripId, linkedPlace.id, { address }) }
catch { /* keep saving the booking; the address still lands in location */ }
}
delete acc.address
}
if (editingReservation) {
// Don't force a day here. The old code pinned it to the (often empty)
// selected day, which dropped the booking out of the Plan; preserving the
@@ -860,7 +890,7 @@ export function useTripPlanner() {
selectedDayId, isLoading, tripActions, can, canUploadFiles,
pushUndo, undo, canUndo, lastActionLabel, handleUndo,
enabledAddons, collabFeatures, tripAccommodations, setTripAccommodations,
allowedFileTypes, tripMembers, setTripMembers, loadAccommodations,
allowedFileTypes, tripMembers, setTripMembers, refreshMembers, loadAccommodations,
TRANSPORT_TYPES, TRIP_TABS, activeTab, setActiveTab, handleTabChange,
leftWidth, rightWidth, leftCollapsed, rightCollapsed, setLeftCollapsed, setRightCollapsed, startResizeLeft, startResizeRight,
selectedPlaceId, selectedAssignmentId, setSelectedPlaceId, selectAssignment,
+6 -2
View File
@@ -12,7 +12,11 @@ export interface ActivePlugin {
name: string
type: 'integration' | 'page' | 'widget' | 'trip-page'
icon: string | null
slot?: 'sidebar' | 'hero' | 'place-detail'
slot?: 'sidebar' | 'hero' | 'place-detail' | 'day-detail' | 'reservation-detail'
/** How a trip-page plugin sits in the planner tab bar: which core tabs it
* replaces while active ('plan' never — enforced server-side) and its
* preferred 0-based tab index. */
tripPage?: { replaces?: string[]; position?: number }
}
interface PluginState {
@@ -42,7 +46,7 @@ export const usePluginStore = create<PluginState>((set, get) => ({
getById: (id) => get().plugins.find((p) => p.id === id),
pages: () => get().plugins.filter((p) => p.type === 'page'),
widgets: () => get().plugins.filter((p) => p.type === 'widget' && p.slot !== 'hero' && p.slot !== 'place-detail'),
widgets: () => get().plugins.filter((p) => p.type === 'widget' && p.slot !== 'hero' && p.slot !== 'place-detail' && p.slot !== 'day-detail' && p.slot !== 'reservation-detail'),
heroWidgets: () => get().plugins.filter((p) => p.type === 'widget' && p.slot === 'hero'),
tripPages: () => get().plugins.filter((p) => p.type === 'trip-page'),
placeDetailWidgets: () => get().plugins.filter((p) => p.type === 'widget' && p.slot === 'place-detail'),
+34 -11
View File
@@ -227,7 +227,21 @@
.trek-dash .hero-title { font-size: 104px; font-weight: 600; line-height: 0.9; letter-spacing: -0.045em; margin: 0; text-shadow: 0 1px 12px oklch(0 0 0 / .32), 0 1px 3px oklch(0 0 0 / .4); }
/* ----------------- boarding pass ----------------- */
/* The pass is split into an outer wrapper (left notch) and an inner glass panel
(right notch). Each element carries a SINGLE-layer radial-gradient mask so we
never rely on multi-layer `mask-composite: intersect` — Safari mis-composites
that path and hides the whole bar (issue #1459). */
.trek-dash .hero-pass {
position: relative;
/* Match the inner panel's radius: the mask + translateZ promotes this wrapper to
its own compositing layer whose bounds are otherwise square, which showed as a
square edge over the rounded glass panel (regression from the #1459 mask split). */
border-radius: 24px;
-webkit-mask-image: radial-gradient(circle 8px at 0 50%, transparent 8px, black 8px);
mask-image: radial-gradient(circle 8px at 0 50%, transparent 8px, black 8px);
transform: translateZ(0);
}
.trek-dash .hero-pass-inner {
background: linear-gradient(135deg,
oklch(0.99 0.006 75 / .75) 0%, oklch(0.985 0.008 70 / .85) 50%, oklch(0.98 0.01 65 / .8) 100%);
backdrop-filter: blur(40px) saturate(1.8) brightness(1.1);
@@ -239,24 +253,17 @@
0 2px 8px -2px oklch(0 0 0 / .08), 0 8px 24px -6px oklch(0 0 0 / .12),
0 20px 60px -16px oklch(0 0 0 / .35), inset 0 1px 1px 0 oklch(1 0 0 / .5);
color: var(--ink); position: relative; overflow: hidden;
mask-image:
radial-gradient(circle 8px at 0 50%, transparent 8px, black 8px),
radial-gradient(circle 8px at 100% 50%, transparent 8px, black 8px);
mask-composite: intersect;
-webkit-mask-image:
radial-gradient(circle 8px at 0 50%, transparent 8px, black 8px),
radial-gradient(circle 8px at 100% 50%, transparent 8px, black 8px);
-webkit-mask-composite: source-in;
transform: translateZ(0);
-webkit-mask-image: radial-gradient(circle 8px at 100% 50%, transparent 8px, black 8px);
mask-image: radial-gradient(circle 8px at 100% 50%, transparent 8px, black 8px);
}
.dark .trek-dash .hero-pass {
.dark .trek-dash .hero-pass-inner {
background: linear-gradient(135deg, oklch(0.28 0 0 / .8) 0%, oklch(0.25 0 0 / .85) 50%, oklch(0.23 0 0 / .8) 100%);
border: 1px solid oklch(1 0 0 / .1);
box-shadow:
0 2px 8px -2px oklch(0 0 0 / .3), 0 8px 24px -6px oklch(0 0 0 / .4),
0 20px 60px -16px oklch(0 0 0 / .6), inset 0 1px 1px 0 oklch(1 0 0 / .08);
}
.trek-dash .hero-pass::before {
.trek-dash .hero-pass-inner::before {
content: ""; position: absolute; inset: 0; border-radius: 24px; padding: 1px;
background: linear-gradient(135deg, oklch(1 0 0 / .25) 0%, oklch(1 0 0 / .08) 40%, oklch(1 0 0 / .02) 70%, oklch(1 0 0 / .15) 100%);
-webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
@@ -453,6 +460,22 @@
.trek-dash .trip-meta div { display: flex; flex-direction: column; gap: 3px; text-align: center; }
.trek-dash .trip-meta .n { font-size: 17px; font-weight: 600; letter-spacing: -0.02em; }
.trek-dash .trip-meta .k { font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.1em; color: var(--ink-3); font-weight: 500; }
/* Plugin-contributed badges (tripCardProvider hook) — small text chips under the meta row. */
.trek-dash .trip-plugin-badges { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 14px; }
.trek-dash .trip-plugin-badge {
display: inline-flex; align-items: center; gap: 5px; max-width: 100%;
padding: 3px 9px; border-radius: 999px; font-size: 11.5px; font-weight: 500; line-height: 1.4;
border: 1px solid var(--line); background: var(--surface-2); color: var(--ink-2); text-decoration: none;
}
.trek-dash a.trip-plugin-badge:hover { border-color: var(--ink-3); }
.trek-dash .trip-plugin-badge .badge-label { color: var(--ink); font-weight: 600; }
.trek-dash .trip-plugin-badge .badge-value { color: var(--ink-2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.trek-dash .trip-plugin-badge.tone-success { border-color: color-mix(in oklch, var(--success) 40%, var(--line)); }
.trek-dash .trip-plugin-badge.tone-success .badge-label { color: var(--success); }
.trek-dash .trip-plugin-badge.tone-warn { border-color: color-mix(in oklch, var(--warn) 45%, var(--line)); }
.trek-dash .trip-plugin-badge.tone-warn .badge-label { color: var(--warn); }
.trek-dash .trip-plugin-badge.tone-danger { border-color: color-mix(in oklch, oklch(0.6 0.2 25) 45%, var(--line)); }
.trek-dash .trip-plugin-badge.tone-danger .badge-label { color: oklch(0.6 0.2 25); }
.trek-dash .add-trip-card {
border-radius: var(--r-xl); border: 1.5px dashed var(--line-2);
background: var(--glass-bg); display: grid; place-items: center;
+28
View File
@@ -0,0 +1,28 @@
declare module 'iso-3166-2' {
interface Subdivision {
type: string
name: string
}
interface SubdivisionDetail extends Subdivision {
countryName: string
countryCode: string
code: string
regionCode: string
}
interface Country {
name: string
sub: Record<string, Subdivision>
}
interface Iso31662 {
/** Look up a country by ISO 3166-1 alpha-2 code (e.g. 'US'). */
country(code: string): Country | undefined
/** Look up a subdivision by full ISO 3166-2 code (e.g. 'US-WA'). */
subdivision(code: string): SubdivisionDetail | undefined
}
const iso31662: Iso31662
export default iso31662
}
+81 -1
View File
@@ -1,6 +1,6 @@
import { describe, it, expect } from 'vitest'
import type { Day, Accommodation } from '../types'
import { getDayOrder, isDayInAccommodationRange, getAccommodationAnchors, getDayBookendHotels } from './dayOrder'
import { getDayOrder, isDayInAccommodationRange, getAccommodationAnchors, getDayBookendHotels, shouldDrawMorningLeg, shouldDrawEveningLeg } from './dayOrder'
const days = [
{ id: 10, day_number: 1 },
@@ -154,3 +154,83 @@ describe('getDayBookendHotels', () => {
expect(r.eveningIsOvernight).toBe(true)
})
})
describe('shouldDrawMorningLeg', () => {
const checkInDay = days[0] // id 10
const into = (over: Partial<Accommodation> = {}) =>
hotel({ start_day_id: 10, end_day_id: 30, check_in: '15:00', ...over })
it('draws when you slept in the morning hotel, regardless of stop time', () => {
const bookends = { morning: into(), morningIsSleptHere: true }
// Mid-stay: even a stop at 06:00 is preceded by the hotel you woke in.
expect(shouldDrawMorningLeg(bookends, checkInDay, { isPlace: true, time: '06:00' })).toBe(true)
})
it('does NOT draw on a check-in day when the first place is before check-in (#1465)', () => {
const bookends = { morning: into({ check_in: '15:00' }), morningIsSleptHere: false }
// Airport place at 10:00, check-in 15:00 — you have not reached the hotel yet.
expect(shouldDrawMorningLeg(bookends, checkInDay, { isPlace: true, time: '10:00' })).toBe(false)
})
it('draws on a check-in day when the first place is at/after check-in (loop preserved)', () => {
const bookends = { morning: into({ check_in: '15:00' }), morningIsSleptHere: false }
expect(shouldDrawMorningLeg(bookends, checkInDay, { isPlace: true, time: '19:00' })).toBe(true)
expect(shouldDrawMorningLeg(bookends, checkInDay, { isPlace: true, time: '15:00' })).toBe(true)
})
it('DRAWS on a check-in day when time info is missing (home-base default, no over-suppression)', () => {
// Without a comparable place time or hotel check-in time, the arrival day stays a
// home-base loop — only a place provably before check-in suppresses the leg.
const bookends = { morning: into({ check_in: '15:00' }), morningIsSleptHere: false }
expect(shouldDrawMorningLeg(bookends, checkInDay, { isPlace: true, time: null })).toBe(true)
const noCheckIn = { morning: into({ check_in: null }), morningIsSleptHere: false }
expect(shouldDrawMorningLeg(noCheckIn, checkInDay, { isPlace: true, time: '19:00' })).toBe(true)
})
it('does NOT draw on a check-in day for a transport arrival (not a place, #1321)', () => {
const bookends = { morning: into({ check_in: '15:00' }), morningIsSleptHere: false }
// A late arrival (16:00) is still no morning leg — you flew in, weren't at the hotel.
expect(shouldDrawMorningLeg(bookends, checkInDay, { isPlace: false, time: '16:00' })).toBe(false)
})
it('does NOT draw when the morning hotel is not checking in today', () => {
// start_day_id 20 ≠ day 10, and not slept-here → no leg.
const bookends = { morning: into({ start_day_id: 20, check_in: '15:00' }), morningIsSleptHere: false }
expect(shouldDrawMorningLeg(bookends, checkInDay, { isPlace: true, time: '19:00' })).toBe(false)
})
})
describe('shouldDrawEveningLeg', () => {
const checkOutDay = days[2] // id 30
const out = (over: Partial<Accommodation> = {}) =>
hotel({ start_day_id: 10, end_day_id: 30, check_out: '11:00', ...over })
it('draws when you sleep in the evening hotel tonight, regardless of stop time', () => {
const bookends = { evening: out(), eveningIsOvernight: true }
expect(shouldDrawEveningLeg(bookends, checkOutDay, { isPlace: true, time: '23:00' })).toBe(true)
})
it('does NOT draw on a check-out day when the last place is after check-out (#1465)', () => {
const bookends = { evening: out({ check_out: '11:00' }), eveningIsOvernight: false }
// "home" place at 18:00, check-out 11:00 — you have already left the hotel.
expect(shouldDrawEveningLeg(bookends, checkOutDay, { isPlace: true, time: '18:00' })).toBe(false)
})
it('draws on a check-out day when the last place is at/before check-out', () => {
const bookends = { evening: out({ check_out: '11:00' }), eveningIsOvernight: false }
expect(shouldDrawEveningLeg(bookends, checkOutDay, { isPlace: true, time: '09:00' })).toBe(true)
expect(shouldDrawEveningLeg(bookends, checkOutDay, { isPlace: true, time: '11:00' })).toBe(true)
})
it('does NOT draw on a check-out day when the place or hotel has no time', () => {
const bookends = { evening: out({ check_out: '11:00' }), eveningIsOvernight: false }
expect(shouldDrawEveningLeg(bookends, checkOutDay, { isPlace: true, time: null })).toBe(false)
const noCheckOut = { evening: out({ check_out: null }), eveningIsOvernight: false }
expect(shouldDrawEveningLeg(noCheckOut, checkOutDay, { isPlace: true, time: '09:00' })).toBe(false)
})
it('does NOT draw on a check-out day for a transport departure (not a place, S7)', () => {
const bookends = { evening: out({ check_out: '11:00' }), eveningIsOvernight: false }
expect(shouldDrawEveningLeg(bookends, checkOutDay, { isPlace: false, time: '09:00' })).toBe(false)
})
})
+38
View File
@@ -1,4 +1,5 @@
import type { Day, Accommodation, RouteAnchors } from '../types'
import { parseTimeToMinutes } from './dayMerge'
export const getDayOrder = (day: Day, days: Day[]): number =>
day.day_number ?? days.indexOf(day)
@@ -56,6 +57,43 @@ export const getAccommodationAnchors = (
}
}
// Whether to draw the morning hotel → first-stop leg. It is a real drive when you slept in the
// morning hotel (a normal home-base day). On that hotel's check-in day the hotel is your base
// once you arrive, so the leg is still the default for a PLACE first stop — suppressed only when
// that place is timed BEFORE check-in (an airport you reach before dropping your bags, #1465), or
// when the first stop is a transport arrival (you flew in, weren't at the hotel yet, #1321).
// Un-timed places keep the loop, avoiding over-suppression on ordinary arrival days.
export const shouldDrawMorningLeg = (
bookends: { morning?: Accommodation; morningIsSleptHere?: boolean },
day: Day,
firstStop?: { isPlace: boolean; time?: string | null },
): boolean => {
if (bookends.morningIsSleptHere) return true
const m = bookends.morning
if (!m || m.start_day_id !== day.id || !firstStop?.isPlace) return false
const checkIn = parseTimeToMinutes(m.check_in)
const stop = parseTimeToMinutes(firstStop.time)
return !(checkIn != null && stop != null && stop < checkIn)
}
// Mirror of shouldDrawMorningLeg for the last-stop → hotel evening leg. It is a real drive when
// you sleep in the evening hotel tonight. On that hotel's check-out day you have already left, so
// the return leg is NOT the default — drawn only when the last stop is a PLACE timed at/before
// check-out (a swing back before checking out). A later stop (heading home, #1465), an un-timed
// stop, or an evening transport departure (S7) all mean no return leg.
export const shouldDrawEveningLeg = (
bookends: { evening?: Accommodation; eveningIsOvernight?: boolean },
day: Day,
lastStop?: { isPlace: boolean; time?: string | null },
): boolean => {
if (bookends.eveningIsOvernight) return true
const e = bookends.evening
if (!e || e.end_day_id !== day.id || !lastStop?.isPlace) return false
const checkOut = parseTimeToMinutes(e.check_out)
const stop = parseTimeToMinutes(lastStop.time)
return checkOut != null && stop != null && stop <= checkOut
}
export const isDayInAccommodationRange = (
day: Day,
startDayId: number,
+46 -2
View File
@@ -1,6 +1,6 @@
import { describe, it, expect } from 'vitest'
import { splitReservationDateTime, resolveDayId, formatMoney } from './formatters'
import { CURRENCIES, SYMBOLS } from '../components/Budget/BudgetPanel.constants'
import { splitReservationDateTime, resolveDayId, formatMoney, currencyDecimals } from './formatters'
import { CURRENCIES, SYMBOLS, currenciesWith } from '../components/Budget/BudgetPanel.constants'
import type { Day } from '../types'
const days = [
@@ -39,6 +39,50 @@ describe('KGS currency (#1400)', () => {
})
})
describe('Frankfurter-supported currency list (#1470)', () => {
it('offers the currencies that were previously missing', () => {
for (const c of ['OMR', 'CRC', 'UGX', 'MKD', 'ALL']) {
expect(CURRENCIES).toContain(c)
}
})
it('drops currencies Frankfurter has archived', () => {
expect(CURRENCIES).not.toContain('BGN')
expect(CURRENCIES).not.toContain('HRK')
})
it('has a symbol for every selectable currency', () => {
for (const c of CURRENCIES) expect(SYMBOLS[c]).toBeTruthy()
})
})
describe('currencyDecimals', () => {
it('uses 2 decimals for standard currencies', () => {
expect(currencyDecimals('USD')).toBe(2)
expect(currencyDecimals('EUR')).toBe(2)
})
it('uses 0 decimals for zero-decimal currencies', () => {
for (const c of ['JPY', 'HUF', 'UGX', 'XOF', 'RWF', 'VUV']) {
expect(currencyDecimals(c)).toBe(0)
}
})
it('uses 3 decimals for the Gulf/dinar currencies', () => {
for (const c of ['OMR', 'KWD', 'BHD', 'TND']) {
expect(currencyDecimals(c)).toBe(3)
}
})
})
describe('currenciesWith (legacy safeguard)', () => {
it('returns the base list unchanged for a supported currency', () => {
expect(currenciesWith('EUR')).toBe(CURRENCIES)
expect(currenciesWith(null)).toBe(CURRENCIES)
})
it('keeps an archived/legacy selection selectable', () => {
const opts = currenciesWith('HRK')
expect(opts).toContain('HRK')
expect(opts.length).toBe(CURRENCIES.length + 1)
})
})
describe('splitReservationDateTime', () => {
it('parses full ISO datetime', () => {
expect(splitReservationDateTime('2026-06-25T10:00')).toEqual({ date: '2026-06-25', time: '10:00' })
+12 -2
View File
@@ -33,10 +33,20 @@ export function formatLocationName(raw: string | null | undefined): string {
return result.join(', ')
}
const ZERO_DECIMAL_CURRENCIES = new Set(['JPY', 'KRW', 'VND', 'CLP', 'ISK', 'HUF'])
// Currencies whose smallest unit isn't 1/100. Most currencies use 2 decimals;
// these two sets cover the exceptions in the supported set (see CURRENCIES).
// HUF is kept zero-decimal by app convention even though ISO lists 2.
const ZERO_DECIMAL_CURRENCIES = new Set([
'JPY', 'KRW', 'VND', 'CLP', 'ISK', 'HUF',
'BIF', 'DJF', 'GNF', 'KMF', 'PYG', 'RWF', 'UGX', 'VUV', 'XAF', 'XOF', 'XPF',
])
const THREE_DECIMAL_CURRENCIES = new Set(['BHD', 'IQD', 'JOD', 'KWD', 'LYD', 'OMR', 'TND'])
export function currencyDecimals(currency: string): number {
return ZERO_DECIMAL_CURRENCIES.has(currency.toUpperCase()) ? 0 : 2
const cur = currency.toUpperCase()
if (ZERO_DECIMAL_CURRENCIES.has(cur)) return 0
if (THREE_DECIMAL_CURRENCIES.has(cur)) return 3
return 2
}
// Each currency formats in its own home convention (symbol position, grouping and
@@ -0,0 +1,27 @@
import { describe, it, expect, afterEach, vi } from 'vitest'
import { maybeInstallTouchDragPolyfill } from './touchDragPolyfill'
// Stub the polyfill so the test exercises only the load gate, not the real
// document-level touch listeners the package installs on import.
vi.mock('drag-drop-touch', () => ({}))
function setWidth(w: number) {
Object.defineProperty(window, 'innerWidth', { value: w, configurable: true, writable: true })
}
describe('maybeInstallTouchDragPolyfill', () => {
const original = window.innerWidth
afterEach(() => setWidth(original))
it('does not load the polyfill on mobile viewports (<1024px)', () => {
setWidth(390)
expect(maybeInstallTouchDragPolyfill()).toBeUndefined()
})
it('loads the polyfill on large viewports (>=1024px)', async () => {
setWidth(1440)
const result = maybeInstallTouchDragPolyfill()
expect(result).toBeInstanceOf(Promise)
await expect(result).resolves.toBeDefined()
})
})
+18
View File
@@ -0,0 +1,18 @@
/**
* `drag-drop-touch` bridges native HTML5 drag-and-drop to touch so the planner's
* place/day reordering works on touch input (#1265). It installs document-level touch
* listeners on import and, on every single-finger touch, records the touchend time and
* synthesises a `dblclick` when the next touch starts within 500 ms. On the map that
* dblclick fires the default double-click-zoom, so two quick one-finger pans zoomed
* instead of panning (#1440).
*
* Reorder DnD is disabled on mobile viewports (#1432), so the polyfill has no job below
* the lg breakpoint — skip it there to remove the phantom-dblclick source on phones
* while keeping touch DnD on desktop / large (touch) viewports.
*/
export function maybeInstallTouchDragPolyfill(): Promise<unknown> | void {
if (typeof window === 'undefined') return
// Mirrors useIsMobile's SSR-safe initial check (lg breakpoint = 1024px).
if (window.innerWidth < 1024) return
return import('drag-drop-touch')
}
@@ -371,6 +371,67 @@ describe('useRouteCalculation', () => {
expect(result.current.route).toBeNull();
});
it('FE-HOOK-ROUTE-020: #1465 check-in day with a place before check-in draws no hotel → first-stop leg', async () => {
// Airport (10:00) and a museum (12:00) on the check-in day, both before the 15:00 check-in.
// You reach them before dropping your bags, so the day starts at the airport — no hotel →
// airport leg. The evening leg to the hotel (where you sleep tonight) still stands.
const airport = buildPlace({ lat: 41.30, lng: 2.08, place_time: '10:00' });
const museum = buildPlace({ lat: 41.38, lng: 2.17, place_time: '12:00' });
const hotel = { lat: 41.39, lng: 2.16 };
const a1 = buildAssignment({ day_id: 1, order_index: 0, place: airport });
const a2 = buildAssignment({ day_id: 1, order_index: 1, place: museum });
const accommodations = [{ id: 1, start_day_id: 1, end_day_id: 2, check_in: '15:00', place_lat: hotel.lat, place_lng: hotel.lng }];
const store = { assignments: { '1': [a1, a2] } } as unknown as TripStoreState;
useTripStore.setState({
assignments: store.assignments,
reservations: [],
days: [{ id: 1, day_number: 1 }, { id: 2, day_number: 2 }],
} as any);
const { result } = renderHook(() =>
useRouteCalculation(store, 1, true, 'driving', accommodations as any)
);
await act(async () => {});
const legs = (result.current.route ?? []).map(run => run.map(p => `${p[0]},${p[1]}`));
// No spurious morning bookend [hotel → airport].
expect(legs).not.toContainEqual([`${hotel.lat},${hotel.lng}`, `${airport.lat},${airport.lng}`]);
// The day starts at the airport, and still ends at the hotel for the night.
expect(result.current.route?.[0]?.[0]).toEqual([airport.lat, airport.lng]);
expect(legs).toContainEqual([`${museum.lat},${museum.lng}`, `${hotel.lat},${hotel.lng}`]);
});
it('FE-HOOK-ROUTE-021: #1465 check-out day with a place after check-out draws no last-stop → hotel leg', async () => {
// Day 2 is the hotel's check-out day (11:00). You wake there, visit a museum (09:00), then
// head "home" (18:00, after check-out). Having left the hotel, there is no return leg — but
// the morning leg [hotel → museum] (you slept there) stays.
const museum = buildPlace({ lat: 41.38, lng: 2.17, place_time: '09:00' });
const home = buildPlace({ lat: 41.10, lng: 1.80, place_time: '18:00' });
const hotel = { lat: 41.39, lng: 2.16 };
const a1 = buildAssignment({ day_id: 2, order_index: 0, place: museum });
const a2 = buildAssignment({ day_id: 2, order_index: 1, place: home });
const accommodations = [{ id: 1, start_day_id: 1, end_day_id: 2, check_out: '11:00', place_lat: hotel.lat, place_lng: hotel.lng }];
const store = { assignments: { '2': [a1, a2] } } as unknown as TripStoreState;
useTripStore.setState({
assignments: store.assignments,
reservations: [],
days: [{ id: 1, day_number: 1 }, { id: 2, day_number: 2 }],
} as any);
const { result } = renderHook(() =>
useRouteCalculation(store, 2, true, 'driving', accommodations as any)
);
await act(async () => {});
const legs = (result.current.route ?? []).map(run => run.map(p => `${p[0]},${p[1]}`));
// No spurious evening bookend [home → hotel].
expect(legs).not.toContainEqual([`${home.lat},${home.lng}`, `${hotel.lat},${hotel.lng}`]);
// The morning leg from the slept-in hotel is still drawn, and the day ends at home.
expect(legs).toContainEqual([`${hotel.lat},${hotel.lng}`, `${museum.lat},${museum.lng}`]);
const flat = result.current.route ?? [];
expect(flat[flat.length - 1]?.[flat[flat.length - 1].length - 1]).toEqual([home.lat, home.lng]);
});
it('FE-HOOK-ROUTE-012: setRoute and setRouteInfo are exposed', () => {
const store = buildMockStore({});
const { result } = renderHook(() =>
-10
View File
@@ -44,16 +44,6 @@ export default defineConfig({
cacheableResponse: { statuses: [0, 200] },
},
},
{
// Leaflet CSS/JS from unpkg CDN
urlPattern: /^https:\/\/unpkg\.com\/.*/i,
handler: 'CacheFirst',
options: {
cacheName: 'cdn-libs',
expiration: { maxEntries: 30, maxAgeSeconds: 365 * 24 * 60 * 60 },
cacheableResponse: { statuses: [0, 200] },
},
},
{
// Mapbox GL style, glyphs, sprites and vector tiles. Best-effort
// offline only: opportunistically caches what the user has already
+7 -1
View File
@@ -36,6 +36,7 @@
"dexie": "^4.4.2",
"drag-drop-touch": "^1.3.1",
"heic-to": "^1.4.2",
"iso-3166-2": "^1.0.0",
"leaflet": "^1.9.4",
"lucide-react": "^0.344.0",
"mapbox-gl": "^3.22.0",
@@ -12750,6 +12751,11 @@
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
"license": "ISC"
},
"node_modules/iso-3166-2": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/iso-3166-2/-/iso-3166-2-1.0.0.tgz",
"integrity": "sha512-xLAazfKZzwlsg/Zz/GQGQk3jJez5/2ORrjD3TjSuqz/arMht/xTK49c0GOE3afO/gEd9tHtBVVlfBla01unUng=="
},
"node_modules/isomorphic-dompurify": {
"version": "3.17.0",
"resolved": "https://registry.npmjs.org/isomorphic-dompurify/-/isomorphic-dompurify-3.17.0.tgz",
@@ -21261,6 +21267,7 @@
"tsconfig-paths": "^4.2.0",
"tsx": "^4.21.0",
"typescript": "^6.0.2",
"tz-lookup": "^6.1.25",
"undici": "^7.0.0",
"unzipper": "^0.12.3",
"uuid": "^14.0.0",
@@ -21301,7 +21308,6 @@
"prettier-plugin-organize-imports": "^4.3.0",
"supertest": "^7.2.2",
"typescript-eslint": "^8.58.2",
"tz-lookup": "^6.1.25",
"unplugin-swc": "^1.5.9",
"vitest": "^4.1.9"
}
+4 -1
View File
@@ -52,7 +52,10 @@ trek.notify('success', 'Saved')
```
The kit applies the theme, mirrors the appearance flags (reduced-motion,
no-transparency) and auto-reports your height. See the
no-transparency) and auto-reports your height. It also upgrades any native
`<select>` into a host-styled, keyboard-accessible dropdown that matches TREK —
the OS-drawn popup never could. Write a plain `<select>` and it just works; add
`data-trek-native` to opt a field out. See the
[Plugin Development wiki](https://github.com/mauriceboe/TREK/wiki/Plugin-Development)
for the full component + token reference.
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "trek-plugin-sdk",
"version": "1.3.0",
"version": "1.4.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "trek-plugin-sdk",
"version": "1.3.0",
"version": "1.4.0",
"license": "MIT",
"dependencies": {
"@clack/prompts": "^1.7.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "trek-plugin-sdk",
"version": "1.3.1",
"version": "1.4.0",
"description": "SDK for building TREK plugins: types, definePlugin, a mock host, manifest validation, and the create-trek-plugin / trek-plugin CLIs.",
"type": "module",
"license": "MIT",
+4 -2
View File
@@ -63,10 +63,12 @@ export function scaffold(name: string, type: string, targetDir: string, opts: Sc
// ({ id, version-range }) that must be installed + satisfied first.
requiredAddons: opts.requiredAddons ?? [],
pluginDependencies: opts.pluginDependencies ?? [],
routes: [{ method: 'GET', path: '/hello', auth: true }],
};
if (opts.egress?.length) manifest.egress = opts.egress;
if (type === 'page') manifest.capabilities = { nav: { label: manifest.name, icon: 'Blocks', position: 'main' } };
// Routes are declared in server/index.js (definePlugin), NOT the manifest — the
// host ignores a manifest `routes`. A `page` plugin gets its nav entry
// automatically, so there's no `capabilities.nav` either; only `widget` carries a
// capability worth scaffolding.
if (type === 'widget') manifest.capabilities = { widget: { title: manifest.name, defaultSize: 'medium' } };
fs.writeFileSync(path.join(root, 'trek-plugin.json'), JSON.stringify(manifest, null, 2) + '\n');

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