* 3.3.0 (#1472)

* 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, whic…

* fix(plugins): repair plain-HTTP egress and forward the private-egress opt-out

Two pre-existing bugs in the plugin egress guard, found by running a plugin
against a real service end to end.

1. Every plain-HTTP request a plugin made was refused, whatever host it had
   declared. Node pre-normalises `net.connect()` args into an [options, cb]
   array and passes THAT array as the single argument; undici's plain-HTTP
   connector takes this path, its TLS connector does not. classifyConnect read
   `host` off the array, got undefined, and fell back to 'localhost' — so a
   fetch to a declared, public host was rejected with the nonsense message
   "localhost is not in the plugin's declared hosts". It failed closed, so it
   was never a security hole, and it went unnoticed because the only shipped
   egress plugin uses HTTPS. unwrapConnectArgs() unwraps the normalised form
   before anything reads host/path.

2. TREK_PLUGIN_ALLOW_PRIVATE_EGRESS could never have any effect. The guard that
   reads it runs INSIDE the child, whose env is scrubbed to a four-entry
   whitelist that never included it — so a documented setting (wiki/
   Environment-Variables.md) was wired to nothing, and no plugin could reach a
   self-hoster's LAN service no matter what the operator set. Forwarded only
   when set, so the default stays the secure block-private policy.

Regression tests cover the normalised form in both directions: the real host is
now resolved, and an undeclared host, a private IP and a unix socket are all
still refused when passed that way.

* feat(notifications): let a plugin register a notification channel

TREK's four channels (in-app, email, webhook, ntfy) were a closed set:
notificationService.send() dispatched with four copy-pasted `if` blocks and no
provider abstraction, so a fifth channel meant editing eight files by hand. A
plugin could produce a notification via ctx.notify.send(), but never deliver
one.

A plugin now registers a channel with `hooks.notificationChannel` +
`hook:notification-channel` on a plain `type: 'integration'` — not a new manifest
type, so the TREK-Plugins registry schema and both its CI gates are untouched.

Core refactor
- New channel registry (services/notifications/): email/webhook/ntfy become
  ExternalChannel providers wrapping the EXISTING send functions — no delivery
  logic is rewritten, only relocated. In-app deliberately stays out: it writes
  typed rows with scope/target/callbacks, not a rendered title+body, the same
  line shared/ already draws with i18n/externalNotifications.
- The event text is now rendered once per recipient instead of once per channel.
- The channel set is open: NotifChannel becomes a string, the matrix is
  registry-derived, and the UI columns are server-driven. The DB column was
  already bare TEXT and the Zod contract already a string record — only the
  TypeScript and the two UIs were ever closed.

The hook runs USERLESS. Every other hook is user-initiated, so actingUserId falls
out of the request; a notification is host-initiated for an ARBITRARY recipient,
so ctx.settings.get() would return undefined. The host resolves the recipient's
decrypted scope:'user' settings itself and passes them as an argument. That is
what lets a channel plugin be handed someone's push token WITHOUT being handed
the right to read their trips as them.

Enabling the plugin is the opt-in: a plugin channel is not gated on the admin's
`notification_channels` list. A built-in always exists in code and needs an
explicit switch; a plugin channel only exists because an admin enabled that
plugin. (Nothing could write a `plugin:` id into that CSV anyway, and the admin
toggle rebuilt it from three booleans, silently dropping anything else — so
requiring a second opt-in meant the channel could never be turned on at all.)

Also fixed, found while building this:
- Plugin settings keys were unvalidated, so a field named `__proto__` or
  `constructor` resolved off Object.prototype: a REQUIRED field with such a name
  reported as configured for every user who had configured nothing — enough, for
  a channel, to be dispatched to everyone with no credentials. Keys are now
  constrained at install and the config blob is parsed null-prototype, so it is
  impossible even for an already-installed plugin.
- A `select` field's options were cast straight through, so the obvious
  `["1","5"]` form rendered every dropdown entry BLANK (the client reads
  value/label). Now coerced, and malformed options are rejected.

Also adds: operator-supplied egress hosts (a plugin talking to a self-hosted
service can't name the operator's host at publish time, so an admin adds it
post-install and the runtime re-spawns the child with the widened allow-list —
only for a plugin that DECLARED operatorEgress, and only an admin, never a user);
settings-page actions (a "Test connection" button, user-initiated so
ctx.settings.get() returns the clicking user's own value); and a Gotify-shaped
notification-channel template in the SDK.

Verified end to end against a real Gotify container, not just in tests.

* docs(wiki): document the plugin notification-channel surface

Covers the pieces added in the previous commits, in the pages a reader would
actually reach for:

- Plugins.md (the admin-facing page) had none of it: notification channels,
  settings actions, and a full "Allowed hosts" section — including what
  operator-supplied egress deliberately does NOT let anyone do.
- Plugin-Development.md: the notificationChannel hook (and why it is the one hook
  with no acting user), settings-page actions, operatorEgress, and the manifest
  reference rows.
- Plugin-Cookbook.md: a "become a notification channel" recipe and a
  "Test connection button" recipe.
- Plugin-Permissions.md: hook:notification-channel, operatorEgress under the
  outbound section, and settings actions under "not a permission".
- Notifications.md: plugin channels alongside the four built-ins.

* fix(sdk): allow empty egress if and only if operatorEgress is true

* ci: don't run repo-specific workflows on forks

Guard release, publish, wiki-deploy and issue/PR-triage workflows with a
`github.repository` check so they no-op in forks instead of failing or
acting on the fork's own issues, PRs, tags and registries.

Also skip the Docker Scout scan for pull requests from forks: Docker Hub
secrets are never exposed there, so the login step could not succeed.

Tests and lint stay ungated — they need no secrets and are the gate for
incoming fork PRs.

* feat(sdk): add missing methods in mock-host

* fix(airports): rebuild the json file

* fix(airports.json): add small airports too

* fix(public transit): only show public transit option when a trip has actual dates

* fix(plugins): reap a queued erasure only once the plugin's data is gone

The orphan reap deleted every queue row whose plugin had left the registry, but
uninstall(deleteData=false) removes the plugins row while deliberately keeping the
data dir AND the queued erasure so a same-id reinstall can still honour it. The reap
now deletes a row only when the plugin's data dir is actually gone; a deleteData=true
uninstall already clears the rows itself.

* fix(backup): snapshot the core DB and swap restores atomically

createBackup archived travel.db via the archiver's lazy live-file read, so a WAL
auto-checkpoint firing mid-stream could write a torn database into the zip. It now
VACUUM INTOs a point-in-time snapshot and archives that, the same guarantee plugin
DBs already get. restoreFromZip swapped the DB by unlink-then-copy, which on an
interrupted restore could leave no valid travel.db; it now copies to a temp file and
renames it into place (atomic), dropping the stale -wal/-shm sidecars first.

* fix(deploy): Recreate strategy for the SQLite volume, pin the root compose image

The Helm Deployment had no strategy, so the default RollingUpdate would start a second
pod holding the same ReadWriteOnce PVC before the old one exits — a Multi-Attach
deadlock or two writers on one SQLite file. Default to Recreate (overridable for
ReadWriteMany). The root docker-compose.yml pinned trek:dev, a tag no workflow builds,
so a clone-and-up at the release tag ran a stale image; pin it to :latest like the README.

* fix(security): re-validate LLM endpoint fetch redirects per hop (GHSA-fmq9)

safeFetchLlm left undici's default redirect:'follow', so a configured LLM
endpoint could 302 to http://169.254.169.254/ and reach cloud-metadata
credentials — the DNS pin does not cover an IP-literal redirect hop, since
net.connect skips the pinned lookup for a literal IP. Follow redirects
manually now, re-resolving/re-checking/re-pinning each hop (allowing LAN/
localhost as before). Also block the Alibaba metadata IPs directly.

* fix(plugins): throttle the plugin log channel to prevent host-thread DoS

The per-plugin RpcRateLimiter only guarded the ctx.* (req) channel; ctx.log.*,
stdout/stderr and unknown evt topics reached a synchronous INSERT+prune on the
host thread unthrottled, so a while(true) ctx.log.error(...) loop could freeze
the instance. Route every plugin-driven log path through a per-plugin log token
bucket; excess lines are dropped with a summary line on resume.

---------

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 22:28:32 +02:00
committed by GitHub
parent 3db2495bcd
commit 19064b3917
539 changed files with 25810 additions and 2292 deletions
@@ -9,6 +9,7 @@ permissions:
jobs:
close-stale:
if: github.repository == 'mauriceboe/TREK'
runs-on: ubuntu-latest
steps:
- name: Close stale invalid-title issues
@@ -10,6 +10,7 @@ permissions:
jobs:
close-stale:
if: github.repository == 'mauriceboe/TREK'
runs-on: ubuntu-latest
steps:
- name: Close stale wrong-base-branch PRs
@@ -9,6 +9,7 @@ permissions:
jobs:
check-title:
if: github.repository == 'mauriceboe/TREK'
runs-on: ubuntu-latest
steps:
- name: Flag or redirect issue
+1
View File
@@ -18,6 +18,7 @@ concurrency:
jobs:
version-bump:
if: github.repository == 'mauriceboe/TREK'
runs-on: ubuntu-latest
outputs:
version: ${{ steps.bump.outputs.VERSION }}
+1
View File
@@ -33,6 +33,7 @@ concurrency:
jobs:
version-bump:
if: github.repository == 'mauriceboe/TREK'
runs-on: ubuntu-latest
outputs:
version: ${{ steps.bump.outputs.VERSION }}
@@ -6,6 +6,7 @@ on:
jobs:
check-target:
if: github.repository == 'mauriceboe/TREK'
runs-on: ubuntu-latest
permissions:
pull-requests: write
+1
View File
@@ -14,6 +14,7 @@ permissions:
jobs:
publish:
if: github.repository == 'mauriceboe/TREK'
runs-on: ubuntu-latest
defaults:
run:
+3
View File
@@ -11,6 +11,9 @@ permissions:
jobs:
scout:
# Docker Hub secrets are not exposed to pull requests from forks, so the
# Scout login can never succeed there.
if: github.repository == 'mauriceboe/TREK' && github.event.pull_request.head.repo.fork != true
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
+1
View File
@@ -17,6 +17,7 @@ concurrency:
jobs:
deploy:
if: github.repository == 'mauriceboe/TREK'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
+6
View File
@@ -6,6 +6,12 @@ metadata:
app: {{ include "trek.name" . }}
spec:
replicas: 1
# TREK is a single-writer SQLite app on a ReadWriteOnce PVC, so the default
# RollingUpdate would start a second pod holding the same volume before the old one
# exits — a Multi-Attach deadlock, or two processes on one travel.db. Recreate tears
# the old pod down first. Override to RollingUpdate only with a ReadWriteMany volume.
strategy:
type: {{ .Values.updateStrategy | default "Recreate" }}
selector:
matchLabels:
app: {{ include "trek.name" . }}
+5
View File
@@ -4,6 +4,11 @@ image:
# tag: latest
pullPolicy: IfNotPresent
# Deployment update strategy. Recreate is the safe default for the single-writer SQLite
# DB on a ReadWriteOnce volume (the old pod is torn down before the new one starts).
# Set to RollingUpdate only if you back the data volume with ReadWriteMany storage.
updateStrategy: Recreate
# Optional image pull secrets for private registries
imagePullSecrets: []
# - name: my-registry-secret
-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>
+162 -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,17 @@ 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),
// Operator-supplied egress hosts: a plugin talking to a SELF-HOSTED service can't name
// the operator's hostname in its manifest, so the admin adds it here. Saving re-spawns
// the plugin with the widened allow-list.
pluginEgressHosts: (id: string): Promise<{ supported: boolean; hosts: string[] }> =>
apiClient.get(`/admin/plugins/${id}/egress-hosts`).then(r => r.data),
pluginSetEgressHosts: (id: string, hosts: string[]): Promise<{ hosts: string[] }> =>
apiClient.put(`/admin/plugins/${id}/egress-hosts`, { hosts }).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 +599,51 @@ 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 }>
}
/** A button a plugin contributes to its own settings page ("Test connection"). */
export interface PluginAction {
key: string; label: string; hint?: string; danger: boolean
}
export const pluginsApi = {
// Active plugins the client renders (page nav entries, dashboard widgets).
active: () => apiClient.get('/plugins').then(r => r.data),
@@ -565,6 +654,58 @@ 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>
actions: PluginAction[]
}),
// Run a settings-page action the plugin declared ("Test connection"). It runs AS the
// caller, so it reads the caller's own settings.
runAction: (id: string, key: string) =>
apiClient.post(`/plugin-settings/${id}/actions/${encodeURIComponent(key)}`)
.then(r => r.data as { ok: boolean; message?: string }),
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 +765,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 +781,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 +837,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 +862,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 +872,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 +935,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 +970,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),
@@ -883,6 +1007,10 @@ export const notificationsApi = {
testSmtp: (email?: string) => apiClient.post('/notifications/test-smtp', { email }).then(r => checkInDev(channelTestResultSchema, r.data, 'notifications.testSmtp')),
testWebhook: (url?: string) => apiClient.post('/notifications/test-webhook', { url }).then(r => checkInDev(channelTestResultSchema, r.data, 'notifications.testWebhook')),
testNtfy: (payload: { topic?: string; server?: string | null; token?: string | null }) => apiClient.post('/notifications/test-ntfy', payload).then(r => checkInDev(channelTestResultSchema, r.data, 'notifications.testNtfy')),
// Generic channel test — this is how a PLUGIN channel's "Send test" button works.
testChannel: (channelId: string) =>
apiClient.post(`/notifications/test/${encodeURIComponent(channelId)}`)
.then(r => checkInDev(channelTestResultSchema, r.data, 'notifications.testChannel')),
}
export const inAppNotificationsApi = {
+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 }),
)
})
})
@@ -0,0 +1,121 @@
import { http, HttpResponse } from 'msw'
import { beforeEach, describe, expect, it } from 'vitest'
import { server } from '../../../tests/helpers/msw/server'
import { fireEvent, render, screen, waitFor } from '../../../tests/helpers/render'
import { resetAllStores } from '../../../tests/helpers/store'
import AdminPluginsPanel from './AdminPluginsPanel'
/**
* The "allowed hosts" chip. A plugin that talks to a SELF-HOSTED service (a Gotify) can't
* name the operator's host in its manifest, so the admin adds it — but they'd never know
* that unless the card says so. Until a host exists the plugin can reach NOTHING and looks
* silently broken, which is why the chip is warning-toned and actionable in that state.
*/
function plugin(over: Record<string, unknown> = {}) {
return {
id: 'trek-gotify', name: 'Gotify', description: 'Push notifications', type: 'integration',
icon: 'Bell', version: '1.0.0', status: 'active', enabled: 1,
last_error: null, reviewed_at: null, source_repo: null,
permissions: JSON.stringify(['hook:notification-channel', 'http:outbound:gotify.net']),
capabilities: '{}',
operatorEgress: true,
egressHostCount: 0,
dependencyStatus: 'ok',
dependencyIssues: { disabledAddons: [], missing: [], versionMismatch: [] },
...over,
}
}
function mockList(p: Record<string, unknown>) {
server.use(
http.get('*/api/admin/plugins', () => HttpResponse.json({ enabled: true, devLink: false, plugins: [p] })),
http.get('*/api/admin/plugins/registry', () => HttpResponse.json({ plugins: [] })),
)
}
beforeEach(() => resetAllStores())
describe('AdminPluginsPanel — allowed-hosts chip', () => {
it('FE-COMP-PLUGINS-EGRESS-001: invites the admin to add a host when none is set', async () => {
mockList(plugin({ egressHostCount: 0 }))
render(<AdminPluginsPanel />)
// The plugin can't reach anything yet — the card must say so, not stay silent.
expect(await screen.findByRole('button', { name: /add allowed host/i })).toBeInTheDocument()
})
it('FE-COMP-PLUGINS-EGRESS-002: shows the count once hosts exist', async () => {
mockList(plugin({ egressHostCount: 2 }))
render(<AdminPluginsPanel />)
expect(await screen.findByRole('button', { name: /2 allowed host/i })).toBeInTheDocument()
expect(screen.queryByRole('button', { name: /add allowed host/i })).not.toBeInTheDocument()
})
it('FE-COMP-PLUGINS-EGRESS-003: a plugin that never declared operatorEgress gets NO chip', async () => {
mockList(plugin({ operatorEgress: false }))
render(<AdminPluginsPanel />)
await screen.findByText('Gotify')
// An admin must never be invited to widen egress for a plugin that didn't ask for it.
expect(screen.queryByRole('button', { name: /allowed host/i })).not.toBeInTheDocument()
})
it('FE-COMP-PLUGINS-EGRESS-004: clicking the chip opens the allowed-hosts dialog', async () => {
mockList(plugin({ egressHostCount: 1 }))
server.use(
http.get('*/api/admin/plugins/trek-gotify/egress-hosts', () =>
HttpResponse.json({ supported: true, hosts: ['gotify.mydomain.com'] })),
)
render(<AdminPluginsPanel />)
fireEvent.click(await screen.findByRole('button', { name: /1 allowed host/i }))
await waitFor(() => expect(screen.getByText('gotify.mydomain.com')).toBeInTheDocument())
})
})
/**
* The Discover (pre-install) modal. Its "Connects to" list is what a reviewer reads to
* judge a plugin's network reach — so for an operatorEgress plugin that list is NOT the
* whole story, and saying nothing would actively mislead them.
*/
function mockDetail(manifest: Record<string, unknown> | null) {
server.use(
http.get('*/api/admin/plugins', () => HttpResponse.json({ enabled: true, devLink: false, plugins: [] })),
// pluginBrowse returns the ARRAY itself, not { plugins: [...] }.
http.get('*/api/admin/plugins/registry', () =>
HttpResponse.json([{ id: 'trek-gotify', name: 'Gotify', author: 'jubnl', description: 'Push', repo: 'jubnl/trek-gotify', type: 'integration', tags: [] }])),
http.get('*/api/admin/plugins/registry/trek-gotify', () =>
HttpResponse.json({
id: 'trek-gotify', name: 'Gotify', author: 'jubnl', description: 'Push', repo: 'jubnl/trek-gotify',
type: 'integration', tags: [], size: 1024, publishedAt: null, latest: '1.0.0', manifest,
})),
)
}
describe('AdminPluginsPanel — Discover modal, operator-egress pill', () => {
const base = { permissions: ['hook:notification-channel', 'http:outbound:gotify.net'], egress: ['gotify.net'], settings: [], license: 'MIT', icon: null }
/** The panel opens on Installed — switch to Discover, then open the plugin's card. */
async function openDetail() {
render(<AdminPluginsPanel />)
fireEvent.click(await screen.findByRole('button', { name: /discover/i }))
fireEvent.click(await screen.findByText('Gotify'))
}
it('FE-COMP-PLUGINS-EGRESS-005: warns that the host list is not the whole story', async () => {
mockDetail({ ...base, operatorEgress: true })
await openDetail()
// The declared host is still listed…
expect(await screen.findByText('gotify.net')).toBeInTheDocument()
// …alongside the pill saying an admin adds more.
expect(screen.getByText(/hosts you add/i)).toBeInTheDocument()
})
it('FE-COMP-PLUGINS-EGRESS-006: an ordinary plugin gets NO such pill', async () => {
mockDetail({ ...base, operatorEgress: false })
await openDetail()
expect(await screen.findByText('gotify.net')).toBeInTheDocument()
// Its egress list IS the whole story — claiming otherwise would be a lie.
expect(screen.queryByText(/hosts you add/i)).not.toBeInTheDocument()
})
})
+250 -23
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'
@@ -41,6 +42,10 @@ interface PluginRow {
source_repo: string | null
permissions: string
capabilities: string
/** The plugin needs OPERATOR-supplied egress hosts (a self-hosted target). */
operatorEgress?: boolean
/** How many hosts the admin has added — 0 means the plugin can't reach anything yet. */
egressHostCount?: number
dependencies?: PluginDependencies
dependencyStatus?: DependencyStatus
dependencyIssues?: DependencyIssues
@@ -56,6 +61,7 @@ interface RegistryItem {
latest: string | null
minTrekVersion: string | null
reviewedAt: string | null
downloadCount?: number | null
screenshotUrl: string | null
requiredAddons?: string[]
pluginDependencies?: PluginDep[]
@@ -66,6 +72,8 @@ interface RegistryDetail extends RegistryItem {
manifest: {
permissions: string[]
egress: string[]
/** The plugin needs OPERATOR-supplied hosts — its egress list is not the whole story. */
operatorEgress?: boolean
settings: Array<{ key: string; label: string; inputType: string; scope: string; required: boolean }>
license: string | null
icon: string | null
@@ -85,7 +93,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 +112,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:notification-channel', 'hook:user-data', 'http:outbound',
]
const KNOWN_TYPES = ['widget', 'page', 'integration', 'trip-page']
@@ -132,7 +147,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,14 +163,19 @@ 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') })
if (perms.includes('hook:place-detail-provider')) out.push({ icon: MapPin, label: t('admin.plugins.cap.placeDetails') })
if (perms.includes('hook:trip-warning-provider')) out.push({ icon: AlertTriangle, label: t('admin.plugins.cap.warnings') })
if (perms.includes('hook:notification-channel')) out.push({ icon: Bell, label: t('admin.plugins.cap.notificationChannel') })
if (perms.includes('events:subscribe')) out.push({ icon: Radio, label: t('admin.plugins.cap.events') })
for (const h of perms.filter(p => p.startsWith('http:outbound:')).map(p => p.slice('http:outbound:'.length)).filter(Boolean)) {
out.push({ icon: ArrowRight, label: h, net: true })
@@ -204,6 +224,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 +246,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)
@@ -225,6 +257,10 @@ export default function AdminPluginsPanel() {
const [latest, setLatest] = useState<Record<string, string>>({})
const [detailFor, setDetailFor] = useState<RegistryItem | null>(null)
const [errorsFor, setErrorsFor] = useState<{ id: string; rows: Array<{ ts: string; level: string; message: string }> } | null>(null)
const [egressFor, setEgressFor] = useState<{ id: string; supported: boolean; hosts: string[] } | null>(null)
const [egressDraft, setEgressDraft] = useState('')
const [egressSaving, setEgressSaving] = useState(false)
const [egressError, setEgressError] = useState('')
const [confirmUninstall, setConfirmUninstall] = useState<PluginRow | null>(null)
// A QUEUE, not one slot: "Update All" can produce several re-consent prompts —
// each must be shown, not silently overwritten by the last one.
@@ -239,15 +275,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()
@@ -312,6 +360,31 @@ export default function AdminPluginsPanel() {
const f = e.dataTransfer.files?.[0]
if (f) void uploadPlugin(f)
}
const openEgress = (id: string) => {
setMenu(null)
setEgressDraft(''); setEgressError('')
adminApi.pluginEgressHosts(id)
.then(d => setEgressFor({ id, supported: d.supported, hosts: d.hosts }))
.catch(() => setEgressFor({ id, supported: false, hosts: [] }))
}
// Saving RE-SPAWNS the plugin: the child's egress guard is installed once at init and
// a second init is refused, so a live child's allow-list can never be widened in place.
const saveEgress = async (hosts: string[]) => {
if (!egressFor) return
setEgressSaving(true); setEgressError('')
try {
const d = await adminApi.pluginSetEgressHosts(egressFor.id, hosts)
setEgressFor({ ...egressFor, hosts: d.hosts })
setEgressDraft('')
} catch (e) {
const err = e as { response?: { data?: { error?: string } } }
setEgressError(err.response?.data?.error || t('common.error'))
} finally {
setEgressSaving(false)
}
}
const openErrors = (id: string) => {
setMenu(null)
adminApi.pluginErrors(id)
@@ -322,6 +395,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 +521,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 +572,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 +642,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)} />
@@ -579,7 +693,8 @@ export default function AdminPluginsPanel() {
hasUpdate={updateAvailable(p)} latestVer={latest[p.id]}
onToggle={() => toggle(p)}
onUpdate={() => runUpdate(p)} onRestart={() => restart(p.id)}
onErrors={() => openErrors(p.id)} onUninstall={() => { setMenu(null); setConfirmUninstall(p) }} />
onErrors={() => openErrors(p.id)} onEgress={() => openEgress(p.id)}
onUninstall={() => { setMenu(null); setConfirmUninstall(p) }} />
))}
</div>
)}
@@ -615,6 +730,56 @@ export default function AdminPluginsPanel() {
</div>
)}
{/* Operator-supplied egress hosts */}
{egressFor && (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" onClick={() => setEgressFor(null)}>
<div className="bg-surface-card border border-edge rounded-2xl w-full max-w-lg shadow-modal" onClick={e => e.stopPropagation()}>
<div className="px-5 py-3.5 border-b border-edge-secondary flex items-center justify-between">
<span className="text-sm font-semibold text-content flex items-center gap-2"><Globe size={15} /> {egressFor.id} — {t('admin.plugins.allowedHosts')}</span>
<button onClick={() => setEgressFor(null)} className="text-content-faint hover:text-content"><X size={16} /></button>
</div>
<div className="p-5 space-y-3">
{!egressFor.supported ? (
<p className="text-sm text-content-faint">{t('admin.plugins.allowedHosts.unsupported')}</p>
) : (
<>
<p className="text-xs text-content-faint">{t('admin.plugins.allowedHosts.hint')}</p>
{egressFor.hosts.length === 0 && (
<p className="text-sm text-content-faint italic">{t('admin.plugins.allowedHosts.none')}</p>
)}
{egressFor.hosts.map(h => (
<div key={h} className="flex items-center justify-between gap-2 rounded-lg border border-edge-secondary px-3 py-2">
<span className="text-sm font-mono text-content break-all">{h}</span>
<button
disabled={egressSaving}
onClick={() => saveEgress(egressFor.hosts.filter(x => x !== h))}
className="text-content-faint hover:text-danger disabled:opacity-50"
aria-label={t('common.delete')}
><Trash2 size={14} /></button>
</div>
))}
<div className="flex gap-2">
<input
value={egressDraft}
onChange={e => setEgressDraft(e.target.value)}
placeholder="gotify.example.com"
className="flex-1 rounded-lg border border-edge bg-surface px-3 py-2 text-sm text-content"
/>
<button
disabled={egressSaving || !egressDraft.trim()}
onClick={() => saveEgress([...egressFor.hosts, egressDraft.trim()])}
className="rounded-lg bg-content px-3 py-2 text-sm text-surface disabled:opacity-50"
>{t('common.add')}</button>
</div>
{egressError && <p className="text-xs text-danger">{egressError}</p>}
<p className="text-xs text-content-faint">{t('admin.plugins.allowedHosts.restartNote')}</p>
</>
)}
</div>
</div>
</div>
)}
<ConfirmDialog
isOpen={!!confirmUninstall}
onClose={() => setConfirmUninstall(null)}
@@ -654,7 +819,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 }) {
@@ -718,10 +886,10 @@ function EmptyState({ t, onDiscover }: { t: T; onDiscover: () => void }) {
)
}
function InstalledRow({ p, t, busy, menu, setMenu, hasUpdate, latestVer, onToggle, onUpdate, onRestart, onErrors, onUninstall }: {
function InstalledRow({ p, t, busy, menu, setMenu, hasUpdate, latestVer, onToggle, onUpdate, onRestart, onErrors, onEgress, onUninstall }: {
p: PluginRow; t: T; busy: string | null; menu: string | null; setMenu: (v: string | null) => void
hasUpdate: boolean; latestVer?: string
onToggle: () => void; onUpdate: () => void; onRestart: () => void; onErrors: () => void; onUninstall: () => void
onToggle: () => void; onUpdate: () => void; onRestart: () => void; onErrors: () => void; onEgress: () => void; onUninstall: () => void
}) {
const caps = deriveCaps(parseJson<string[]>(p.permissions, []), parseJson<{ widget?: { slot?: string } }>(p.capabilities, {}), t)
const deps = deriveDeps(p, t)
@@ -742,13 +910,14 @@ 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 ? (
<div className="flex items-center gap-1.5 mt-1.5 text-[11.5px] text-danger">
<AlertTriangle size={13} className="shrink-0" /><span className="truncate">{p.last_error}</span>
</div>
) : caps.length > 0 && (
) : (caps.length > 0 || p.operatorEgress) && (
<div className="hidden sm:flex items-center gap-1.5 flex-wrap mt-2">
{caps.map((c, i) => (
<span key={i} className={`inline-flex items-center gap-1.5 text-[11px] font-medium px-2 py-[3px] rounded-md border ${
@@ -756,6 +925,25 @@ function InstalledRow({ p, t, busy, menu, setMenu, hasUpdate, latestVer, onToggl
<c.icon size={12} className={c.net ? 'text-info' : 'text-content-muted'} />{c.label}
</span>
))}
{/* This plugin talks to a service only the OPERATOR can name (a self-hosted
Gotify/ntfy), so its manifest can't list the host — the admin adds it.
Actionable, and warning-toned until at least one host exists, because
until then the plugin cannot reach anything and looks silently broken. */}
{p.operatorEgress && (
<button
onClick={onEgress}
title={t('admin.plugins.allowedHosts.hint')}
className={`inline-flex items-center gap-1.5 text-[11px] font-medium px-2 py-[3px] rounded-md border transition-colors ${
p.egressHostCount > 0
? 'text-info border-info/25 bg-info-soft hover:border-info/50'
: 'text-warning border-warning/30 bg-warning-soft hover:border-warning/60'}`}
>
<Globe size={12} className={p.egressHostCount > 0 ? 'text-info' : 'text-warning'} />
{p.egressHostCount > 0
? t('admin.plugins.allowedHosts.count').replace('{n}', String(p.egressHostCount))
: t('admin.plugins.allowedHosts.add')}
</button>
)}
</div>
)}
{deps.length > 0 && (
@@ -792,11 +980,18 @@ 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>
<MenuItem icon={<Globe size={14} />} label={t('admin.plugins.allowedHosts')} onClick={onEgress} />
{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 +1071,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 +1089,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)
@@ -969,14 +1177,26 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
</div>
)}
{manifest && manifest.egress.length > 0 && (
{manifest && (manifest.egress.length > 0 || manifest.operatorEgress) && (
<div className="mt-5">
<h4 className="text-[11px] font-semibold uppercase tracking-wider text-content-muted">{t('admin.plugins.connectsTitle')}</h4>
<div className="flex flex-wrap gap-1.5 mt-2">
<div className="flex flex-wrap items-center gap-1.5 mt-2">
{manifest.egress.map(h => (
<code key={h} className="text-[12px] font-mono text-info bg-info-soft rounded-md px-2 py-1">{h}</code>
))}
{/* The hosts above are NOT the whole story for this plugin: it talks to a
service only the operator can name, so its reach is whatever an admin
adds after install. Say so HERE — this is the pre-install review, and a
reviewer who reads only the host list would otherwise be misled. */}
{manifest.operatorEgress && (
<span className="inline-flex items-center gap-1.5 text-[12px] font-medium text-warning bg-warning-soft border border-warning/30 rounded-md px-2 py-1">
<Globe size={12} />{t('admin.plugins.operatorEgressPill')}
</span>
)}
</div>
{manifest.operatorEgress && (
<p className="text-[11.5px] text-content-faint mt-2">{t('admin.plugins.operatorEgressHint')}</p>
)}
</div>
)}
@@ -1002,6 +1222,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 +1234,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';
@@ -385,12 +387,38 @@ describe('TransportModal', () => {
expect(screen.queryByPlaceholderText(/e\.g\. Lufthansa/i)).not.toBeInTheDocument();
});
it('FE-PLANNER-TRANSMODAL-022b: a trip without start/end dates only offers the manual form', () => {
render(<TransportModal {...defaultProps} tripHasDates={false} places={[]} accommodations={[]} />);
expect(screen.queryByRole('button', { name: 'Automated transport' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Manual transport' })).not.toBeInTheDocument();
expect(screen.getByPlaceholderText(/e\.g\. Lufthansa/i)).toBeInTheDocument();
});
it('FE-PLANNER-TRANSMODAL-023: initialAutomated opens straight in the transit search with the day preset', () => {
const days = [{ id: 10, trip_id: 1, day_number: 1, date: '2025-06-01', title: 'Day 1' }] as any;
render(<TransportModal {...defaultProps} days={days} selectedDayId={10} initialAutomated places={[]} accommodations={[]} />);
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,14 +151,18 @@ 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
/** Transit search needs real dates to depart on, so the Automated mode is hidden on a dateless trip. */
tripHasDates?: boolean
/** Pre-seed the transit search — used by "change route" on an existing journey. */
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, tripHasDates = true }: TransportModalProps) {
const { t, locale } = useTranslation()
const toast = useToast()
const isBudgetEnabled = useAddonStore(s => s.isEnabled('budget'))
@@ -604,8 +608,10 @@ export function TransportModal({ isOpen, onClose, onSave, reservation, days, sel
}
>
{/* Manual vs Automated creation switch (#1065) — creating only; editing a
journey re-enters via "change route" with the switch hidden. */}
{!reservation && (
journey re-enters via "change route" with the switch hidden. Without
trip dates there is nothing to plan a departure against, so Automated
is not offered and only the manual form shows. */}
{!reservation && tripHasDates && (
<div className="bg-surface-secondary" style={{ display: 'flex', borderRadius: 11, padding: 3, gap: 2, marginBottom: 14 }}>
{([['manual', t('transport.modeManual')], ['automated', t('transport.modeAutomated')]] as const).map(([m, label]) => {
const active = (m === 'automated') === automated
@@ -639,11 +645,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>
@@ -1,11 +1,10 @@
import React from 'react';
import { render, screen, waitFor } from '../../../tests/helpers/render';
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
import { server } from '../../../tests/helpers/msw/server';
import { useAuthStore } from '../../store/authStore';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { buildUser } from '../../../tests/helpers/factories';
import { server } from '../../../tests/helpers/msw/server';
import { render, screen, waitFor } from '../../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { useAuthStore } from '../../store/authStore';
import { ToastContainer } from '../shared/Toast';
import NotificationsTab from './NotificationsTab';
@@ -13,7 +12,29 @@ const minimalMatrix = {
preferences: {
trip_invite: { inapp: true, email: false },
},
available_channels: { email: true, webhook: false, inapp: true },
channels: [
{
id: 'email',
source: 'builtin',
labelKey: 'settings.notificationPreferences.email',
active: true,
configured: true,
},
{
id: 'webhook',
source: 'builtin',
labelKey: 'settings.notificationPreferences.webhook',
active: false,
configured: true,
},
{
id: 'inapp',
source: 'builtin',
labelKey: 'settings.notificationPreferences.inapp',
active: true,
configured: true,
},
],
event_types: ['trip_invite'],
implemented_combos: { trip_invite: ['inapp', 'email'] },
};
@@ -25,15 +46,13 @@ beforeEach(() => {
server.use(
http.get('/api/notifications/preferences', () => HttpResponse.json(minimalMatrix)),
http.get('/api/settings', () => HttpResponse.json({ settings: { webhook_url: '' } })),
http.put('/api/notifications/preferences', () => HttpResponse.json({ success: true })),
http.put('/api/notifications/preferences', () => HttpResponse.json({ success: true }))
);
});
describe('NotificationsTab', () => {
it('FE-COMP-NOTIFICATIONS-001: shows loading state initially', () => {
server.use(
http.get('/api/notifications/preferences', () => new Promise(() => {})),
);
server.use(http.get('/api/notifications/preferences', () => new Promise(() => {})));
render(<NotificationsTab />);
expect(screen.getByText('Loading...')).toBeInTheDocument();
});
@@ -64,11 +83,33 @@ describe('NotificationsTab', () => {
http.get('/api/notifications/preferences', () =>
HttpResponse.json({
preferences: {},
available_channels: { email: false, webhook: false, inapp: false },
channels: [
{
id: 'email',
source: 'builtin',
labelKey: 'settings.notificationPreferences.email',
active: false,
configured: true,
},
{
id: 'webhook',
source: 'builtin',
labelKey: 'settings.notificationPreferences.webhook',
active: false,
configured: true,
},
{
id: 'inapp',
source: 'builtin',
labelKey: 'settings.notificationPreferences.inapp',
active: false,
configured: true,
},
],
event_types: ['trip_invite'],
implemented_combos: { trip_invite: ['inapp', 'email'] },
}),
),
})
)
);
render(<NotificationsTab />);
await waitFor(() => {
@@ -86,14 +127,36 @@ describe('NotificationsTab', () => {
http.get('/api/notifications/preferences', () =>
HttpResponse.json({
preferences: { trip_invite: { inapp: true }, booking_change: { email: true } },
available_channels: { email: true, webhook: false, inapp: true },
channels: [
{
id: 'email',
source: 'builtin',
labelKey: 'settings.notificationPreferences.email',
active: true,
configured: true,
},
{
id: 'webhook',
source: 'builtin',
labelKey: 'settings.notificationPreferences.webhook',
active: false,
configured: true,
},
{
id: 'inapp',
source: 'builtin',
labelKey: 'settings.notificationPreferences.inapp',
active: true,
configured: true,
},
],
event_types: ['trip_invite', 'booking_change'],
implemented_combos: {
trip_invite: ['inapp'], // no email → dash in email column
booking_change: ['email'], // no inapp → dash in inapp column
trip_invite: ['inapp'], // no email → dash in email column
booking_change: ['email'], // no inapp → dash in inapp column
},
}),
),
})
)
);
render(<NotificationsTab />);
await waitFor(() => {
@@ -111,7 +174,7 @@ describe('NotificationsTab', () => {
http.put('/api/notifications/preferences', async ({ request }) => {
capturedBody = await request.json();
return HttpResponse.json({ success: true });
}),
})
);
render(<NotificationsTab />);
@@ -138,9 +201,7 @@ describe('NotificationsTab', () => {
it('FE-COMP-NOTIFICATIONS-007: toggle rolls back on API error', async () => {
const user = userEvent.setup();
server.use(
http.put('/api/notifications/preferences', () => HttpResponse.json({ error: 'fail' }, { status: 500 })),
);
server.use(http.put('/api/notifications/preferences', () => HttpResponse.json({ error: 'fail' }, { status: 500 })));
render(<NotificationsTab />);
await waitFor(() => {
@@ -169,11 +230,13 @@ describe('NotificationsTab', () => {
const user = userEvent.setup();
let resolveRequest!: () => void;
server.use(
http.put('/api/notifications/preferences', () =>
new Promise<Response>(resolve => {
resolveRequest = () => resolve(HttpResponse.json({ success: true }) as unknown as Response);
}),
),
http.put(
'/api/notifications/preferences',
() =>
new Promise<Response>((resolve) => {
resolveRequest = () => resolve(HttpResponse.json({ success: true }) as unknown as Response);
})
)
);
render(<NotificationsTab />);
@@ -200,11 +263,33 @@ describe('NotificationsTab', () => {
http.get('/api/notifications/preferences', () =>
HttpResponse.json({
preferences: { trip_invite: { inapp: true, webhook: false } },
available_channels: { email: false, webhook: true, inapp: true },
channels: [
{
id: 'email',
source: 'builtin',
labelKey: 'settings.notificationPreferences.email',
active: false,
configured: true,
},
{
id: 'webhook',
source: 'builtin',
labelKey: 'settings.notificationPreferences.webhook',
active: true,
configured: true,
},
{
id: 'inapp',
source: 'builtin',
labelKey: 'settings.notificationPreferences.inapp',
active: true,
configured: true,
},
],
event_types: ['trip_invite'],
implemented_combos: { trip_invite: ['inapp', 'webhook'] },
}),
),
})
)
);
render(<NotificationsTab />);
@@ -218,7 +303,7 @@ describe('NotificationsTab', () => {
// Save button should be present
const buttons = screen.getAllByRole('button');
expect(buttons.some(b => /save/i.test(b.textContent || ''))).toBe(true);
expect(buttons.some((b) => /save/i.test(b.textContent || ''))).toBe(true);
});
it('FE-COMP-NOTIFICATIONS-010: webhook URL input shows masked placeholder when webhook is already set', async () => {
@@ -226,14 +311,34 @@ describe('NotificationsTab', () => {
http.get('/api/notifications/preferences', () =>
HttpResponse.json({
preferences: { trip_invite: { inapp: true, webhook: false } },
available_channels: { email: false, webhook: true, inapp: true },
channels: [
{
id: 'email',
source: 'builtin',
labelKey: 'settings.notificationPreferences.email',
active: false,
configured: true,
},
{
id: 'webhook',
source: 'builtin',
labelKey: 'settings.notificationPreferences.webhook',
active: true,
configured: true,
},
{
id: 'inapp',
source: 'builtin',
labelKey: 'settings.notificationPreferences.inapp',
active: true,
configured: true,
},
],
event_types: ['trip_invite'],
implemented_combos: { trip_invite: ['inapp', 'webhook'] },
}),
),
http.get('/api/settings', () =>
HttpResponse.json({ settings: { webhook_url: '••••••••' } }),
})
),
http.get('/api/settings', () => HttpResponse.json({ settings: { webhook_url: '••••••••' } }))
);
render(<NotificationsTab />);
@@ -252,15 +357,37 @@ describe('NotificationsTab', () => {
http.get('/api/notifications/preferences', () =>
HttpResponse.json({
preferences: { trip_invite: { inapp: true, webhook: false } },
available_channels: { email: false, webhook: true, inapp: true },
channels: [
{
id: 'email',
source: 'builtin',
labelKey: 'settings.notificationPreferences.email',
active: false,
configured: true,
},
{
id: 'webhook',
source: 'builtin',
labelKey: 'settings.notificationPreferences.webhook',
active: true,
configured: true,
},
{
id: 'inapp',
source: 'builtin',
labelKey: 'settings.notificationPreferences.inapp',
active: true,
configured: true,
},
],
event_types: ['trip_invite'],
implemented_combos: { trip_invite: ['inapp', 'webhook'] },
}),
})
),
http.put('/api/settings', async ({ request }) => {
capturedBody = await request.json();
return HttpResponse.json({ success: true });
}),
})
);
render(<NotificationsTab />);
@@ -271,7 +398,7 @@ describe('NotificationsTab', () => {
const input = await screen.findByRole('textbox');
await user.type(input, 'https://example.com/hook');
const saveBtn = screen.getAllByRole('button').find(b => /save/i.test(b.textContent || ''));
const saveBtn = screen.getAllByRole('button').find((b) => /save/i.test(b.textContent || ''));
expect(saveBtn).toBeDefined();
await user.click(saveBtn!);
@@ -285,14 +412,34 @@ describe('NotificationsTab', () => {
http.get('/api/notifications/preferences', () =>
HttpResponse.json({
preferences: { trip_invite: { inapp: true, webhook: false } },
available_channels: { email: false, webhook: true, inapp: true },
channels: [
{
id: 'email',
source: 'builtin',
labelKey: 'settings.notificationPreferences.email',
active: false,
configured: true,
},
{
id: 'webhook',
source: 'builtin',
labelKey: 'settings.notificationPreferences.webhook',
active: true,
configured: true,
},
{
id: 'inapp',
source: 'builtin',
labelKey: 'settings.notificationPreferences.inapp',
active: true,
configured: true,
},
],
event_types: ['trip_invite'],
implemented_combos: { trip_invite: ['inapp', 'webhook'] },
}),
),
http.get('/api/settings', () =>
HttpResponse.json({ settings: { webhook_url: '' } }),
})
),
http.get('/api/settings', () => HttpResponse.json({ settings: { webhook_url: '' } }))
);
render(<NotificationsTab />);
@@ -301,7 +448,7 @@ describe('NotificationsTab', () => {
});
await screen.findByRole('textbox');
const testBtn = screen.getAllByRole('button').find(b => /test/i.test(b.textContent || ''));
const testBtn = screen.getAllByRole('button').find((b) => /test/i.test(b.textContent || ''));
expect(testBtn).toBeDefined();
expect(testBtn).toBeDisabled();
});
@@ -312,21 +459,41 @@ describe('NotificationsTab', () => {
http.get('/api/notifications/preferences', () =>
HttpResponse.json({
preferences: { trip_invite: { inapp: true, webhook: false } },
available_channels: { email: false, webhook: true, inapp: true },
channels: [
{
id: 'email',
source: 'builtin',
labelKey: 'settings.notificationPreferences.email',
active: false,
configured: true,
},
{
id: 'webhook',
source: 'builtin',
labelKey: 'settings.notificationPreferences.webhook',
active: true,
configured: true,
},
{
id: 'inapp',
source: 'builtin',
labelKey: 'settings.notificationPreferences.inapp',
active: true,
configured: true,
},
],
event_types: ['trip_invite'],
implemented_combos: { trip_invite: ['inapp', 'webhook'] },
}),
),
http.post('/api/notifications/test-webhook', () =>
HttpResponse.json({ success: true }),
})
),
http.post('/api/notifications/test-webhook', () => HttpResponse.json({ success: true }))
);
render(
<>
<NotificationsTab />
<ToastContainer />
</>,
</>
);
await waitFor(() => {
@@ -336,7 +503,7 @@ describe('NotificationsTab', () => {
const input = await screen.findByRole('textbox');
await user.type(input, 'https://example.com/hook');
const testBtn = screen.getAllByRole('button').find(b => /test/i.test(b.textContent || ''));
const testBtn = screen.getAllByRole('button').find((b) => /test/i.test(b.textContent || ''));
expect(testBtn).toBeDefined();
await user.click(testBtn!);
@@ -352,11 +519,40 @@ describe('NotificationsTab', () => {
http.get('/api/notifications/preferences', () =>
HttpResponse.json({
preferences: { trip_invite: { inapp: true, ntfy: false } },
available_channels: { email: false, webhook: false, inapp: true, ntfy: true },
channels: [
{
id: 'email',
source: 'builtin',
labelKey: 'settings.notificationPreferences.email',
active: false,
configured: true,
},
{
id: 'webhook',
source: 'builtin',
labelKey: 'settings.notificationPreferences.webhook',
active: false,
configured: true,
},
{
id: 'inapp',
source: 'builtin',
labelKey: 'settings.notificationPreferences.inapp',
active: true,
configured: true,
},
{
id: 'ntfy',
source: 'builtin',
labelKey: 'settings.notificationPreferences.ntfy',
active: true,
configured: true,
},
],
event_types: ['trip_invite'],
implemented_combos: { trip_invite: ['inapp', 'ntfy'] },
}),
),
})
)
);
render(<NotificationsTab />);
@@ -374,12 +570,41 @@ describe('NotificationsTab', () => {
http.get('/api/notifications/preferences', () =>
HttpResponse.json({
preferences: { trip_invite: { inapp: true, ntfy: false } },
available_channels: { email: false, webhook: false, inapp: true, ntfy: true },
channels: [
{
id: 'email',
source: 'builtin',
labelKey: 'settings.notificationPreferences.email',
active: false,
configured: true,
},
{
id: 'webhook',
source: 'builtin',
labelKey: 'settings.notificationPreferences.webhook',
active: false,
configured: true,
},
{
id: 'inapp',
source: 'builtin',
labelKey: 'settings.notificationPreferences.inapp',
active: true,
configured: true,
},
{
id: 'ntfy',
source: 'builtin',
labelKey: 'settings.notificationPreferences.ntfy',
active: true,
configured: true,
},
],
event_types: ['trip_invite'],
implemented_combos: { trip_invite: ['inapp', 'ntfy'] },
}),
})
),
http.get('/api/settings', () => HttpResponse.json({ settings: { ntfy_topic: '' } })),
http.get('/api/settings', () => HttpResponse.json({ settings: { ntfy_topic: '' } }))
);
render(<NotificationsTab />);
@@ -389,7 +614,7 @@ describe('NotificationsTab', () => {
// Test button should be disabled when topic is empty
const allButtons = await screen.findAllByRole('button');
const testBtn = allButtons.find(b => /test/i.test(b.textContent || ''));
const testBtn = allButtons.find((b) => /test/i.test(b.textContent || ''));
expect(testBtn).toBeDefined();
expect(testBtn).toBeDisabled();
});
@@ -401,22 +626,51 @@ describe('NotificationsTab', () => {
http.get('/api/notifications/preferences', () =>
HttpResponse.json({
preferences: { trip_invite: { inapp: true, ntfy: false } },
available_channels: { email: false, webhook: false, inapp: true, ntfy: true },
channels: [
{
id: 'email',
source: 'builtin',
labelKey: 'settings.notificationPreferences.email',
active: false,
configured: true,
},
{
id: 'webhook',
source: 'builtin',
labelKey: 'settings.notificationPreferences.webhook',
active: false,
configured: true,
},
{
id: 'inapp',
source: 'builtin',
labelKey: 'settings.notificationPreferences.inapp',
active: true,
configured: true,
},
{
id: 'ntfy',
source: 'builtin',
labelKey: 'settings.notificationPreferences.ntfy',
active: true,
configured: true,
},
],
event_types: ['trip_invite'],
implemented_combos: { trip_invite: ['inapp', 'ntfy'] },
}),
})
),
http.post('/api/notifications/test-ntfy', () => {
ntfyCalled = true;
return HttpResponse.json({ success: true });
}),
})
);
render(
<>
<NotificationsTab />
<ToastContainer />
</>,
</>
);
await waitFor(() => {
@@ -429,7 +683,7 @@ describe('NotificationsTab', () => {
// Test button should now be enabled
const allButtons = screen.getAllByRole('button');
const testBtn = allButtons.find(b => /test/i.test(b.textContent || ''));
const testBtn = allButtons.find((b) => /test/i.test(b.textContent || ''));
expect(testBtn).toBeDefined();
expect(testBtn).not.toBeDisabled();
@@ -446,21 +700,43 @@ describe('NotificationsTab', () => {
http.get('/api/notifications/preferences', () =>
HttpResponse.json({
preferences: { trip_invite: { inapp: true, webhook: false } },
available_channels: { email: false, webhook: true, inapp: true },
channels: [
{
id: 'email',
source: 'builtin',
labelKey: 'settings.notificationPreferences.email',
active: false,
configured: true,
},
{
id: 'webhook',
source: 'builtin',
labelKey: 'settings.notificationPreferences.webhook',
active: true,
configured: true,
},
{
id: 'inapp',
source: 'builtin',
labelKey: 'settings.notificationPreferences.inapp',
active: true,
configured: true,
},
],
event_types: ['trip_invite'],
implemented_combos: { trip_invite: ['inapp', 'webhook'] },
}),
})
),
http.post('/api/notifications/test-webhook', () =>
HttpResponse.json({ success: false, error: 'Connection refused' }),
),
HttpResponse.json({ success: false, error: 'Connection refused' })
)
);
render(
<>
<NotificationsTab />
<ToastContainer />
</>,
</>
);
await waitFor(() => {
@@ -470,7 +746,7 @@ describe('NotificationsTab', () => {
const input = await screen.findByRole('textbox');
await user.type(input, 'https://example.com/hook');
const testBtn = screen.getAllByRole('button').find(b => /test/i.test(b.textContent || ''));
const testBtn = screen.getAllByRole('button').find((b) => /test/i.test(b.textContent || ''));
expect(testBtn).toBeDefined();
await user.click(testBtn!);
@@ -480,3 +756,98 @@ describe('NotificationsTab', () => {
});
});
});
// ─────────────────────────────────────────────────────────────────────────────
// Plugin notification channels (e.g. a Gotify plugin)
// ─────────────────────────────────────────────────────────────────────────────
//
// A plugin channel must be a first-class citizen here alongside in-app/email/ntfy:
// its own column in the matrix, its state visible, and a way to act on it. The
// credentials themselves live on the plugin's settings page, so an UNconfigured
// channel links there rather than just naming the place.
const pluginMatrix = (over: Record<string, unknown> = {}) => ({
preferences: { trip_invite: { inapp: true, 'plugin:trek-gotify': true } },
channels: [
{ id: 'inapp', source: 'builtin', labelKey: 'settings.notificationPreferences.inapp', active: true, configured: true },
{
id: 'plugin:trek-gotify',
source: 'plugin',
label: 'Gotify',
settingsPath: '/settings?tab=plugins',
active: true,
configured: true,
...over,
},
],
event_types: ['trip_invite'],
implemented_combos: { trip_invite: ['inapp', 'plugin:trek-gotify'] },
});
function mockMatrix(matrix: unknown) {
server.use(
http.get('*/api/notifications/preferences', () => HttpResponse.json(matrix)),
http.get('*/api/settings', () => HttpResponse.json({ settings: {} })),
);
}
describe('NotificationsTab — plugin channels', () => {
beforeEach(() => {
resetAllStores();
seedStore(useAuthStore, { isAuthenticated: true, user: buildUser() });
});
it('FE-COMP-NOTIFICATIONS-PLUGIN-001: a configured plugin channel gets its own column, by its own name', async () => {
mockMatrix(pluginMatrix());
render(<NotificationsTab />);
// The server sends the display name outright — plugin channels have no i18n key.
// It appears TWICE by design: once as the channel's own card, once as the matrix
// column header — i.e. it really is a first-class column, not just a side panel.
const shown = await screen.findAllByText('Gotify');
expect(shown.length).toBe(2);
// …and it is togglable per event, exactly like a built-in.
await waitFor(() => expect(screen.getAllByRole('button').length).toBeGreaterThan(0));
});
it('FE-COMP-NOTIFICATIONS-PLUGIN-002: configured → offers a test send, no Configure link', async () => {
mockMatrix(pluginMatrix({ configured: true }));
render(<NotificationsTab />);
const test = await screen.findByRole('button', { name: /send test/i });
expect(test).toBeEnabled();
expect(screen.queryByRole('link', { name: /configure/i })).not.toBeInTheDocument();
});
it('FE-COMP-NOTIFICATIONS-PLUGIN-003: NOT configured → links to the plugin settings tab, test disabled', async () => {
mockMatrix(pluginMatrix({ configured: false }));
render(<NotificationsTab />);
const link = await screen.findByRole('link', { name: /configure/i });
// A real route — settings is one page with a ?tab= param, not a route per plugin.
expect(link).toHaveAttribute('href', '/settings?tab=plugins');
expect(screen.getByRole('button', { name: /send test/i })).toBeDisabled();
});
it('FE-COMP-NOTIFICATIONS-PLUGIN-004: Send test calls the generic channel-test route', async () => {
mockMatrix(pluginMatrix());
let called = '';
server.use(
http.post('*/api/notifications/test/:channelId', ({ params }) => {
called = String(params.channelId);
return HttpResponse.json({ success: true });
}),
);
render(<><NotificationsTab /><ToastContainer /></>);
await userEvent.click(await screen.findByRole('button', { name: /send test/i }));
await waitFor(() => expect(called).toBe('plugin:trek-gotify'));
});
it('FE-COMP-NOTIFICATIONS-PLUGIN-005: an INACTIVE plugin channel is not shown at all', async () => {
mockMatrix(pluginMatrix({ active: false }));
render(<NotificationsTab />);
await screen.findByText(/in-app/i);
// The admin hasn't enabled the channel — it must not appear as an option.
expect(screen.queryByText('Gotify')).not.toBeInTheDocument();
});
});
@@ -1,4 +1,5 @@
import React, { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { Lock } from 'lucide-react'
import { useTranslation } from '../../i18n'
import { notificationsApi, settingsApi } from '../../api/client'
@@ -6,19 +7,30 @@ import { useToast } from '../shared/Toast'
import ToggleSwitch from './ToggleSwitch'
import Section from './Section'
interface ChannelDescriptor {
id: string
source: 'builtin' | 'plugin'
/** Built-ins: an i18n key. */
labelKey?: string
/** Plugin channels: a literal name, already resolved by the server. */
label?: string
settingsPath?: string
active: boolean
configured: boolean
}
interface PreferencesMatrix {
preferences: Record<string, Record<string, boolean>>
available_channels: { email: boolean; webhook: boolean; inapp: boolean; ntfy: boolean }
channels: ChannelDescriptor[]
event_types: string[]
implemented_combos: Record<string, string[]>
defaults?: { ntfyServer: string | null }
}
const CHANNEL_LABEL_KEYS: Record<string, string> = {
email: 'settings.notificationPreferences.email',
webhook: 'settings.notificationPreferences.webhook',
inapp: 'settings.notificationPreferences.inapp',
ntfy: 'settings.notificationPreferences.ntfy',
/** Plugin channels have no i18n — the server sends their display name outright. */
function channelLabel(ch: ChannelDescriptor, t: (k: string) => string): string {
if (ch.labelKey) return t(ch.labelKey) || ch.id
return ch.label || ch.id
}
const EVENT_LABEL_KEYS: Record<string, string> = {
@@ -48,6 +60,7 @@ export default function NotificationsTab(): React.ReactElement {
const [ntfyTokenIsSet, setNtfyTokenIsSet] = useState(false)
const [ntfySaving, setNtfySaving] = useState(false)
const [ntfyTesting, setNtfyTesting] = useState(false)
const [channelTesting, setChannelTesting] = useState<string | null>(null)
useEffect(() => {
notificationsApi.getPreferences().then((data: PreferencesMatrix) => setMatrix(data)).catch(() => {})
@@ -71,13 +84,34 @@ export default function NotificationsTab(): React.ReactElement {
}).catch(() => {})
}, [])
// Columns are whatever the server says exists and the admin turned on — so a
// plugin channel gets a column here with no client change.
const visibleChannels = matrix
? (['email', 'webhook', 'ntfy', 'inapp'] as const).filter(ch => {
if (!matrix.available_channels[ch as keyof typeof matrix.available_channels]) return false
return matrix.event_types.some(evt => matrix.implemented_combos[evt]?.includes(ch))
? matrix.channels.filter(ch => {
if (!ch.active) return false
return matrix.event_types.some(evt => matrix.implemented_combos[evt]?.includes(ch.id))
})
: []
const hasChannel = (id: string) => matrix?.channels.some(ch => ch.id === id && ch.active) ?? false
// Plugin channels have no bespoke credential form here — the user fills those in on the
// plugin's own settings page. What they DO get is a test send, through the generic route.
const pluginChannels = matrix?.channels.filter(ch => ch.source === 'plugin' && ch.active) ?? []
const testChannel = async (ch: ChannelDescriptor) => {
setChannelTesting(ch.id)
try {
const result = await notificationsApi.testChannel(ch.id)
if (result.success) toast.success(t('settings.notificationPreferences.testSuccess'))
else toast.error(result.error || t('settings.notificationPreferences.testFailed'))
} catch {
toast.error(t('settings.notificationPreferences.testFailed'))
} finally {
setChannelTesting(null)
}
}
const toggle = async (eventType: string, channel: string) => {
if (!matrix) return
const current = matrix.preferences[eventType]?.[channel] ?? true
@@ -184,7 +218,7 @@ export default function NotificationsTab(): React.ReactElement {
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
{saving && <p style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', color: 'var(--text-faint)', marginBottom: 8 }}>{t('common.saving')}</p>}
{matrix.available_channels.webhook && (
{hasChannel('webhook') && (
<div style={{ marginBottom: 16, padding: '12px', background: 'var(--bg-secondary)', borderRadius: 8, border: '1px solid var(--border-primary)' }}>
<label style={{ display: 'block', fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600, color: 'var(--text-secondary)', marginBottom: 4 }}>
{t('settings.webhookUrl.label')}
@@ -215,7 +249,7 @@ export default function NotificationsTab(): React.ReactElement {
</div>
</div>
)}
{matrix.available_channels.ntfy && (
{hasChannel('ntfy') && (
<div style={{ marginBottom: 16, padding: '12px', background: 'var(--bg-secondary)', borderRadius: 8, border: '1px solid var(--border-primary)' }}>
<label style={{ display: 'block', fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600, color: 'var(--text-secondary)', marginBottom: 4 }}>
{t('settings.ntfyUrl.topicLabel')}
@@ -275,19 +309,50 @@ export default function NotificationsTab(): React.ReactElement {
</div>
</div>
)}
{pluginChannels.map(ch => (
<div key={ch.id} style={{ marginBottom: 16, padding: '12px', background: 'var(--bg-secondary)', borderRadius: 8, border: '1px solid var(--border-primary)' }}>
<label style={{ display: 'block', fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600, color: 'var(--text-secondary)', marginBottom: 4 }}>
{channelLabel(ch, t)}
</label>
<p style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', color: 'var(--text-faint)', marginBottom: 8 }}>
{ch.configured
? t('settings.notificationPreferences.pluginConfigured')
: t('settings.notificationPreferences.notConfigured')}
</p>
<div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
{/* Unconfigured is the common case on first use — send them to where the
credentials actually live rather than just naming the place. */}
{!ch.configured && ch.settingsPath && (
<Link
to={ch.settingsPath}
style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', padding: '6px 12px', background: 'var(--text-primary)', color: 'var(--bg-primary)', border: 'none', borderRadius: 6, textDecoration: 'none' }}
>
{t('settings.notificationPreferences.configure')}
</Link>
)}
<button
onClick={() => testChannel(ch)}
disabled={!ch.configured || channelTesting === ch.id}
style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', padding: '6px 12px', background: 'transparent', color: 'var(--text-secondary)', border: '1px solid var(--border-primary)', borderRadius: 6, cursor: (!ch.configured || channelTesting === ch.id) ? 'not-allowed' : 'pointer', opacity: (!ch.configured || channelTesting === ch.id) ? 0.5 : 1 }}
>
{t('settings.notificationPreferences.sendTest')}
</button>
</div>
</div>
))}
{/* Header row */}
<div style={{ display: 'grid', gridTemplateColumns: `1fr ${visibleChannels.map(() => '64px').join(' ')}`, gap: 4, paddingBottom: 6, marginBottom: 4, borderBottom: '1px solid var(--border-primary)' }}>
<span />
{visibleChannels.map(ch => (
<span key={ch} style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 600, color: 'var(--text-faint)', textAlign: 'center', textTransform: 'uppercase', letterSpacing: '0.04em' }}>
{t(CHANNEL_LABEL_KEYS[ch]) || ch}
<span key={ch.id} title={!ch.configured ? t('settings.notificationPreferences.notConfigured') : undefined} style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 600, color: ch.configured ? 'var(--text-faint)' : 'var(--color-warning, #d69e2e)', textAlign: 'center', textTransform: 'uppercase', letterSpacing: '0.04em' }}>
{channelLabel(ch, t)}
</span>
))}
</div>
{/* Event rows */}
{matrix.event_types.map(eventType => {
const implementedForEvent = matrix.implemented_combos[eventType] ?? []
const relevantChannels = visibleChannels.filter(ch => implementedForEvent.includes(ch))
const relevantChannels = visibleChannels.filter(ch => implementedForEvent.includes(ch.id))
if (relevantChannels.length === 0) return null
return (
<div key={eventType} style={{ display: 'grid', gridTemplateColumns: `1fr ${visibleChannels.map(() => '64px').join(' ')}`, gap: 4, alignItems: 'center', padding: '6px 0', borderBottom: '1px solid var(--border-primary)' }}>
@@ -295,13 +360,13 @@ export default function NotificationsTab(): React.ReactElement {
{t(EVENT_LABEL_KEYS[eventType]) || eventType}
</span>
{visibleChannels.map(ch => {
if (!implementedForEvent.includes(ch)) {
return <span key={ch} style={{ textAlign: 'center', color: 'var(--text-faint)', fontSize: 'calc(14px * var(--fs-scale-body, 1))' }}>—</span>
if (!implementedForEvent.includes(ch.id)) {
return <span key={ch.id} style={{ textAlign: 'center', color: 'var(--text-faint)', fontSize: 'calc(14px * var(--fs-scale-body, 1))' }}>—</span>
}
const isOn = matrix.preferences[eventType]?.[ch] ?? true
const isOn = matrix.preferences[eventType]?.[ch.id] ?? true
return (
<div key={ch} style={{ display: 'flex', justifyContent: 'center' }}>
<ToggleSwitch on={isOn} onToggle={() => toggle(eventType, ch)} />
<div key={ch.id} style={{ display: 'flex', justifyContent: 'center' }}>
<ToggleSwitch on={isOn} onToggle={() => toggle(eventType, ch.id)} />
</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,239 @@
import { useEffect, useState } from 'react'
import { Blocks, Save, Loader2, Link2, Unlink, CheckCircle } from 'lucide-react'
import { pluginsApi, type PluginUserSettingField, type PluginAction } 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)
const [actions, setActions] = useState<PluginAction[]>([])
const [running, setRunning] = useState<string | null>(null)
const [actionResult, setActionResult] = useState<Record<string, { ok: boolean; message?: string }>>({})
useEffect(() => {
let alive = true
pluginsApi.userSettings(id)
.then(r => {
if (!alive) return
setFields(r.fields)
setActions(r.actions ?? [])
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, actions, OR an OAuth connection to offer.
if (fields === null || (!hasFields && actions.length === 0 && !oauth?.configured)) return null
// An action runs AS the caller, so it sees the values they just saved — run the save
// first if the form is dirty would be nicer, but keeping it explicit is less surprising.
const runAction = async (a: PluginAction) => {
if (a.danger && !window.confirm(t('settings.plugins.actions.confirm'))) return
setRunning(a.key)
try {
const res = await pluginsApi.runAction(id, a.key)
setActionResult(prev => ({ ...prev, [a.key]: res }))
} catch {
setActionResult(prev => ({ ...prev, [a.key]: { ok: false, message: t('common.error') } }))
} finally {
setRunning(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>
)}
{actions.length > 0 && (
<div className="mt-4 border-t border-border pt-4">
<span className="block text-xs font-semibold uppercase tracking-wide text-content-muted mb-2">
{t('settings.plugins.actions')}
</span>
<div className="flex flex-col gap-2">
{actions.map(a => {
const res = actionResult[a.key]
return (
<div key={a.key} className="flex flex-wrap items-center gap-2">
<button
onClick={() => runAction(a)}
disabled={running !== null}
className={`inline-flex items-center gap-2 rounded-lg border px-3 py-1.5 text-sm font-semibold disabled:opacity-60 ${
a.danger ? 'border-danger text-danger' : 'border-border text-content'
}`}
>
{running === a.key && <Loader2 className="w-4 h-4 animate-spin" />}
{a.label}
</button>
{a.hint && <span className="text-xs text-content-muted">{a.hint}</span>}
{res && (
<span className={`text-xs font-medium ${res.ok ? 'text-success' : 'text-danger'}`}>
{res.message || (res.ok ? t('common.success') : t('common.error'))}
</span>
)}
</div>
)
})}
</div>
</div>
)}
<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()
+86 -43
View File
@@ -1,11 +1,10 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { render, screen, waitFor, fireEvent, within } from '../../tests/helpers/render';
import { http, HttpResponse } from 'msw';
import { beforeEach, describe, expect, it } from 'vitest';
import { buildAdmin } from '../../tests/helpers/factories';
import { server } from '../../tests/helpers/msw/server';
import { fireEvent, render, screen, waitFor, within } from '../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../tests/helpers/store';
import { buildUser, buildAdmin } from '../../tests/helpers/factories';
import { useAuthStore } from '../store/authStore';
import { useAddonStore } from '../store/addonStore';
import AdminPage from './AdminPage';
// Mock heavy sub-panels to focus on page-level concerns
@@ -145,7 +144,7 @@ describe('AdminPage', () => {
}),
http.get('/api/admin/stats', () => {
return HttpResponse.json({ error: 'Forbidden' }, { status: 403 });
}),
})
);
seedStore(useAuthStore, {
@@ -237,7 +236,7 @@ describe('AdminPage', () => {
await waitFor(() => {
expect(screen.getByText('42')).toBeInTheDocument(); // totalPlaces — unique on page
expect(screen.getByText('8')).toBeInTheDocument(); // totalFiles — unique on page
expect(screen.getByText('8')).toBeInTheDocument(); // totalFiles — unique on page
});
});
});
@@ -302,7 +301,7 @@ describe('AdminPage', () => {
server.use(
http.get('/api/admin/version-check', () => {
return HttpResponse.json({ update_available: true, latest: '9.9.9', current: '1.0.0' });
}),
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
@@ -330,7 +329,7 @@ describe('AdminPage', () => {
return HttpResponse.json({
addons: [{ id: 'mcp', name: 'MCP Tokens', type: 'mcp', icon: '', enabled: true }],
});
}),
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
@@ -347,9 +346,9 @@ describe('AdminPage', () => {
let capturedBody: Record<string, unknown> | null = null;
server.use(
http.put('/api/auth/app-settings', async ({ request }) => {
capturedBody = await request.json() as Record<string, unknown>;
capturedBody = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({});
}),
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
@@ -462,9 +461,9 @@ describe('AdminPage', () => {
let capturedBody: Record<string, unknown> | null = null;
server.use(
http.put('/api/auth/app-settings', async ({ request }) => {
capturedBody = await request.json() as Record<string, unknown>;
capturedBody = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({});
}),
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
@@ -543,9 +542,18 @@ describe('AdminPage', () => {
server.use(
http.get('/api/admin/invites', () => {
return HttpResponse.json({
invites: [{ id: 1, token: 'abcdef123456789', max_uses: 5, used_count: 0, expires_at: null, created_by_name: 'admin' }],
invites: [
{
id: 1,
token: 'abcdef123456789',
max_uses: 5,
used_count: 0,
expires_at: null,
created_by_name: 'admin',
},
],
});
}),
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
@@ -573,9 +581,18 @@ describe('AdminPage', () => {
server.use(
http.get('/api/admin/invites', () => {
return HttpResponse.json({
invites: [{ id: 1, token: 'abcdef123456789', max_uses: 5, used_count: 0, expires_at: null, created_by_name: 'admin' }],
invites: [
{
id: 1,
token: 'abcdef123456789',
max_uses: 5,
used_count: 0,
expires_at: null,
created_by_name: 'admin',
},
],
});
}),
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
@@ -612,11 +629,26 @@ describe('AdminPage', () => {
http.get('/api/admin/notification-preferences', () => {
return HttpResponse.json({
event_types: ['version_available'],
available_channels: { inapp: true, email: true },
channels: [
{
id: 'inapp',
source: 'builtin',
labelKey: 'settings.notificationPreferences.inapp',
active: true,
configured: true,
},
{
id: 'email',
source: 'builtin',
labelKey: 'settings.notificationPreferences.email',
active: true,
configured: true,
},
],
implemented_combos: { version_available: ['inapp', 'email'] },
preferences: { version_available: { inapp: true, email: true } },
});
}),
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
@@ -640,7 +672,7 @@ describe('AdminPage', () => {
return HttpResponse.json({
addons: [{ id: 'mcp', name: 'MCP Tokens', type: 'mcp', icon: '', enabled: true }],
});
}),
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
@@ -659,7 +691,7 @@ describe('AdminPage', () => {
server.use(
http.get('/api/admin/version-check', () => {
return HttpResponse.json({ update_available: true, latest: '9.9.9', current: '1.0.0' });
}),
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
@@ -723,9 +755,9 @@ describe('AdminPage', () => {
let capturedBody: Record<string, unknown> | null = null;
server.use(
http.put('/api/auth/app-settings', async ({ request }) => {
capturedBody = await request.json() as Record<string, unknown>;
capturedBody = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({});
}),
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
@@ -755,7 +787,7 @@ describe('AdminPage', () => {
server.use(
http.put('/api/admin/oidc', async ({ request }) => {
return HttpResponse.json(await request.json());
}),
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
@@ -788,9 +820,9 @@ describe('AdminPage', () => {
let capturedBody: Record<string, unknown> | null = null;
server.use(
http.put('/api/auth/app-settings', async ({ request }) => {
capturedBody = await request.json() as Record<string, unknown>;
capturedBody = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({});
}),
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
@@ -816,16 +848,16 @@ describe('AdminPage', () => {
let capturedBody: Record<string, unknown> | null = null;
server.use(
http.put('/api/auth/app-settings', async ({ request }) => {
capturedBody = await request.json() as Record<string, unknown>;
capturedBody = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({});
}),
})
);
// Start with email enabled by seeding smtpValues
server.use(
http.get('/api/auth/app-settings', () => {
return HttpResponse.json({ notification_channels: 'email', smtp_host: 'mail.example.com' });
}),
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
@@ -882,7 +914,7 @@ describe('AdminPage', () => {
server.use(
http.get('/api/admin/version-check', () => {
return HttpResponse.json({ update_available: true, latest: '9.9.9', current: '1.0.0' });
}),
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
@@ -942,8 +974,9 @@ describe('AdminPage', () => {
target: { value: 'alice-new@example.com' },
});
expect((screen.getByDisplayValue('alice-new@example.com') as HTMLInputElement).value)
.toBe('alice-new@example.com');
expect((screen.getByDisplayValue('alice-new@example.com') as HTMLInputElement).value).toBe(
'alice-new@example.com'
);
});
});
@@ -954,7 +987,7 @@ describe('AdminPage', () => {
http.put('/api/auth/me/api-keys', async ({ request }) => {
capturedBody = await request.json();
return HttpResponse.json({ success: true });
}),
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
@@ -986,7 +1019,7 @@ describe('AdminPage', () => {
http.put('/api/auth/me/api-keys', async ({ request }) => {
capturedBody = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({ success: true });
}),
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
@@ -1018,7 +1051,7 @@ describe('AdminPage', () => {
}),
http.get('/api/auth/validate-keys', () => {
return HttpResponse.json({ maps: true, weather: false });
}),
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
@@ -1079,7 +1112,7 @@ describe('AdminPage', () => {
http.delete('/api/admin/users/:id', ({ params }) => {
deletedId = params.id as string;
return HttpResponse.json({ success: true });
}),
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
@@ -1109,7 +1142,7 @@ describe('AdminPage', () => {
http.post('/api/admin/rotate-jwt-secret', () => {
rotateCalled = true;
return HttpResponse.json({ success: true });
}),
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
@@ -1142,7 +1175,7 @@ describe('AdminPage', () => {
smtp_host: 'mail.example.com',
smtp_skip_tls_verify: 'false',
});
}),
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
@@ -1186,7 +1219,7 @@ describe('AdminPage', () => {
http.post('/api/notifications/test-smtp', () => {
testSmtpCalled = true;
return HttpResponse.json({ success: true });
}),
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
@@ -1223,7 +1256,7 @@ describe('AdminPage', () => {
http.put('/api/auth/app-settings', async () => {
appSettingsCalled = true;
return HttpResponse.json({});
}),
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
@@ -1260,7 +1293,7 @@ describe('AdminPage', () => {
http.put('/api/auth/app-settings', async ({ request }) => {
savedPayload = await request.json();
return HttpResponse.json({});
}),
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
@@ -1292,7 +1325,15 @@ describe('AdminPage', () => {
http.get('/api/admin/notification-preferences', () => {
return HttpResponse.json({
event_types: ['trip.created'],
available_channels: { email: true },
channels: [
{
id: 'email',
source: 'builtin',
labelKey: 'settings.notificationPreferences.email',
active: true,
configured: true,
},
],
implemented_combos: { 'trip.created': ['email'] },
preferences: { 'trip.created': { email: true } },
});
@@ -1300,7 +1341,7 @@ describe('AdminPage', () => {
http.put('/api/admin/notification-preferences', async () => {
prefUpdateCalled = true;
return HttpResponse.json({ success: true });
}),
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
@@ -1346,7 +1387,9 @@ describe('AdminPage', () => {
// Discovery URL field
const discoveryInput = within(oidcCard!).getByPlaceholderText(/openid-configuration/i);
fireEvent.change(discoveryInput, { target: { value: 'https://auth.example.com/.well-known/openid-configuration' } });
fireEvent.change(discoveryInput, {
target: { value: 'https://auth.example.com/.well-known/openid-configuration' },
});
// Client ID field
const clientIdLabel = within(oidcCard!).getByText('Client ID');
+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 }] : []),
+62
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';
@@ -656,6 +657,30 @@ describe('TripPlannerPage', () => {
});
});
describe('FE-PAGE-PLANNER-020b: the transit (tram) action needs trip dates', () => {
async function renderWithTripDates(dates: { start_date: string | null; end_date: string | null }) {
vi.useFakeTimers();
const { trip } = seedTripStore({ id: 42 });
seedStore(useTripStore, { trip: { ...trip, ...dates } } as any);
renderPlannerPage(42);
act(() => { vi.runAllTimers(); });
vi.useRealTimers();
await waitFor(() => {
expect(screen.getByTestId('day-plan-sidebar')).toBeInTheDocument();
});
}
it('passes onPlanTransit when the trip has a start and end date', async () => {
await renderWithTripDates({ start_date: '2025-06-01', end_date: '2025-06-05' });
expect(capturedDayPlanSidebarProps.current.onPlanTransit).toBeInstanceOf(Function);
});
it('omits onPlanTransit — hiding the tram button — when the trip has no dates', async () => {
await renderWithTripDates({ start_date: null, end_date: null });
expect(capturedDayPlanSidebarProps.current.onPlanTransit).toBeUndefined();
});
});
describe('FE-PAGE-PLANNER-021: handlePlaceClick covers place selection logic', () => {
it('calls handlePlaceClick through captured DayPlanSidebar props', async () => {
vi.useFakeTimers();
@@ -1336,6 +1361,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();
+15 -9
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,
@@ -223,6 +223,9 @@ export default function TripPlannerPage(): React.ReactElement | null {
const meId = useAuthStore(s => s.user?.id ?? -1)
const displayCurrency = useSettingsStore(s => s.settings.default_currency)
const costsBase = (displayCurrency || trip?.currency || 'EUR').toUpperCase()
// Transit search departs against a real date, so the whole Automated mode —
// the day-header tram button and the modal's mode switch — is off without one.
const tripHasDates = Boolean(trip?.start_date && trip?.end_date)
const loadBudgetItems = useTripStore(s => s.loadBudgetItems)
const [bookingExpense, setBookingExpense] = useState<{ editing: BudgetItem | null; prefill?: ExpensePrefill } | null>(null)
const openBookingExpense = (req: BookingExpenseRequest) => {
@@ -300,12 +303,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}
@@ -407,7 +412,7 @@ export default function TripPlannerPage(): React.ReactElement | null {
onAddReservation={(dayId) => { setEditingReservation(null); tripActions.setSelectedDay(dayId); setShowReservationModal(true) }}
onAddTransport={can('day_edit', trip) ? (dayId) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill(null); setTransportModalAutomated(false); setShowTransportModal(true) } : undefined}
onOpenTransit={(r) => setTransitJourney(r)}
onPlanTransit={can('day_edit', trip) ? (dayId) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill(null); setTransportModalAutomated(true); setShowTransportModal(true) } : undefined}
onPlanTransit={can('day_edit', trip) && tripHasDates ? (dayId) => { setTransportModalDayId(dayId); setEditingTransport(null); setTransitPrefill(null); setTransportModalAutomated(true); setShowTransportModal(true) } : undefined}
onEditTransport={can('day_edit', trip) ? (reservation) => { setEditingTransport(reservation); setTransportModalDayId(reservation.day_id ?? null); setShowTransportModal(true) } : undefined}
onEditReservation={can('reservation_edit', trip) ? (r) => { setEditingReservation(r); setShowReservationModal(true) } : undefined}
onDayDetail={(day) => { setShowDayDetail(day); setSelectedPlaceId(null); selectAssignment(null) }}
@@ -628,9 +633,9 @@ 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 />
? <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) && tripHasDates ? (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 }} />
}
</div>
@@ -659,6 +664,7 @@ export default function TripPlannerPage(): React.ReactElement | null {
onNavigateToFiles={() => handleTabChange('dateien')}
titleKey="transport.title"
addManualKey="transport.addManual"
contributionView="transports"
/>
</div>
)}
@@ -718,7 +724,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 +737,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} tripHasDates={tripHasDates} />}
{/* Journey view for a saved public-transit entry (#1065) */}
{transitJourney && (
<TransitJourneyModal
@@ -15,8 +15,11 @@ export default function AdminNotificationsPanel({ t, toast }: { t: (k: string) =
if (!matrix) return <p className="text-content-faint" style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontStyle: 'italic', padding: 16 }}>Loading…</p>
// Admin-scoped events only ever go out over the built-in channels (plugin channels
// are user-scoped), so this list stays explicit rather than server-driven.
const isActive = (id: string) => matrix.channels?.some((c: { id: string; active: boolean }) => c.id === id && c.active) ?? false
const visibleChannels = (['inapp', 'email', 'webhook', 'ntfy'] as const).filter(ch => {
if (!matrix.available_channels[ch]) return false
if (!isActive(ch)) return false
return matrix.event_types.some((evt: string) => matrix.implemented_combos[evt]?.includes(ch))
})
@@ -26,13 +26,16 @@ export default function AdminNotificationsTab({ admin, t }: AdminNotificationsTa
const tripRemindersActive = smtpValues.notify_trip_reminder !== 'false'
const setChannels = async (email: boolean, webhook: boolean, ntfy: boolean) => {
const chans = [email && 'email', webhook && 'webhook', ntfy && 'ntfy'].filter(Boolean).join(',') || 'none'
// Preserve any id this toggle doesn't know about instead of rebuilding the CSV from
// just these three booleans — that used to silently DROP anything else stored here.
const others = activeChans.filter((c: string) => c !== 'email' && c !== 'webhook' && c !== 'ntfy')
const chans = [email && 'email', webhook && 'webhook', ntfy && 'ntfy', ...others].filter(Boolean).join(',') || 'none'
setSmtpValues(prev => ({ ...prev, notification_channels: chans }))
try {
await authApi.updateAppSettings({ notification_channels: chans })
} catch {
// Revert state on failure
const reverted = [emailActive && 'email', webhookActive && 'webhook', ntfyActive && 'ntfy'].filter(Boolean).join(',') || 'none'
const reverted = [emailActive && 'email', webhookActive && 'webhook', ntfyActive && 'ntfy', ...others].filter(Boolean).join(',') || 'none'
setSmtpValues(prev => ({ ...prev, notification_channels: reverted }))
toast.error(t('common.error'))
}
+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',
+8
View File
@@ -35,5 +35,13 @@ export function useSettings() {
}
}, [searchParams])
// Deep link into a tab: /settings?tab=plugins. Lets one tab point at another —
// e.g. an unconfigured plugin notification channel sends you to where its
// credentials actually live, instead of just naming the place.
useEffect(() => {
const tab = searchParams.get('tab')
if (tab) setActiveTab(tab)
}, [searchParams])
return { hasIntegrations, appVersion, activeTab, setActiveTab }
}

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