mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-10-18 21:16:47 +00:00
Comprehensive mobile UI rewrite + desktop Vacay & Journey redesign (#1577)
* 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. * fix(plugin-sdk): serve dev /ui frame at /ui/index.html so relative assets resolve (#1526) The dev server embedded the plugin UI as <iframe src="/ui"> (no trailing slash), so a multi-file build's relative asset URLs (./assets/x.js from Vite base:'./') resolved against the origin root -> /assets/x.js -> 404, even though the files are served at /ui/assets/*. The real host loads the frame at /plugin-frame/<id>/index.html where the same relative URLs resolve correctly, so dev now matches it by loading /ui/index.html (and also serves /ui/ as index.html). * i18n: improve Russian translations (#1539) * v3.4.0 (#1527) * fix(plugins): unknown column * fix(mcp): reuse MCP sessions instead of creating one per tool call The /mcp CORS layer never set exposedHeaders, so Access-Control-Expose-Headers was absent and browser-context MCP clients (Claude Desktop connectors, Claude.ai, MCP Inspector) could not read Mcp-Session-Id off the initialize response. Unable to echo it back, every request looked like a fresh initialize: one McpServer and one session per tool call, until the per-user cap returned a 429 and the integration died until the container was restarted. The idle sweep was not at fault — it expires on lastActivity with a 1h default, so sessions born seconds apart are nowhere near expiry, hence 'cleaned 0'. - expose Mcp-Session-Id, MCP-Protocol-Version and WWW-Authenticate - evict a user's least-recently-active session at the cap rather than refusing the request, so a client that cannot persist its session id (or a proxy that strips the header) can never wedge the server - close the McpServer/transport orphaned by every session-less non-initialize POST, which was leaked: never mapped, never swept, never closed - return the cap error as JSON-RPC so clients surface the real reason - warn on session-less POSTs to make a header-stripping proxy diagnosable * chore(deps): declare @modelcontextprotocol/sdk ^1.29.0 Matches the version already resolved in the lockfile; no dependency-tree change. * docs(mcp): add the reverse proxy specs for MCP * fix(plugins): stop the row ⋯ menu being clipped by the sidebar The menu was an in-flow `absolute` div, and its ancestor (PageSidebar) is `overflow-hidden` — which clips absolutely-positioned descendants regardless of z-index. With enough plugins installed a row sits low enough that its menu runs past the sidebar's bottom edge and gets chopped, taking Delete with it, so the plugin could no longer be uninstalled from the UI. Portal the menu to <body> and position it `fixed` against the ⋯ button, flipping upward when the bottom is tight and re-anchoring on scroll/resize. A fixed child of <body> has no overflow ancestor, so nothing can clip it. Closes #1523 * feat(plugins): surface author-signature status and add a scoped re-trust override TREK has always verified an author's Ed25519 signature and TOFU-pinned the key on first install, but none of it was ever shown: a successfully-installed UNSIGNED plugin looked identical to a signed one, and a signature-refused update left the plugin quietly pinned at its old version with the reason dying in a toast. Give the four refusal conditions machine-readable codes (SIGNATURE_MISSING / _INCOMPLETE / _KEY_CHANGED / _INVALID), persist a refusal on the plugin row so the admin list keeps showing it, and badge Signed/Unsigned in the list and in Discover. Only SIGNATURE_KEY_CHANGED is overridable — an author can legitimately rotate a key; a signature that does not verify means the bytes are not what the author signed, and there is no story where waving that through is right. The override re-pins and updates in ONE call (POST :id/retrust): a re-pin that waited for a follow-up /update would leave the plugin pinned to a key no install had ever been verified against if that second call never came. The artifact must still verify under the new key, so a re-trust moves the pin from one verified key to another. assertRetrustable re-derives the condition server-side, so the UI hiding the button is a convenience, not the control, and it echoes back the full key the admin was shown so a re-key since the dialog rendered is refused. The rotation is written to the admin audit log with both fingerprints — after an incident, "which key did we move from, and to what?" is the question a single key cannot answer. * fix(plugins): let a plugin's frame reach the hosts an admin added for it The frame's connect-src was built from the manifest's http:outbound grants alone, but the child's egress guard is the UNION of those and the hosts an admin added after install for an operatorEgress plugin (a self-hosted Gotify, an ntfy — hosts the author cannot know in advance). So such a plugin WITH A UI could call the operator's host from its server and was CSP-blocked in its own iframe. Match the frame to the child. The admin consented to these hosts at install and the child already reaches them, so this widens no trust boundary that isn't already crossed. Both sources stay validated on the way in, and the interpolation filter is unchanged. * fix(plugins): report a rejected events.emit on the plugin's own log stream The host can reject an emit (an undeclared event name, a rate limit). The rejection must not escape — a detached rejection crashes the child and terminally disables the plugin over one bad emit — but swallowing it silently left an author with no way to discover that `emits` was missing from their manifest. Surface it as a warning instead. * feat(plugin-sdk): expose the raw request body for webhook signature checks A webhook author must run their HMAC over the exact bytes the sender signed. `body` is the PARSED value, and re-serializing it will not reproduce those bytes — key order, whitespace and unicode escaping all differ — so the signature never matches. Document `rawBodyBase64`, which the host already sets on auth:false routes. * fix(plugin-sdk): refuse to overwrite a released artifact, and keep the packed zip A released artifact is IMMUTABLE: the registry pins its sha256, so overwriting the bytes of a release already in the registry breaks the checksum for everyone who installed that version — they can no longer install or update it. The old code blanket-caught every `gh release create` failure (auth, network, a bad repo) and turned it into a --clobber upload. Probe for the release explicitly and refuse unless --force. Also stop deleting plugin.zip on the way out. It is the exact bytes the release and the entry's sha256 pin were computed from; a re-pack on another machine or SDK version can differ (CRLF, walk order), so anyone re-running `entry`/`sign` afterwards must hash THAT file, not a rebuild. * fix(plugin-sdk): don't fail submit when the fork already has an upstream remote `gh repo clone` of a fork may already have wired `upstream`, in which case a bare `remote add` exits non-zero and took the whole submit down. Set it either way. * fix(plugin-sdk): make the dev server behave like the host Three ways `dev` lied to an author about how their plugin would run in production: - ctx.db: one try/catch wrapped both the node:sqlite probe AND opening the database, so an mkdir/permission failure silently degraded to the in-memory stub — which swallows every write while reporting success. A db:own plugin "worked" in dev and persisted nothing. Probe separately: fail loudly on a real error, degrade only on old Node, and say plainly that the stub discards writes. - notificationChannel: the host fires it with no acting user and hands the recipient's decrypted settings in as a separate `config` argument — send(msg, config, ctx) / test(config, ctx). Firing it like an ordinary hook passed `ctx` where `config` belongs, so a channel plugin read its settings off ctx and was broken in production. - /preview pinned tripId 42 while the scaffold seeds trip 1, so the widget's first trek:invoke hit assertMember(42) and 500'd. Preview against a trip that exists. * fix(plugin-sdk): reject unknown flags, wire up create's new flags, and add --help `parse()` accepts any --x, so a flag a command does not read was silently dropped: `create --template notification-channel` cheerfully scaffolded a blank plugin. Silently ignoring an author's explicit instruction is worse than refusing it, so unknown flags are now an error, and create actually forwards --template/--egress/--required-addons. A bare --permissions used to split the string "true" into a permission literally named `true`; listFlag() now treats a valueless flag as absent. Since an unknown flag is now fatal, `--help` has to exist: it is intercepted before the flag check and prints usage on stdout with exit 0. * chore(plugins): drop three unused eslint-disable directives The no-console rule is not enabled for these files, so the directives were dead and eslint reports them as unused. * fix(plugin-sdk): bring preflight back in step with the registry's gates preflight exists to tell an author what TREK-Plugins' CI will say before they open the PR. The registry now verifies author signatures, and preflight didn't — so it drifted into the one failure mode it must never have: a false green. An author trusts a green. - Verify the signature against the artifact bytes. preflight already downloads them for the sha256 check, so this costs one call. Without it, signing with the wrong key (or re-packing after signing) sails through and is caught at review. - Check the signature SHAPE (checkSignatureShape): a key with no signed version, a signature with no key, a malformed key or signature. TREK refuses to install a half-signed entry, so such an entry is dead on arrival. - Default apiVersion to 1 before comparing. It is OPTIONAL in the manifest — install/ manifest.ts and `entry` both default it — so a manifest that legally omits it was failing preflight with "manifest apiVersion undefined != entry 1" while the registry passed it. A false RED, which teaches authors to ignore the tool. - Check requiredAddons/pluginDependencies parity, and operatorEgress without an http:outbound grant. The verifier is a port of the host's install/verify-signature.ts (the registry has its own port); sign.ts's verifyArtifact only understands the bare key/signature pair the SDK itself emits and cannot judge a minisign key. A test pins all three to the same verdicts. * feat(plugins): enforce compatibility range * chore: bump sdk version * test(e2e): repair the trip-creation specs create-trip and trip-planner have been failing for a while — long enough for three separate UI changes to drift past them, which nothing caught because CI runs vitest only and never invokes Playwright. Each failure was masking the next: - The release-notice modal greets a freshly seeded user and its backdrop swallowed the click on .add-trip-card. Added a shared dismissSystemNotices() helper (the X only shows on the notice's last page, so it has to page through first). - .modal-backdrop no longer exists — the class was namespaced to .trek-modal-backdrop so content blockers stop hiding it. - input[type=text].first() is no longer the Title field: the cover-image search inputs now sit above it, so the specs were typing the trip name into the photo search box and creating an untitled trip that never matched getByText(title). * fix(planner): gate drag & drop on pointer type, not viewport width (#1432) The 3.2.1 fix disabled drag on "mobile", but nothing in the client has ever detected touch — "mobile" was inferred from viewport width, at four independent breakpoints. A tablet is a coarse-pointer device at a *desktop* width, so an iPad (820-1366px) fell on the wrong side of all four, which is why iPhone was fixed and iPad was not: - useTripPlanner's isMobile (<768px) is what disarmed `draggable`, so on iPad rows stayed draggable and a scroll swipe became an HTML5 drag. - TripPlannerPage hardcoded isMobile={false} on the desktop PlacesSidebar, so its drop handlers and the drop-to-import overlay could never be disabled — that overlay is the reported symptom. - The arrow-button reorder fallback was revealed only below 767px, leaving iPad with no drag *and* no fallback. - touchDragPolyfill loaded drag-drop-touch at >=1024px, synthesising drags from touchmove — on a landscape iPad that re-armed the very gesture hijack 3.2.1 removed. Adds useIsTouch() ((pointer: coarse)) as a signal separate from isMobile: layout stays width-driven, so the iPad keeps the desktop two-pane planner, while every drag affordance is gated on isMobile || isTouch. The reorder arrows now show on coarse pointers, and the polyfill loads only on hybrid laptops ((pointer: fine) and (any-pointer: coarse)), which also removes the #1440 phantom-dblclick map zoom on tablets. Guarded by unit tests plus an e2e spec on real WebKit in an iPad Pro 11 context — the engine matters, since every browser on iPadOS is WebKit underneath, which is why the reporter hit this in all three they tried. * test(planner): guard the day-plan reorder arrows against phantom clicks The hover rule that reveals the reorder arrows had been dead since the TypeScript migration: it targeted `.place-row:hover .reorder-btns`, and neither class exists — the component renders `.reorder-buttons` inside an unclassed row. The buttons sat at opacity:0 on desktop with nothing to reveal them. That was not merely invisible. opacity:0 still hit-tests, so every itinerary row and day note carried an invisible, fully clickable target that silently reordered the trip: opacity: "0", visibility: "visible", pointerEvents: "auto" elementFromPoint(centre) -> BUTTON, inside .reorder-buttons The repair — pointer-events: none while hidden, plus a working .dp-row:hover/:focus-within reveal (focus-within so the buttons are also reachable by keyboard, which the file's JS-hover pattern cannot do) — lives in index.css and DayPlanSidebar.tsx. Both files also carry the #1432 drag gating, so they went with that commit rather than being split mid-file; this commit is the regression guard for them. E2E rather than unit, because jsdom does not evaluate :hover. Against the old CSS it fails on exactly the right assertion: "hidden arrows must not swallow clicks" — expected false, received true. * fix(pdf): keep the header gap on day-header overflow pages (#1531) The repeated <thead> day header (#1471) carried no gap before the first card on overflow pages: the 12px sat in .day-body's block-start padding, which a fragmented box only paints on its first fragment. Move it to the thead cell so it repeats with the header; the day's first page renders pixel-identically. * fix(budget): keep "no one paid yet" when editing an expense (#1533) The ExpenseModal payer initializer fell back to the current user whenever the edited item had no payer, so reopening an expense saved with "no one paid yet" silently reselected "You" — and re-saving then recorded the current user as the payer, corrupting the balances. An absent payer on an existing expense is a deliberate value, so only a brand-new expense defaults to me. * feat(sdk): support for plugin icons * fix(planner): keep the places filter applied and visible across tab switches The category and all/unplanned/tracks filters lived twice: a local copy in the sidebar driving the checkboxes and the list, and a page-level copy driving the map markers, synced only when a checkbox was clicked. Switching planner tabs unmounts the sidebar, so the local copy reset to "All Categories" while the markers stayed filtered — and the only way out was toggling any category on and off again (#1541). The filter now lives once in the trip store, next to selectedDayId: it survives the Plan tab unmounting (and the mobile places sheet closing), keeps both sidebar instances in agreement, and resets when another trip loads. * feat(airtrail): import connecting flights as one multi-leg booking AirTrail flights always imported as separate single-leg reservations, so a layover could not be expressed and the connection country ended up counted as visited in Atlas (#1535). The import picker now detects connection chains among the listed flights — each leg departing from the airport the previous one landed at, onward within 24 hours, and never back to the origin (an out-and-back is a return, not a connection) — and offers to import each chain as one flight with layover stops, on by default. The joined booking keeps per-leg airline, flight number, times and seat in metadata.legs, files every leg on its own trip day, and mirrors the first/last leg flat, exactly like the manual multi-leg form. With the connection stored as a stop endpoint, the existing Atlas role filter excludes the layover country on its own. AirTrail has no multi-leg flight a joined booking could round-trip to, so it imports detached from live sync, with every source flight id recorded in metadata.airtrail_ids — the picker and the server-side dedupe both treat those legs as imported, per leg, even across trip members. The server re-validates each requested chain and falls back to individual imports when it does not actually connect. * fix(airtrail): stop syncing a booking once it grows extra stops A linked flight that becomes multi-leg locally no longer matches the single AirTrail flight it was imported from: pushing would rewrite that flight to span the whole route, and the next pull would flatten the layover chain back to a plain from/to. Both sync directions now detach the link instead — the same state a joined import starts in, surfaced by the existing "Not synced" badge. TransportModal also carries metadata.airtrail_ids through re-saves (like it already does for transit itineraries and day positions), so editing a joined booking cannot cost it its import dedupe and get its legs re-offered in the picker. * fix(planner): default a new accommodation to checking out the next day The hotel picker pre-filled "Apply to days" with the same day for check-in and check-out — a stay that ends the day it begins. New accommodations now default to the following day for check-out; the last trip day keeps the same-day range, and editing still seeds from the stored range. * docs(wiki): document the AirTrail import and connection joining * fix(plugins): fold resolvePluginIcon into PluginIcon pluginIcon.ts and PluginIcon.tsx resolve to the same file on the case-insensitive filesystems dev checkouts commonly sit on (Windows, macOS) — tsc sees both casings of one module and fails with TS1149 in every importer. Keep the resolver and the component in one module. * feat(sdk): add update verification * chore: remove test files * fix(sdk) rework the sdk helpers and DX/UX * fix(sdk) harden dev environment * fix(budget): add back the multi payer selection * fix(map): stop MapLibre mouse rotation from reversing near mid-screen Since MapLibre 5's camera rewrite, the right-button rotate handler flips its sign whenever the cursor sits above a mid-screen line it derives by re-projecting the map center. That line drifts with the bearing by a fraction of a pixel, so inside the 100px band around the screen center a steady horizontal drag lands alternately above and below it — every processed movement reverses the previous one and the camera ping-pongs in place instead of rotating (#1545). A real hand crossing the line mid-drag flips the rotation direction outright. maplibre-gl 4.x rotated from plain horizontal movement and had none of this. Passing aroundCenter: false opts the handler out of the around-center mode and restores the 4.x/mapbox-gl behaviour: horizontal drag rotates, vertical drag pitches, in one continuous motion. Applied to all three GL map builds (planner, journey, settings preview); mapbox-gl keeps its options untouched. * fix(budget): settle in the trip's real currency, not always EUR The settlement route read `currency` off the row returned by canAccessTrip, whose SELECT never included the column. A cast hid the mistake, so trip.currency was always undefined and the settlement was told every trip is in EUR. Balances are netted in the trip currency and converted to the display currency once. With the trip mislabelled EUR, expenses in the trip's own currency still cancelled out, but an expense booked in a foreign currency was divided by its frozen rate into trip-currency units, then converted again as if those were euros — inflating balances by the EUR/trip rate (~27x for a RUB trip with a USD expense, #1543). MCP was unaffected: it reads the currency with its own SELECT. Select the currency in canAccessTrip so the read is real. The settlement maths was correct all along; it was simply being lied to about the base currency. Fixes #1543 * feat(trips): let users set the trip currency, and rebase the budget when it changes The trip currency is the base every expense and settle-up is netted against, but the only picker for it lived in the legacy Budget addon panel — so on the Costs panel a trip was stuck with whatever it was created as. Add the field to the trip form, on create and on edit, gated on trip_edit. The REST and MCP write paths already accepted `currency`; only the form was missing. Changing it is not a rename, though: an expense's frozen `exchange_rate` is "units of its currency per 1 trip currency", and `currency = NULL` means "the trip's own", so both are relative to the outgoing base. Swapping it out from under them redenominates the implicit rows (9 000 RUB becoming 9 000 EUR) and leaves the frozen rates pointing at a currency the trip no longer uses — the same mismatch that inflated #1543. So rebaseTripCurrency() runs first, while the old currency is still on the row: it pins the implicit rows to the outgoing currency and re-freezes every rate against the incoming one, for expenses and settle-up transfers alike. No stored amount is rewritten — each keeps the figure the user typed, in the currency they typed it in, and its real-world value survives the switch. Also covers the #1543 data as a settlement regression test. * feat(budget): give settle-up payments their own currency A transfer settling a shared bill can be made in any currency — paying a rouble debt in euros is normal — and the server has stored `currency` + a frozen `exchange_rate` on every transfer since #1445, re-freezing it on edit. The UI just never let anyone choose one, so a payment silently inherited whatever the viewer's display currency happened to be. Add the picker to the payment modal, mirroring the expense modal, and reopen an existing payment in the currency it was actually recorded in. The ledger row now shows a foreign payment as `$30.00 -> 27,00 EUR` like a foreign expense does, instead of stamping the display currency's symbol onto the raw stored number. The Settle buttons on the suggested flows keep sending the display currency: those amounts are computed in it. * feat(settings): make the display currency optional, falling back to the trip's Costs already resolved `default_currency || trip.currency || 'EUR'`, but the setting could never actually be empty: the store seeded 'USD', so a user who had never touched it silently had every trip converted into dollars, and the picker offered no way to unset it. Seed it empty and lead the picker with a "Trip currency" option, so an unset preference means "show each trip in its own currency" instead of forcing them all through one code. An explicit empty value persists and beats the admin-set instance default — it is a deliberate choice, not an absence. This also brings the public share's fallback to life: the share payload has resolved sharer's currency -> trip currency since #1361, but the trip-currency branch was unreachable while every owner had a currency forced on them. Plugins are handed `formats.currency` as a concrete code, so PluginFrame now resolves the same chain rather than passing an empty string through the bridge. * docs(wiki): explain the three currencies and how they relate Trip currency, expense currency and display currency answer three different questions, and nothing said so: the trip currency wasn't documented at all (it had no picker until now), and Budget-Tracking conflated the other two while still claiming 47 currencies and a display currency that always came from Settings. Add a Currencies page as the one place they're defined together — the trip currency as the accounting base, the expense currency as the receipt with its rate frozen at entry, the display currency as presentation-only — plus what happens when a trip's currency changes, which currency a public share renders in, and what belongs to the Costs addon versus the trip itself. Rewrite Budget-Tracking's currency section against it, document the currency field in Creating-a-Trip and the display currency in Display-Settings (which never mentioned it), and note the sharer-or-trip fallback in Public-Share-Links. * feat(help): serve the in-app wiki from disk instead of fetching GitHub The /help pages fetched their markdown from raw.githubusercontent.com at runtime, so a self-hosted install was served docs from main rather than the version it was actually running, and help was unusable without network access. The wiki/ directory was in the repo the whole time; the bundled-snapshot fallback the code reached for was gitignored and never populated by any build step, so it was dead code. Read wiki/ straight from disk instead. server/{src,dist}/services both sit three levels under the repo root, so a single __dirname anchor resolves in dev, a built source install, vitest and Docker with no copy or build step. GitHub is kept strictly as a fallback for when the directory cannot be resolved, decided once at load by probing for _Sidebar.md: a page missing from a present wiki is a genuine 404, since falling back per-file would reintroduce the version skew this removes. Ship wiki/ in the image: .dockerignore excluded it outright, so the COPY alone would have produced an image with no wiki, and the GitHub fallback would have masked that at runtime. Add a real path-containment check on assets now that the path becomes a filesystem read rather than a URL, and document TREK_WIKI_DIR as an off-by-default escape hatch across the deployment configs. * fix(plugins): serve frame assets root-relative and cross-origin loadable res.sendFile(absolutePath) resolves against the rewritten req.url under the Nest ExpressAdapter and 404s spuriously (files-download already works around the same trap), which broke every plugin frame document. And helmet's CORP: same-origin made the browser drop the opaque-origin frame's own script/style subresources, so a multi-file plugin client could never boot. Serve root-relative and mark frame responses cross-origin — sandbox + per-plugin CSP stay the isolation boundary. * feat(plugins): let a plugin ship its own settings page A plugin that declares capabilities.settingsUi: true gets its client/settings.html framed as a card under Settings -> Plugins — same opaque-origin sandbox and postMessage bridge as its widget, sized via trek:resize. Hosts that predate the flag strip it at install, so old instances keep working and simply don't show the card. * feat(map): open maps framed on their places (builds on #1393) (#1556) * fix(map): fit MapLibre routes reliably * fix(map): default planner map to world view * fix(map): only await route geometry when a route is actually pending The fit armed a pending route-refit slot on every fitKey change, even with no route drawn, and only ever cleared it when a route arrived. So a route toggled on much later — after the user had panned elsewhere — was mistaken for the awaited geometry and yanked the camera back, and only on the first toggle. Arm the slot only when a route is already on screen: updateRouteForDay lays down straight lines in the same batch as the fit and upgrades them to real geometry a moment later, so an empty route at fit time means none is coming. * fix(collections): open the empty collection map on the world view A collection with no mappable places centred on Paris, the same hardcoded default this branch removes everywhere else. * feat(map): open the map framed on its places A trip in Japan opened on the world view at 0,0 and only then animated a fitBounds flight across the planet — the hardcoded default was the map's answer to a question its own places already answer. Each renderer now derives its opening camera from the places it receives, at construction: MapView for Leaflet, MapViewGL for MapLibre and Mapbox (whose zoom runs one level below Leaflet's, measuring against a 512px world tile rather than 256px). Doing it at construction is what confines it to load — the map is built once, and by then the trip's places are in hand. Nothing recomputes it afterwards, so the camera stays where the user leaves it, and the opening fit stands down rather than overruling the gentler zoom a lone place opens at. A trip with no coordinates still falls back to the world view. Collections and the public shared-trip page frame themselves the same way. * refactor(settings): drop the default map centre and zoom Nothing reads them now that every map frames itself on its own places, and a home-city default was the wrong answer for the next trip on the other side of the world. The style preview keeps a fixed location of its own: it needs a city to show label density and 3D buildings, which open ocean cannot. * fix(map): frame the map the way each renderer can actually draw Two defects the unit tests missed and running the app exposed. MapLibre and Mapbox opened on Null Island at zoom 2 regardless of the places: the effect that mirrors an external centre prop onto the camera also ran on mount, so it jumped straight to the default nobody passed and threw away the camera the map had just been built with. It now only responds to actual changes, which is what it was for. Leaflet was unaffected — its controller already guarded on the centre changing. A trip spanning Sydney, Reykjavik and Santiago lost Sydney's marker entirely. The narrowest arc containing all three crosses the antimeridian, and framing there is only sound on a renderer that repeats the world: MapLibre and Mapbox draw a marker on whichever copy is nearest the camera, Leaflet draws one world and puts the marker at its absolute position — off-screen. Leaflet now spans the long way round, as L.latLngBounds would. The test that should have caught this wrapped the x-offset in its own projection helper, quietly assuming behaviour Leaflet does not have; it now models each renderer's real wrapping. --------- Co-authored-by: Azalea <noreply@aza.moe> * feat(mcp): expose public transit planning tools (#1558) * feat(mcp): add public transit planning tools * refactor(transit): reuse local time conversion * fix(mcp): harden transit journey validation * refactor(transit): centralize itinerary processing * fix(mcp): return the transit itineraries the provider actually offers search_transit_routes validated each itinerary leg's mode against SCHEDULED_TRANSIT_MODES, but that constant is the request-side filter whitelist — the modes a caller may ask for — not the modes MOTIS can return. Its default TRANSIT mode expands to TRAM,FERRY,AIRPLANE,BUS,COACH,RAIL,ODM, RIDE_SHARING,FUNICULAR,AERIAL_LIFT,OTHER, and street legs can be BIKE/CAR/ RENTAL. Any itinerary carrying one of those failed the parse and was dropped by the flatMap, so the tool reported fewer routes than exist — or none at all. Against the live provider, Trondheim → Ålesund returns 5 itineraries and 3 of them contain an AIRPLANE leg, so the tool silently discarded them; the web app shows all 5, because it treats mode as a free string and renders anything non-WALK as a transit leg. Accept any mode token on a leg and keep the existing "at least one non-WALK leg" rule as the real gate, which restores parity with the web app. Everything downstream keeps its mode !== 'WALK' semantics, so a journey created over MCP is identical to one created in the app. Dropping an itinerary is still possible when provider data fails the remaining consistency rules, but it is indistinguishable from "no routes exist" — so search_transit_routes now reports a `dropped` count alongside the results. --------- Co-authored-by: Uzini <43294422+Uziniii@users.noreply.github.com> * fix: show map poi search controls on mobile (#1555) * fix(pdf): use the trip's actual currency instead of hardcoded EUR (#1519) * fix(pdf): use the trip's actual currency instead of hardcoded EUR Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * fix(i18n): drop hardcoded currency text from pdf.costLabel across locales Remove redundant EUR/currency references from pdf.costLabel translations across 21 locales now that the PDF export correctly renders amounts with their actual trip currency via formatMoney(). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * fix(pdf): drop hardcoded euro-shaped icon from place price chip svgEuro rendered a fixed € glyph next to the price chip regardless of the trip's actual currency, undermining the currency fix. Swap for a currency-neutral coin icon. --------- Co-authored-by: Nguyen Trong Binh <nguytb15@VN1N07HO1CD1015.local> Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com> * fix(trips): pin place prices when the trip currency changes A place price with no currency of its own means "the trip's own currency" — that is how the PDF export and the place chips read it since #1519. But rebaseTripCurrency() only pinned budget_items and budget_settlements, so switching a trip's currency silently redenominated every implicit place price: a €15 museum on a trip moved to JPY started reading as ¥15. Same class of mismatch as #1543, on the places surface. Pin priced, currency-less places to the outgoing currency inside the same transaction. No amount is rewritten — the figure the user typed keeps its real-world value, it just stops being ambiguous about which unit it is in. Bump updated_at as well: it doubles as the optimistic-concurrency token (#1135), so a client holding the pre-switch row can no longer write the pin away. Document place prices in the wiki's currency model, and drop the now-stale "in EUR" from the PDF export's estimated-cost stat. * fix(budget): re-split expenses when a member is removed * fix(plugins): derive plugin req.user.isAdmin from role, not is_admin * chore(test): make jsdom Storage work under Node's native Web Storage globals * fix: recompute vacay calendar when week start changes (#1554) * feat(mobile): comprehensive mobile UI rewrite Add a dedicated phone UI (<768px) under client/src/mobile/, mounted by MobileShell while the desktop/tablet code paths stay untouched. Each page delegates to an M-screen that reuses the existing hooks, stores and services. Covers dashboard, trip planner (plan timeline, map, places, tabs and sheets), vacay, atlas, journey, collections, settings, admin and notifications, with a shared component kit (MSheet, MBottomNav, MGlassBar, MSegmented, MToggle, …) and design tokens in mobile.css. Empty states use an animated TREK mascot (MDancingTrek) with per-scene props. Adds the mobile* i18n namespaces (mobileTrip/mobileJourney/mobileVacay/ mobileAtlas/mobileNav/mobileAdmin/mobileSettings/mobileCollections) across all 22 locales. * fix(websocket): handle socket 'error' events to prevent crash on malformed frames (#1584) * fix(packing): apply templates into the active list tab (#1581) * Fix packing list readability on mobile * Localize packing quantity label in overflow menu * feat(mobile): accommodation & save-to-collection sheets, trip loading splash Add a dedicated mobile accommodation sheet and a save-to-collection sheet, plus an animated trip loading splash with stepped status copy. Make the vacay day/company-holiday toggles optimistic so cells react instantly and roll back on error. Wire up the "subscribe to all trips" calendar feed and cover-image add on the new-trip sheet. Sync the new dashboard/trip i18n keys across all 22 locales. * fix(atlas): stream boundary GeoJSON instead of caching parsed bundles (#1585) * fix(atlas): stream boundary GeoJSON instead of caching parsed bundles * fix(atlas): scan admin1 features in one pass to avoid O(n^2) build createFeatureSplitter re-scanned each partial Feature from the start on every gunzip chunk, so a large feature (Canada ~5.5MB, ~340 chunks) made the one-time admin1 store build O(n^2). That pushed the streaming build (~4.2s) past the 15s test timeout under CI coverage/fork contention and added the same latency to the first live region request. Carry scan state (position, brace depth, string state) across chunks so each character is examined once. Output is byte-identical (3228 features, 197 countries) and peak build memory is unchanged (~192MB RSS under a hard 512MB cap); build time drops to ~1.7s. * fix(i18n): add packing.quantity to all locales The packing.quantity key existed only in en (Qty) and de (Menge), so i18n:parity:strict and the client parity test failed for the other 20 locales. Add the key everywhere; en/de are unchanged. --------- Co-authored-by: jubnl <jgunther021@gmail.com> * fix(trips): keep accommodations on their dates when the trip range shifts (#1288) The v3.1.3 fix re-anchored dated bookings after a trip date change but explicitly excluded hotels: day_accommodations has no absolute date columns, so stays remained glued to positionally re-dated day rows and shifted with the range. updateTrip now snapshots day dates before generateDays and a new resyncAccommodationDays re-anchors each stay (and its linked hotel reservation, restamping its stale reservation_time) to the days holding its pre-change dates; out-of-range stays stay glued so whole-trip moves still shift together. Unlinked dated hotels resync like any booking, and the date-change block is wrapped in a transaction. Changing the start date now also asks how plans should follow via a new date_shift_mode field ('keep_bookings' default / 'shift_all', which reuses the reorder/insert restamp path to glue everything), exposed in the trip edit modal (all 22 locales), the shared contract, and the MCP update_trip tool. Clients no longer show stale state: the initiator reloads reservations + accommodations after saving, collaborators refetch on a date-changing trip:updated, and reconnect hydration nudges the planner's accommodations too. * fix(extract): retry with json_object and surface AI import failures (#1546) OpenAI-compatible providers that only support json_object (DeepSeek, Mistral, some vLLM/llama.cpp) reject the json_schema response_format with a 400, and the resulting error was swallowed silently: not logged server-side and never rendered by the background-task widget, leaving only a generic "no reservations" message. - Retry the chat/completions request once with response_format json_object when the json_schema attempt returns 400 (non-NuExtract only); the system prompt already dictates the output shape - Log swallowed llm-parse errors with an [llm-parse] tag so failures show up in server logs - Render task warnings under the empty-preview note in the background tasks widget so the actual provider error reaches the user * fix(costs): keep ticket item amounts visible on narrow screens (#1568) * chore: update repo url * chore: update repo url * chore: update repo url * chore: update repo url * fix(security): block IPv6 transition addresses (NAT64/6to4/Teredo) in SSRF guard An attacker-controlled DNS record pointing at a NAT64 (64:ff9b::/96), 6to4 (2002::/16), or Teredo (2001:0000::/32) address that embeds a private IPv4 (e.g. 64:ff9b::a9fe:a9fe = 169.254.169.254) bypassed the SSRF guard: none of the guard functions recognised these ranges, so on a host that routes the transition prefix the connection reached the embedded private target (cloud metadata / internal SSRF). Add a shared embeddedTransitionIpv4() detector and re-apply each guard's own blocklist to the extracted IPv4 in isAlwaysBlocked, isPrivateNetwork, isLinkLocal (ssrfGuard.ts) and isBlockedIp (egress-policy.ts). A transition address to a public IPv4 stays allowed so legitimate IPv6-only egress is unaffected. egress-policy.ts keeps the detector inline to preserve its dependency-free contract for the isolated plugin subprocess. * chore: Add star history * Revert "chore: Add star history" This reverts commitf9d5f75837. * fix(map): draw transit routes even without other places on the day The reservation overlays hide any transport whose from/to endpoints project closer than a per-type pixel threshold (200px for transit) to declutter tiny no-op straight connectors. A transit journey, though, draws its real rail/bus alignment rather than a straight endpoint line, so on a zoomed-out day — one with no other places to tighten the map onto — its stations fall under the threshold and the whole route vanishes. Exempt a transit booking that carries real per-leg geometry from the proximity gate in both renderers (Leaflet + MapLibre); a geometry-less transit keeps the straight-arc declutter. * fix(atlas): resolve region AND country by coordinates against the bundled polygons Rebased onto dev's streaming atlas index (#1576): region resolution now resolves a place's lat/lng directly against the same bundled admin1 polygons the client renders — offline, deterministic, and guaranteed to match a bundle feature — rather than trusting Nominatim's address level, which can name a subdivision the bundle doesn't carry (Barcelona's ES-B province vs the bundle's ES-CT autonomous community) and never highlight. Country resolution moves to the same coordinates-first order, so a place stored "..., San Francisco, CA" no longer resolves to Canada. admin1 is held as per-country GeoJSON text (never parsed whole, #1576), so a country's regions are flattened to the compact Float64Array form and cached on first use — only visited countries pay the parse. The stale GB constituent-country rescue is removed, and a one-time migration clears the re-derivable place_regions cache so every place re-resolves under the new logic. Closes #1547 * fix(client): convert mixed-currency day/trip cost totals instead of mislabeling raw sums (#1561) Day headers, the plan sidebar footer and the PDF day/cover totals summed raw place prices across currencies and labeled the result with a single currency — a $2,730.27 hotel on a NOK trip read as "2730 NOK". Totals now convert every amount into a base currency via the existing frankfurter rates (sidebar: the user's display currency, falling back to the trip's; PDF: the trip currency, resolved once before rendering so the document is consistent), marked with "≈" when a conversion happened. When a rate is unavailable (offline, blocked egress, unknown code) they fall back to an honest per-currency breakdown ("2 500 kr + $2,730.27") instead of folding foreign amounts into a mislabeled number. All-same-currency trips make no FX request, so offline PDF export keeps working. Also swaps the place inspector's hardcoded € chip icon for a neutral one and formats the price via formatMoney in the place's own currency. Note: day-header totals move from "50 EUR" to Intl formatting ("50 €"). * feat(atlas): let a visited region be hidden, cascading to the country when none remain (server) Countries already have a hide/tombstone mechanism (hidden_countries, #1490): a zero-count derived country can be dismissed and stays gone across reloads. Regions had no equivalent — unmarkRegionVisited only ever deleted a manually-marked visited_regions row, a no-op for the common case of a region derived fresh from place_regions on every request, so there was no way to dismiss one at all (place-derived or otherwise). Adds the region-level counterpart: - New hidden_regions table (user_id, region_code, country_code), mirroring hidden_countries. - getVisitedRegions() filters its result through it, the same way getStats() already filters through getHiddenCountries(). - unmarkRegionVisited() now tombstones unconditionally (not just for a manually-marked region — a region with a real place attached, e.g. one misassigned by a border-simplification gap, is exactly the case this exists for) and derives the country code from the region code's "<country>-<rest>" prefix when there's no visited_regions row to read it from. - Cascade: after hiding a region, if the country has no other visible region left (checked against place_regions + visited_regions, minus hidden_regions), the country is hidden too via the existing unmarkCountryVisited. - markRegionVisited() clears both tombstones on re-mark, so a region (and its cascade-hidden country) can come back. Note the cascade only has a visible effect on a country with no real place attached to it — getStats' places-derived country entries are never suppressed by hidden_countries (#1490's deliberate "reappears with a real place" rule), so hiding every region of a country that DOES have real places leaves the country visible, by the same existing design. Test coverage reflects this. Server-side only — client wiring (a way to trigger this from the map) is a separate commit. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * feat(atlas): let a visited region be hidden, cascading to the country when none remain (client) Client wiring for the server-side hide-region feature (previous commit). Clicking a visited region on the map used to open the hide/unmark confirmation only when it was manually marked (visitedRegions[...].manuallyMarked); a region derived from real place data instead opened the country-detail view, with no way to dismiss it at all. Now any visited region offers the same "Remove this region from your visited list?" confirmation regardless of how it was derived — country details remain reachable via the country search/sidebar, which was never gated on this in the first place. The confirm handler's optimistic country-removal check dropped its `&& r.manuallyMarked` filter on the remaining-regions count, matching the server's unconditional cascade — but keeps the existing "only when the country has zero real places/trips" guard, since a country backed by real data is never actually hidden server-side (#1490) and removing it from the UI early would just flash and reappear on the next reload. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * fix(settings): make fresh-instance unit defaults internally consistent A brand-new instance — no admin-set defaults, no saved value — rendered temperatures in Fahrenheit and times on the 12-hour clock while distances defaulted to metric, a mix that matches no locale. The store also seeded 'fahrenheit'/'12h' while DisplaySettingsTab's fallback said 'celsius', so the two paths disagreed about the intended default in the first place. Default to one system — celsius / metric / 24h — matching the already-metric distance_unit. The unit defaults now live in a single exported DEFAULT_SETTINGS that both the store and DisplaySettingsTab's fallback read, so they can't drift apart again. Admin-set user defaults (getAdminUserDefaults) and any value a user has already saved still take precedence; only the code-level default changed. * feat(i18n): complete Catalan (ca) translation Adds Catalan as a supported language — the full shared/src/i18n/ca locale (all domain files plus the notification texts), registered in SUPPORTED_LANGUAGES and the client locale loader. Rebuilt onto current dev so the locale is at full key parity with en (i18n:parity:strict clean). * fix(map): stop real road-route fetches from dying under StrictMode useTransportRoutes cached its AbortController in a ref that was created once and aborted on unmount. React StrictMode's dev-only mount->cleanup->remount cycle ran that abort during the *simulated* cleanup, permanently poisoning the controller before the real mount's fetch ever started — every road-routed booking (car/bus/taxi/bicycle) silently fell back to a straight line in local dev, while production builds (no StrictMode double-invoke) worked fine. Fix: create a fresh AbortController per effect run instead of a ref-cached singleton, and synchronously un-mark a job as "attempted" in that same run's cleanup if it didn't settle before the cleanup fired — so a StrictMode remount (or any other pre-completion cancellation) retries instead of being skipped forever. Verified against the real OSRM endpoint in a running dev server: all four road-routed legs on a live trip now resolve with real road geometry instead of straight lines. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * feat(map): add reservation route-visibility util Extracts the route-visibility filter that was hand-copied, identically, in both MapView.tsx and MapViewGL.tsx into one pure, unit-tested function: a reservation's route shows on the map when it's a transit booking with the day-route toggle on, or its id is in the caller's visible-ids set. isRoutableReservation (>= 2 endpoints) is exported separately since callers besides the map filter need the same check. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * feat(map): add per-trip connections-visibility resolution util Pure storage/resolution logic for a trip's booking-route visibility preference, keyed trek:visible-connections:<tripId>. Two modes: 'only' (nothing shown except the listed ids — today's existing behavior; a legacy bare-array localStorage value parses as this mode for backward compatibility) and 'all-except' (everything routable shown except the listed ids). A trip with no stored preference falls back to the account-wide default (all or nothing) without writing anything, so flipping the account setting later never silently overrides a trip with an explicit per-trip choice already recorded. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * feat(settings): add always-show-booking-routes account setting New map_always_show_routes account setting, defaulting to off, i18n'd across all 22 supported locales. Lives in Display > Travel & map, directly under Booking route labels — its closest sibling — using that section's immediate-save On/Off pattern rather than a separate toggle+Save flow, since it's a booking-display preference, not a map render-config option. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * feat(map): per-trip booking-route visibility with account default and bulk toggle Lets a user see a booking's route on the map without manually toggling it per item, two ways: - The account setting from the previous commit sets the default for any trip that's never had its routes touched before. - A new bulk "show all / hide all" button in the day-plan toolbar flips a trip explicitly between the two connectionsVisibility modes, independent of the per-item toggle (which still edits whichever mode's id list is active, in both directions, including while the account default is on). useTripPlanner.ts resolves a trip's effective visible-connection ids from connectionsVisibility.ts + the account setting + the trip's routable reservations, and exposes it through the same visibleConnections/toggleConnection contract MapView, MapViewGL and DayPlanSidebar already had, plus allConnectionsShown/ toggleAllConnections for the new bulk control. MapView/MapViewGL consume it via the shared reservationRoutes util instead of each carrying their own copy of the filter. The bulk toggle's tooltip gets its own map.showAllConnections/ hideAllConnections i18n keys (all 22 locales) distinct from the per-item toggle's text, and matches the per-item toggle's active (solid blue) styling rather than the toolbar's generic hover tint. Manually verified end-to-end in a running dev server: the account default seeding an untouched trip, the bulk toggle flipping a trip between all-shown/all-hidden, and a single per-leg override while the trip is in all-shown mode. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * Update documentation for booking visibility change * fix(i18n): add Catalan keys for the booking-route toggle + fix the language-count test #1483 added map.showAllConnections/hideAllConnections and settings.alwaysShowRoutes/Hint to every locale that existed when it was written; Catalan (#1418) landed just after and was missing them, which broke i18n parity. Also bumps the SUPPORTED_LANGUAGES test to 23 entries and asserts the Catalan one — the ca addition left that assertion stale. * test(e2e): add a reproducible documentation screenshot run The wiki screenshots had drifted three months and two releases behind the UI: 39 of 46 assets came from a single commit in April, and pages such as Budget-Tracking carry a disclaimer that their own images are out of date. Retaking them by hand is what created that drift in the first place. This adds a `screenshots` Playwright project that captures them from a dev build instead: - seed.ts populates a demo trip over the REST API — deliberately in JPY, so the 3.4.0 currency work (per-trip currency, frozen FX rates, foreign-currency settle-up) is actually visible rather than hidden behind EUR. - shot.ts settles the page before capturing (fonts, images, transitions) so captures don't catch skeleton loaders, and rewrites /auth/app-config to clear dev_mode — the E2E backend runs NODE_ENV=development, which would otherwise put a "Dev: Notifications" tab no real deployment has into every admin shot. - promote.mjs downscales 2880px captures to 1600px on the way into wiki/assets/, which is 70% smaller for detail the wiki never renders. Tabs are located by their visible label, so a rename like Budget → Costs fails the run loudly instead of quietly capturing the wrong panel. npm run shots && npm run shots:promote * docs(wiki): retake screenshots against 3.4.0 Regenerated with `npm run shots` from the dev build. Replaces 21 assets and adds 13 surfaces that had no screenshot at all. Notable corrections: - Collections.md referenced assets/Collections.png, which was never committed — the only broken image in the wiki. It now exists. - The Budget panel became Costs in 3.3.0 (#1464); every budget image still showed the old label. - The trip-create dialog gained a Currency field in 3.4.0, absent from the old TripCreate.png. - Settings grew a Plugins tab and the admin sidebar a Plugins entry; neither appeared in the old sidebar shots. - Weather now renders in Celsius. A fresh instance defaults to Fahrenheit while distance defaults to metric, so the seed pins both units — the mismatched defaults are a separate bug, not fixed here. Koffi is installed from the community registry rather than dev-linked, because dev-link and sideload both stamp a badge on the plugin card that an ordinary install never shows. Total 3.6 MB for 34 images, against 26 MB for the 46 assets already in the directory. No wiki page text is touched here — pages still point at the old filenames where those were kept, and the newly added images are not referenced yet. * fix(help): make wiki links and anchors work in the in-app reader The wiki pages are written in GitHub-wiki style, and 455 of their links across 81 pages use the bare relative form — `[Currencies](Currencies)` — against only 114 `[[..]]` links. processMarkdown only rewrote the latter, so in-app every one of those 455 fell through to HelpPage's external-link branch, opened a new tab and 404'd. Since6c87bf2fserves the wiki from disk, that is the primary way users read these docs. Rewriting them in the renderer fixes every page at once and keeps the sources GitHub-compatible, so contributors can keep writing either form and neither target breaks. Rewriting the 81 files instead would have fixed today's pages and left the trap open for tomorrow's. Also: - Code is protected from the rewrite. Plugin-Development.md documents `actions[key](ctx)`, which reads as a markdown link and would otherwise be corrupted into `actions[key](/help/ctx)` inside a verbatim snippet. - `[[Page#anchor|Slug]]` no longer renders its anchor as visible link text. - Headings carry GitHub-compatible ids, so the 22 in-page `](#anchor)` links scroll instead of doing nothing. * docs(wiki): correct settings, map and addon docs against 3.4.0 The wiki described settings that no longer exist and pointed at UI labels that had been renamed. Each correction below was checked against the code. - The Settings tab is labelled **General**, not "Display" (shared/src/i18n/en/settings.ts:6). Every "Settings → Display" path was wrong. The *display currency* setting keeps its name — only the tab was renamed. - Colour mode is on the **Appearance** tab, not Display. - The "Route calculation" setting does not exist: no hits for route_calc / routeCalc / auto_route / calculateRoutes anywhere in client or server. - Default map centre and zoom were removed in 3.4.0 (0f4766e1). Replaced with what actually happens now, written from client/src/utils/mapViewport.ts: every map frames itself on its own places, world view when a trip has no coordinates. - A third map provider, MapLibre GL / OpenFreeMap, was undocumented. It needs no access token, which is the reason a reader would choose it over Mapbox. - Budget-Tracking.md said the feature is called Costs everywhere and then told the reader to open the "Budget" tab. The screenshot disclaimer is gone too — the images now show Costs. - The admin tab table was missing Plugins. - The `packing` addon is seeded as "Lists", not "Packing list management". - Install docs pinned `mauriceboe/TREK:3.0.15` as the exact-release example, four minor versions stale. * docs(wiki): document passkeys, calendar feeds, appearance, plugins and help Five shipped features had no user documentation at all: - **Passkeys** — WebAuthn enrolment and sign-in, admin policy, RP ID/origins. Previously mentioned only in passing in Environment-Variables. - **Calendar Feeds** — the subscribable per-trip and per-user ICS feeds. Note Day-Plans-and-Notes documents only the one-off .ics *export*; the two are cross-referenced so it is clear which is which. - **Appearance Settings** — the whole tab, including the custom accent colour and its contrast check. - **Admin: Plugins** — installing from the registry, the pre-install permission review, egress hosts, and what Reviewed/Signed/Unsigned actually guarantee. - **In-App Help** — that the wiki ships in the image and is served from disk since 3.4.0, with the GitHub fallback and TREK_WIKI_DIR. One deliberate deviation from the brief: the Appearance settings are documented as account-level, not per-device. They persist to /api/settings on the user account with nothing in localStorage, so the dashboard widget picker's desktop/mobile split still changes both from either device. All five are listed in _Sidebar.md. * docs(wiki): add screenshots for the remaining surfaces Second capture pass, bringing the run to 42 screenshots. Adds the surfaces that need more than a navigation to reach: collection and journey detail, MCP access, two-factor setup, the settle-up payment dialog, and the trip file manager. Two fixes to the harness itself, both of which had produced misleading images: - The admin captures showed a "Dev: Notifications" tab that only exists when the server runs NODE_ENV=development. The run now clears dev_mode in the /auth/app-config response; switching the server to production instead would have enabled HSTS and broken the run over http://localhost. - The settle-up capture clicked "Settle up", which does not open a view — it records the transfers. It zeroed every balance and photographed "Everyone's square", and because the specs share one database it poisoned Costs.png in the same run. Screenshot specs must not mutate state; it now captures the "Add payment" dialog instead. Koffi is installed from the community registry rather than dev-linked, since dev-link and sideload both badge the plugin card in a way no ordinary install does. * test(e2e): capture the detail pages and dialogs Adds the second wave of screenshot specs (collection/journey detail, MCP access, 2FA, settle-up dialog, files) and enables the mcp, documents and collab addons in the seed so their surfaces render instead of 404ing. * docs(wiki): point plugin authors at the agent skill and the registry Plugin-Development jumped straight into scaffolding without saying that two supporting resources exist. TREK-Plugins was referenced only in passing far down the page, and Plugin-Skill — an agent skill that teaches Claude Code and other SKILL.md-compatible agents to build and publish a plugin — was not mentioned anywhere in the wiki. Both are called out up front, with a note that neither is required: the registry only matters once you want other instances to find your plugin. * test(e2e): capture the four collab surfaces separately One Collab.png illustrated chat, notes, polls and the What's Next widget, so at most one of those four wiki pages showed the feature it described. Each now has its own capture. Two things the collab seed needed: - The conversation is posted by three different people. Every collab write is attributed to the acting user, and a single-voice chat log would misrepresent the feature outright. - Each member therefore gets its OWN request context, created with an explicit `storageState: undefined`. Without that, newContext inherits the project's storageState — the admin's trek_session cookie — and extractToken reads the cookie BEFORE the Authorization header (server/src/middleware/auth.ts:9). The posts still return 200; they are just all recorded as the admin. That is exactly what happened on the first attempt, and the DB was the only place it showed. The collab view is not tabbed — CollabPanel renders all panels at once — so the captures target cards by seeded content rather than clicking tabs or matching headings, whose DOM text is 'Notes'/'Polls' while CSS renders them uppercase. * docs(wiki): show every screenshot on the page it belongs to Finishes the wiring the screenshot commits deliberately left out. - Embeds the 14 images that were committed but displayed nowhere: the Costs panel and settle-up dialog, the trip planner, transports, documents, collection and journey detail, the notifications inbox, the Offline and Account settings tabs, appearance, admin user defaults, registration and password reset. - Splits the four collab pages onto their own images. Chat, Notes, Polls and What's Next each showed the same Collab.png until now; the overview shot moves to Real-Time-Collaboration, which had no image at all. - Day-Plans-and-Notes pointed at TripPlaner.png — one 'n'. It now uses the correctly spelled file, and the misspelled one is deleted since nothing else referenced it. - Removes 45 dead '<!-- TODO: screenshot -->' markers whose screenshot had long since been added. 9 remain, each on a page that genuinely still lacks the image it asks for — so the marker means something again and the gap is greppable, which is how this drifted unnoticed for three months. Every asset in wiki/assets/ is now referenced by a page, and every image reference resolves to a file. * docs(wiki): add the four collab screenshots Chat now shows a real three-person conversation rather than one voice talking to itself, and the poll shows three separate votes across two options. 44 images, 4.6 MB total. * test(help): point the asset test at the correctly spelled screenshot The integration test hard-coded assets/TripPlaner.png — one 'n' — so deleting the misspelled file broke it. It was the only thing keeping that filename alive. * docs(wiki): regenerate the screenshots on top of the rebased devba3733dachanged the fresh-instance defaults to celsius/metric/24h. Every capture showing a clock — chat timestamps, bookings, day plans — and the General settings tab itself were still on the 12-hour clock, so 39 of 44 images needed a new run. Regenerating them is one command, which is the point. The seed keeps pinning the units explicitly: it now matches the new defaults, but stating them keeps the captures reproducible if a default moves again. * docs(wiki): regenerate screenshots after rebasing onto dev dev added a Catalan translation, an always-show-booking-routes account setting and a bulk route toggle in the day-plan toolbar since the last run — all visible on captures we ship. 15 of 44 images changed. Also resolves the Map-Features conflict from41d12e89: upstream's new bulk-options section is kept, with the two 'Settings → Display' paths corrected to 'General'. The tab is labelled General (shared/src/i18n/en/settings.ts:6), and upstream's own i18n key for that section is settings.general.travelMap. * chore: only allow manual trigger for the build&push * feat(mobile): rebuild Settings & Admin panels natively * feat(mobile): native booking, transport & expense form sheets * feat(mobile): unify empty states, streamline nav, collab & collections * feat(mobile): white atlas bucket button + custom month/year picker * feat(mobile): show accommodation route legs in the day plan * feat(mobile): auto-draw the day route in map mode * feat(mobile): move the vacay invite button left of the year switcher * fix(mobile): don't render the global dock inside the trip planner * feat(mobile): reachable add-list, roomier packing rows & owner avatars * fix(mobile): use the custom date picker for the to-do due date * feat(mobile): open a running trip on today's day * chore(client): serve the PWA manifest in dev for on-device testing * fix(i18n): complete the Catalan (ca) locale for the mobile rewrite * test(transport): match the shortened Manual/Automated switch labels * test(mobile): mock the admin permissions panel MAdmin renders * feat(vacay): rework the desktop vacation planner in the glass style Move the calendar, sidebar cards and stats onto the --vg-* glass tokens, soften the person-day fills, pad every month to six week-rows so the cards line up, tighten the sidebar spacing and add You/Pending badges to the people list. * feat(vacay): redesign the vacation settings dialog Widen the modal and split the options into two columns, and restyle the holiday calendar rows, inputs and add button to match the rest of the planner. * feat(journey): rework the journeys dashboard in the glass style Move the hero to a blur-mask magazine cover, put the journey cards on glass with cover/title overlays, widen the grid to match the rest of the app, drop the top toolbar, and add a subtitle field to the create flow. * feat(journey): modernise the journey detail page Centre and widen the feed+map layout, restyle the hero with a frosted cover, glass stat pill and round controls, turn the view switch into a glass segmented pill with a labelled add-entry button, and give the timeline day headers, entry cards, suggestion cards and the entry editor a rounder, glassier look. * feat(journey): lay out the journey settings dialog in two columns Widen the dialog and split the options into two glass cards, and round the inputs and the save/cancel buttons. * feat(journey): lay out the entry editor in two columns Widen the new/edit entry dialog and split it into two columns — title, photos and the story on the left (the story now grows to fill the column), date/location, pros & cons, mood and weather on the right. * feat(journey): polish the detail, settings and share UI Move the gallery upload into the view switch as a matching pill and drop the old button, badge the day-place and photo counts, tidy the entry editor location field, round the settings inputs and buttons, restyle the contributor role and share controls, and put delete next to copy. * feat(journey): always feature a hero on the frontpage The desktop frontpage only rendered the hero header when a journey trip was currently live, so with no live trip there was no header at all. The hero now always features one journey — the live one when there is one, otherwise the most recent — and its eyebrow reads "Latest Journey" when the featured journey is not live. * feat(mobile): customizable bottom navbar layout Add a Mobile section under Settings → Appearance where you arrange the bottom navbar: reorder items and choose which sit in the bar versus under the "More" popover, with a live preview. Dashboard stays pinned first. The layout persists per-user in the appearance config and drives MBottomNav; an un-customised account keeps the current Dashboard + Vacay/Atlas dock. * fix(mobile): widen the nav customizer zone buttons to a single row * refactor(mobile): show the nav customizer only in mobile settings The bottom-nav layout only exists on phones, so configuring it from the desktop settings made little sense. Drop the desktop customizer (and its two now-unused labels) and keep the editor on the mobile appearance screen. * fix(mobile): neutral tiles and no subtitle in the bottom-nav More menu * feat(desktop): TREK mascot empty states + trip-open splash Bring the mobile TREK mascot to desktop as a shared EmptyState (mascot + a single title, no subtitle, one uniform look) across the app empty states: reservations, transport, costs, packing, to-dos, files, collab notes/polls/chat, upcoming activities, the day plan, journey timeline and gallery, collections, atlas, dashboard and notifications. The trip planner now plays the same little mascot journey while a trip loads. * feat(desktop): animated glassmorphism background for the trip loading splash The trip-open splash now takes over the viewport with a calm, slowly drifting pastel gradient wash (soft pink/lavender/periwinkle, toned down), a gently breathing hue veil, a whisper of filmic grain and a soft vignette, with the mascot journey floating on a frosted liquid-glass card. Theme-aware for light and dark; the background freezes under prefers-reduced-motion. * fix(planner): keep the empty-day itinerary as small text, no mascot * fix(mobile): cap the bottom-nav dock at Dashboard + 2 so the More slot fits * feat(mobile): reorderable dashboard arrangement Add a mobile-only dashboard order control under Settings → Appearance → Mobile: reorder how the trip list and the inline widgets (currency, collections, world clocks, upcoming reservations) stack on the phone dashboard — e.g. move the currency converter above your trips. The featured trip always stays pinned on top. Stored per-user in the appearance blob (dashboard.mobileOrder); an un-arranged account keeps the current order. * feat(plugins): map layer provider hook for the trip map Plugins can now draw bounded vector overlays (polylines, polygons, metric circles) on the trip map via hooks.mapLayerProvider — routes, reachable-range corridors, zones. Same contract as map markers: declarative data only, tone palette styling with clamped numerics, hard per-plugin budgets (4 layers / 150 features / 8000 vertices), oversized or partly-invalid shapes dropped whole. Rendered beneath the core day route. The GL renderer now also mounts the plugin markers it was missing — both hooks work on Leaflet and Mapbox/MapLibre, desktop and mobile. * feat(plugins): route provider hook with planner route profiles A routeProvider plugin can now register routing profiles (capabilities. routeProfiles, max 3) that show up in the planner's route toggle next to Driving/Walking — e.g. EV routing with charging stops. Selecting one asks exactly that plugin to route the day's stops (POST /api/plugin-routes, 20 s budget for external solvers); the result is validated whole (leg count must match the waypoint pairs, vertex/via caps) and rendered like an OSRM response: geometry on the map, via points as stops on the line, per-leg times + an optional note ("25 min charge") on the connectors. A failing provider degrades to straight lines, same as an OSRM outage. The feed only offers profiles whose hook grant is actually recorded, and the route endpoint re-checks provider + declared profile against the DB row, so a hand-edited capabilities blob can't invent routable profiles. * feat(plugins): day schedule contributions in the planner A dayScheduleProvider plugin can attach time entries to the day plan — "35 min charging at this stop", "45 min security before this flight". Rows are host-rendered under their anchor (a place/booking row, or a day's start/end) on both the desktop sidebar and the mobile timeline, and the contributed minutes are folded into the day's route-footer total as "+X min". Because this output feeds displayed timing, the server clamps minutes to a day, checks every dayId against the trip's own days and budgets the item count per provider; labels go through the usual sanitize+cap pipeline. * feat(plugins): geolocation bridge permission New geolocation:read permission — the first bridge-level grant: a plugin's sandboxed frames can ask the HOST for the browser position over postMessage (window.trek.geolocation.get()/watch()). The sandbox itself never gains the geolocation API; the host page reads navigator.geolocation, so the browser's own site permission prompt still applies on top of the admin consent, and the position only travels parent -> frame, never to the server. The feed flags granted plugins, an ungranted frame gets a 'forbidden' answer without touching the browser API, one GPS watch per frame, and the watch is force-stopped when the frame closes. The dev preview answers with a fixed position so trek.geolocation works without a prompt. * fix(mobile): render trip-page plugin tabs The mobile trip shell listed plugin tabs in the Mehr sheet and let the user open them, but MTripTabPanel had no plugin: branch — the tab came up as an empty scroller. Mount the same sandboxed PluginFrame the desktop planner uses, filling the panel above the dock. * test(plugins): add granted_permissions to the feed fixture schema The plugins feed now selects granted_permissions (route profiles + the geolocation flag are gated on the recorded grant), so the hand-written in-memory schema this suite shares needs the column. * fix(map): don't crash the trip map when the pane API is absent PluginMapLayers called map.getPane/createPane unconditionally, which threw 'map.getPane is not a function' on a minimal Leaflet map (breaking MapView in tests and any renderer state without pane support). Pane placement is a z-index optimization — guard it and fall back to drawing the plugin features without the dedicated pane when it isn't available. * harden(plugins): bound normalize work, scope route cache, enforce geo grant live Adversarial audit of the four new hooks found no trust-boundary defect; these close the low-severity gaps it confirmed: - map-layers / day-schedule / plugin-routes: slice the raw provider array before iterating, so an all-invalid oversized payload can't force an unbounded scan on the host event loop (the output was already capped; this bounds the work too). - RouteCalculator: a plugin route is trip-/day-specific, so its cache key now includes tripId/dayId — two days with identical coordinates no longer share one plugin route (its charging stops/notes differ per day). - PluginFrame: a live geolocation watch re-checks the grant on every fix and stops at once if an admin revokes geolocation:read while the frame stays open. * test(client): update stale assertions to the mobile-rewrite UI The mobile rewrite moved empty states to the shared EmptyState mascot component (title only, no subtitle) and replaced the loading gif with TripLoadingSplash, but several tests still asserted the old copy/markup: - CollabChat / PackingListPanel / ReservationsPanel / AtlasPage / JourneyDetailPage: assert the current empty-state (title + scene mascot) instead of the removed hint paragraphs. - TripPlannerPage: mock TripLoadingSplash (its mascot-cycling setInterval never drains under fake timers, aborting 14 splash-gated tests) and assert the current loading node. Test-only — no component behavior changed. --------- 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> Co-authored-by: Pavel Zolotarevskiy <code@fxgn.dev> Co-authored-by: jubnl <66769052+jubnl@users.noreply.github.com> Co-authored-by: Azalea <noreply@aza.moe> Co-authored-by: Uzini <43294422+Uziniii@users.noreply.github.com> Co-authored-by: Daniel <drmoreno271@gmail.com> Co-authored-by: trongbinhnguyen <43725147+trongbinh15@users.noreply.github.com> Co-authored-by: Konstantinos Thermos <info@subdee.org> Co-authored-by: Konstantinos Thermos <subdee@users.noreply.github.com> Co-authored-by: Lucas Español <lucas.espanol@tutanota.com> Co-authored-by: fbnlrz <frlrnzn@gmail.com>
This commit is contained in:
@@ -3,3 +3,6 @@ e2e/.tmp/
|
||||
test-results/
|
||||
playwright-report/
|
||||
playwright/.cache/
|
||||
|
||||
# vite-plugin-pwa dev output (devOptions.enabled)
|
||||
dev-dist/
|
||||
|
||||
+11
-8
@@ -27,8 +27,10 @@ import InAppNotificationsPage from './pages/InAppNotificationsPage.tsx'
|
||||
import OAuthAuthorizePage from './pages/OAuthAuthorizePage'
|
||||
import { ToastContainer } from './components/shared/Toast'
|
||||
import SaveToCollectionModal from './components/Collections/SaveToCollectionModal'
|
||||
import MSaveToCollectionSheet from './components/Collections/MSaveToCollectionSheet'
|
||||
import BackgroundTasksWidget from './components/BackgroundTasks/BackgroundTasksWidget'
|
||||
import BottomNav from './components/Layout/BottomNav'
|
||||
import MobileShell from './mobile/MobileShell'
|
||||
import { useIsPhone } from './mobile/useIsPhone'
|
||||
import { TranslationProvider, useTranslation } from './i18n'
|
||||
import { authApi } from './api/client'
|
||||
import { usePermissionsStore, PermissionLevel } from './store/permissionsStore'
|
||||
@@ -53,6 +55,7 @@ function ProtectedRoute({ children, adminRequired = false, addonId }: ProtectedR
|
||||
const addonStore = useAddonStore()
|
||||
const { t } = useTranslation()
|
||||
const location = useLocation()
|
||||
const isPhone = useIsPhone()
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
@@ -87,12 +90,11 @@ function ProtectedRoute({ children, adminRequired = false, addonId }: ProtectedR
|
||||
return <Navigate to="/dashboard" replace />
|
||||
}
|
||||
|
||||
return (
|
||||
<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>
|
||||
)
|
||||
// Below the md breakpoint the new mobile shell owns chrome (tokens, dock,
|
||||
// sheets, toasts); from 768px up the legacy wrapper stays untouched. The
|
||||
// shell branches internally so pages keep their state when the viewport
|
||||
// crosses the breakpoint.
|
||||
return <MobileShell isPhone={isPhone}>{children}</MobileShell>
|
||||
}
|
||||
|
||||
function RootRedirect() {
|
||||
@@ -200,6 +202,7 @@ export default function App() {
|
||||
}
|
||||
}, [settings.dark_mode, settings.appearance, isSharedPage])
|
||||
|
||||
const isPhone = useIsPhone()
|
||||
const isAuthPage = location.pathname.startsWith('/login')
|
||||
|| location.pathname.startsWith('/register')
|
||||
|| location.pathname.startsWith('/forgot-password')
|
||||
@@ -210,7 +213,7 @@ export default function App() {
|
||||
{!isAuthPage && <SystemNoticeHost />}
|
||||
<ToastContainer />
|
||||
{!isAuthPage && <BackgroundTasksWidget />}
|
||||
{!isAuthPage && <SaveToCollectionModal />}
|
||||
{!isAuthPage && (isPhone ? <MSaveToCollectionSheet /> : <SaveToCollectionModal />)}
|
||||
<OfflineBanner />
|
||||
<Routes>
|
||||
<Route path="/" element={<RootRedirect />} />
|
||||
|
||||
@@ -624,6 +624,50 @@ export interface PluginMapMarker {
|
||||
tone: 'default' | 'success' | 'warn' | 'danger'
|
||||
}
|
||||
|
||||
/** One shape of a plugin map layer (mapLayerProvider hook). Server-normalized:
|
||||
* coordinates range-checked, vertex budget capped, styling clamped to the tone
|
||||
* palette + bounded numerics — never free-form CSS or markup. */
|
||||
export interface PluginMapLayerFeature {
|
||||
type: 'polyline' | 'polygon' | 'circle';
|
||||
points?: Array<[number, number]>;
|
||||
center?: [number, number];
|
||||
radiusM?: number;
|
||||
tone: 'default' | 'success' | 'warn' | 'danger';
|
||||
width: number;
|
||||
dash: 'solid' | 'dash' | 'dot';
|
||||
opacity: number;
|
||||
fill: boolean;
|
||||
label?: string;
|
||||
}
|
||||
|
||||
/** A vector overlay a plugin draws on the trip map (routes, corridors, zones). */
|
||||
export interface PluginMapLayer {
|
||||
pluginId: string; id: string; name?: string;
|
||||
features: PluginMapLayerFeature[];
|
||||
}
|
||||
|
||||
/** A time contribution a dayScheduleProvider plugin attaches to the day plan
|
||||
* ("35 min charging at this stop"). Server-normalized: dayIds checked against
|
||||
* the trip, minutes clamped to a day, labels sanitized + capped. */
|
||||
export interface PluginDayScheduleItem {
|
||||
pluginId: string; id: string; dayId: number;
|
||||
assignmentId?: number; reservationId?: number;
|
||||
position?: 'start' | 'end';
|
||||
minutes?: number; label: string;
|
||||
tone: 'default' | 'success' | 'warn' | 'danger';
|
||||
}
|
||||
|
||||
/** A route computed by a routeProvider plugin (server-normalized: coordinates
|
||||
* range-checked, legs forced to waypoints-1, vias capped). null = provider failed
|
||||
* or refused — the caller falls back to straight lines like on an OSRM outage. */
|
||||
export interface PluginRouteResult {
|
||||
pluginId: string; profile: string;
|
||||
coordinates: Array<[number, number]>;
|
||||
distance: number; duration: number;
|
||||
legs: Array<{ distance: number; duration: number; note?: string }>;
|
||||
viaPoints: Array<{ lat: number; lng: number; label?: string; tone: 'default' | 'success' | 'warn' | 'danger'; dwellSeconds?: number }>;
|
||||
}
|
||||
|
||||
/** 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 {
|
||||
@@ -667,6 +711,19 @@ export const pluginsApi = {
|
||||
// (#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[] }),
|
||||
// Vector overlays (polylines/polygons/circles) plugins draw on the trip map via
|
||||
// the mapLayerProvider hook. Host-normalized + vertex-budgeted; fail-safe.
|
||||
mapLayers: (tripId: number | string) =>
|
||||
apiClient.get(`/map-layers/${tripId}`).then(r => r.data as { layers: PluginMapLayer[] }),
|
||||
// Route the given waypoints through ONE routeProvider plugin profile (targeted,
|
||||
// not a fan-out — the user picked this profile in the route toggle). Slow by
|
||||
// design (external solvers): the server allows the plugin 20 s.
|
||||
pluginRoute: (pluginId: string, profileId: string, body: { tripId: number | string; dayId?: number | null; waypoints: Array<{ lat: number; lng: number; name?: string; placeId?: number }> }, opts: { signal?: AbortSignal } = {}) =>
|
||||
apiClient.post(`/plugin-routes/${pluginId}/${profileId}`, body, { timeout: 25000, signal: opts.signal }).then(r => r.data as { route: PluginRouteResult | null }),
|
||||
// Time contributions plugins attach to the day plan via the dayScheduleProvider
|
||||
// hook (charging stops, security buffers). Host-normalized; fail-safe.
|
||||
daySchedule: (tripId: number | string) =>
|
||||
apiClient.get(`/day-schedule/${tripId}`).then(r => r.data as { items: PluginDayScheduleItem[] }),
|
||||
// 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) =>
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
ArrowUpCircle, Github, ExternalLink, ChevronDown, Check, Lock, Search, Link2, KeyRound, ShieldAlert,
|
||||
SlidersHorizontal, ArrowUpDown, CircleDot, MoreHorizontal, RotateCw, ArrowRight, Database, Users, LayoutDashboard,
|
||||
Radio, Luggage, Globe, Image, CalendarDays, Bell,
|
||||
Wallet, Puzzle, MapPin, ListChecks, Pencil, Tag, FileText,
|
||||
Wallet, Puzzle, MapPin, ListChecks, Pencil, Tag, FileText, Route, Navigation, Clock, LocateFixed,
|
||||
} from 'lucide-react'
|
||||
import PluginIcon from '../shared/PluginIcon'
|
||||
import { adminApi } from '../../api/client'
|
||||
@@ -188,6 +188,7 @@ const PERM_KEYS = [
|
||||
'events:subscribe', 'jobs:run',
|
||||
'ws:broadcast:trip', 'ws:broadcast:user',
|
||||
'hook:photo-provider', 'hook:calendar-source', 'hook:place-detail-provider', 'hook:trip-warning-provider', 'hook:table-contributor', 'hook:map-marker-provider',
|
||||
'hook:map-layer-provider', 'hook:route-provider', 'hook:day-schedule-provider', 'geolocation:read',
|
||||
'hook:pdf-section-provider', 'hook:atlas-layer-provider', 'hook:journal-entry-provider', 'hook:trip-card-provider', 'hook:notification-channel', 'hook:user-data', 'http:outbound',
|
||||
]
|
||||
|
||||
@@ -239,6 +240,10 @@ function deriveCaps(perms: string[], caps: { widget?: { slot?: string }; tripPag
|
||||
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:map-layer-provider')) out.push({ icon: Route, label: t('admin.plugins.cap.mapLayers') })
|
||||
if (perms.includes('hook:route-provider')) out.push({ icon: Navigation, label: t('admin.plugins.cap.routing') })
|
||||
if (perms.includes('hook:day-schedule-provider')) out.push({ icon: Clock, label: t('admin.plugins.cap.daySchedule') })
|
||||
if (perms.includes('geolocation:read')) out.push({ icon: LocateFixed, label: t('admin.plugins.cap.geolocation') })
|
||||
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)) {
|
||||
|
||||
@@ -21,6 +21,7 @@ import type { BudgetItem } from '../../types'
|
||||
import type { TripMember } from './BudgetPanelMemberChips'
|
||||
import GuestBadge from '../shared/GuestBadge'
|
||||
import { NumericInput } from '../shared/NumericInput'
|
||||
import EmptyState from '../shared/EmptyState'
|
||||
|
||||
export function splitEqualShares(total: number, members: { user_id: number }[], itemId: number): Record<number, number> {
|
||||
const n = members.length
|
||||
@@ -467,9 +468,13 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
|
||||
{dayBanner}
|
||||
{dayGroups.length === 0 ? (
|
||||
<div className="text-content-faint" style={{ textAlign: 'center', padding: '60px 20px' }}>
|
||||
{search ? t('costs.noMatch') : t('costs.emptyText')}
|
||||
</div>
|
||||
search ? (
|
||||
<div className="text-content-faint" style={{ textAlign: 'center', padding: '60px 20px' }}>
|
||||
{t('costs.noMatch')}
|
||||
</div>
|
||||
) : (
|
||||
<EmptyState scene="costs" title={t('costs.emptyText')} />
|
||||
)
|
||||
) : dayGroups.map(g => {
|
||||
const dtot = g.entries.reduce((a, en) => en.kind === 'expense' ? a + baseTotal(en.e) : a, 0)
|
||||
return (
|
||||
|
||||
@@ -124,9 +124,13 @@ describe('CollabChat', () => {
|
||||
expect(screen.getByPlaceholderText('Type a message...')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-CHAT-009: shows hint text in empty state', async () => {
|
||||
it('FE-COMP-CHAT-009: shows guidance in empty state', async () => {
|
||||
render(<CollabChat {...defaultProps} />);
|
||||
await screen.findByText(/Share ideas, plans/i);
|
||||
// The empty state now renders the shared EmptyState: a chat-scene mascot
|
||||
// plus the single "Start the conversation" title (the separate hint
|
||||
// paragraph was dropped in the mobile rewrite).
|
||||
await screen.findByText('Start the conversation');
|
||||
expect(document.querySelector('svg.trek--chat')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-CHAT-010: chat container renders', () => {
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import React from 'react'
|
||||
import { Trash2, Reply, ChevronUp, MessageCircle } from 'lucide-react'
|
||||
import { Trash2, Reply, ChevronUp } from 'lucide-react'
|
||||
import { URL_REGEX } from './CollabChat.constants'
|
||||
import { formatTime, formatDateSeparator, shouldShowDateSeparator } from './CollabChat.helpers'
|
||||
import { MessageText } from './CollabChatMessageText'
|
||||
import { LinkPreview } from './CollabChatLinkPreview'
|
||||
import { ReactionBadge } from './CollabChatReactionBadge'
|
||||
import EmptyState from '../shared/EmptyState'
|
||||
|
||||
export function ChatMessages(props: any) {
|
||||
const { currentUser, tripId, t, is12h, can, trip, canEdit, messages, setMessages, loading, setLoading, hasMore, setHasMore, loadingMore, setLoadingMore, text, setText, replyTo, setReplyTo, hoveredId, setHoveredId, sending, setSending, showEmoji, setShowEmoji, reactMenu, setReactMenu, deletingIds, setDeletingIds, deleteTimersRef, containerRef, messagesRef, scrollRef, textareaRef, emojiBtnRef, isAtBottom, scrollToBottom, checkAtBottom, handleLoadMore, handleTextChange, handleSend, handleKeyDown, handleDelete, handleReact, handleEmojiSelect, isOwn, isEmojiOnly } = props
|
||||
@@ -12,11 +13,7 @@ export function ChatMessages(props: any) {
|
||||
<>
|
||||
{/* Messages */}
|
||||
{messages.length === 0 ? (
|
||||
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 8, color: 'var(--text-faint)', padding: 32, textAlign: 'center' }}>
|
||||
<MessageCircle size={40} strokeWidth={1.2} style={{ opacity: 0.4 }} />
|
||||
<span style={{ fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 600 }}>{t('collab.chat.empty')}</span>
|
||||
<span style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', opacity: 0.6, fontFamily: 'var(--font-subtext)' }}>{t('collab.chat.emptyDesc') || ''}</span>
|
||||
</div>
|
||||
<EmptyState scene="chat" title={t('collab.chat.empty')} />
|
||||
) : (
|
||||
<div ref={scrollRef} onScroll={checkAtBottom} className="chat-scroll" style={{
|
||||
flex: 1, overflowY: 'auto', overflowX: 'hidden', padding: '8px 14px 4px', WebkitOverflowScrolling: 'touch',
|
||||
|
||||
@@ -11,6 +11,7 @@ import { addListener, removeListener } from '../../api/websocket'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import ConfirmDialog from '../shared/ConfirmDialog'
|
||||
import EmptyState from '../shared/EmptyState'
|
||||
import type { User } from '../../types'
|
||||
import type { CollabNote } from './CollabNotes.types'
|
||||
import { FONT, NOTE_COLORS } from './CollabNotes.constants'
|
||||
@@ -329,18 +330,7 @@ function CollabNotesGrid(S: NotesState) {
|
||||
<div style={{ flex: 1, overflowY: 'auto', padding: 12 }}>
|
||||
{sortedNotes.length === 0 ? (
|
||||
/* ── Empty state ── */
|
||||
<div style={{
|
||||
display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
|
||||
padding: '48px 20px', textAlign: 'center', height: '100%',
|
||||
}}>
|
||||
<Pencil size={36} color="var(--text-faint)" style={{ marginBottom: 12 }} />
|
||||
<div style={{ fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 600, color: 'var(--text-secondary)', marginBottom: 4, fontFamily: FONT }}>
|
||||
{t('collab.notes.empty')}
|
||||
</div>
|
||||
<div style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', color: 'var(--text-faint)', fontFamily: FONT }}>
|
||||
{t('collab.notes.emptyDesc') || 'Create a note to get started'}
|
||||
</div>
|
||||
</div>
|
||||
<EmptyState scene="notes" title={t('collab.notes.empty')} />
|
||||
) : (
|
||||
/* ── Notes grid — 2 columns ── */
|
||||
<div style={{
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useTranslation } from '../../i18n'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import { useCanDo } from '../../store/permissionsStore'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import EmptyState from '../shared/EmptyState'
|
||||
import ReactDOM from 'react-dom'
|
||||
import type { User } from '../../types'
|
||||
|
||||
@@ -461,11 +462,7 @@ export default function CollabPolls({ tripId, currentUser }: CollabPollsProps) {
|
||||
{/* Content */}
|
||||
<div className="chat-scroll" style={{ flex: 1, overflowY: 'auto', padding: '0 12px 12px' }}>
|
||||
{polls.length === 0 ? (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '48px 20px', textAlign: 'center', height: '100%' }}>
|
||||
<BarChart3 size={36} color="var(--text-faint)" strokeWidth={1.3} style={{ marginBottom: 12 }} />
|
||||
<div style={{ fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 600, color: 'var(--text-secondary)', marginBottom: 4 }}>{t('collab.polls.empty')}</div>
|
||||
<div style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', color: 'var(--text-faint)' }}>{t('collab.polls.emptyHint')}</div>
|
||||
</div>
|
||||
<EmptyState scene="polls" title={t('collab.polls.empty')} />
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
|
||||
{activePolls.length > 0 && activePolls.map(poll => (
|
||||
|
||||
@@ -3,7 +3,8 @@ import { avatarSrc } from '../../utils/avatarSrc'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { MapPin, Clock, Calendar, Users, Sparkles } from 'lucide-react'
|
||||
import { MapPin, Clock, Users, Sparkles } from 'lucide-react'
|
||||
import EmptyState from '../shared/EmptyState'
|
||||
|
||||
function formatTime(timeStr, is12h) {
|
||||
if (!timeStr) return ''
|
||||
@@ -100,11 +101,7 @@ export default function WhatsNextWidget({ tripMembers = [] }: WhatsNextWidgetPro
|
||||
{/* List */}
|
||||
<div className="chat-scroll" style={{ flex: 1, overflowY: 'auto', padding: '8px 10px' }}>
|
||||
{upcoming.length === 0 ? (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', padding: '48px 20px', textAlign: 'center' }}>
|
||||
<Calendar size={36} color="var(--text-faint)" strokeWidth={1.3} style={{ marginBottom: 12 }} />
|
||||
<div style={{ fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 600, color: 'var(--text-secondary)', marginBottom: 4 }}>{t('collab.whatsNext.empty')}</div>
|
||||
<div style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', color: 'var(--text-faint)' }}>{t('collab.whatsNext.emptyHint')}</div>
|
||||
</div>
|
||||
<EmptyState scene="guide" title={t('collab.whatsNext.empty')} />
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
|
||||
{upcoming.map((item, idx) => {
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
import { useEffect, useMemo, useState, useCallback } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { Bookmark, BookmarkCheck, Check, Loader2, Plus, X } from 'lucide-react'
|
||||
import MSheet from '../../mobile/components/MSheet'
|
||||
import MIconBtn from '../../mobile/components/MIconBtn'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { collectionsApi } from '../../api/collections'
|
||||
import { useSaveToCollectionStore } from '../../store/saveToCollectionStore'
|
||||
import { getApiErrorMessage } from '../../utils/apiError'
|
||||
import type { Collection, CollectionMembership } from '@trek/shared'
|
||||
|
||||
/**
|
||||
* Mobile counterpart of SaveToCollectionModal — the same store-driven list
|
||||
* picker (load lists + membership, toggle the place in/out of each), dressed in
|
||||
* the mobile design language (MSheet card, m-* tokens) so it matches the place
|
||||
* detail sheet. Rendered instead of the desktop modal on phones (see App.tsx).
|
||||
*/
|
||||
export default function MSaveToCollectionSheet() {
|
||||
const target = useSaveToCollectionStore(s => s.target)
|
||||
const close = useSaveToCollectionStore(s => s.close)
|
||||
const bumpVersion = useSaveToCollectionStore(s => s.bumpVersion)
|
||||
const { t } = useTranslation()
|
||||
const toast = useToast()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const [lists, setLists] = useState<Collection[]>([])
|
||||
const [membership, setMembership] = useState<CollectionMembership | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [busyId, setBusyId] = useState<number | null>(null)
|
||||
|
||||
const membershipQuery = useMemo(() => {
|
||||
if (!target) return null
|
||||
return {
|
||||
google_place_id: target.google_place_id ?? undefined,
|
||||
google_ftid: target.google_ftid ?? undefined,
|
||||
name: target.name,
|
||||
lat: target.lat ?? undefined,
|
||||
lng: target.lng ?? undefined,
|
||||
}
|
||||
}, [target])
|
||||
|
||||
const refreshMembership = useCallback(async () => {
|
||||
if (!membershipQuery) return
|
||||
try {
|
||||
setMembership(await collectionsApi.membership(membershipQuery))
|
||||
} catch {
|
||||
setMembership({ saved: false, lists: [] })
|
||||
}
|
||||
}, [membershipQuery])
|
||||
|
||||
// Load lists + membership whenever the picker opens for a new target.
|
||||
useEffect(() => {
|
||||
if (!target) return
|
||||
let cancelled = false
|
||||
setLoading(true)
|
||||
setMembership(null)
|
||||
Promise.all([
|
||||
collectionsApi.list().catch(() => ({ collections: [], incomingInvites: [] })),
|
||||
membershipQuery
|
||||
? collectionsApi.membership(membershipQuery).catch(() => ({ saved: false, lists: [] as CollectionMembership['lists'] }))
|
||||
: Promise.resolve({ saved: false, lists: [] as CollectionMembership['lists'] }),
|
||||
])
|
||||
.then(([listRes, m]) => {
|
||||
if (cancelled) return
|
||||
setLists(listRes.collections)
|
||||
setMembership(m)
|
||||
})
|
||||
.finally(() => { if (!cancelled) setLoading(false) })
|
||||
return () => { cancelled = true }
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [target])
|
||||
|
||||
const savedByCollection = new Map<number, number>()
|
||||
for (const l of membership?.lists ?? []) savedByCollection.set(l.collection_id, l.place_id)
|
||||
|
||||
const handleToggle = async (list: Collection) => {
|
||||
if (busyId != null || !target) return
|
||||
const savedPlaceId = savedByCollection.get(list.id)
|
||||
setBusyId(list.id)
|
||||
try {
|
||||
if (savedPlaceId != null) {
|
||||
await collectionsApi.deletePlace(savedPlaceId)
|
||||
toast.success(t('collections.removedFromList', { name: list.name }))
|
||||
} else {
|
||||
await collectionsApi.savePlace({
|
||||
collection_id: list.id,
|
||||
source_trip_id: target.source_trip_id ?? null,
|
||||
source_place_id: target.source_place_id ?? null,
|
||||
name: target.name,
|
||||
description: target.description ?? null,
|
||||
lat: target.lat ?? null,
|
||||
lng: target.lng ?? null,
|
||||
address: target.address ?? null,
|
||||
category_id: target.category_id ?? null,
|
||||
price: target.price ?? null,
|
||||
currency: target.currency ?? null,
|
||||
notes: target.notes ?? null,
|
||||
image_url: target.image_url ?? null,
|
||||
google_place_id: target.google_place_id ?? null,
|
||||
google_ftid: target.google_ftid ?? null,
|
||||
osm_id: target.osm_id ?? null,
|
||||
website: target.website ?? null,
|
||||
phone: target.phone ?? null,
|
||||
force: true,
|
||||
})
|
||||
toast.success(t('collections.addedToList', { name: list.name }))
|
||||
}
|
||||
await refreshMembership()
|
||||
bumpVersion()
|
||||
} catch (err) {
|
||||
toast.error(getApiErrorMessage(err, t('common.error')))
|
||||
} finally {
|
||||
setBusyId(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<MSheet open={!!target} onClose={close} variant="card" material="glass" ariaLabel={t('collections.pickList')}>
|
||||
{/* Header — mirrors the place detail sheet: icon + title + target name + close */}
|
||||
<div className="flex-none px-[18px] pt-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<span className="flex h-[42px] w-[42px] flex-none items-center justify-center rounded-[14px] bg-[color:var(--m-ic)] text-m-muted">
|
||||
<Bookmark size={18} strokeWidth={2} />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-[1rem] font-bold leading-snug">{t('collections.pickList')}</div>
|
||||
{target?.name && (
|
||||
<div className="mt-[2px] truncate font-geist text-[0.6875rem] text-m-muted">{target.name}</div>
|
||||
)}
|
||||
</div>
|
||||
<MIconBtn variant="neutral" size={34} onClick={close} ariaLabel={t('common.close')}>
|
||||
<X size={15} strokeWidth={2.2} />
|
||||
</MIconBtn>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-[14px] pb-[16px] pt-2">
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-10 text-m-faint">
|
||||
<Loader2 size={20} className="animate-spin" />
|
||||
</div>
|
||||
) : lists.length === 0 ? (
|
||||
<div className="flex flex-col items-center px-4 py-10 text-center">
|
||||
<span className="mb-3 flex h-11 w-11 items-center justify-center rounded-2xl bg-[color:var(--m-ic)] text-m-faint">
|
||||
<Bookmark size={20} strokeWidth={2} />
|
||||
</span>
|
||||
<p className="mb-3 font-geist text-[0.75rem] text-m-faint">{t('collections.noListsYet')}</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { close(); navigate('/collections') }}
|
||||
className="inline-flex items-center gap-1.5 rounded-full bg-m-act px-4 py-[9px] text-[0.75rem] font-semibold text-m-actfg"
|
||||
>
|
||||
<Plus size={14} strokeWidth={2.2} /> {t('collections.newList')}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
lists.map(list => {
|
||||
const saved = savedByCollection.has(list.id)
|
||||
const busy = busyId === list.id
|
||||
return (
|
||||
<button
|
||||
key={list.id}
|
||||
type="button"
|
||||
onClick={() => handleToggle(list)}
|
||||
disabled={busyId != null}
|
||||
className={`mt-2 flex w-full items-center gap-[11px] rounded-[14px] border px-3 py-[10px] text-left disabled:opacity-60 ${
|
||||
saved
|
||||
? 'border-[color:var(--m-act)] bg-[color:var(--m-inner)]'
|
||||
: 'border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)]'
|
||||
}`}
|
||||
>
|
||||
<span
|
||||
className="flex h-9 w-9 flex-none items-center justify-center rounded-xl text-white"
|
||||
style={{ background: list.color || '#6366f1' }}
|
||||
>
|
||||
<Bookmark size={15} strokeWidth={2} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-[0.8125rem] font-semibold text-m-ink">{list.name}</span>
|
||||
<span className="mt-px block font-geist text-[0.65625rem] text-m-muted">
|
||||
{t('collections.placeCount', { count: list.place_count ?? 0 })}
|
||||
</span>
|
||||
</span>
|
||||
{list.is_owner === false && (
|
||||
<span className="flex-none font-geist text-[0.5625rem] font-bold uppercase tracking-[.05em] text-m-faint">
|
||||
{t('collections.shared')}
|
||||
</span>
|
||||
)}
|
||||
<span
|
||||
className={`flex h-[26px] w-[26px] flex-none items-center justify-center rounded-full ${
|
||||
saved ? 'bg-m-act text-m-actfg' : 'border border-[color:var(--m-rowbr)] text-m-faint'
|
||||
}`}
|
||||
>
|
||||
{busy ? <Loader2 size={14} className="animate-spin" /> : saved ? <BookmarkCheck size={14} strokeWidth={2} /> : <Check size={14} strokeWidth={2} />}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
|
||||
{lists.length > 0 && (
|
||||
<div className="flex flex-none items-center justify-between gap-2 border-t border-[color:var(--m-rowbr)] px-[18px] py-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { close(); navigate('/collections') }}
|
||||
className="text-[0.78125rem] font-semibold text-[color:var(--m-act)]"
|
||||
>
|
||||
{t('collections.viewInCollection')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={close}
|
||||
className="rounded-full bg-[color:var(--m-ic)] px-4 py-[8px] text-[0.78125rem] font-semibold text-m-ink"
|
||||
>
|
||||
{t('common.close')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</MSheet>
|
||||
)
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
import { Fragment } from 'react'
|
||||
import { Upload, FileText, Star } from 'lucide-react'
|
||||
import { Upload, Star } from 'lucide-react'
|
||||
import type { FileManagerState } from './useFileManager'
|
||||
import { FileRow } from './FileManagerRow'
|
||||
import { usePluginViewContributions, PluginCardFooter } from '../Plugins/PluginContributions'
|
||||
import EmptyState from '../shared/EmptyState'
|
||||
|
||||
export function FilesView(S: FileManagerState) {
|
||||
const {
|
||||
@@ -66,11 +67,7 @@ export function FilesView(S: FileManagerState) {
|
||||
{/* File list */}
|
||||
<div style={{ flex: 1, overflowY: 'auto', padding: '12px 28px 16px' }} className="max-md:!px-4">
|
||||
{filteredFiles.length === 0 ? (
|
||||
<div style={{ textAlign: 'center', padding: '60px 20px', color: 'var(--text-faint)' }}>
|
||||
<FileText size={40} style={{ color: 'var(--text-faint)', display: 'block', margin: '0 auto 12px' }} />
|
||||
<p style={{ fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 600, color: 'var(--text-secondary)', margin: '0 0 4px' }}>{t('files.empty')}</p>
|
||||
<p style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))', color: 'var(--text-faint)', margin: 0 }}>{t('files.emptyHint')}</p>
|
||||
</div>
|
||||
<EmptyState scene="files" title={t('files.empty')} />
|
||||
) : (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
{filteredFiles.map(file => {
|
||||
|
||||
@@ -7,8 +7,8 @@ export function MoodChip({ mood }: { mood: string }) {
|
||||
if (!config) return null
|
||||
const Icon = config.icon
|
||||
return (
|
||||
<div className="flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-medium" style={{ background: config.bg, color: config.text }}>
|
||||
<Icon size={11} />
|
||||
<div className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10.5px] font-semibold" style={{ background: config.bg, color: config.text }}>
|
||||
<Icon size={12} />
|
||||
{t(config.label)}
|
||||
</div>
|
||||
)
|
||||
@@ -20,8 +20,8 @@ export function WeatherChip({ weather }: { weather: string }) {
|
||||
if (!config) return null
|
||||
const Icon = config.icon
|
||||
return (
|
||||
<div className="flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-medium bg-zinc-100 dark:bg-zinc-800 text-zinc-600 dark:text-zinc-400">
|
||||
<Icon size={11} />
|
||||
<div className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10.5px] font-semibold" style={{ background: 'var(--vg-surf2)', color: 'var(--vg-ink2)' }}>
|
||||
<Icon size={12} />
|
||||
{t(config.label)}
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useRef, useEffect } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import { MapPin, Clock, MoreHorizontal, Pencil, Trash2 } from 'lucide-react'
|
||||
import { MapPin, Clock, MoreHorizontal, Pencil, Trash2, Plus } from 'lucide-react'
|
||||
import { formatLocationName } from '../../utils/formatters'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { pluginsApi } from '../../api/client'
|
||||
@@ -45,7 +45,7 @@ export function EntryCard({ entry, readOnly, onEdit, onDelete, onPhotoClick }: {
|
||||
const hasProscons = prosArr.length > 0 || consArr.length > 0
|
||||
|
||||
return (
|
||||
<div className="bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 rounded-2xl overflow-hidden transition-[border-color,box-shadow] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] hover:border-zinc-400 dark:hover:border-zinc-500 hover:shadow-sm">
|
||||
<div className="bg-white dark:bg-zinc-900 rounded-[20px] overflow-hidden transition-[transform,box-shadow] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] hover:-translate-y-0.5 hover:shadow-md" style={{ border: '1px solid var(--vg-line)' }}>
|
||||
|
||||
{/* Hero area: photos with title overlay */}
|
||||
{photos.length > 0 ? (
|
||||
@@ -185,22 +185,25 @@ export function SkeletonCard({ entry, onClick }: { entry: JourneyEntry; onClick?
|
||||
return (
|
||||
<div
|
||||
onClick={onClick}
|
||||
className={`bg-white dark:bg-zinc-900 border border-dashed border-zinc-200 dark:border-zinc-700 rounded-xl px-4 py-3.5 flex items-center gap-3 transition-[border-color,border-style] duration-150 ease-[cubic-bezier(0.23,1,0.32,1)] ${onClick ? 'hover:border-solid hover:border-zinc-400 dark:hover:border-zinc-500 cursor-pointer' : ''}`}
|
||||
className={`rounded-[18px] px-3.5 py-3 flex items-center gap-3 transition-transform duration-150 ease-[cubic-bezier(0.23,1,0.32,1)] ${onClick ? 'hover:-translate-y-0.5 cursor-pointer' : ''}`}
|
||||
style={{ border: '1.5px dashed var(--vg-line2)', background: 'var(--vg-surf2)' }}
|
||||
>
|
||||
<div className="w-9 h-9 rounded-lg bg-zinc-100 dark:bg-zinc-800 flex items-center justify-center text-zinc-500 flex-shrink-0">
|
||||
<MapPin size={14} />
|
||||
<div className="w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0" style={{ background: 'var(--vg-surf)', border: '1px solid var(--vg-line)', color: 'var(--vg-ink3)' }}>
|
||||
<MapPin size={15} />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-[13px] font-medium text-zinc-900 dark:text-white">
|
||||
<div className="text-[13px] font-semibold truncate" style={{ color: 'var(--vg-ink)' }}>
|
||||
{entry.title || t('journey.detail.newEntry')}
|
||||
</div>
|
||||
<div className="text-[11px] text-zinc-500 mt-0.5">
|
||||
<div className="text-[11px] mt-0.5 truncate" style={{ color: 'var(--vg-ink3)' }}>
|
||||
{formatLocationName(entry.location_name)}{entry.entry_time ? ` · ${entry.entry_time}` : ''}
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-[11px] text-zinc-500 font-medium flex-shrink-0">
|
||||
{t('journey.detail.addEntry')} →
|
||||
</div>
|
||||
{onClick && (
|
||||
<span className="inline-flex items-center gap-1 flex-shrink-0 rounded-full px-3 py-1.5 text-[11px] font-semibold" style={{ background: 'var(--vg-ink)', color: 'var(--vg-bg)' }}>
|
||||
<Plus size={12} strokeWidth={2.6} /> {t('journey.detail.addEntry')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import { type ResilientResult, type UploadProgress } from '../../utils/uploadQue
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { journeyApi, mapsApi } from '../../api/client'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import { useIsMobile } from '../../hooks/useIsMobile'
|
||||
import { getApiErrorMessage } from '../../types'
|
||||
import type { JourneyEntry, JourneyPhoto, GalleryPhoto } from '../../store/journeyStore'
|
||||
import { MOOD_CONFIG, WEATHER_CONFIG } from '../../pages/journeyDetail/JourneyDetailPage.constants'
|
||||
@@ -25,7 +24,6 @@ export function EntryEditor({ entry, journeyId, tripDates, galleryPhotos, onClos
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const toast = useToast()
|
||||
const isMobile = useIsMobile()
|
||||
const [title, setTitle] = useState(entry.title || '')
|
||||
const [story, setStory] = useState(entry.story || '')
|
||||
const [entryDate, setEntryDate] = useState(entry.entry_date || new Date().toISOString().split('T')[0])
|
||||
@@ -139,20 +137,21 @@ export function EntryEditor({ entry, journeyId, tripDates, galleryPhotos, onClos
|
||||
centers there — but the backdrop stays full-width (covering the map
|
||||
too) for a uniform dim/blur across the whole page. */}
|
||||
<div
|
||||
className="absolute top-0 bottom-0 left-0 flex items-end sm:items-center sm:justify-center sm:p-5"
|
||||
style={{ right: isMobile ? 0 : 'clamp(420px, 44vw, 760px)' }}
|
||||
className="absolute inset-0 flex items-end sm:items-center sm:justify-center sm:p-5"
|
||||
>
|
||||
<div className="bg-white dark:bg-zinc-900 sm:rounded-2xl shadow-[0_20px_40px_rgba(0,0,0,0.2)] sm:max-w-[640px] w-full flex flex-col overflow-hidden h-full sm:h-auto sm:max-h-[90vh]" style={{ paddingBottom: 'var(--bottom-nav-h)' }}>
|
||||
<div className="bg-white dark:bg-zinc-900 rounded-t-[24px] sm:rounded-[24px] shadow-[0_20px_40px_rgba(0,0,0,0.2)] sm:max-w-[1040px] w-full flex flex-col overflow-hidden h-full sm:h-auto sm:max-h-[90vh]" style={{ paddingBottom: 'var(--bottom-nav-h)' }}>
|
||||
|
||||
|
||||
<div className="flex items-center justify-between px-6 py-4 border-b border-zinc-200 dark:border-zinc-700">
|
||||
<h2 className="text-[16px] font-bold text-zinc-900 dark:text-white">{entry.id === 0 ? t('journey.detail.newEntry') : t('journey.detail.editEntry')}</h2>
|
||||
<button onClick={handleClose} className="w-8 h-8 rounded-lg flex items-center justify-center text-zinc-400 hover:bg-zinc-100 dark:hover:bg-zinc-800">
|
||||
<button onClick={handleClose} className="w-8 h-8 rounded-full flex items-center justify-center text-zinc-400 hover:bg-zinc-100 dark:hover:bg-zinc-800">
|
||||
<X size={16} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-h-0 overflow-y-auto px-6 py-5 flex flex-col gap-4">
|
||||
<div className="flex-1 min-h-0 overflow-y-auto px-6 py-5">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-4 items-stretch">
|
||||
<div className="flex flex-col gap-4 min-w-0">
|
||||
<input
|
||||
value={title}
|
||||
onChange={e => setTitle(e.target.value)}
|
||||
@@ -166,7 +165,7 @@ export function EntryEditor({ entry, journeyId, tripDates, galleryPhotos, onClos
|
||||
<button
|
||||
onClick={() => fileRef.current?.click()}
|
||||
disabled={saving}
|
||||
className="flex-1 border border-dashed border-zinc-200 dark:border-zinc-700 rounded-lg py-4 text-[12px] text-zinc-500 hover:border-zinc-400 dark:hover:border-zinc-500 hover:bg-zinc-50 dark:hover:bg-zinc-800 flex items-center justify-center gap-1.5 disabled:opacity-50"
|
||||
className="flex-1 border border-dashed border-zinc-200 dark:border-zinc-700 rounded-xl py-4 text-[12px] text-zinc-500 hover:border-zinc-400 dark:hover:border-zinc-500 hover:bg-zinc-50 dark:hover:bg-zinc-800 flex items-center justify-center gap-1.5 disabled:opacity-50"
|
||||
>
|
||||
{uploadProgress ? (
|
||||
<><div className="w-3.5 h-3.5 border-2 border-zinc-300 border-t-zinc-600 rounded-full animate-spin" /> {t('journey.editor.uploadingProgress', { done: String(uploadProgress.done), total: String(uploadProgress.total) })}</>
|
||||
@@ -177,7 +176,7 @@ export function EntryEditor({ entry, journeyId, tripDates, galleryPhotos, onClos
|
||||
{galleryPhotos.length > 0 && (
|
||||
<button
|
||||
onClick={() => setShowGalleryPick(!showGalleryPick)}
|
||||
className={`flex-1 border rounded-lg py-4 text-[12px] text-zinc-500 flex items-center justify-center gap-1.5 ${
|
||||
className={`flex-1 border rounded-xl py-4 text-[12px] text-zinc-500 flex items-center justify-center gap-1.5 ${
|
||||
showGalleryPick
|
||||
? 'border-zinc-900 dark:border-white bg-zinc-50 dark:bg-zinc-800'
|
||||
: 'border-dashed border-zinc-200 dark:border-zinc-700 hover:border-zinc-400 dark:hover:border-zinc-500 hover:bg-zinc-50 dark:hover:bg-zinc-800'
|
||||
@@ -209,7 +208,7 @@ export function EntryEditor({ entry, journeyId, tripDates, galleryPhotos, onClos
|
||||
setPhotos(prev => [...prev, gp])
|
||||
}
|
||||
}}
|
||||
className="relative w-full rounded-lg overflow-hidden cursor-pointer hover:ring-2 hover:ring-zinc-900 dark:hover:ring-white hover:ring-offset-1 dark:hover:ring-offset-zinc-900 transition-all"
|
||||
className="relative w-full rounded-xl overflow-hidden cursor-pointer hover:ring-2 hover:ring-zinc-900 dark:hover:ring-white hover:ring-offset-1 dark:hover:ring-offset-zinc-900 transition-all"
|
||||
style={{ paddingTop: '100%' }}
|
||||
>
|
||||
<img src={photoUrl(gp)} alt="" className="absolute inset-0 w-full h-full object-cover" loading="lazy" onError={e => { const img = e.currentTarget; const orig = photoUrl(gp, 'original'); if (!img.src.includes('/original')) img.src = orig }} />
|
||||
@@ -225,7 +224,7 @@ export function EntryEditor({ entry, journeyId, tripDates, galleryPhotos, onClos
|
||||
<div className="mt-3">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{photos.map((p, idx) => (
|
||||
<div key={p.id} className={`w-20 h-20 rounded-lg overflow-hidden relative group ${idx === 0 && photos.length > 1 ? 'ring-2 ring-zinc-900 dark:ring-white ring-offset-1 dark:ring-offset-zinc-900' : ''}`}>
|
||||
<div key={p.id} className={`w-20 h-20 rounded-xl overflow-hidden relative group ${idx === 0 && photos.length > 1 ? 'ring-2 ring-zinc-900 dark:ring-white ring-offset-1 dark:ring-offset-zinc-900' : ''}`}>
|
||||
<img src={photoUrl(p)} className="w-full h-full object-cover" alt="" onError={e => { const img = e.currentTarget; const orig = photoUrl(p, 'original'); if (!img.src.includes('/original')) img.src = orig }} />
|
||||
{idx === 0 && photos.length > 1 && (
|
||||
<span className="absolute bottom-0.5 left-0.5 px-1 py-px rounded text-[8px] font-bold bg-zinc-900/70 text-white">{t('journey.editor.photoFirst')}</span>
|
||||
@@ -265,7 +264,7 @@ export function EntryEditor({ entry, journeyId, tripDates, galleryPhotos, onClos
|
||||
</div>
|
||||
))}
|
||||
{pendingFiles.map((f, i) => (
|
||||
<div key={`pending-${i}`} className="w-20 h-20 rounded-lg overflow-hidden relative group">
|
||||
<div key={`pending-${i}`} className="w-20 h-20 rounded-xl overflow-hidden relative group">
|
||||
<img src={URL.createObjectURL(f)} className="w-full h-full object-cover" alt="" />
|
||||
<button
|
||||
onClick={() => setPendingFiles(prev => prev.filter((_, j) => j !== i))}
|
||||
@@ -280,7 +279,7 @@ export function EntryEditor({ entry, journeyId, tripDates, galleryPhotos, onClos
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="shrink-0 border border-zinc-200 dark:border-zinc-700 rounded-lg overflow-hidden focus-within:border-zinc-400 dark:focus-within:border-zinc-500">
|
||||
<div className="flex-1 flex flex-col min-h-[220px] border border-zinc-200 dark:border-zinc-700 rounded-xl overflow-hidden focus-within:border-zinc-400 dark:focus-within:border-zinc-500">
|
||||
<MarkdownToolbar textareaRef={storyRef} onUpdate={setStory} />
|
||||
<textarea
|
||||
ref={storyRef}
|
||||
@@ -289,10 +288,13 @@ export function EntryEditor({ entry, journeyId, tripDates, galleryPhotos, onClos
|
||||
placeholder={t('journey.editor.writeStory')}
|
||||
rows={6}
|
||||
style={{ minHeight: '144px' }}
|
||||
className="w-full px-3 py-2.5 text-[14px] bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white outline-none resize-none border-0 shrink-0"
|
||||
className="w-full flex-1 px-3 py-2.5 text-[14px] bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white outline-none resize-none border-0"
|
||||
/>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-4 min-w-0">
|
||||
{/* Pros & Cons */}
|
||||
<div className="bg-zinc-50 dark:bg-zinc-800/50 rounded-2xl p-5">
|
||||
<div className="mb-4">
|
||||
@@ -369,8 +371,6 @@ export function EntryEditor({ entry, journeyId, tripDates, galleryPhotos, onClos
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="h-px bg-zinc-200 dark:bg-zinc-700" />
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="text-[10px] font-semibold tracking-[0.12em] uppercase text-zinc-500 block mb-1.5">{t('journey.editor.date')}</label>
|
||||
@@ -405,11 +405,6 @@ export function EntryEditor({ entry, journeyId, tripDates, galleryPhotos, onClos
|
||||
placeholder={t('journey.editor.searchLocation')}
|
||||
className="w-full px-3 py-2 border border-zinc-200 dark:border-zinc-700 rounded-lg text-[13px] bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white outline-none focus:border-zinc-400 dark:focus:border-zinc-500"
|
||||
/>
|
||||
{locationLat && (
|
||||
<div className="absolute right-2 top-1/2 -translate-y-1/2">
|
||||
<MapPin size={13} className="text-zinc-500 dark:text-zinc-400" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{showLocationResults && locationResults.length > 0 && (
|
||||
<>
|
||||
@@ -448,13 +443,13 @@ export function EntryEditor({ entry, journeyId, tripDates, galleryPhotos, onClos
|
||||
|
||||
<div>
|
||||
<label className="text-[10px] font-semibold tracking-[0.12em] uppercase text-zinc-500 block mb-2">{t('journey.editor.mood')}</label>
|
||||
<div className="flex gap-2">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{Object.entries(MOOD_CONFIG).map(([key, config]) => {
|
||||
const Icon = config.icon
|
||||
const active = mood === key
|
||||
return (
|
||||
<button key={key} onClick={() => setMood(active ? '' : key)}
|
||||
className={`flex items-center gap-1 px-2.5 py-1 rounded-full text-[11px] font-medium border transition-all ${
|
||||
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-[12px] font-semibold border transition-all ${
|
||||
active ? '' : 'border-zinc-200 dark:border-zinc-700 text-zinc-500'
|
||||
}`}
|
||||
style={active ? { background: config.bg, color: config.text, borderColor: config.text + '30' } : undefined}>
|
||||
@@ -474,7 +469,7 @@ export function EntryEditor({ entry, journeyId, tripDates, galleryPhotos, onClos
|
||||
const active = weather === key
|
||||
return (
|
||||
<button key={key} onClick={() => setWeather(active ? '' : key)}
|
||||
className={`flex items-center gap-1 px-2 py-1 rounded-full text-[11px] font-medium border transition-all ${
|
||||
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-[12px] font-semibold border transition-all ${
|
||||
active ? 'bg-zinc-900 dark:bg-white text-white dark:text-zinc-900 border-zinc-900 dark:border-white' : 'border-zinc-200 dark:border-zinc-700 text-zinc-500 hover:border-zinc-400'
|
||||
}`}>
|
||||
<Icon size={12} />
|
||||
@@ -484,12 +479,14 @@ export function EntryEditor({ entry, journeyId, tripDates, galleryPhotos, onClos
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="flex items-center justify-end gap-2 px-6 py-4 border-t border-zinc-200 dark:border-zinc-700 bg-zinc-50 dark:bg-zinc-800/50" style={{ paddingBottom: 'max(16px, env(safe-area-inset-bottom, 16px))' }}>
|
||||
<button onClick={handleClose} className="px-3.5 py-2 rounded-lg border border-zinc-200 dark:border-zinc-600 text-[13px] font-medium text-zinc-700 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-700">{t('common.cancel')}</button>
|
||||
<button onClick={handleSave} disabled={saving} className="px-3.5 py-2 rounded-lg bg-zinc-900 dark:bg-white text-white dark:text-zinc-900 text-[13px] font-medium hover:bg-zinc-800 dark:hover:bg-zinc-100 disabled:opacity-50">
|
||||
<button onClick={handleClose} className="px-4 h-10 flex items-center rounded-full border border-zinc-200 dark:border-zinc-600 text-[13px] font-semibold text-zinc-700 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-700 transition-colors">{t('common.cancel')}</button>
|
||||
<button onClick={handleSave} disabled={saving} className="px-5 h-10 flex items-center rounded-full bg-zinc-900 dark:bg-white text-white dark:text-zinc-900 text-[13px] font-semibold hover:bg-zinc-800 dark:hover:bg-zinc-100 disabled:opacity-50 transition-colors">
|
||||
{saving ? t('common.saving') : t('common.save')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useState, useRef } from 'react'
|
||||
import { RefreshCw, Camera, Image, Plus, X, Play } from 'lucide-react'
|
||||
import { RefreshCw, Camera, Image, X, Play } from 'lucide-react'
|
||||
import { normalizeImageFiles } from '../../utils/convertHeic'
|
||||
import { isVideoFile } from '../../utils/videoPoster'
|
||||
import { useJourneyStore } from '../../store/journeyStore'
|
||||
@@ -10,8 +10,9 @@ import { getApiErrorMessage } from '../../types'
|
||||
import type { JourneyEntry, GalleryPhoto, JourneyTrip } from '../../store/journeyStore'
|
||||
import { photoUrl } from '../../pages/journeyDetail/JourneyDetailPage.helpers'
|
||||
import { ProviderPicker } from './JourneyDetailPageProviderPicker'
|
||||
import EmptyState from '../shared/EmptyState'
|
||||
|
||||
export function GalleryView({ entries, gallery, journeyId, userId, trips, onPhotoClick, onRefresh }: {
|
||||
export function GalleryView({ entries, gallery, journeyId, userId, trips, onPhotoClick, onRefresh, onRegisterUpload }: {
|
||||
entries: JourneyEntry[]
|
||||
gallery: GalleryPhoto[]
|
||||
journeyId: number
|
||||
@@ -19,6 +20,7 @@ export function GalleryView({ entries, gallery, journeyId, userId, trips, onPhot
|
||||
trips: JourneyTrip[]
|
||||
onPhotoClick: (photos: GalleryPhoto[], index: number) => void
|
||||
onRefresh: () => void
|
||||
onRegisterUpload?: (fn: () => void) => void
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
const [showPicker, setShowPicker] = useState(false)
|
||||
@@ -61,6 +63,7 @@ export function GalleryView({ entries, gallery, journeyId, userId, trips, onPhot
|
||||
}
|
||||
|
||||
const galleryFileRef = useRef<HTMLInputElement>(null)
|
||||
useEffect(() => { onRegisterUpload?.(() => galleryFileRef.current?.click()) }, [onRegisterUpload])
|
||||
|
||||
const handleGalleryUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const files = e.target.files
|
||||
@@ -119,21 +122,10 @@ export function GalleryView({ entries, gallery, journeyId, userId, trips, onPhot
|
||||
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between mb-4 flex-wrap gap-2">
|
||||
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-zinc-100 dark:bg-zinc-800 text-[10px] font-medium text-zinc-500 dark:text-zinc-400">
|
||||
<Camera size={10} /> {allPhotos.length} {t('journey.detail.photos')}
|
||||
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10px] font-bold uppercase tracking-[0.07em]" style={{ background: 'var(--vg-surf2)', color: 'var(--vg-ink3)' }}>
|
||||
<Camera size={11} /> {allPhotos.length} {t('journey.detail.photos')}
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => galleryFileRef.current?.click()}
|
||||
disabled={galleryUploading}
|
||||
className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg bg-zinc-900 dark:bg-white text-white dark:text-zinc-900 text-[11px] font-medium hover:bg-zinc-800 dark:hover:bg-zinc-100 disabled:opacity-50"
|
||||
>
|
||||
{galleryUploading ? (
|
||||
<><div className="w-3 h-3 border-2 border-white/30 dark:border-zinc-900/30 border-t-white dark:border-t-zinc-900 rounded-full animate-spin" /> {galleryProgress ? t('journey.editor.uploadingProgress', { done: String(galleryProgress.done), total: String(galleryProgress.total) }) : t('journey.editor.uploading')}</>
|
||||
) : (
|
||||
<><Plus size={12} /> {t('common.upload')}</>
|
||||
)}
|
||||
</button>
|
||||
{availableProviders.map(p => (
|
||||
<button
|
||||
key={p.id}
|
||||
@@ -148,13 +140,7 @@ export function GalleryView({ entries, gallery, journeyId, userId, trips, onPhot
|
||||
</div>
|
||||
|
||||
{allPhotos.length === 0 ? (
|
||||
<div className="text-center py-16">
|
||||
<div className="w-16 h-16 rounded-full bg-zinc-100 dark:bg-zinc-800 flex items-center justify-center mx-auto mb-4">
|
||||
<Image size={24} className="text-zinc-400" />
|
||||
</div>
|
||||
<p className="text-[15px] font-medium text-zinc-700 dark:text-zinc-300">{t('journey.detail.noPhotos')}</p>
|
||||
<p className="text-[12px] text-zinc-500 mt-1">{t('journey.detail.noPhotosHint')}</p>
|
||||
</div>
|
||||
<EmptyState scene="journey" title={t('journey.detail.noPhotos')} />
|
||||
) : (
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-1.5 pb-24 md:pb-6">
|
||||
{allPhotos.map((photo, i) => (
|
||||
|
||||
@@ -88,17 +88,20 @@ export function JourneySettingsDialog({ journey, onClose, onSaved, onOpenInvite,
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-[200] flex items-end md:items-center justify-center md:p-5 overscroll-none bg-[rgba(9,9,11,0.75)]" onClick={handleClose} onTouchMove={e => { if (e.target === e.currentTarget) e.preventDefault() }}>
|
||||
<div className="bg-white dark:bg-zinc-900 rounded-t-2xl md:rounded-2xl shadow-[0_20px_40px_rgba(0,0,0,0.2)] max-w-[480px] w-full max-h-[85vh] md:max-h-[90vh] flex flex-col overflow-hidden" style={{ paddingBottom: 'env(safe-area-inset-bottom, 0px)' }} onClick={e => e.stopPropagation()}>
|
||||
<div className="bg-white dark:bg-zinc-900 rounded-t-2xl md:rounded-[24px] shadow-[0_20px_40px_rgba(0,0,0,0.2)] max-w-[980px] w-full max-h-[85vh] md:max-h-[90vh] flex flex-col overflow-hidden" style={{ paddingBottom: 'env(safe-area-inset-bottom, 0px)' }} onClick={e => e.stopPropagation()}>
|
||||
|
||||
<div className="flex items-center justify-between px-6 py-4 border-b border-zinc-200 dark:border-zinc-700">
|
||||
<h2 className="text-[16px] font-bold text-zinc-900 dark:text-white">{t('journey.settings.title')}</h2>
|
||||
<button onClick={handleClose} className="w-8 h-8 rounded-lg flex items-center justify-center text-zinc-400 hover:bg-zinc-100 dark:hover:bg-zinc-800">
|
||||
<button onClick={handleClose} className="w-8 h-8 rounded-xl flex items-center justify-center text-zinc-400 hover:bg-zinc-100 dark:hover:bg-zinc-800">
|
||||
<X size={16} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto overscroll-contain px-6 py-5 flex flex-col gap-5">
|
||||
{/* Cover Image */}
|
||||
<div className="flex-1 overflow-y-auto overscroll-contain px-6 py-5">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-5 items-start">
|
||||
{/* Left column */}
|
||||
<div className="flex flex-col gap-5 rounded-2xl p-4" style={{ background: 'var(--vg-surf2)', border: '1px solid var(--vg-line)' }}>
|
||||
{/*Cover Image */}
|
||||
<div>
|
||||
<label className="text-[10px] font-semibold tracking-[0.12em] uppercase text-zinc-500 block mb-2">{t('journey.settings.coverImage')}</label>
|
||||
<input ref={coverRef} type="file" accept="image/*" onChange={handleCoverUpload} className="hidden" />
|
||||
@@ -123,7 +126,7 @@ export function JourneySettingsDialog({ journey, onClose, onSaved, onOpenInvite,
|
||||
<input
|
||||
value={title}
|
||||
onChange={e => setTitle(e.target.value)}
|
||||
className="w-full px-3 py-2 border border-zinc-200 dark:border-zinc-700 rounded-lg text-[14px] bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white outline-none focus:border-zinc-400"
|
||||
className="w-full px-3.5 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-xl text-[14px] bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white outline-none focus:border-zinc-400"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -134,18 +137,20 @@ export function JourneySettingsDialog({ journey, onClose, onSaved, onOpenInvite,
|
||||
value={subtitle}
|
||||
onChange={e => setSubtitle(e.target.value)}
|
||||
placeholder={t('journey.settings.subtitlePlaceholder')}
|
||||
className="w-full px-3 py-2 border border-zinc-200 dark:border-zinc-700 rounded-lg text-[14px] bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white outline-none focus:border-zinc-400"
|
||||
className="w-full px-3.5 py-2.5 border border-zinc-200 dark:border-zinc-700 rounded-xl text-[14px] bg-white dark:bg-zinc-800 text-zinc-900 dark:text-white outline-none focus:border-zinc-400"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="h-px bg-zinc-200 dark:bg-zinc-700" />
|
||||
</div>
|
||||
|
||||
{/* Synced Trips */}
|
||||
{/* Right column */}
|
||||
<div className="flex flex-col gap-5 rounded-2xl p-4" style={{ background: 'var(--vg-surf2)', border: '1px solid var(--vg-line)' }}>
|
||||
{/*Synced Trips */}
|
||||
<div>
|
||||
<label className="text-[10px] font-semibold tracking-[0.12em] uppercase text-zinc-500 block mb-2">{t('journey.detail.syncedTrips')}</label>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
{journey.trips.map((trip: any) => (
|
||||
<div key={trip.trip_id} className="flex items-center gap-2.5 p-2 rounded-lg bg-zinc-50 dark:bg-zinc-800">
|
||||
<div key={trip.trip_id} className="flex items-center gap-2.5 p-2 rounded-xl bg-zinc-50 dark:bg-zinc-800">
|
||||
<div className="w-8 h-8 rounded-md flex-shrink-0" style={{ background: pickGradient(trip.trip_id) }} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-[12px] font-medium text-zinc-900 dark:text-white">{trip.title}</div>
|
||||
@@ -153,7 +158,7 @@ export function JourneySettingsDialog({ journey, onClose, onSaved, onOpenInvite,
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setUnlinkTarget({ trip_id: trip.trip_id, title: trip.title })}
|
||||
className="w-8 h-8 rounded-lg flex-shrink-0 flex items-center justify-center bg-red-500/10 text-red-500 hover:bg-red-500/20 dark:bg-red-500/15 dark:hover:bg-red-500/25 transition-colors"
|
||||
className="w-8 h-8 rounded-xl flex-shrink-0 flex items-center justify-center bg-red-500/10 text-red-500 hover:bg-red-500/20 dark:bg-red-500/15 dark:hover:bg-red-500/25 transition-colors"
|
||||
title="Unlink trip"
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
@@ -163,7 +168,7 @@ export function JourneySettingsDialog({ journey, onClose, onSaved, onOpenInvite,
|
||||
{journey.trips.length === 0 && <p className="text-[11px] text-zinc-400">{t('journey.trips.noTripsLinkedSettings')}</p>}
|
||||
<button
|
||||
onClick={() => setShowAddTrip(true)}
|
||||
className="w-full mt-1 flex items-center justify-center gap-1.5 py-2.5 rounded-lg border border-dashed border-zinc-300 dark:border-zinc-600 text-[12px] font-medium text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 dark:hover:border-zinc-500 dark:hover:text-zinc-300 transition-colors"
|
||||
className="w-full mt-1 flex items-center justify-center gap-1.5 py-2.5 rounded-xl border border-dashed border-zinc-300 dark:border-zinc-600 text-[12px] font-medium text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 dark:hover:border-zinc-500 dark:hover:text-zinc-300 transition-colors"
|
||||
>
|
||||
<Plus size={14} /> {t('journey.trips.addTrip')}
|
||||
</button>
|
||||
@@ -180,7 +185,7 @@ export function JourneySettingsDialog({ journey, onClose, onSaved, onOpenInvite,
|
||||
{(c.username || '?')[0].toUpperCase()}
|
||||
</div>
|
||||
<div className="flex-1 text-[12px] font-medium text-zinc-900 dark:text-white">{c.username}</div>
|
||||
<span className={`text-[9px] font-medium px-1.5 py-0.5 rounded-full ${c.role === 'owner' ? 'bg-zinc-900 dark:bg-white text-white dark:text-zinc-900' : 'bg-zinc-100 dark:bg-zinc-800 text-zinc-500'}`}>{c.role}</span>
|
||||
<span className="shrink-0 rounded-full font-semibold uppercase" style={{ fontSize: 8.5, letterSpacing: '0.05em', padding: '2px 7px', ...(c.role === 'owner' ? { background: 'var(--vg-ink)', color: 'var(--vg-bg)' } : { background: 'color-mix(in srgb, var(--vg-ink3) 14%, transparent)', color: 'var(--vg-ink2)' }) }}>{c.role}</span>
|
||||
{c.role !== 'owner' && (
|
||||
<button
|
||||
onClick={async () => {
|
||||
@@ -195,7 +200,7 @@ export function JourneySettingsDialog({ journey, onClose, onSaved, onOpenInvite,
|
||||
}}
|
||||
aria-label={t('journey.contributors.remove')}
|
||||
title={t('journey.contributors.remove')}
|
||||
className="w-7 h-7 rounded-lg flex items-center justify-center text-zinc-400 hover:bg-red-50 dark:hover:bg-red-900/20 hover:text-red-500 transition-colors"
|
||||
className="w-7 h-7 rounded-xl flex items-center justify-center text-zinc-400 hover:bg-red-50 dark:hover:bg-red-900/20 hover:text-red-500 transition-colors"
|
||||
>
|
||||
<X size={13} />
|
||||
</button>
|
||||
@@ -204,14 +209,17 @@ export function JourneySettingsDialog({ journey, onClose, onSaved, onOpenInvite,
|
||||
))}
|
||||
<button
|
||||
onClick={onOpenInvite}
|
||||
className="w-full mt-1 flex items-center justify-center gap-1.5 py-2.5 rounded-lg border border-dashed border-zinc-300 dark:border-zinc-600 text-[12px] font-medium text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 dark:hover:border-zinc-500 dark:hover:text-zinc-300 transition-colors"
|
||||
className="w-full mt-1 flex items-center justify-center gap-1.5 py-2.5 rounded-xl border border-dashed border-zinc-300 dark:border-zinc-600 text-[12px] font-medium text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 dark:hover:border-zinc-500 dark:hover:text-zinc-300 transition-colors"
|
||||
>
|
||||
<UserPlus size={14} /> {t('journey.contributors.invite')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="h-px bg-zinc-200 dark:bg-zinc-700" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="h-3" />
|
||||
|
||||
{/* Public Share */}
|
||||
<JourneyShareSection journeyId={journey.id} />
|
||||
@@ -224,7 +232,7 @@ export function JourneySettingsDialog({ journey, onClose, onSaved, onOpenInvite,
|
||||
onClick={() => setShowDeleteConfirm(true)}
|
||||
aria-label={t('journey.settings.delete')}
|
||||
title={t('journey.settings.delete')}
|
||||
className="flex items-center justify-center gap-1.5 h-9 min-w-9 px-2 md:px-2.5 text-[12px] font-medium text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg"
|
||||
className="flex items-center justify-center gap-1.5 h-9 min-w-9 px-3 md:px-3.5 text-[12px] font-semibold text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-full transition-colors"
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
<span className="hidden md:inline">{t('journey.settings.delete')}</span>
|
||||
@@ -234,13 +242,13 @@ export function JourneySettingsDialog({ journey, onClose, onSaved, onOpenInvite,
|
||||
disabled={archiving}
|
||||
aria-label={journey.status === 'archived' ? t('journey.settings.reopenJourney') : t('journey.settings.endJourney')}
|
||||
title={t('journey.settings.endDescription')}
|
||||
className="flex items-center justify-center gap-1.5 h-9 min-w-9 px-2 md:px-2.5 text-[12px] font-medium text-zinc-600 dark:text-zinc-400 hover:bg-zinc-100 dark:hover:bg-zinc-700 rounded-lg mr-auto disabled:opacity-40"
|
||||
className="flex items-center justify-center gap-1.5 h-9 min-w-9 px-3 md:px-3.5 text-[12px] font-semibold text-zinc-600 dark:text-zinc-400 hover:bg-zinc-100 dark:hover:bg-zinc-700 rounded-full mr-auto disabled:opacity-40 transition-colors"
|
||||
>
|
||||
{journey.status === 'archived' ? <ArchiveRestore size={14} /> : <Archive size={14} />}
|
||||
<span className="hidden md:inline">{journey.status === 'archived' ? t('journey.settings.reopenJourney') : t('journey.settings.endJourney')}</span>
|
||||
</button>
|
||||
<button onClick={handleClose} className="h-9 px-3.5 rounded-lg border border-zinc-200 dark:border-zinc-600 text-[13px] font-medium text-zinc-700 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-700">{t('common.cancel')}</button>
|
||||
<button onClick={handleSave} disabled={saving || !title.trim()} className="h-9 px-3.5 rounded-lg bg-zinc-900 dark:bg-white text-white dark:text-zinc-900 text-[13px] font-medium hover:bg-zinc-800 dark:hover:bg-zinc-100 disabled:opacity-40">
|
||||
<button onClick={handleClose} className="h-10 px-4 rounded-full border border-zinc-200 dark:border-zinc-600 text-[13px] font-semibold text-zinc-700 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-700 transition-colors">{t('common.cancel')}</button>
|
||||
<button onClick={handleSave} disabled={saving || !title.trim()} className="h-10 px-5 rounded-full bg-zinc-900 dark:bg-white text-white dark:text-zinc-900 text-[13px] font-semibold hover:bg-zinc-800 dark:hover:bg-zinc-100 disabled:opacity-40 transition-colors">
|
||||
{saving ? t('common.saving') : t('common.save')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -57,22 +57,28 @@ export default function JourneyShareSection({ journeyId }: { journeyId: number }
|
||||
{!link ? (
|
||||
<button
|
||||
onClick={createLink}
|
||||
className="w-full flex items-center justify-center gap-1.5 py-2.5 rounded-lg border border-dashed border-zinc-300 dark:border-zinc-600 text-[12px] font-medium text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 dark:hover:border-zinc-500 dark:hover:text-zinc-300 transition-colors"
|
||||
className="w-full flex items-center justify-center gap-1.5 py-2.5 rounded-xl border border-dashed border-zinc-300 dark:border-zinc-600 text-[12px] font-medium text-zinc-500 hover:border-zinc-400 hover:text-zinc-700 dark:hover:border-zinc-500 dark:hover:text-zinc-300 transition-colors"
|
||||
>
|
||||
<Link size={14} /> {t('journey.share.createLink')}
|
||||
</button>
|
||||
) : (
|
||||
<div className="flex flex-col gap-3">
|
||||
{/* URL + Copy */}
|
||||
<div className="flex items-center gap-2 p-2.5 rounded-lg bg-zinc-50 dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700">
|
||||
<Link size={13} className="text-zinc-400 flex-shrink-0" />
|
||||
<div className="flex items-center gap-2 p-2 rounded-2xl bg-zinc-50 dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700">
|
||||
<Link size={13} className="text-zinc-400 flex-shrink-0 ml-1.5" />
|
||||
<span className="flex-1 text-[11px] text-zinc-600 dark:text-zinc-400 truncate">{shareUrl}</span>
|
||||
<button
|
||||
onClick={copyLink}
|
||||
className="flex-shrink-0 px-2.5 py-1 rounded-md bg-zinc-900 dark:bg-white text-white dark:text-zinc-900 text-[11px] font-medium hover:bg-zinc-700 dark:hover:bg-zinc-200"
|
||||
className="flex-shrink-0 px-3 py-1.5 rounded-full bg-zinc-900 dark:bg-white text-white dark:text-zinc-900 text-[11px] font-semibold hover:bg-zinc-700 dark:hover:bg-zinc-200 transition-colors"
|
||||
>
|
||||
{copied ? t('journey.share.copied') : t('journey.share.copy')}
|
||||
</button>
|
||||
<button
|
||||
onClick={deleteLink}
|
||||
className="flex-shrink-0 px-3 py-1.5 rounded-full text-[11px] font-semibold text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors"
|
||||
>
|
||||
{t('share.deleteLink')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Permission toggles */}
|
||||
@@ -85,7 +91,7 @@ export default function JourneyShareSection({ journeyId }: { journeyId: number }
|
||||
<button
|
||||
key={key}
|
||||
onClick={() => togglePerm(key)}
|
||||
className={`flex items-center gap-2.5 px-3 py-2 rounded-lg border text-[12px] font-medium transition-all ${
|
||||
className={`flex items-center gap-2.5 px-3 py-2 rounded-xl border text-[12px] font-medium transition-all ${
|
||||
link[key]
|
||||
? 'border-zinc-900 dark:border-white bg-zinc-900 dark:bg-white text-white dark:text-zinc-900'
|
||||
: 'border-zinc-200 dark:border-zinc-700 text-zinc-500 hover:border-zinc-400'
|
||||
@@ -97,14 +103,6 @@ export default function JourneyShareSection({ journeyId }: { journeyId: number }
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Delete link */}
|
||||
<button
|
||||
onClick={deleteLink}
|
||||
className="text-[11px] font-medium text-red-500 hover:text-red-600 self-start"
|
||||
>
|
||||
{t('share.deleteLink')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { LayoutGrid } from 'lucide-react'
|
||||
import { buildNavItems, splitMobileNav, type NavItemDef } from './navItems'
|
||||
|
||||
const item = (id: string): NavItemDef => ({ id, to: `/${id}`, label: id, icon: LayoutGrid })
|
||||
const ids = (xs: NavItemDef[]) => xs.map((x) => x.id)
|
||||
|
||||
// Dashboard + four global addons in store order.
|
||||
const items = [item('dashboard'), item('vacay'), item('atlas'), item('journey'), item('collections')]
|
||||
|
||||
describe('buildNavItems', () => {
|
||||
const t = (k: string) => k // untranslated → falls back to the addon/plugin name
|
||||
|
||||
it('puts Dashboard first, then addons, then page plugins as plugin:<id>', () => {
|
||||
const out = buildNavItems(
|
||||
[{ id: 'vacay', name: 'Vacay', icon: 'CalendarDays' }],
|
||||
[{ id: 'foo', name: 'My Plugin', icon: null }],
|
||||
t,
|
||||
)
|
||||
expect(ids(out)).toEqual(['dashboard', 'vacay', 'plugin:foo'])
|
||||
expect(out[0].pinned).toBe(true)
|
||||
expect(out[2].to).toBe('/plugins/foo')
|
||||
expect(out[2].label).toBe('My Plugin')
|
||||
})
|
||||
})
|
||||
|
||||
describe('splitMobileNav', () => {
|
||||
it('falls back to Dashboard + first two in the bar when there is no config', () => {
|
||||
for (const cfg of [undefined, { bar: [], more: [] }]) {
|
||||
const s = splitMobileNav(items, cfg)
|
||||
expect(ids(s.bar)).toEqual(['dashboard', 'vacay', 'atlas'])
|
||||
expect(ids(s.more)).toEqual(['journey', 'collections'])
|
||||
}
|
||||
})
|
||||
|
||||
it('honours a custom split and order, Dashboard still first', () => {
|
||||
const s = splitMobileNav(items, { bar: ['journey'], more: ['collections', 'vacay', 'atlas'] })
|
||||
expect(ids(s.bar)).toEqual(['dashboard', 'journey'])
|
||||
expect(ids(s.more)).toEqual(['collections', 'vacay', 'atlas'])
|
||||
})
|
||||
|
||||
it('drops stored ids that no longer exist and appends newly available ones under More', () => {
|
||||
const s = splitMobileNav(items, { bar: ['ghost', 'vacay'], more: ['journey'] })
|
||||
expect(ids(s.bar)).toEqual(['dashboard', 'vacay'])
|
||||
// atlas + collections are new since the config was saved → appended to More
|
||||
expect(ids(s.more)).toEqual(['journey', 'atlas', 'collections'])
|
||||
})
|
||||
|
||||
it('caps the bar and overflows the excess into More', () => {
|
||||
const s = splitMobileNav(items, { bar: ['vacay', 'atlas', 'journey', 'collections'], more: [] })
|
||||
expect(ids(s.bar)).toEqual(['dashboard', 'vacay', 'atlas']) // Dashboard + 2
|
||||
expect(ids(s.more)).toEqual(['journey', 'collections'])
|
||||
})
|
||||
|
||||
it('never lets a stored dashboard id take a bar slot from the pinned one', () => {
|
||||
const s = splitMobileNav(items, { bar: ['dashboard', 'vacay'], more: [] })
|
||||
expect(ids(s.bar)).toEqual(['dashboard', 'vacay'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,124 @@
|
||||
import { useMemo } from 'react'
|
||||
import { LayoutGrid, CalendarDays, Globe, Compass, Bookmark, type LucideIcon } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { useAddonStore } from '../../store/addonStore'
|
||||
import { usePluginStore } from '../../store/pluginStore'
|
||||
import { resolvePluginIcon } from '../shared/PluginIcon'
|
||||
|
||||
/**
|
||||
* The canonical main-navigation item model, shared by the mobile dock
|
||||
* (MBottomNav) and the appearance settings customizer, so ids/labels/icons
|
||||
* never drift between them.
|
||||
*
|
||||
* Stable ids used for persistence: `'dashboard'` (pinned), an enabled global
|
||||
* addon's id (vacay|atlas|journey|collections|future), or `'plugin:<id>'` for a
|
||||
* page plugin. Dashboard is always first and immovable.
|
||||
*/
|
||||
export interface NavItemDef {
|
||||
id: string
|
||||
to: string
|
||||
label: string
|
||||
icon: LucideIcon
|
||||
pinned?: boolean
|
||||
}
|
||||
|
||||
// Signature glyphs for the four catalog global addons, keyed by id so the known
|
||||
// nav items keep their icon regardless of the (string) icon the addon row ships;
|
||||
// any future/unknown global addon resolves through its manifest icon name.
|
||||
const ADDON_ICONS: Record<string, LucideIcon> = {
|
||||
vacay: CalendarDays,
|
||||
atlas: Globe,
|
||||
journey: Compass,
|
||||
collections: Bookmark,
|
||||
}
|
||||
|
||||
/** The bar holds Dashboard + at most this many custom items; the rest go to More.
|
||||
* Two keeps the dock at 3 destinations (Dashboard + 2) so the More slot still fits. */
|
||||
export const MOBILE_NAV_MAX_BAR = 2
|
||||
/** The built-in dock next to Dashboard for an un-customised account; everything else starts under More. */
|
||||
export const DEFAULT_DOCK_IDS = ['vacay', 'atlas']
|
||||
|
||||
export function buildNavItems(
|
||||
globalAddons: { id: string; name: string; icon: string }[],
|
||||
pagePlugins: { id: string; name: string; icon: string | null }[],
|
||||
t: (key: string) => string,
|
||||
): NavItemDef[] {
|
||||
return [
|
||||
{ id: 'dashboard', to: '/dashboard', label: t('nav.myTrips'), icon: LayoutGrid, pinned: true },
|
||||
...globalAddons.map((a) => {
|
||||
const key = `admin.addons.catalog.${a.id}.name`
|
||||
const translated = t(key)
|
||||
return {
|
||||
id: a.id,
|
||||
to: `/${a.id}`,
|
||||
label: translated && translated !== key ? translated : a.name || a.id,
|
||||
icon: ADDON_ICONS[a.id] ?? resolvePluginIcon(a.icon),
|
||||
}
|
||||
}),
|
||||
...pagePlugins.map((p) => ({
|
||||
id: `plugin:${p.id}`,
|
||||
to: `/plugins/${p.id}`,
|
||||
label: p.name,
|
||||
icon: resolvePluginIcon(p.icon),
|
||||
})),
|
||||
]
|
||||
}
|
||||
|
||||
/** Live, ordered nav items from the addon + plugin stores (Dashboard first). */
|
||||
export function useNavItems(): NavItemDef[] {
|
||||
const { t } = useTranslation()
|
||||
const addons = useAddonStore((s) => s.addons)
|
||||
const plugins = usePluginStore((s) => s.plugins)
|
||||
return useMemo(
|
||||
() =>
|
||||
buildNavItems(
|
||||
addons.filter((a) => a.type === 'global' && a.enabled),
|
||||
plugins.filter((p) => p.type === 'page'),
|
||||
t,
|
||||
),
|
||||
[addons, plugins, t],
|
||||
)
|
||||
}
|
||||
|
||||
export interface MobileNavSplit {
|
||||
/** Items shown directly in the dock, Dashboard first. */
|
||||
bar: NavItemDef[]
|
||||
/** Items demoted under the "More" overflow popover. */
|
||||
more: NavItemDef[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the persisted `{ bar, more }` id split against the live nav items.
|
||||
* Dashboard is always pinned first in the bar. An empty/absent config falls back
|
||||
* to the built-in dock (Dashboard + Vacay/Atlas where enabled, everything else
|
||||
* under More) so an un-customised user sees exactly today's layout. Stored ids
|
||||
* that no longer resolve are dropped; newly available items are appended under
|
||||
* More.
|
||||
*/
|
||||
export function splitMobileNav(
|
||||
items: NavItemDef[],
|
||||
cfg?: { bar: string[]; more: string[] },
|
||||
): MobileNavSplit {
|
||||
const dashboard = items.find((i) => i.id === 'dashboard')
|
||||
const head = dashboard ? [dashboard] : []
|
||||
const rest = items.filter((i) => i.id !== 'dashboard')
|
||||
|
||||
if (!cfg || (cfg.bar.length === 0 && cfg.more.length === 0)) {
|
||||
return {
|
||||
bar: [...head, ...rest.filter((i) => DEFAULT_DOCK_IDS.includes(i.id))],
|
||||
more: rest.filter((i) => !DEFAULT_DOCK_IDS.includes(i.id)),
|
||||
}
|
||||
}
|
||||
|
||||
const byId = new Map(rest.map((i) => [i.id, i]))
|
||||
const pick = (ids: string[]) => ids.map((id) => byId.get(id)).filter((x): x is NavItemDef => !!x)
|
||||
const known = new Set([...cfg.bar, ...cfg.more])
|
||||
|
||||
const barPicked = pick(cfg.bar)
|
||||
const fresh = rest.filter((i) => !known.has(i.id))
|
||||
|
||||
return {
|
||||
bar: [...head, ...barPicked.slice(0, MOBILE_NAV_MAX_BAR)],
|
||||
more: [...barPicked.slice(MOBILE_NAV_MAX_BAR), ...pick(cfg.more), ...fresh],
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Circle, Polygon, Polyline, Tooltip, useMap } from 'react-leaflet'
|
||||
import { pluginsApi, type PluginMapLayer, type PluginMapLayerFeature } from '../../api/client'
|
||||
|
||||
/**
|
||||
* Host-rendered overlay for the `mapLayerProvider` plugin hook. A plugin returns
|
||||
* bounded geometry specs (polylines/polygons/metric circles + tone/width/dash);
|
||||
* the server range-checks + clamps them, and this layer draws them with plain
|
||||
* react-leaflet primitives. Plugin JS NEVER runs on the map canvas — every value
|
||||
* here is host-vetted data, and the only text (label) renders as a tooltip.
|
||||
*
|
||||
* Drawn in a dedicated pane just under Leaflet's overlayPane so core geometry
|
||||
* (day routes, transport arcs) always stays on top of plugin shapes. Features
|
||||
* without a label are non-interactive so they never steal map clicks.
|
||||
*/
|
||||
const TONE_COLORS: Record<PluginMapLayerFeature['tone'], string> = {
|
||||
default: '#4F46E5',
|
||||
success: '#10b981',
|
||||
warn: '#f59e0b',
|
||||
danger: '#ef4444',
|
||||
}
|
||||
|
||||
const PANE = 'trek-plugin-layers'
|
||||
|
||||
const DASH_ARRAYS: Record<PluginMapLayerFeature['dash'], string | undefined> = {
|
||||
solid: undefined,
|
||||
dash: '8, 8',
|
||||
dot: '1, 7',
|
||||
}
|
||||
|
||||
function pathOptions(f: PluginMapLayerFeature, pane: string | undefined) {
|
||||
const color = TONE_COLORS[f.tone] ?? TONE_COLORS.default
|
||||
return {
|
||||
...(pane ? { pane } : {}),
|
||||
color,
|
||||
weight: f.width,
|
||||
opacity: f.opacity,
|
||||
dashArray: DASH_ARRAYS[f.dash],
|
||||
lineCap: 'round' as const,
|
||||
lineJoin: 'round' as const,
|
||||
fill: f.fill,
|
||||
fillColor: color,
|
||||
fillOpacity: f.fill ? Math.min(0.25, f.opacity) : 0,
|
||||
interactive: !!f.label,
|
||||
}
|
||||
}
|
||||
|
||||
export function PluginMapLayers({ tripId }: { tripId?: number | string }) {
|
||||
const map = useMap()
|
||||
const [layers, setLayers] = useState<PluginMapLayer[]>([])
|
||||
// Whether our dedicated below-overlay pane exists. Pane support is a Leaflet
|
||||
// optimization — if the map has no pane API (e.g. a minimal renderer), the
|
||||
// features still draw, just without the z-index separation, so we don't gate on it.
|
||||
const [hasPane, setHasPane] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof map.getPane !== 'function' || typeof map.createPane !== 'function') return
|
||||
if (!map.getPane(PANE)) {
|
||||
const pane = map.createPane(PANE)
|
||||
if (pane) pane.style.zIndex = '399' // under overlayPane (400): core routes/arcs win
|
||||
}
|
||||
setHasPane(true)
|
||||
}, [map])
|
||||
|
||||
useEffect(() => {
|
||||
if (tripId == null) { setLayers([]); return }
|
||||
let alive = true
|
||||
pluginsApi.mapLayers(tripId)
|
||||
.then(r => { if (alive) setLayers(r.layers || []) })
|
||||
.catch(() => { if (alive) setLayers([]) }) // fail-safe: no extra layers
|
||||
return () => { alive = false }
|
||||
}, [tripId])
|
||||
|
||||
if (layers.length === 0) return null
|
||||
const pane = hasPane ? PANE : undefined
|
||||
|
||||
return (
|
||||
<>
|
||||
{layers.map(layer => layer.features.map((f, i) => {
|
||||
const key = `${layer.pluginId}:${layer.id}:${i}`
|
||||
const tooltip = f.label ? <Tooltip sticky>{f.label}</Tooltip> : null
|
||||
if (f.type === 'polyline' && f.points) {
|
||||
return <Polyline key={key} positions={f.points} pathOptions={pathOptions(f, pane)}>{tooltip}</Polyline>
|
||||
}
|
||||
if (f.type === 'polygon' && f.points) {
|
||||
return <Polygon key={key} positions={f.points} pathOptions={pathOptions(f, pane)}>{tooltip}</Polygon>
|
||||
}
|
||||
if (f.type === 'circle' && f.center && f.radiusM) {
|
||||
return <Circle key={key} center={f.center} radius={f.radiusM} pathOptions={pathOptions(f, pane)}>{tooltip}</Circle>
|
||||
}
|
||||
return null
|
||||
}))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -10,9 +10,10 @@ import { mapsApi } from '../../api/client'
|
||||
import { getCategoryIcon, CATEGORY_ICON_MAP } from '../shared/categoryIcons'
|
||||
import ReservationOverlay from './ReservationOverlay'
|
||||
import { PluginMapMarkers } from './MapPluginMarkers'
|
||||
import { PluginMapLayers } from './MapPluginLayers'
|
||||
import { useTransportRoutes } from '../../hooks/useTransportRoutes'
|
||||
import { visibleRouteReservations } from '../../utils/reservationRoutes'
|
||||
import type { Reservation } from '../../types'
|
||||
import type { Reservation, RouteVia } from '../../types'
|
||||
import { POI_CATEGORY_BY_KEY, type Poi } from './poiCategories'
|
||||
import { DEFAULT_MAP_CENTER, DEFAULT_MAP_ZOOM } from '../../constants/mapDefaults'
|
||||
import { computeMapViewport, TILE_SIZE_RASTER, type ViewportPadding } from '../../utils/mapViewport'
|
||||
@@ -45,6 +46,32 @@ function escAttr(s) {
|
||||
|
||||
const iconCache = new Map<string, L.DivIcon>()
|
||||
|
||||
// Tone dot for a plugin route's via points (charging stops, rest areas) — smaller
|
||||
// than the plugin markers so the day route's own stops stay visually dominant.
|
||||
const VIA_TONE_COLORS: Record<string, string> = {
|
||||
default: '#4F46E5', success: '#10b981', warn: '#f59e0b', danger: '#ef4444',
|
||||
}
|
||||
const viaIconCache = new Map<string, L.DivIcon>()
|
||||
function routeViaIcon(tone: string): L.DivIcon {
|
||||
const cached = viaIconCache.get(tone)
|
||||
if (cached) return cached
|
||||
const color = VIA_TONE_COLORS[tone] ?? VIA_TONE_COLORS.default
|
||||
const icon = L.divIcon({
|
||||
className: 'route-via-marker',
|
||||
html: `<span style="display:block;width:13px;height:13px;border-radius:50%;background:#fff;border:3.5px solid ${color};box-shadow:0 1px 4px rgba(0,0,0,0.35);box-sizing:border-box"></span>`,
|
||||
iconSize: [13, 13],
|
||||
iconAnchor: [6.5, 6.5],
|
||||
})
|
||||
viaIconCache.set(tone, icon)
|
||||
return icon
|
||||
}
|
||||
|
||||
function formatViaDwell(seconds: number): string {
|
||||
const h = Math.floor(seconds / 3600)
|
||||
const m = Math.round((seconds % 3600) / 60)
|
||||
return h > 0 ? `${h} h ${m} min` : `${m} min`
|
||||
}
|
||||
|
||||
function createPlaceIcon(place, orderNumbers, isSelected) {
|
||||
const cacheKey = `${place.id}:${isSelected}:${place.image_url || ''}:${place.category_color || ''}:${place.category_icon || ''}:${orderNumbers?.join(',') || ''}`
|
||||
const cached = iconCache.get(cacheKey)
|
||||
@@ -467,6 +494,7 @@ export const MapView = memo(function MapView({
|
||||
onPoiClick,
|
||||
onViewportChange,
|
||||
tripId,
|
||||
routeVias = [],
|
||||
}: any) {
|
||||
const poiMarkers = useMemo(() => (pois as Poi[]).map((poi: Poi) => (
|
||||
<Marker
|
||||
@@ -753,7 +781,21 @@ export const MapView = memo(function MapView({
|
||||
/>
|
||||
|
||||
{poiMarkers}
|
||||
{/* Charging stops / rest areas a plugin route places on the drawn day route.
|
||||
Host-vetted data (server-normalized), rendered as plain tone dots. */}
|
||||
{(routeVias as RouteVia[]).map((v, i) => (
|
||||
<Marker key={`route-via-${i}`} position={[v.lat, v.lng]} icon={routeViaIcon(v.tone)} zIndexOffset={800}>
|
||||
{(v.label || v.dwellSeconds != null) && (
|
||||
<Tooltip direction="top" offset={[0, -8]}>
|
||||
{v.label}
|
||||
{v.label && v.dwellSeconds != null ? ' · ' : ''}
|
||||
{v.dwellSeconds != null ? formatViaDwell(v.dwellSeconds) : ''}
|
||||
</Tooltip>
|
||||
)}
|
||||
</Marker>
|
||||
))}
|
||||
<PluginMapMarkers tripId={tripId} />
|
||||
<PluginMapLayers tripId={tripId} />
|
||||
</MapContainer>
|
||||
{isMobile && <LocationButton
|
||||
mode={trackingMode}
|
||||
|
||||
@@ -16,9 +16,10 @@ import { visibleRouteReservations } from '../../utils/reservationRoutes'
|
||||
import { MAPBOX_DEFAULT_STYLE, styleForActiveProvider, basemapLanguage, type GlMapProvider } from './glProviders'
|
||||
import LocationButton from './LocationButton'
|
||||
import { useGeolocation } from '../../hooks/useGeolocation'
|
||||
import type { Place, Reservation } from '../../types'
|
||||
import type { Place, Reservation, RouteVia } from '../../types'
|
||||
import { POI_CATEGORY_BY_KEY, type Poi } from './poiCategories'
|
||||
import { buildPoiPopupHtml } from './placePopup'
|
||||
import { pluginsApi, type PluginMapMarker, type PluginMapLayer } from '../../api/client'
|
||||
import { DEFAULT_MAP_CENTER, DEFAULT_MAP_ZOOM } from '../../constants/mapDefaults'
|
||||
import { computeMapViewport, TILE_SIZE_GL } from '../../utils/mapViewport'
|
||||
|
||||
@@ -72,6 +73,12 @@ interface RouteSegment {
|
||||
interface Props {
|
||||
places: Place[]
|
||||
dayPlaces?: Place[]
|
||||
// Enables the plugin map contributions (markers + layers). Absent on surfaces
|
||||
// without a trip (CollectionMap), which naturally excludes them — same rule as
|
||||
// the Leaflet MapPluginMarkers.
|
||||
tripId?: number | string
|
||||
// Charging stops / rest areas a plugin route places on the drawn day route.
|
||||
routeVias?: RouteVia[]
|
||||
route?: [number, number][][] | null
|
||||
routeSegments?: RouteSegment[]
|
||||
selectedPlaceId?: number | null
|
||||
@@ -177,6 +184,122 @@ function createMarkerElement(place: Place & { category_color?: string; category_
|
||||
return wrap
|
||||
}
|
||||
|
||||
// Plugin map contributions (mapMarkerProvider / mapLayerProvider hooks) — the GL
|
||||
// twins of MapPluginMarkers/MapPluginLayers. Same contract: host-vetted declarative
|
||||
// data only, tone palette, plugin JS never touches the canvas. Layer features live
|
||||
// in one geojson source with data-driven paint; the dash style can't be data-driven
|
||||
// in GL, so the stroke is split across three filtered line layers.
|
||||
const PLUGIN_LAYER_SOURCE_ID = 'trek-plugin-layers'
|
||||
const PLUGIN_LINE_LAYER_IDS: Record<'solid' | 'dash' | 'dot', string> = {
|
||||
solid: 'trek-plugin-layers-line-solid',
|
||||
dash: 'trek-plugin-layers-line-dash',
|
||||
dot: 'trek-plugin-layers-line-dot',
|
||||
}
|
||||
const PLUGIN_FILL_LAYER_ID = 'trek-plugin-layers-fill'
|
||||
const PLUGIN_TONE_COLORS: Record<string, string> = {
|
||||
default: '#4F46E5',
|
||||
success: '#10b981',
|
||||
warn: '#f59e0b',
|
||||
danger: '#ef4444',
|
||||
}
|
||||
|
||||
// GL circle layers size in screen pixels, so a metric circle has to become a
|
||||
// polygon. Equirectangular approximation — plenty for a display-only overlay.
|
||||
function circleToRing(center: [number, number], radiusM: number): [number, number][] {
|
||||
const [lat, lng] = center
|
||||
const dLat = radiusM / 111_320
|
||||
const cos = Math.cos((lat * Math.PI) / 180)
|
||||
const dLng = radiusM / (111_320 * Math.max(0.01, Math.abs(cos)))
|
||||
const ring: [number, number][] = []
|
||||
for (let i = 0; i <= 64; i++) {
|
||||
const a = (i / 64) * 2 * Math.PI
|
||||
ring.push([lng + Math.cos(a) * dLng, lat + Math.sin(a) * dLat])
|
||||
}
|
||||
return ring
|
||||
}
|
||||
|
||||
interface PluginLayerGeoFeature {
|
||||
type: 'Feature'
|
||||
properties: { id: string; color: string; width: number; opacity: number; dash: string; fillOpacity: number; label: string }
|
||||
geometry: { type: 'LineString'; coordinates: number[][] } | { type: 'Polygon'; coordinates: number[][][] }
|
||||
}
|
||||
|
||||
function buildPluginLayerData(layers: PluginMapLayer[]) {
|
||||
const features = layers.flatMap(layer => layer.features.flatMap((f, i): PluginLayerGeoFeature[] => {
|
||||
const color = PLUGIN_TONE_COLORS[f.tone] ?? PLUGIN_TONE_COLORS.default
|
||||
const properties = {
|
||||
id: `${layer.pluginId}:${layer.id}:${i}`,
|
||||
color,
|
||||
width: f.width,
|
||||
opacity: f.opacity,
|
||||
dash: f.dash,
|
||||
fillOpacity: f.fill ? Math.min(0.25, f.opacity) : 0,
|
||||
label: f.label || '',
|
||||
}
|
||||
if (f.type === 'polyline' && f.points) {
|
||||
return [{
|
||||
type: 'Feature' as const,
|
||||
properties,
|
||||
geometry: { type: 'LineString' as const, coordinates: f.points.map(([lat, lng]) => [lng, lat]) },
|
||||
}]
|
||||
}
|
||||
if (f.type === 'polygon' && f.points) {
|
||||
const ring = f.points.map(([lat, lng]) => [lng, lat])
|
||||
if (ring.length && (ring[0][0] !== ring[ring.length - 1][0] || ring[0][1] !== ring[ring.length - 1][1])) ring.push(ring[0])
|
||||
return [{ type: 'Feature' as const, properties, geometry: { type: 'Polygon' as const, coordinates: [ring] } }]
|
||||
}
|
||||
if (f.type === 'circle' && f.center && f.radiusM) {
|
||||
return [{ type: 'Feature' as const, properties, geometry: { type: 'Polygon' as const, coordinates: [circleToRing(f.center, f.radiusM)] } }]
|
||||
}
|
||||
return []
|
||||
}))
|
||||
return { type: 'FeatureCollection' as const, features }
|
||||
}
|
||||
|
||||
function formatViaDwellGl(seconds: number): string {
|
||||
const h = Math.floor(seconds / 3600)
|
||||
const m = Math.round((seconds % 3600) / 60)
|
||||
return h > 0 ? `${h} h ${m} min` : `${m} min`
|
||||
}
|
||||
|
||||
// Tone dot for a plugin marker — visual twin of MapPluginMarkers' divIcon.
|
||||
function createPluginMarkerElement(tone: PluginMapMarker['tone']): HTMLDivElement {
|
||||
const color = PLUGIN_TONE_COLORS[tone] ?? PLUGIN_TONE_COLORS.default
|
||||
const el = document.createElement('div')
|
||||
el.style.cssText = 'width:16px;height:16px;cursor:pointer;'
|
||||
el.innerHTML = `<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);box-sizing:border-box;"></span>`
|
||||
return el
|
||||
}
|
||||
|
||||
// Popup body for a plugin marker, built with textContent — the values are already
|
||||
// host-sanitized, but nothing plugin-supplied is ever handed to innerHTML anyway.
|
||||
function buildPluginMarkerPopup(mk: PluginMapMarker): HTMLDivElement {
|
||||
const box = document.createElement('div')
|
||||
box.style.cssText = 'min-width:120px;font-size:13px;'
|
||||
if (mk.label) {
|
||||
const t = document.createElement('div')
|
||||
t.style.cssText = `font-weight:600;${mk.popupText ? 'margin-bottom:4px;' : ''}`
|
||||
t.textContent = mk.label
|
||||
box.appendChild(t)
|
||||
}
|
||||
if (mk.popupText) {
|
||||
const p = document.createElement('div')
|
||||
p.style.color = '#4b5563'
|
||||
p.textContent = mk.popupText
|
||||
box.appendChild(p)
|
||||
}
|
||||
if (mk.url) {
|
||||
const a = document.createElement('a')
|
||||
a.href = mk.url // http/https/mailto only — enforced server-side
|
||||
a.target = '_blank'
|
||||
a.rel = 'noreferrer noopener'
|
||||
a.style.cssText = `display:inline-block;margin-top:6px;color:${PLUGIN_TONE_COLORS.default};`
|
||||
a.textContent = mk.url
|
||||
box.appendChild(a)
|
||||
}
|
||||
return box
|
||||
}
|
||||
|
||||
// Small coloured pin for an OSM "explore" POI (matches the pill category colour).
|
||||
function createPoiMarkerElement(category: string): HTMLDivElement {
|
||||
const cat = POI_CATEGORY_BY_KEY[category]
|
||||
@@ -191,6 +314,8 @@ function createPoiMarkerElement(category: string): HTMLDivElement {
|
||||
export function MapViewGL({
|
||||
places = [],
|
||||
dayPlaces = [],
|
||||
tripId,
|
||||
routeVias = [],
|
||||
route = null,
|
||||
routeSegments = [],
|
||||
selectedPlaceId = null,
|
||||
@@ -265,6 +390,14 @@ export function MapViewGL({
|
||||
onReservationClickRef.current = onReservationClick
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const poiMarkersRef = useRef<any[]>([])
|
||||
// Plugin map contributions — data fetched per trip, elements owned imperatively
|
||||
// like the POI markers so they survive the React render cycle.
|
||||
const [pluginMarkers, setPluginMarkers] = useState<PluginMapMarker[]>([])
|
||||
const [pluginLayers, setPluginLayers] = useState<PluginMapLayer[]>([])
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const pluginMarkersRef = useRef<any[]>([])
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const routeViaMarkersRef = useRef<any[]>([])
|
||||
// Single reusable hover popup for POI markers. Planned places use the
|
||||
// cursor-following React tooltip below so they match the Leaflet map.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
@@ -478,6 +611,45 @@ export function MapViewGL({
|
||||
map.on('mouseenter', PLACE_CLUSTER_CIRCLE_LAYER_ID, setClusterCursor)
|
||||
map.on('mouseleave', PLACE_CLUSTER_CIRCLE_LAYER_ID, clearClusterCursor)
|
||||
}
|
||||
// Plugin layer overlays (mapLayerProvider hook). Inserted BENEATH the day
|
||||
// route so core geometry always wins — the GL twin of the Leaflet pane 399.
|
||||
// Dash can't be data-driven, hence one filtered line layer per dash style.
|
||||
if (!map.getSource(PLUGIN_LAYER_SOURCE_ID)) {
|
||||
map.addSource(PLUGIN_LAYER_SOURCE_ID, { type: 'geojson', data: { type: 'FeatureCollection', features: [] } })
|
||||
map.addLayer({
|
||||
id: PLUGIN_FILL_LAYER_ID,
|
||||
type: 'fill',
|
||||
source: PLUGIN_LAYER_SOURCE_ID,
|
||||
paint: { 'fill-color': ['get', 'color'], 'fill-opacity': ['get', 'fillOpacity'] },
|
||||
}, 'trip-route-casing')
|
||||
const dashArrays: Record<string, number[] | undefined> = { solid: undefined, dash: [2, 2], dot: [0, 2] }
|
||||
for (const dash of ['solid', 'dash', 'dot'] as const) {
|
||||
map.addLayer({
|
||||
id: PLUGIN_LINE_LAYER_IDS[dash],
|
||||
type: 'line',
|
||||
source: PLUGIN_LAYER_SOURCE_ID,
|
||||
filter: ['==', ['get', 'dash'], dash],
|
||||
paint: {
|
||||
'line-color': ['get', 'color'],
|
||||
'line-width': ['get', 'width'],
|
||||
'line-opacity': ['get', 'opacity'],
|
||||
...(dashArrays[dash] ? { 'line-dasharray': dashArrays[dash] } : {}),
|
||||
},
|
||||
layout: { 'line-cap': 'round', 'line-join': 'round' },
|
||||
}, 'trip-route-casing')
|
||||
}
|
||||
// A labelled feature answers a click with a plain-text popup (setText —
|
||||
// never HTML). Unlabelled features stay inert, like the Leaflet twin.
|
||||
const showLabel = (e: any) => { // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
const label = e.features?.[0]?.properties?.label
|
||||
if (typeof label === 'string' && label && popupRef.current) {
|
||||
popupRef.current.setLngLat(e.lngLat).setText(label).addTo(map)
|
||||
}
|
||||
}
|
||||
for (const id of [PLUGIN_FILL_LAYER_ID, ...Object.values(PLUGIN_LINE_LAYER_IDS)]) {
|
||||
map.on('click', id, showLabel)
|
||||
}
|
||||
}
|
||||
// Signal that sources/layers are attached so overlay effects can
|
||||
// safely add their own sources. Style rebuilds reset this via the
|
||||
// cleanup below.
|
||||
@@ -882,6 +1054,72 @@ export function MapViewGL({
|
||||
}
|
||||
}, [pois, mapReady, glProvider])
|
||||
|
||||
// Fetch plugin map contributions (markers + layers) per trip. Fail-safe: an
|
||||
// error or missing tripId just means no plugin overlays, the core map is fine.
|
||||
useEffect(() => {
|
||||
if (tripId == null) { setPluginMarkers([]); setPluginLayers([]); return }
|
||||
let alive = true
|
||||
pluginsApi.mapMarkers(tripId)
|
||||
.then(r => { if (alive) setPluginMarkers(r.markers || []) })
|
||||
.catch(() => { if (alive) setPluginMarkers([]) })
|
||||
pluginsApi.mapLayers(tripId)
|
||||
.then(r => { if (alive) setPluginLayers(r.layers || []) })
|
||||
.catch(() => { if (alive) setPluginLayers([]) })
|
||||
return () => { alive = false }
|
||||
}, [tripId])
|
||||
|
||||
// Update plugin layer geojson
|
||||
useEffect(() => {
|
||||
const map = mapRef.current
|
||||
if (!map || !mapReady) return
|
||||
const src = map.getSource(PLUGIN_LAYER_SOURCE_ID) as mapboxgl.GeoJSONSource | undefined
|
||||
if (!src) return
|
||||
src.setData(buildPluginLayerData(pluginLayers))
|
||||
}, [pluginLayers, mapReady, glProvider])
|
||||
|
||||
// Reconcile the via-point markers of a plugin route (charging stops) — small
|
||||
// tone-ringed dots, popup with label + planned stop time on tap.
|
||||
useEffect(() => {
|
||||
const map = mapRef.current
|
||||
if (!map || !mapReady) return
|
||||
routeViaMarkersRef.current.forEach(m => m.remove())
|
||||
routeViaMarkersRef.current = []
|
||||
for (const v of routeVias) {
|
||||
const el = document.createElement('div')
|
||||
el.style.cssText = 'width:13px;height:13px;cursor:pointer;'
|
||||
const color = PLUGIN_TONE_COLORS[v.tone] ?? PLUGIN_TONE_COLORS.default
|
||||
el.innerHTML = `<span style="display:block;width:13px;height:13px;border-radius:50%;background:#fff;border:3.5px solid ${color};box-shadow:0 1px 4px rgba(0,0,0,0.35);box-sizing:border-box"></span>`
|
||||
if (v.label || v.dwellSeconds != null) {
|
||||
const text = [v.label, v.dwellSeconds != null ? formatViaDwellGl(v.dwellSeconds) : null].filter(Boolean).join(' · ')
|
||||
el.addEventListener('click', (ev) => {
|
||||
ev.stopPropagation()
|
||||
popupRef.current?.setLngLat([v.lng, v.lat]).setText(text).addTo(map)
|
||||
})
|
||||
}
|
||||
const m = new gl.Marker({ element: el, anchor: 'center' }).setLngLat([v.lng, v.lat]).addTo(map)
|
||||
routeViaMarkersRef.current.push(m)
|
||||
}
|
||||
}, [routeVias, mapReady, glProvider])
|
||||
|
||||
// Reconcile plugin markers (imperative, same lifecycle as the POI markers).
|
||||
useEffect(() => {
|
||||
const map = mapRef.current
|
||||
if (!map || !mapReady) return
|
||||
pluginMarkersRef.current.forEach(m => m.remove())
|
||||
pluginMarkersRef.current = []
|
||||
for (const mk of pluginMarkers) {
|
||||
const el = createPluginMarkerElement(mk.tone)
|
||||
if (mk.label || mk.popupText || mk.url) {
|
||||
el.addEventListener('click', (ev) => {
|
||||
ev.stopPropagation()
|
||||
popupRef.current?.setLngLat([mk.lng, mk.lat]).setDOMContent(buildPluginMarkerPopup(mk)).addTo(map)
|
||||
})
|
||||
}
|
||||
const m = new gl.Marker({ element: el, anchor: 'center' }).setLngLat([mk.lng, mk.lat]).addTo(map)
|
||||
pluginMarkersRef.current.push(m)
|
||||
}
|
||||
}, [pluginMarkers, mapReady, glProvider])
|
||||
|
||||
// Update route geojson
|
||||
useEffect(() => {
|
||||
const map = mapRef.current
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { pluginsApi } from '../../api/client'
|
||||
import type { DistanceUnit, RouteResult, RouteSegment, RouteWithLegs, Waypoint, RouteAnchors } from '../../types'
|
||||
import { formatDistance } from '../../utils/units'
|
||||
|
||||
@@ -18,6 +19,21 @@ const OSRM_PROFILE_BASE: Record<'driving' | 'walking' | 'cycling', string> = {
|
||||
const routeCache = new Map<string, RouteWithLegs>()
|
||||
const ROUTE_CACHE_MAX = 200
|
||||
|
||||
/**
|
||||
* A route profile is either one of the built-in OSRM profiles or a plugin profile
|
||||
* key `plugin:<pluginId>/<profileId>` — the route toggle offers those for every
|
||||
* active routeProvider plugin, and calculateRouteWithLegs dispatches on the prefix.
|
||||
*/
|
||||
export type RouteProfileKey = 'driving' | 'walking' | 'cycling' | (string & {})
|
||||
|
||||
export function parsePluginProfile(profile: string): { pluginId: string; profileId: string } | null {
|
||||
if (!profile.startsWith('plugin:')) return null
|
||||
const rest = profile.slice('plugin:'.length)
|
||||
const slash = rest.indexOf('/')
|
||||
if (slash <= 0 || slash === rest.length - 1) return null
|
||||
return { pluginId: rest.slice(0, slash), profileId: rest.slice(slash + 1) }
|
||||
}
|
||||
|
||||
/** Fetches a full route via OSRM and returns coordinates, distance, and duration estimates for driving/walking. */
|
||||
export async function calculateRoute(
|
||||
waypoints: Waypoint[],
|
||||
@@ -233,7 +249,7 @@ export async function calculateSegments(
|
||||
*/
|
||||
export async function calculateRouteWithLegs(
|
||||
waypoints: Waypoint[],
|
||||
{ signal, profile = 'driving' }: { signal?: AbortSignal; profile?: 'driving' | 'walking' | 'cycling' } = {}
|
||||
{ signal, profile = 'driving', tripId, dayId }: { signal?: AbortSignal; profile?: RouteProfileKey; tripId?: number | string | null; dayId?: number | null } = {}
|
||||
): Promise<RouteWithLegs> {
|
||||
if (!waypoints || waypoints.length < 2) {
|
||||
return { coordinates: [], distance: 0, duration: 0, legs: [] }
|
||||
@@ -242,11 +258,58 @@ export async function calculateRouteWithLegs(
|
||||
const coords = waypoints.map((p) => `${p.lng},${p.lat}`).join(';')
|
||||
// The cached result carries formatted leg distances, so the active distance unit is
|
||||
// part of the key — otherwise switching km↔mi would return stale text (#1300).
|
||||
const cacheKey = `${profile}:${getDistanceUnit()}:${coords}`
|
||||
// A plugin route is trip-/day-specific (it may return different charging stops for
|
||||
// the same coordinates on a different day), so its key includes tripId/dayId;
|
||||
// the built-in OSRM profiles are context-free and leave those out.
|
||||
const pluginScope = profile.startsWith('plugin:') ? `:${tripId ?? ''}:${dayId ?? ''}` : ''
|
||||
const cacheKey = `${profile}:${getDistanceUnit()}:${coords}${pluginScope}`
|
||||
const cached = routeCache.get(cacheKey)
|
||||
if (cached) return cached
|
||||
|
||||
const url = `${OSRM_PROFILE_BASE[profile]}/${coords}?overview=full&geometries=geojson&annotations=distance,duration`
|
||||
// Plugin profile (`plugin:<id>/<profile>`): the server invokes that routeProvider
|
||||
// and normalizes its answer; null means the provider failed or refused, and the
|
||||
// throw makes callers fall back to straight lines exactly like an OSRM outage.
|
||||
const pluginProfile = parsePluginProfile(profile)
|
||||
if (pluginProfile) {
|
||||
if (tripId == null) throw new Error('Plugin routing needs a trip context')
|
||||
const { route } = await pluginsApi.pluginRoute(pluginProfile.pluginId, pluginProfile.profileId, {
|
||||
tripId,
|
||||
dayId: dayId ?? null,
|
||||
waypoints: waypoints.map((p) => ({ lat: p.lat, lng: p.lng })),
|
||||
}, { signal })
|
||||
if (!route) throw new Error('No route found')
|
||||
const legs: RouteSegment[] = route.legs.map((leg, i): RouteSegment => {
|
||||
const from: [number, number] = [waypoints[i].lat, waypoints[i].lng]
|
||||
const to: [number, number] = [waypoints[i + 1].lat, waypoints[i + 1].lng]
|
||||
const mid: [number, number] = [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2]
|
||||
return {
|
||||
mid, from, to,
|
||||
distance: leg.distance,
|
||||
duration: leg.duration,
|
||||
walkingText: formatDuration(leg.distance / (5000 / 3600)),
|
||||
drivingText: formatDuration(leg.duration),
|
||||
distanceText: formatRouteDistance(leg.distance),
|
||||
durationText: formatDuration(leg.duration),
|
||||
...(leg.note ? { noteText: leg.note } : {}),
|
||||
}
|
||||
})
|
||||
const result: RouteWithLegs = {
|
||||
coordinates: route.coordinates,
|
||||
distance: route.distance,
|
||||
duration: route.duration,
|
||||
legs,
|
||||
...(route.viaPoints.length ? { vias: route.viaPoints } : {}),
|
||||
}
|
||||
routeCache.set(cacheKey, result)
|
||||
if (routeCache.size > ROUTE_CACHE_MAX) {
|
||||
const oldest = routeCache.keys().next().value
|
||||
if (oldest !== undefined) routeCache.delete(oldest)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
const osrmProfile = (profile === 'walking' || profile === 'cycling') ? profile : 'driving'
|
||||
const url = `${OSRM_PROFILE_BASE[osrmProfile]}/${coords}?overview=full&geometries=geojson&annotations=distance,duration`
|
||||
const response = await fetch(url, { signal })
|
||||
if (!response.ok) throw new Error('Route could not be calculated')
|
||||
|
||||
|
||||
@@ -58,9 +58,11 @@ describe('PackingListPanel', () => {
|
||||
expect(els.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('FE-COMP-PACKING-003: empty state shows hint text', () => {
|
||||
render(<PackingListPanel tripId={1} items={[]} />);
|
||||
expect(screen.getByText(/Add items or use the suggestions/i)).toBeInTheDocument();
|
||||
it('FE-COMP-PACKING-003: empty state shows the packing mascot illustration', () => {
|
||||
const { container } = render(<PackingListPanel tripId={1} items={[]} />);
|
||||
// The reworded empty state drops the old hint copy in favour of the shared
|
||||
// EmptyState: the TREK mascot acting out the "packing" scene beside the title.
|
||||
expect(container.querySelector('.trek--packing')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-PACKING-004: shows items from props grouped by category', () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Luggage } from 'lucide-react'
|
||||
import type { PackingState } from './usePackingListPanel'
|
||||
import { KategorieGruppe } from './PackingListPanelCategoryGroup'
|
||||
import EmptyState from '../shared/EmptyState'
|
||||
|
||||
export function PackingList(S: PackingState) {
|
||||
const {
|
||||
@@ -12,11 +12,7 @@ export function PackingList(S: PackingState) {
|
||||
return (
|
||||
<div style={{ flex: 1, overflowY: 'auto', padding: '10px 0 16px' }}>
|
||||
{items.length === 0 ? (
|
||||
<div style={{ textAlign: 'center', padding: '60px 20px' }}>
|
||||
<Luggage size={40} style={{ color: 'var(--text-faint)', display: 'block', margin: '0 auto 10px' }} />
|
||||
<p style={{ fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 600, color: 'var(--text-secondary)', margin: '0 0 4px' }}>{t('packing.emptyTitle')}</p>
|
||||
<p style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))', color: 'var(--text-faint)', margin: 0 }}>{t('packing.emptyHint')}</p>
|
||||
</div>
|
||||
<EmptyState scene="packing" title={t('packing.emptyTitle')} />
|
||||
) : Object.keys(gruppiert).length === 0 ? (
|
||||
<div style={{ textAlign: 'center', padding: '40px 20px', color: 'var(--text-faint)' }}>
|
||||
<p style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))', margin: 0 }}>{t('packing.emptyFiltered')}</p>
|
||||
|
||||
@@ -4,7 +4,7 @@ declare global { interface Window { __dragData: DragDataPayload | null } }
|
||||
|
||||
import React, { useState, useEffect, useLayoutEffect, useRef, useMemo } from 'react'
|
||||
import { avatarSrc } from '../../utils/avatarSrc'
|
||||
import { ChevronDown, ChevronRight, ChevronUp, Navigation, RotateCcw, ExternalLink, Clock, Pencil, GripVertical, Ticket, Plus, FileText, Trash2, Car, Lock, Hotel, Footprints, Route as RouteIcon, Bookmark, TramFront } from 'lucide-react'
|
||||
import { ChevronDown, ChevronRight, ChevronUp, Navigation, RotateCcw, ExternalLink, Clock, Pencil, GripVertical, Ticket, Plus, FileText, Trash2, Car, Lock, Hotel, Footprints, Route as RouteIcon, Bookmark, TramFront, Zap } from 'lucide-react'
|
||||
import { assignmentsApi, reservationsApi } from '../../api/client'
|
||||
import { calculateRoute, calculateRouteWithLegs, optimizeRoute, generateGoogleMapsUrl } from '../Map/RouteCalculator'
|
||||
import PlaceAvatar from '../shared/PlaceAvatar'
|
||||
@@ -19,6 +19,7 @@ import { useTripStore } from '../../store/tripStore'
|
||||
import { useCanDo } from '../../store/permissionsStore'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { useAddonStore } from '../../store/addonStore'
|
||||
import { usePluginStore } from '../../store/pluginStore'
|
||||
import { useSaveToCollectionStore } from '../../store/saveToCollectionStore'
|
||||
import { placeToSaveTarget } from '../Collections/saveTarget'
|
||||
import { useTranslation } from '../../i18n'
|
||||
@@ -33,6 +34,7 @@ import { useDayNotes } from '../../hooks/useDayNotes'
|
||||
import { useExchangeRates } from '../../hooks/useExchangeRates'
|
||||
import { RES_ICONS, getNoteIcon } from './DayPlanSidebar.constants'
|
||||
import { RouteConnector, HotelRouteConnector } from './DayPlanSidebarRouteConnector'
|
||||
import { usePluginDaySchedule, PluginDayScheduleRow, formatScheduleMinutes } from '../Plugins/PluginDaySchedule'
|
||||
import { MobileAddPlaceButton } from './DayPlanSidebarMobileAddPlaceButton'
|
||||
import { DayPlanSidebarToolbar } from './DayPlanSidebarToolbar'
|
||||
import { DayPlanSidebarNoteModal } from './DayPlanSidebarNoteModal'
|
||||
@@ -76,9 +78,9 @@ interface DayPlanSidebarProps {
|
||||
onAddReservation: (dayId: number) => void
|
||||
onNavigateToFiles?: () => void
|
||||
routeShown?: boolean
|
||||
routeProfile?: 'driving' | 'walking'
|
||||
routeProfile?: string
|
||||
onToggleRoute?: () => void
|
||||
onSetRouteProfile?: (profile: 'driving' | 'walking') => void
|
||||
onSetRouteProfile?: (profile: string) => void
|
||||
onAddPlace?: () => void
|
||||
onAddPlaceToDay?: (placeId: number, dayId: number) => void
|
||||
onExpandedDaysChange?: (expandedDayIds: Set<number>) => void
|
||||
@@ -519,10 +521,11 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
|
||||
const legsByDay: Record<number, Record<number, RouteSegment>> = {}
|
||||
const hotelByDay: Record<number, { top?: { seg: RouteSegment; name: string }; bottom?: { seg: RouteSegment; name: string } }> = {}
|
||||
|
||||
// One cached OSRM call per waypoint pair; shares RouteCalculator's cache.
|
||||
const legBetween = async (a: { lat: number; lng: number }, b: { lat: number; lng: number }): Promise<RouteSegment | undefined> => {
|
||||
// One cached OSRM/plugin call per waypoint pair; shares RouteCalculator's cache.
|
||||
// tripId/dayId ride along for plugin route profiles (the server access-checks them).
|
||||
const legBetween = async (a: { lat: number; lng: number }, b: { lat: number; lng: number }, dayId: number): Promise<RouteSegment | undefined> => {
|
||||
try {
|
||||
const r = await calculateRouteWithLegs([a, b], { signal: controller.signal, profile: routeProfile })
|
||||
const r = await calculateRouteWithLegs([a, b], { signal: controller.signal, profile: routeProfile, tripId, dayId })
|
||||
return r.legs[0]
|
||||
} catch { return undefined }
|
||||
}
|
||||
@@ -532,7 +535,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
|
||||
const dayLegs: Record<number, RouteSegment> = {}
|
||||
for (const run of runs) {
|
||||
try {
|
||||
const r = await calculateRouteWithLegs(run.map(p => ({ lat: p.lat, lng: p.lng })), { signal: controller.signal, profile: routeProfile })
|
||||
const r = await calculateRouteWithLegs(run.map(p => ({ lat: p.lat, lng: p.lng })), { signal: controller.signal, profile: routeProfile, tripId, dayId })
|
||||
r.legs.forEach((leg, i) => { dayLegs[run[i].id] = leg })
|
||||
} catch (err) {
|
||||
if (err instanceof Error && err.name === 'AbortError') return
|
||||
@@ -541,11 +544,11 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) {
|
||||
if (Object.keys(dayLegs).length) legsByDay[dayId] = dayLegs
|
||||
const hotel: { top?: { seg: RouteSegment; name: string }; bottom?: { seg: RouteSegment; name: string } } = {}
|
||||
if (wantTop) {
|
||||
const seg = await legBetween({ lat: startHotel!.place_lat as number, lng: startHotel!.place_lng as number }, { lat: firstWay!.lat, lng: firstWay!.lng })
|
||||
const seg = await legBetween({ lat: startHotel!.place_lat as number, lng: startHotel!.place_lng as number }, { lat: firstWay!.lat, lng: firstWay!.lng }, dayId)
|
||||
if (seg) hotel.top = { seg, name: hotelName(startHotel!) }
|
||||
}
|
||||
if (wantBottom) {
|
||||
const seg = await legBetween({ lat: lastWay!.lat, lng: lastWay!.lng }, { lat: endHotel!.place_lat as number, lng: endHotel!.place_lng as number })
|
||||
const seg = await legBetween({ lat: lastWay!.lat, lng: lastWay!.lng }, { lat: endHotel!.place_lat as number, lng: endHotel!.place_lng as number }, dayId)
|
||||
if (seg) hotel.bottom = { seg, name: hotelName(endHotel!) }
|
||||
}
|
||||
if (controller.signal.aborted) return
|
||||
@@ -1163,6 +1166,22 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
// keeps its own copy, so read it reactively here in the component scope too.
|
||||
const optimizeFromAccommodation = useSettingsStore(s => s.settings.optimize_from_accommodation)
|
||||
const collectionsEnabled = useAddonStore(s => s.isEnabled('collections'))
|
||||
// Route-profile picker entries: the two built-ins plus every profile an active
|
||||
// routeProvider plugin declared (keyed 'plugin:<id>/<profile>', labeled by the
|
||||
// plugin's manifest). The feed only lists granted providers.
|
||||
const activePlugins = usePluginStore(s => s.plugins)
|
||||
// Plugin time contributions in the day plan (dayScheduleProvider hook).
|
||||
const daySchedule = usePluginDaySchedule(S.tripId)
|
||||
const routeProfileOptions = useMemo(() => {
|
||||
const opts: Array<{ key: string; label: string }> = [
|
||||
{ key: 'driving', label: 'Driving' },
|
||||
{ key: 'walking', label: 'Walking' },
|
||||
]
|
||||
for (const p of activePlugins) {
|
||||
for (const prof of p.routeProfiles ?? []) opts.push({ key: `plugin:${p.id}/${prof.id}`, label: prof.label })
|
||||
}
|
||||
return opts
|
||||
}, [activePlugins])
|
||||
const {
|
||||
tripId,
|
||||
trip,
|
||||
@@ -1624,6 +1643,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
{hotelLegs[day.id]?.top && (
|
||||
<HotelRouteConnector seg={hotelLegs[day.id]!.top!.seg} name={hotelLegs[day.id]!.top!.name} profile={routeProfile} placement="top" />
|
||||
)}
|
||||
{daySchedule.byPosition[day.id]?.start.map(si => <PluginDayScheduleRow key={`${si.pluginId}:${si.id}`} item={si} />)}
|
||||
{merged.length === 0 && !dayNoteUi ? (
|
||||
<div
|
||||
onDragOver={e => { e.preventDefault(); if (dragOverDayId !== day.id) setDragOverDayId(day.id) }}
|
||||
@@ -1974,6 +1994,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{daySchedule.byAssignment[day.id]?.[assignment.id]?.map(si => <PluginDayScheduleRow key={`${si.pluginId}:${si.id}`} item={si} />)}
|
||||
{routeLegs[day.id]?.[assignment.id] && <RouteConnector seg={routeLegs[day.id]![assignment.id]} profile={routeProfile} />}
|
||||
</React.Fragment>
|
||||
)
|
||||
@@ -2202,6 +2223,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
<TransitItineraryInline legs={transitMeta.legs} t={t} />
|
||||
</div>
|
||||
)}
|
||||
{daySchedule.byReservation[day.id]?.[res.id]?.map(si => <PluginDayScheduleRow key={`${si.pluginId}:${si.id}`} item={si} />)}
|
||||
{routeLegs[day.id]?.[res.id] && <RouteConnector seg={routeLegs[day.id]![res.id]} profile={routeProfile} />}
|
||||
</React.Fragment>
|
||||
)
|
||||
@@ -2311,6 +2333,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
)
|
||||
})
|
||||
)}
|
||||
{daySchedule.byPosition[day.id]?.end.map(si => <PluginDayScheduleRow key={`${si.pluginId}:${si.id}`} item={si} />)}
|
||||
{hotelLegs[day.id]?.bottom && (
|
||||
<HotelRouteConnector seg={hotelLegs[day.id]!.bottom!.seg} name={hotelLegs[day.id]!.bottom!.name} profile={routeProfile} placement="bottom" />
|
||||
)}
|
||||
@@ -2436,14 +2459,15 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
{t('dayplan.optimize')}
|
||||
</button>
|
||||
<div style={{ display: 'flex', borderRadius: 8, overflow: 'hidden', border: '1px solid var(--border-faint)', flexShrink: 0 }}>
|
||||
{(['driving', 'walking'] as const).map(p => {
|
||||
const ModeIcon = p === 'driving' ? Car : Footprints
|
||||
const active = routeProfile === p
|
||||
{routeProfileOptions.map(p => {
|
||||
const ModeIcon = p.key === 'driving' ? Car : p.key === 'walking' ? Footprints : Zap
|
||||
const active = routeProfile === p.key
|
||||
return (
|
||||
<button
|
||||
key={p}
|
||||
onClick={() => onSetRouteProfile?.(p)}
|
||||
aria-label={p === 'driving' ? 'Driving' : 'Walking'}
|
||||
key={p.key}
|
||||
onClick={() => onSetRouteProfile?.(p.key)}
|
||||
aria-label={p.label}
|
||||
title={p.label}
|
||||
className={active ? 'bg-accent text-accent-text' : 'bg-transparent text-content-secondary'}
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
@@ -2456,11 +2480,20 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
{isSelected && routeInfo && (
|
||||
<div className="text-content-secondary bg-surface-hover" style={{ display: 'flex', justifyContent: 'center', gap: 12, fontSize: 'calc(12px * var(--fs-scale-body, 1))', borderRadius: 8, padding: '5px 10px' }}>
|
||||
<span>{routeInfo.distance}</span>
|
||||
<span className="text-content-faint">·</span>
|
||||
<span>{routeInfo.duration}</span>
|
||||
{isSelected && (routeInfo || daySchedule.minutesByDay[day.id]) && (
|
||||
<div className="text-content-secondary bg-surface-hover" style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 12, fontSize: 'calc(12px * var(--fs-scale-body, 1))', borderRadius: 8, padding: '5px 10px' }}>
|
||||
{routeInfo && <span>{routeInfo.distance}</span>}
|
||||
{routeInfo && <span className="text-content-faint">·</span>}
|
||||
{routeInfo && <span>{routeInfo.duration}</span>}
|
||||
{/* Time plugins contributed to this day (charging, buffers) — the
|
||||
dayScheduleProvider minutes folded into the footer total. */}
|
||||
{daySchedule.minutesByDay[day.id] ? (
|
||||
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
|
||||
{routeInfo && <span className="text-content-faint">·</span>}
|
||||
<Zap size={11} strokeWidth={2} />
|
||||
+{formatScheduleMinutes(daySchedule.minutesByDay[day.id])}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,10 +1,19 @@
|
||||
import { Car, Footprints, Hotel } from 'lucide-react'
|
||||
import { Car, Footprints, Hotel, Zap } from 'lucide-react'
|
||||
import type { RouteSegment } from '../../types'
|
||||
|
||||
// Walking gets the foot icon; a plugin route profile ('plugin:…') gets the bolt —
|
||||
// its legs carry the profile-true durationText anyway, the icon just signals that
|
||||
// the time came from a plugin router (e.g. EV routing with charge time folded in).
|
||||
function profileIcon(profile: string) {
|
||||
if (profile === 'walking') return Footprints
|
||||
if (profile.startsWith('plugin:')) return Zap
|
||||
return Car
|
||||
}
|
||||
|
||||
/** Slim travel-time connector shown between two consecutive located stops in a day. */
|
||||
export function RouteConnector({ seg, profile }: { seg: RouteSegment; profile: 'driving' | 'walking' }) {
|
||||
const driving = profile === 'driving'
|
||||
const Icon = driving ? Car : Footprints
|
||||
export function RouteConnector({ seg, profile }: { seg: RouteSegment; profile: string }) {
|
||||
const driving = profile !== 'walking'
|
||||
const Icon = profileIcon(profile)
|
||||
const line = { flex: 1, height: 1, minHeight: 1, alignSelf: 'center', background: 'var(--border-primary)' }
|
||||
return (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '3px 14px', fontSize: 'calc(10.5px * var(--fs-scale-caption, 1))', color: 'var(--text-faint)', lineHeight: 1.2 }}>
|
||||
@@ -14,6 +23,12 @@ export function RouteConnector({ seg, profile }: { seg: RouteSegment; profile: '
|
||||
<span>{seg.durationText ?? (driving ? seg.drivingText : seg.walkingText)}</span>
|
||||
<span style={{ opacity: 0.4 }}>·</span>
|
||||
<span>{seg.distanceText}</span>
|
||||
{seg.noteText && (
|
||||
<>
|
||||
<span style={{ opacity: 0.4 }}>·</span>
|
||||
<span style={{ color: 'var(--text-muted)' }}>{seg.noteText}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div style={line} />
|
||||
</div>
|
||||
@@ -33,12 +48,12 @@ export function HotelRouteConnector({
|
||||
placement,
|
||||
}: {
|
||||
seg: RouteSegment
|
||||
profile: 'driving' | 'walking'
|
||||
profile: string
|
||||
name: string
|
||||
placement: 'top' | 'bottom'
|
||||
}) {
|
||||
const driving = profile === 'driving'
|
||||
const Icon = driving ? Car : Footprints
|
||||
const driving = profile !== 'walking'
|
||||
const Icon = profileIcon(profile)
|
||||
const line = { flex: 1, height: 1, minHeight: 1, alignSelf: 'center', background: 'var(--border-primary)' }
|
||||
const hotelRow = (
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5, padding: '0 14px', minWidth: 0 }}>
|
||||
@@ -56,6 +71,12 @@ export function HotelRouteConnector({
|
||||
<span>{seg.durationText ?? (driving ? seg.drivingText : seg.walkingText)}</span>
|
||||
<span style={{ opacity: 0.4 }}>·</span>
|
||||
<span>{seg.distanceText}</span>
|
||||
{seg.noteText && (
|
||||
<>
|
||||
<span style={{ opacity: 0.4 }}>·</span>
|
||||
<span style={{ color: 'var(--text-muted)' }}>{seg.noteText}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div style={line} />
|
||||
</div>
|
||||
|
||||
@@ -49,9 +49,11 @@ describe('ReservationsPanel', () => {
|
||||
expect(els.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('FE-COMP-RES-004: shows empty hint text', () => {
|
||||
it('FE-COMP-RES-004: shows empty-state mascot illustration', () => {
|
||||
render(<ReservationsPanel {...defaultProps} reservations={[]} />);
|
||||
expect(screen.getByText(/Add reservations for flights/i)).toBeInTheDocument();
|
||||
// The mobile rewrite dropped the hint subtitle in favour of the shared
|
||||
// EmptyState mascot; the bookings scene renders the TREK mark svg.
|
||||
expect(document.querySelector('.trek--bookings')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-COMP-RES-005: shows Manual Booking add button', () => {
|
||||
|
||||
@@ -8,7 +8,7 @@ import { useTranslation } from '../../i18n'
|
||||
import {
|
||||
Plane, Hotel, Utensils, Train, Car, Ship, Bus, Sailboat, Bike, CarTaxiFront, Route, Ticket, FileText, MapPin,
|
||||
Calendar, Hash, CheckCircle2, Circle, Pencil, Trash2, Plus, ChevronDown, ChevronRight, Users,
|
||||
ExternalLink, BookMarked, Lightbulb, Link2, Clock, ArrowRight, AlertCircle, Download,
|
||||
ExternalLink, Lightbulb, Link2, Clock, ArrowRight, AlertCircle, Download,
|
||||
TramFront, Footprints, StickyNote,
|
||||
} from 'lucide-react'
|
||||
import { openFile } from '../../utils/fileDownload'
|
||||
@@ -22,6 +22,7 @@ import { usePluginViewContributions, PluginCardFooter } from '../Plugins/PluginC
|
||||
import { usePluginStore, type ActivePlugin } from '../../store/pluginStore'
|
||||
import PluginFrame from '../Plugins/PluginFrame'
|
||||
import { splitReservationDateTime, formatTime } from '../../utils/formatters'
|
||||
import EmptyState from '../shared/EmptyState'
|
||||
|
||||
interface AssignmentLookupEntry {
|
||||
dayNumber: number
|
||||
@@ -834,11 +835,7 @@ export default function ReservationsPanel({ tripId, reservations, days, assignme
|
||||
{/* Content */}
|
||||
<div style={{ flex: 1, overflowY: 'auto', padding: '24px 28px 80px' }} className="max-md:!px-4 max-md:!pt-4">
|
||||
{total === 0 && reservations.length === 0 ? (
|
||||
<div style={{ textAlign: 'center', padding: '60px 20px' }}>
|
||||
<BookMarked size={36} className="text-content-faint" style={{ display: 'block', margin: '0 auto 12px' }} />
|
||||
<p className="text-content-secondary" style={{ fontSize: 'calc(14px * var(--fs-scale-body, 1))', fontWeight: 600, margin: '0 0 4px' }}>{t('reservations.empty')}</p>
|
||||
<p className="text-content-faint" style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', margin: 0 }}>{t('reservations.emptyHint')}</p>
|
||||
</div>
|
||||
<EmptyState scene={contributionView === 'transports' ? 'transport' : 'bookings'} title={t('reservations.empty')} />
|
||||
) : total === 0 ? (
|
||||
<div style={{ textAlign: 'center', padding: '60px 20px' }}>
|
||||
<p className="text-content-faint" style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}>{t('places.noneFound')}</p>
|
||||
|
||||
@@ -404,8 +404,8 @@ describe('TransportModal', () => {
|
||||
|
||||
it('FE-PLANNER-TRANSMODAL-022: creating shows the Manual/Automated switch; Automated opens the transit search', async () => {
|
||||
render(<TransportModal {...defaultProps} places={[]} accommodations={[]} />);
|
||||
expect(screen.getByRole('button', { name: 'Manual transport' })).toBeInTheDocument();
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Automated transport' }));
|
||||
expect(screen.getByRole('button', { name: 'Manual' })).toBeInTheDocument();
|
||||
await userEvent.click(screen.getByRole('button', { name: 'Automated' }));
|
||||
// No day selected in defaultProps (days: []) — the pick-day hint shows.
|
||||
expect(screen.getByText(/Pick a day/)).toBeInTheDocument();
|
||||
// The manual form is gone in automated mode.
|
||||
@@ -414,8 +414,8 @@ describe('TransportModal', () => {
|
||||
|
||||
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.queryByRole('button', { name: 'Automated' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Manual' })).not.toBeInTheDocument();
|
||||
expect(screen.getByPlaceholderText(/e\.g\. Lufthansa/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
@@ -447,7 +447,7 @@ describe('TransportModal', () => {
|
||||
it('FE-PLANNER-TRANSMODAL-024: editing shows no Manual/Automated switch', () => {
|
||||
const res = buildReservation({ title: 'My Train', type: 'train' });
|
||||
render(<TransportModal {...defaultProps} reservation={res} />);
|
||||
expect(screen.queryByRole('button', { name: 'Automated transport' })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: 'Automated' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
// ── Multi-leg trains (#1150) ───────────────────────────────────────────────
|
||||
|
||||
@@ -730,7 +730,7 @@ export function TransportModal({ isOpen, onClose, onSave, reservation, days, sel
|
||||
{wp.airport && (
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<label className={labelClass}>{t('reservations.meta.arrivalTimezone')}</label>
|
||||
<div className={inputClass} style={{ padding: '8px 12px', color: 'var(--text-muted)', fontSize: 'calc(12px * var(--fs-scale-body, 1))', background: 'var(--bg-tertiary)' }}>{wp.airport.tz}</div>
|
||||
<div className={inputClass} style={{ padding: '8px 12px', color: 'var(--text-muted)', fontSize: 'calc(12px * var(--fs-scale-body, 1))', background: 'var(--bg-tertiary)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }} title={wp.airport.tz}>{wp.airport.tz}</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -749,7 +749,7 @@ export function TransportModal({ isOpen, onClose, onSave, reservation, days, sel
|
||||
{wp.airport && (
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<label className={labelClass}>{t('reservations.meta.departureTimezone')}</label>
|
||||
<div className={inputClass} style={{ padding: '8px 12px', color: 'var(--text-muted)', fontSize: 'calc(12px * var(--fs-scale-body, 1))', background: 'var(--bg-tertiary)' }}>{wp.airport.tz}</div>
|
||||
<div className={inputClass} style={{ padding: '8px 12px', color: 'var(--text-muted)', fontSize: 'calc(12px * var(--fs-scale-body, 1))', background: 'var(--bg-tertiary)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }} title={wp.airport.tz}>{wp.airport.tz}</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Zap } from 'lucide-react'
|
||||
import { pluginsApi, type PluginDayScheduleItem } from '../../api/client'
|
||||
|
||||
/**
|
||||
* Host-rendered rows for the `dayScheduleProvider` plugin hook — time
|
||||
* contributions in the day plan ("35 min charging at this stop", "45 min
|
||||
* security before this flight"). Everything here is host-vetted data from
|
||||
* /api/day-schedule; the hook groups it by anchor so the timelines can slot
|
||||
* a row under the right place/booking (or at a day's start/end), and sums
|
||||
* the minutes per day for the route footer.
|
||||
*/
|
||||
const TONE_COLORS: Record<PluginDayScheduleItem['tone'], string> = {
|
||||
default: '#4F46E5',
|
||||
success: '#10b981',
|
||||
warn: '#f59e0b',
|
||||
danger: '#ef4444',
|
||||
}
|
||||
|
||||
export interface PluginDaySchedule {
|
||||
/** dayId → assignmentId → rows anchored under that place row. */
|
||||
byAssignment: Record<number, Record<number, PluginDayScheduleItem[]>>
|
||||
/** dayId → reservationId → rows anchored under that booking row. */
|
||||
byReservation: Record<number, Record<number, PluginDayScheduleItem[]>>
|
||||
/** dayId → rows pinned to the start / end of the day (end = default anchor). */
|
||||
byPosition: Record<number, { start: PluginDayScheduleItem[]; end: PluginDayScheduleItem[] }>
|
||||
/** dayId → total contributed minutes (for the route-footer "+X min"). */
|
||||
minutesByDay: Record<number, number>
|
||||
}
|
||||
|
||||
const EMPTY: PluginDaySchedule = { byAssignment: {}, byReservation: {}, byPosition: {}, minutesByDay: {} }
|
||||
|
||||
export function usePluginDaySchedule(tripId?: number | string | null): PluginDaySchedule {
|
||||
const [items, setItems] = useState<PluginDayScheduleItem[]>([])
|
||||
|
||||
useEffect(() => {
|
||||
if (tripId == null) { setItems([]); return }
|
||||
let alive = true
|
||||
pluginsApi.daySchedule(tripId)
|
||||
.then(r => { if (alive) setItems(r.items || []) })
|
||||
.catch(() => { if (alive) setItems([]) }) // fail-safe: no extra rows
|
||||
return () => { alive = false }
|
||||
}, [tripId])
|
||||
|
||||
return useMemo(() => {
|
||||
if (items.length === 0) return EMPTY
|
||||
const out: PluginDaySchedule = { byAssignment: {}, byReservation: {}, byPosition: {}, minutesByDay: {} }
|
||||
for (const it of items) {
|
||||
if (it.assignmentId != null) {
|
||||
const day = (out.byAssignment[it.dayId] ??= {})
|
||||
;(day[it.assignmentId] ??= []).push(it)
|
||||
} else if (it.reservationId != null) {
|
||||
const day = (out.byReservation[it.dayId] ??= {})
|
||||
;(day[it.reservationId] ??= []).push(it)
|
||||
} else {
|
||||
const day = (out.byPosition[it.dayId] ??= { start: [], end: [] })
|
||||
day[it.position === 'start' ? 'start' : 'end'].push(it)
|
||||
}
|
||||
if (it.minutes) out.minutesByDay[it.dayId] = (out.minutesByDay[it.dayId] || 0) + it.minutes
|
||||
}
|
||||
return out
|
||||
}, [items])
|
||||
}
|
||||
|
||||
export function formatScheduleMinutes(minutes: number): string {
|
||||
const h = Math.floor(minutes / 60)
|
||||
const m = minutes % 60
|
||||
return h > 0 ? `${h} h ${m} min` : `${m} min`
|
||||
}
|
||||
|
||||
/** One contributed row — a slim line in the timeline, styled like the route
|
||||
* connectors so it reads as schedule information, not as an itinerary item. */
|
||||
export function PluginDayScheduleRow({ item }: { item: PluginDayScheduleItem }) {
|
||||
const color = TONE_COLORS[item.tone] ?? TONE_COLORS.default
|
||||
return (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '3px 14px', fontSize: 'calc(10.5px * var(--fs-scale-caption, 1))', color: 'var(--text-muted)', lineHeight: 1.3 }}>
|
||||
<Zap size={11} strokeWidth={2} style={{ color, flexShrink: 0 }} />
|
||||
{item.minutes != null && <span style={{ fontWeight: 600, flexShrink: 0 }}>{formatScheduleMinutes(item.minutes)}</span>}
|
||||
{item.minutes != null && <span style={{ opacity: 0.4 }}>·</span>}
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{item.label}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
// FE-PLUGINS-FRAME-001 to 012
|
||||
import { render, cleanup, waitFor, fireEvent, screen, act } from '@testing-library/react';
|
||||
import PluginFrame from './PluginFrame';
|
||||
import { usePluginStore } from '../../store/pluginStore';
|
||||
|
||||
const navigate = vi.fn();
|
||||
const toast = { info: vi.fn(), success: vi.fn(), warning: vi.fn(), error: vi.fn() };
|
||||
@@ -223,4 +224,91 @@ describe('PluginFrame', () => {
|
||||
fromFrame(next, { type: 'trek:navigate', to: '/dashboard' });
|
||||
expect(navigate).toHaveBeenCalledWith('/dashboard');
|
||||
});
|
||||
|
||||
describe('geolocation bridge (geolocation:read)', () => {
|
||||
const geo = {
|
||||
getCurrentPosition: vi.fn(),
|
||||
watchPosition: vi.fn((..._args: unknown[]) => 7),
|
||||
clearWatch: vi.fn(),
|
||||
};
|
||||
const grant = (granted: boolean) => {
|
||||
usePluginStore.setState({
|
||||
plugins: granted ? [{ id: 'demo', name: 'Demo', type: 'widget', icon: null, geolocation: true }] : [],
|
||||
});
|
||||
};
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(navigator, 'geolocation', { value: geo, configurable: true });
|
||||
geo.getCurrentPosition.mockClear();
|
||||
geo.watchPosition.mockClear();
|
||||
geo.clearWatch.mockClear();
|
||||
});
|
||||
afterEach(() => { grant(false); });
|
||||
|
||||
function mount(granted: boolean) {
|
||||
grant(granted);
|
||||
const { container, unmount } = 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>);
|
||||
return { iframe, posted, unmount };
|
||||
}
|
||||
|
||||
it('FE-PLUGINS-FRAME-015: refuses an ungranted plugin without touching the browser API', () => {
|
||||
const { iframe, posted } = mount(false);
|
||||
fromFrame(iframe, { type: 'trek:geolocation', requestId: 'g1' });
|
||||
expect(posted.find((m) => m.type === 'trek:geolocation:result')).toMatchObject({ requestId: 'g1', error: 'forbidden' });
|
||||
expect(geo.getCurrentPosition).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-PLUGINS-FRAME-016: a granted get posts plain position data into the frame', () => {
|
||||
geo.getCurrentPosition.mockImplementation((ok: (p: unknown) => void) =>
|
||||
ok({ coords: { latitude: 52.5, longitude: 13.4, accuracy: 9, heading: null, speed: null }, timestamp: 1234 }));
|
||||
const { iframe, posted } = mount(true);
|
||||
fromFrame(iframe, { type: 'trek:geolocation', requestId: 'g2' });
|
||||
expect(posted.find((m) => m.type === 'trek:geolocation:result')).toMatchObject({
|
||||
requestId: 'g2',
|
||||
position: { lat: 52.5, lng: 13.4, accuracy: 9, timestamp: 1234 },
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-PLUGINS-FRAME-017: watch streams updates and the GPS watch dies with the frame', () => {
|
||||
let tick: ((p: unknown) => void) | null = null;
|
||||
geo.watchPosition.mockImplementation((ok: (p: unknown) => void) => { tick = ok; return 7; });
|
||||
const { iframe, posted, unmount } = mount(true);
|
||||
|
||||
fromFrame(iframe, { type: 'trek:geolocation', requestId: 'g3', action: 'watch' });
|
||||
expect(posted.find((m) => m.type === 'trek:geolocation:result')).toMatchObject({ requestId: 'g3', watching: true });
|
||||
act(() => tick!({ coords: { latitude: 1, longitude: 2, accuracy: 5, heading: null, speed: null }, timestamp: 1 }));
|
||||
expect(posted.find((m) => m.type === 'trek:geolocation:update')).toMatchObject({ position: { lat: 1, lng: 2 } });
|
||||
|
||||
// Unmounting must never leave a live GPS watch behind.
|
||||
unmount();
|
||||
expect(geo.clearWatch).toHaveBeenCalledWith(7);
|
||||
});
|
||||
|
||||
it('FE-PLUGINS-FRAME-018: clear stops the watch on request', () => {
|
||||
const { iframe, posted } = mount(true);
|
||||
fromFrame(iframe, { type: 'trek:geolocation', requestId: 'g4', action: 'watch' });
|
||||
fromFrame(iframe, { type: 'trek:geolocation', requestId: 'g5', action: 'clear' });
|
||||
expect(geo.clearWatch).toHaveBeenCalledWith(7);
|
||||
expect(posted.find((m) => m.type === 'trek:geolocation:result' && m.requestId === 'g5')).toMatchObject({ cleared: true });
|
||||
});
|
||||
|
||||
it('FE-PLUGINS-FRAME-019: a running watch stops streaming the moment the grant is revoked', () => {
|
||||
let tick: ((p: unknown) => void) | null = null;
|
||||
geo.watchPosition.mockImplementation((ok: (p: unknown) => void) => { tick = ok; return 7; });
|
||||
const { iframe, posted } = mount(true);
|
||||
fromFrame(iframe, { type: 'trek:geolocation', requestId: 'g6', action: 'watch' });
|
||||
|
||||
// Admin revokes geolocation:read while the frame stays mounted (re-render
|
||||
// updates the ref the watch callback reads).
|
||||
act(() => grant(false));
|
||||
const before = posted.length;
|
||||
act(() => tick!({ coords: { latitude: 3, longitude: 4, accuracy: 5, heading: null, speed: null }, timestamp: 2 }));
|
||||
// No further position leaks, and the OS watch is released.
|
||||
expect(posted.length).toBe(before);
|
||||
expect(geo.clearWatch).toHaveBeenCalledWith(7);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useTranslation } from '../../i18n'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { usePluginStore } from '../../store/pluginStore'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import ConfirmDialog from '../shared/ConfirmDialog'
|
||||
import { pluginsApi } from '../../api/client'
|
||||
@@ -114,6 +115,23 @@ type Inbound =
|
||||
| { 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 }
|
||||
| { type: 'trek:geolocation'; requestId: string; action?: 'get' | 'watch' | 'clear' }
|
||||
|
||||
/** The wire shape of a position sent to the frame — plain data, no prototype. */
|
||||
function geoPosition(p: GeolocationPosition) {
|
||||
return {
|
||||
lat: p.coords.latitude,
|
||||
lng: p.coords.longitude,
|
||||
accuracy: p.coords.accuracy,
|
||||
heading: p.coords.heading,
|
||||
speed: p.coords.speed,
|
||||
timestamp: p.timestamp,
|
||||
}
|
||||
}
|
||||
|
||||
function geoErrorCode(e: GeolocationPositionError): 'denied' | 'unavailable' | 'timeout' {
|
||||
return e.code === e.PERMISSION_DENIED ? 'denied' : e.code === e.TIMEOUT ? 'timeout' : 'unavailable'
|
||||
}
|
||||
|
||||
interface ConfirmRequest {
|
||||
requestId: string
|
||||
@@ -160,6 +178,13 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, d
|
||||
// side effects inside a setState updater (StrictMode runs updaters twice).
|
||||
const [confirmReq, setConfirmReq] = useState<ConfirmRequest | null>(null)
|
||||
const confirmReqRef = useRef<ConfirmRequest | null>(null)
|
||||
// geolocation:read gate — the feed only flags plugins whose grant is recorded.
|
||||
// Read via ref (like toastRef) so the bridge effect doesn't re-run on store churn.
|
||||
const geoAllowed = usePluginStore((s) => s.getById(pluginId)?.geolocation === true)
|
||||
const geoAllowedRef = useRef(geoAllowed)
|
||||
geoAllowedRef.current = geoAllowed
|
||||
// The single live watchPosition of this frame (id from navigator.geolocation).
|
||||
const geoWatchRef = useRef<number | 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
|
||||
@@ -280,6 +305,50 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, d
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'trek:geolocation': {
|
||||
// The sandbox blocks navigator.geolocation inside the frame (deliberately —
|
||||
// no blanket permissions-policy delegation). The HOST reads the position and
|
||||
// posts plain data, gated on the plugin's geolocation:read grant, and the
|
||||
// browser's own site permission prompt still applies on top. Nothing here
|
||||
// reaches the server — the position only travels parent → this frame.
|
||||
if (typeof msg.requestId !== 'string' || !msg.requestId) break
|
||||
const requestId = msg.requestId
|
||||
const fail = (error: string) => post({ type: 'trek:geolocation:result', requestId, error })
|
||||
if (!geoAllowedRef.current) { fail('forbidden'); break }
|
||||
if (!('geolocation' in navigator)) { fail('unsupported'); break }
|
||||
const action = msg.action ?? 'get'
|
||||
if (action === 'clear') {
|
||||
if (geoWatchRef.current != null) { navigator.geolocation.clearWatch(geoWatchRef.current); geoWatchRef.current = null }
|
||||
post({ type: 'trek:geolocation:result', requestId, cleared: true })
|
||||
break
|
||||
}
|
||||
const geoOpts = { enableHighAccuracy: true, maximumAge: 5000, timeout: 15000 }
|
||||
if (action === 'watch') {
|
||||
// One watch per frame — a new request replaces the old one. Confirmed
|
||||
// immediately; positions stream as trek:geolocation:update messages.
|
||||
if (geoWatchRef.current != null) navigator.geolocation.clearWatch(geoWatchRef.current)
|
||||
post({ type: 'trek:geolocation:result', requestId, watching: true })
|
||||
// Re-check the grant on every fix, not just at start: if an admin revokes
|
||||
// geolocation:read while the frame stays open, the stream stops at once.
|
||||
const stillAllowed = () => {
|
||||
if (geoAllowedRef.current) return true
|
||||
if (geoWatchRef.current != null) { navigator.geolocation.clearWatch(geoWatchRef.current); geoWatchRef.current = null }
|
||||
return false
|
||||
}
|
||||
geoWatchRef.current = navigator.geolocation.watchPosition(
|
||||
(p) => { if (loadsRef.current <= 1 && stillAllowed()) post({ type: 'trek:geolocation:update', position: geoPosition(p) }) },
|
||||
(e) => { if (loadsRef.current <= 1 && stillAllowed()) post({ type: 'trek:geolocation:update', error: geoErrorCode(e) }) },
|
||||
geoOpts,
|
||||
)
|
||||
break
|
||||
}
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(p) => { if (loadsRef.current <= 1) post({ type: 'trek:geolocation:result', requestId, position: geoPosition(p) }) },
|
||||
(e) => { if (loadsRef.current <= 1) fail(geoErrorCode(e)) },
|
||||
geoOpts,
|
||||
)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -344,6 +413,8 @@ export default function PluginFrame({ pluginId, tripId = null, placeId = null, d
|
||||
window.removeEventListener('message', onMessage)
|
||||
themeObserver.disconnect()
|
||||
if (wsForward) removeListener(wsForward)
|
||||
// The frame is going away (or re-bridging) — never leave a live GPS watch behind.
|
||||
if (geoWatchRef.current != null) { navigator.geolocation.clearWatch(geoWatchRef.current); geoWatchRef.current = null }
|
||||
}
|
||||
}, [pluginId, tripId, fill, navigate, postFrame, buildContext])
|
||||
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { Plus, MoreHorizontal } from 'lucide-react'
|
||||
import type { NavItemDef } from '../Layout/navItems'
|
||||
|
||||
/**
|
||||
* A live, non-interactive mock of the mobile bottom dock that mirrors the
|
||||
* customizer's current split: Dashboard + bar items around the raised centre
|
||||
* "+", with a trailing "More" circle when items are demoted. Themed via base
|
||||
* tokens so it reads correctly in light and dark.
|
||||
*/
|
||||
export default function MobileNavPreview({
|
||||
bar,
|
||||
hasMore,
|
||||
moreLabel,
|
||||
}: {
|
||||
bar: NavItemDef[]
|
||||
hasMore: boolean
|
||||
moreLabel: string
|
||||
}) {
|
||||
// Mirror MBottomNav's geometry: split the slots (bar items + the More slot)
|
||||
// around the centre so the "+" sits dead centre.
|
||||
const slotCount = bar.length + (hasMore ? 1 : 0)
|
||||
const splitAt = Math.ceil(slotCount / 2)
|
||||
const left = bar.slice(0, splitAt)
|
||||
const right = bar.slice(splitAt)
|
||||
|
||||
const circle = (item: NavItemDef) => {
|
||||
const Icon = item.icon
|
||||
return (
|
||||
<span
|
||||
key={item.id}
|
||||
title={item.label}
|
||||
className="flex h-8 w-8 flex-none items-center justify-center rounded-full"
|
||||
style={{ background: 'var(--bg-card)', color: 'var(--text-secondary)', boxShadow: 'inset 0 0 0 1px var(--border-faint)' }}
|
||||
>
|
||||
<Icon size={16} strokeWidth={1.9} />
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex items-center justify-center gap-1.5 rounded-full px-3 py-2"
|
||||
style={{ background: 'var(--bg-hover)', border: '1px solid var(--border-faint)' }}
|
||||
>
|
||||
{left.map(circle)}
|
||||
|
||||
<span
|
||||
className="mx-1 flex h-9 w-9 flex-none items-center justify-center rounded-full"
|
||||
style={{ background: 'var(--text-primary)', color: 'var(--bg-card)' }}
|
||||
>
|
||||
<Plus size={18} strokeWidth={2.4} />
|
||||
</span>
|
||||
|
||||
{right.map(circle)}
|
||||
{hasMore && (
|
||||
<span
|
||||
title={moreLabel}
|
||||
className="flex h-8 w-8 flex-none items-center justify-center rounded-full"
|
||||
style={{ background: 'var(--bg-card)', color: 'var(--text-secondary)', boxShadow: 'inset 0 0 0 1px var(--border-faint)' }}
|
||||
>
|
||||
<MoreHorizontal size={16} strokeWidth={1.9} />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { useNavItems, splitMobileNav, MOBILE_NAV_MAX_BAR, type NavItemDef } from '../Layout/navItems'
|
||||
|
||||
export interface MobileNavValue {
|
||||
bar: string[]
|
||||
more: string[]
|
||||
}
|
||||
|
||||
export type NavZone = 'bar' | 'more'
|
||||
|
||||
export interface MobileNavEditor {
|
||||
/** The pinned Dashboard item (always first in the bar, never editable). */
|
||||
dashboard: NavItemDef | undefined
|
||||
/** Editable bar items (Dashboard excluded). */
|
||||
barItems: NavItemDef[]
|
||||
/** Items under the "More" overflow. */
|
||||
moreItems: NavItemDef[]
|
||||
/** Dashboard + bar items — exactly what the dock renders. */
|
||||
previewBar: NavItemDef[]
|
||||
hasMore: boolean
|
||||
barFull: boolean
|
||||
/** Move an item within a zone from one index to another (drag or arrows). */
|
||||
move: (zone: NavZone, from: number, to: number) => void
|
||||
/** Demote a bar item under "More". */
|
||||
toMore: (id: string) => void
|
||||
/** Promote a "More" item into the bar (no-op when the bar is full). */
|
||||
toBar: (id: string) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Editor logic for the mobile bottom-nav customizer, shared by the desktop and
|
||||
* mobile presentational shells. It derives the current split from the persisted
|
||||
* `{ bar, more }` id lists via splitMobileNav and returns operations that emit
|
||||
* the next value (ids only) — the caller persists it through the appearance blob.
|
||||
*/
|
||||
export function useMobileNavEditor(
|
||||
value: MobileNavValue,
|
||||
onChange: (next: MobileNavValue) => void,
|
||||
): MobileNavEditor {
|
||||
const items = useNavItems()
|
||||
const split = splitMobileNav(items, value)
|
||||
const dashboard = split.bar.find((i) => i.id === 'dashboard')
|
||||
const barItems = split.bar.filter((i) => i.id !== 'dashboard')
|
||||
const moreItems = split.more
|
||||
|
||||
const emit = (bar: NavItemDef[], more: NavItemDef[]) =>
|
||||
onChange({ bar: bar.map((i) => i.id), more: more.map((i) => i.id) })
|
||||
|
||||
const reorder = (list: NavItemDef[], from: number, to: number): NavItemDef[] => {
|
||||
if (to < 0 || to >= list.length || from === to) return list
|
||||
const next = [...list]
|
||||
const [moved] = next.splice(from, 1)
|
||||
next.splice(to, 0, moved)
|
||||
return next
|
||||
}
|
||||
|
||||
const move = (zone: NavZone, from: number, to: number) => {
|
||||
if (zone === 'bar') emit(reorder(barItems, from, to), moreItems)
|
||||
else emit(barItems, reorder(moreItems, from, to))
|
||||
}
|
||||
|
||||
const toMore = (id: string) => {
|
||||
const item = barItems.find((i) => i.id === id)
|
||||
if (!item) return
|
||||
emit(
|
||||
barItems.filter((i) => i.id !== id),
|
||||
[...moreItems, item],
|
||||
)
|
||||
}
|
||||
|
||||
const toBar = (id: string) => {
|
||||
if (barItems.length >= MOBILE_NAV_MAX_BAR) return
|
||||
const item = moreItems.find((i) => i.id === id)
|
||||
if (!item) return
|
||||
emit(
|
||||
[...barItems, item],
|
||||
moreItems.filter((i) => i.id !== id),
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
dashboard,
|
||||
barItems,
|
||||
moreItems,
|
||||
previewBar: split.bar,
|
||||
hasMore: moreItems.length > 0,
|
||||
barFull: barItems.length >= MOBILE_NAV_MAX_BAR,
|
||||
move,
|
||||
toMore,
|
||||
toBar,
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import { KAT_COLORS, PRIO_CONFIG, katColor, type FilterType, type Member } from
|
||||
import { useTodoList } from './useTodoList'
|
||||
import TodoRow from './TodoRow'
|
||||
import { usePluginViewContributions, PluginCardFooter } from '../Plugins/PluginContributions'
|
||||
import EmptyState from '../shared/EmptyState'
|
||||
|
||||
export default function TodoListPanel({ tripId, items, addItemSignal = 0 }: { tripId: number; items: TodoItem[]; addItemSignal?: number }) {
|
||||
// Layout component: state/effects/derived/handlers live in useTodoList.
|
||||
@@ -206,7 +207,7 @@ 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.length === 0 ? <EmptyState scene="tasks" title={t('todo.empty')} /> : (
|
||||
filtered.map(item => {
|
||||
const contributions = contribFor(item.id)
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
interface VacayBadgeProps {
|
||||
label: string
|
||||
// 'amber' flags a pending/attention state; the default is a neutral grey pill.
|
||||
tone?: 'amber'
|
||||
}
|
||||
|
||||
export default function VacayBadge({ label, tone }: VacayBadgeProps) {
|
||||
const toneStyle = tone === 'amber'
|
||||
? { background: 'rgba(245,158,11,0.16)', color: '#b45309' }
|
||||
: { background: 'color-mix(in srgb, var(--vg-ink3) 14%, transparent)', color: 'var(--vg-ink2)' }
|
||||
return (
|
||||
<span
|
||||
className="shrink-0 rounded-full font-semibold uppercase"
|
||||
style={{ fontSize: 8.5, letterSpacing: '0.05em', padding: '2px 6px', lineHeight: 1.4, ...toneStyle }}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -125,7 +125,8 @@ describe('VacayCalendar', () => {
|
||||
|
||||
await user.click(companyBtn)
|
||||
|
||||
expect(companyBtn).toHaveClass('bg-[#d97706]')
|
||||
// Active company mode paints the button amber via inline style (glass facelift).
|
||||
expect(companyBtn.style.background).toMatch(/#d97706|217,\s*119,\s*6/i)
|
||||
})
|
||||
|
||||
it('FE-COMP-VACAYCALENDAR-006: cell click in vacation mode calls toggleEntry', async () => {
|
||||
|
||||
@@ -54,7 +54,7 @@ export default function VacayCalendar() {
|
||||
const weekendDays: number[] = plan?.weekend_days ? String(plan.weekend_days).split(',').map(Number) : [0, 6]
|
||||
const companyHolidaysEnabled = plan?.company_holidays_enabled !== false
|
||||
|
||||
const handleCellClick = useCallback(async (dateStr) => {
|
||||
const handleCellClick = useCallback(async (dateStr: string) => {
|
||||
if (companyMode) {
|
||||
if (!companyHolidaysEnabled) return
|
||||
await toggleCompanyHoliday(dateStr)
|
||||
@@ -69,7 +69,7 @@ export default function VacayCalendar() {
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3" style={{ paddingBottom: 'calc(var(--bottom-nav-h, 0px) + 80px)' }}>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-[18px]" style={{ paddingBottom: 'calc(var(--bottom-nav-h, 0px) + 80px)' }}>
|
||||
{Array.from({ length: 12 }, (_, i) => (
|
||||
<VacayMonthCard
|
||||
key={i}
|
||||
@@ -91,10 +91,13 @@ export default function VacayCalendar() {
|
||||
|
||||
{/* Floating toolbar — lift above the mobile bottom nav (z-60). On desktop --bottom-nav-h is 0px. */}
|
||||
<div className="sticky mt-3 sm:mt-4 flex items-center justify-center px-2" style={{ bottom: 'calc(var(--bottom-nav-h, 0px) + 12px)', zIndex: 61 }}>
|
||||
<div className="flex items-center gap-1.5 sm:gap-2 px-2 sm:px-3 py-1.5 sm:py-2 rounded-xl border bg-surface-card border-edge" style={{ boxShadow: '0 8px 32px rgba(0,0,0,0.12)' }}>
|
||||
<div className="vg-card flex items-center gap-1.5 sm:gap-2 px-2 sm:px-3 py-1.5 sm:py-2 rounded-full">
|
||||
<button
|
||||
onClick={() => setCompanyMode(false)}
|
||||
className={`flex items-center gap-1 sm:gap-1.5 px-2 sm:px-3 py-1.5 rounded-lg text-[11px] sm:text-xs font-medium transition-[background-color,color,border-color] duration-150 ease-[cubic-bezier(0.23,1,0.32,1)] border ${!companyMode ? 'bg-content text-surface-card border-transparent' : 'bg-transparent text-content-muted border-edge'}`}>
|
||||
className="flex items-center gap-1 sm:gap-1.5 px-2 sm:px-3 py-1.5 rounded-full text-[11px] sm:text-xs font-semibold transition-[background-color,color] duration-150 ease-[cubic-bezier(0.23,1,0.32,1)]"
|
||||
style={!companyMode
|
||||
? { background: 'var(--vg-ink)', color: 'var(--vg-bg)' }
|
||||
: { background: 'transparent', color: 'var(--vg-ink2)' }}>
|
||||
<MousePointer2 size={13} />
|
||||
{selectedUser && <span className="w-2.5 h-2.5 rounded-full shrink-0" style={{ backgroundColor: selectedUser.color }} />}
|
||||
{selectedUser ? selectedUser.username : t('vacay.modeVacation')}
|
||||
@@ -102,7 +105,10 @@ export default function VacayCalendar() {
|
||||
{companyHolidaysEnabled && (
|
||||
<button
|
||||
onClick={() => setCompanyMode(true)}
|
||||
className={`flex items-center gap-1 sm:gap-1.5 px-2 sm:px-3 py-1.5 rounded-lg text-[11px] sm:text-xs font-medium transition-[background-color,color,border-color] duration-150 ease-[cubic-bezier(0.23,1,0.32,1)] border ${companyMode ? 'bg-[#d97706] text-[#fff] border-transparent' : 'bg-transparent text-content-muted border-edge'}`}>
|
||||
className="flex items-center gap-1 sm:gap-1.5 px-2 sm:px-3 py-1.5 rounded-full text-[11px] sm:text-xs font-semibold transition-[background-color,color] duration-150 ease-[cubic-bezier(0.23,1,0.32,1)]"
|
||||
style={companyMode
|
||||
? { background: '#d97706', color: '#fff' }
|
||||
: { background: 'transparent', color: 'var(--vg-ink2)' }}>
|
||||
<Building2 size={13} />
|
||||
{t('vacay.modeCompany')}
|
||||
</button>
|
||||
|
||||
@@ -76,7 +76,7 @@ describe('VacayMonthCard', () => {
|
||||
expect(cell.style.cursor).toBe('default')
|
||||
})
|
||||
|
||||
it('FE-COMP-VACAYMONTHCARD-007: Company holiday overlay renders', () => {
|
||||
it('FE-COMP-VACAYMONTHCARD-007: Company holiday cell shows amber fill', () => {
|
||||
const props = {
|
||||
...baseProps,
|
||||
companyHolidaySet: new Set(['2025-01-10']),
|
||||
@@ -86,13 +86,11 @@ describe('VacayMonthCard', () => {
|
||||
// January 10, 2025 is a Friday (not a weekend)
|
||||
const daySpan = screen.getByText('10')
|
||||
const cell = daySpan.closest('div') as HTMLElement
|
||||
// Company overlay is a direct child div with amber background
|
||||
const overlayDivs = Array.from(cell.querySelectorAll(':scope > div')) as HTMLElement[]
|
||||
const companyOverlay = overlayDivs.find(el => el.className.includes('bg-[rgba(245,158,11'))
|
||||
expect(companyOverlay).toBeTruthy()
|
||||
// Amber fill is applied to the cell background itself (glass facelift).
|
||||
expect(cell.style.background).toMatch(/245,\s*158,\s*11/)
|
||||
})
|
||||
|
||||
it('FE-COMP-VACAYMONTHCARD-008: Single vacation entry renders colored overlay', () => {
|
||||
it('FE-COMP-VACAYMONTHCARD-008: Single vacation entry fills the cell with the person colour', () => {
|
||||
const props = {
|
||||
...baseProps,
|
||||
entryMap: { '2025-01-15': [{ date: '2025-01-15', user_id: 1, person_color: '#6366f1' }] },
|
||||
@@ -100,12 +98,9 @@ describe('VacayMonthCard', () => {
|
||||
render(<VacayMonthCard {...props} />)
|
||||
const daySpan = screen.getByText('15')
|
||||
const cell = daySpan.closest('div') as HTMLElement
|
||||
// The overlay div should have opacity: 0.4 and a backgroundColor set
|
||||
const overlayDivs = Array.from(cell.querySelectorAll(':scope > div')) as HTMLElement[]
|
||||
const colorOverlay = overlayDivs.find(
|
||||
el => el.style.opacity === '0.4' && el.style.backgroundColor !== '',
|
||||
)
|
||||
expect(colorOverlay).toBeTruthy()
|
||||
// Person colour is the cell background; the day number flips to white.
|
||||
expect(cell.style.background).toMatch(/#6366f1|99,\s*102,\s*241/i)
|
||||
expect(daySpan.style.color).toMatch(/#fff|255,\s*255,\s*255/i)
|
||||
})
|
||||
|
||||
it('FE-COMP-VACAYMONTHCARD-009: Day number font-weight is bold when entries exist', () => {
|
||||
@@ -132,6 +127,7 @@ describe('VacayMonthCard', () => {
|
||||
|
||||
const getFirstWeekLabels = () =>
|
||||
Array.from(container.querySelectorAll('.grid.grid-cols-7')[1].children)
|
||||
.slice(0, 7)
|
||||
.map((cell) => cell.textContent?.trim() || '')
|
||||
|
||||
// January 1, 2025 is Wednesday: two leading blanks for Monday-first weeks.
|
||||
@@ -144,7 +140,7 @@ describe('VacayMonthCard', () => {
|
||||
expect(getFirstWeekLabels()).toEqual(['', '', '', '1', '2', '3', '4'])
|
||||
})
|
||||
|
||||
it('FE-COMP-VACAYMONTHCARD-011: Two vacation entries render gradient overlay', () => {
|
||||
it('FE-COMP-VACAYMONTHCARD-011: Two vacation entries fill the cell with a split gradient', () => {
|
||||
const props = {
|
||||
...baseProps,
|
||||
entryMap: {
|
||||
@@ -154,11 +150,8 @@ describe('VacayMonthCard', () => {
|
||||
render(<VacayMonthCard {...props} />)
|
||||
const daySpan = screen.getByText('15')
|
||||
const cell = daySpan.closest('div') as HTMLElement
|
||||
const overlayDivs = Array.from(cell.querySelectorAll(':scope > div')) as HTMLElement[]
|
||||
const gradientOverlay = overlayDivs.find(
|
||||
el => el.style.opacity === '0.4' && el.style.background.includes('linear-gradient'),
|
||||
)
|
||||
expect(gradientOverlay).toBeTruthy()
|
||||
// The split gradient is the cell background itself (glass facelift).
|
||||
expect(cell.style.background).toContain('linear-gradient')
|
||||
})
|
||||
|
||||
it('FE-COMP-VACAYMONTHCARD-012: Four vacation entries render quadrant overlay', () => {
|
||||
|
||||
@@ -1,17 +1,9 @@
|
||||
import { useMemo } from 'react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { isWeekend } from './holidays'
|
||||
import type { HolidaysMap, VacayEntry } from '../../types'
|
||||
|
||||
const WEEKDAY_KEYS = ['vacay.mon', 'vacay.tue', 'vacay.wed', 'vacay.thu', 'vacay.fri', 'vacay.sat', 'vacay.sun'] as const
|
||||
|
||||
function hexToRgba(hex: string, alpha: number): string {
|
||||
const r = parseInt(hex.slice(1, 3), 16)
|
||||
const g = parseInt(hex.slice(3, 5), 16)
|
||||
const b = parseInt(hex.slice(5, 7), 16)
|
||||
return `rgba(${r},${g},${b},${alpha})`
|
||||
}
|
||||
|
||||
interface VacayMonthCardProps {
|
||||
year: number
|
||||
month: number
|
||||
@@ -46,13 +38,22 @@ export default function VacayMonthCard({
|
||||
const cells = []
|
||||
for (let i = 0; i < startDow; i++) cells.push(null)
|
||||
for (let d = 1; d <= daysInMonth; d++) cells.push(d)
|
||||
while (cells.length % 7 !== 0) cells.push(null)
|
||||
// Always pad to 6 full weeks (42 cells) so every month card is the same height,
|
||||
// regardless of how many week-rows the month actually spans.
|
||||
while (cells.length < 42) cells.push(null)
|
||||
const w = []
|
||||
for (let i = 0; i < cells.length; i += 7) w.push(cells.slice(i, i + 7))
|
||||
return w
|
||||
}, [year, month, weekStart])
|
||||
|
||||
const pad = (n) => String(n).padStart(2, '0')
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
// Optimistic toggles synthesize an entry that can briefly lack person_color;
|
||||
// fall back to the default so the cell paints instantly instead of staying
|
||||
// transparent until the server refetch lands (mirrors the mobile calendar).
|
||||
const pc = (c?: string) => c || '#6366f1'
|
||||
// Soften the person colour a touch so the filled days don't look overly loud
|
||||
// against the light glass surface (the raw colour reads very saturated).
|
||||
const fill = (c?: string) => `color-mix(in srgb, ${pc(c)} 78%, transparent)`
|
||||
|
||||
const todayStr = useMemo(() => {
|
||||
const d = new Date()
|
||||
@@ -60,113 +61,113 @@ export default function VacayMonthCard({
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border overflow-hidden bg-surface-card border-edge">
|
||||
<div className="px-3 py-2 border-b border-edge-secondary">
|
||||
<span className="text-xs font-semibold capitalize text-content">{monthName}</span>
|
||||
<div className="vg-card rounded-[22px]" style={{ padding: '15px 16px 14px' }}>
|
||||
<div style={{ fontSize: 15, fontWeight: 600, letterSpacing: '-0.02em', color: 'var(--vg-ink)', marginBottom: 9, paddingLeft: 2 }} className="capitalize">
|
||||
{monthName}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-7 border-b border-edge-secondary">
|
||||
<div className="grid grid-cols-7" style={{ gap: 3, marginBottom: 6 }}>
|
||||
{weekdays.map((wd, i) => {
|
||||
// Map column index back to JS day (0=Sun..6=Sat) to check if it's a weekend column
|
||||
// Map column index back to JS day (0=Sun..6=Sat) to fade the weekend columns.
|
||||
const jsDay = (i + weekStart) % 7
|
||||
const isWeekendCol = weekendDays.includes(jsDay)
|
||||
return (
|
||||
<div key={`${wd}-${i}`} className={`text-center text-[10px] font-medium py-1 ${isWeekendCol ? 'text-content-faint' : 'text-content-muted'}`}>
|
||||
<span key={`${wd}-${i}`} style={{
|
||||
textAlign: 'center',
|
||||
fontFamily: 'var(--font-subtext)',
|
||||
fontSize: 9.5,
|
||||
fontWeight: 700,
|
||||
letterSpacing: '0.02em',
|
||||
color: isWeekendCol ? 'color-mix(in srgb, var(--vg-ink3) 55%, transparent)' : 'var(--vg-ink3)',
|
||||
}}>
|
||||
{wd}
|
||||
</div>
|
||||
</span>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
{weeks.map((week, wi) => (
|
||||
<div key={wi} className="grid grid-cols-7">
|
||||
{week.map((day, di) => {
|
||||
if (day === null) return <div key={di} style={{ height: 28 }} />
|
||||
<div className="grid grid-cols-7" style={{ gap: 4 }}>
|
||||
{weeks.flat().map((day, di) => {
|
||||
if (day === null) return <div key={di} style={{ height: 28 }} />
|
||||
|
||||
const dateStr = `${year}-${pad(month + 1)}-${pad(day)}`
|
||||
const dayOfWeek = new Date(year, month, day).getDay()
|
||||
const weekend = weekendDays.includes(dayOfWeek)
|
||||
const holiday = holidays[dateStr]
|
||||
const isCompany = companyHolidaysEnabled && companyHolidaySet.has(dateStr)
|
||||
const dayEntries = entryMap[dateStr] || []
|
||||
const isBlocked = (weekend && blockWeekends) || (isCompany && !companyMode)
|
||||
const isToday = dateStr === todayStr
|
||||
const dateStr = `${year}-${pad(month + 1)}-${pad(day)}`
|
||||
const dayOfWeek = new Date(year, month, day).getDay()
|
||||
const weekend = weekendDays.includes(dayOfWeek)
|
||||
const holiday = holidays[dateStr]
|
||||
const isCompany = companyHolidaysEnabled && companyHolidaySet.has(dateStr)
|
||||
const dayEntries = entryMap[dateStr] || []
|
||||
const hasEntries = dayEntries.length > 0
|
||||
const isBlocked = (weekend && blockWeekends) || (isCompany && !companyMode)
|
||||
const isToday = dateStr === todayStr
|
||||
const plain = !hasEntries && !holiday && !isCompany
|
||||
|
||||
return (
|
||||
<div
|
||||
key={di}
|
||||
title={holiday ? (holiday.label ? `${holiday.label}: ${holiday.localName}` : holiday.localName) : undefined}
|
||||
className="relative flex items-center justify-center cursor-pointer transition-colors"
|
||||
style={{
|
||||
height: 28,
|
||||
background: weekend ? 'var(--bg-secondary)' : 'transparent',
|
||||
borderTop: '1px solid var(--border-secondary)',
|
||||
borderRight: '1px solid var(--border-secondary)',
|
||||
cursor: isBlocked ? 'default' : 'pointer',
|
||||
}}
|
||||
onClick={() => onCellClick(dateStr)}
|
||||
onMouseEnter={e => { if (!isBlocked) e.currentTarget.style.background = 'var(--bg-hover)' }}
|
||||
onMouseLeave={e => { e.currentTarget.style.background = weekend ? 'var(--bg-secondary)' : 'transparent' }}
|
||||
>
|
||||
{holiday && <div className="absolute inset-0.5 rounded" style={{ background: hexToRgba(holiday.color, 0.12) }} />}
|
||||
{isCompany && <div className="absolute inset-0.5 rounded bg-[rgba(245,158,11,0.15)]" />}
|
||||
// Cell fill — people win, then company, then holiday (keeps each calendar's own colour).
|
||||
let background = 'transparent'
|
||||
if (dayEntries.length === 1) background = fill(dayEntries[0].person_color)
|
||||
else if (dayEntries.length === 2) background = `linear-gradient(135deg, ${fill(dayEntries[0].person_color)} 50%, ${fill(dayEntries[1].person_color)} 50%)`
|
||||
else if (dayEntries.length === 0 && isCompany) background = 'rgba(245,158,11,0.22)'
|
||||
else if (dayEntries.length === 0 && holiday) background = `color-mix(in srgb, ${holiday.color} 22%, transparent)`
|
||||
// Weekend / settings-blocked days read as inactive: subtle grey fill, like before the facelift.
|
||||
else if (weekend && blockWeekends) background = 'color-mix(in srgb, var(--vg-ink3) 7%, transparent)'
|
||||
|
||||
{dayEntries.length === 1 && (
|
||||
<div className="absolute inset-0.5 rounded" style={{ backgroundColor: dayEntries[0].person_color, opacity: 0.4 }} />
|
||||
)}
|
||||
{dayEntries.length === 2 && (
|
||||
<div className="absolute inset-0.5 rounded" style={{
|
||||
background: `linear-gradient(135deg, ${dayEntries[0].person_color} 50%, ${dayEntries[1].person_color} 50%)`,
|
||||
opacity: 0.4,
|
||||
}} />
|
||||
)}
|
||||
{dayEntries.length === 3 && (
|
||||
<div className="absolute inset-0.5 rounded overflow-hidden" style={{ opacity: 0.4 }}>
|
||||
<div className="absolute top-0 left-0 w-1/2 h-full" style={{ backgroundColor: dayEntries[0].person_color }} />
|
||||
<div className="absolute top-0 right-0 w-1/2 h-1/2" style={{ backgroundColor: dayEntries[1].person_color }} />
|
||||
<div className="absolute bottom-0 right-0 w-1/2 h-1/2" style={{ backgroundColor: dayEntries[2].person_color }} />
|
||||
</div>
|
||||
)}
|
||||
{dayEntries.length >= 4 && (
|
||||
<div className="absolute inset-0.5 rounded overflow-hidden" style={{ opacity: 0.4 }}>
|
||||
<div className="absolute top-0 left-0 w-1/2 h-1/2" style={{ backgroundColor: dayEntries[0].person_color }} />
|
||||
<div className="absolute top-0 right-0 w-1/2 h-1/2" style={{ backgroundColor: dayEntries[1].person_color }} />
|
||||
<div className="absolute bottom-0 left-0 w-1/2 h-1/2" style={{ backgroundColor: dayEntries[2].person_color }} />
|
||||
<div className="absolute bottom-0 right-0 w-1/2 h-1/2" style={{ backgroundColor: dayEntries[3].person_color }} />
|
||||
</div>
|
||||
)}
|
||||
// Ring — today's inset outline beats the entry drop-shadow.
|
||||
const boxShadow = isToday
|
||||
? 'inset 0 0 0 2px var(--vg-ink)'
|
||||
: hasEntries ? `0 3px 8px -3px ${pc(dayEntries[0].person_color)}` : undefined
|
||||
|
||||
{tripDates?.has(dateStr) && (
|
||||
<span className="absolute top-[3px] right-[3px] w-[5px] h-[5px] rounded-full z-[2] bg-[#3b82f6]" />
|
||||
)}
|
||||
let numColor = 'var(--vg-ink2)'
|
||||
if (hasEntries) numColor = '#fff'
|
||||
else if (holiday) numColor = holiday.color
|
||||
else if (weekend) numColor = 'var(--vg-ink3)'
|
||||
|
||||
<span className="relative z-[1] text-[11px]" style={{
|
||||
fontWeight: dayEntries.length > 0 ? 700 : 500,
|
||||
color: isToday
|
||||
? '#fff'
|
||||
: dayEntries.length > 0
|
||||
? 'var(--text-primary)'
|
||||
: holiday ? holiday.color
|
||||
: weekend ? 'var(--text-faint)'
|
||||
: 'var(--text-primary)',
|
||||
...(isToday ? {
|
||||
display: 'inline-flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
width: 18,
|
||||
height: 18,
|
||||
borderRadius: '50%',
|
||||
background: '#3b82f6',
|
||||
} : {}),
|
||||
}}>
|
||||
{day}
|
||||
</span>
|
||||
return (
|
||||
<div
|
||||
key={di}
|
||||
title={holiday ? (holiday.label ? `${holiday.label}: ${holiday.localName}` : holiday.localName) : undefined}
|
||||
className="relative flex items-center justify-center transition-colors"
|
||||
style={{
|
||||
height: 28,
|
||||
borderRadius: 10,
|
||||
background,
|
||||
boxShadow,
|
||||
cursor: isBlocked ? 'default' : 'pointer',
|
||||
}}
|
||||
onClick={() => onCellClick(dateStr)}
|
||||
onMouseEnter={e => { if (!isBlocked && plain) e.currentTarget.style.background = 'var(--vg-surf2)' }}
|
||||
onMouseLeave={e => { if (!isBlocked && plain) e.currentTarget.style.background = background }}
|
||||
>
|
||||
{/* 3+ people: quadrant overlay at full colour (1 & 2 use the cell background). */}
|
||||
{dayEntries.length === 3 && (
|
||||
<div className="absolute inset-0 overflow-hidden" style={{ borderRadius: 10 }}>
|
||||
<div className="absolute top-0 left-0 w-1/2 h-full" style={{ backgroundColor: fill(dayEntries[0].person_color) }} />
|
||||
<div className="absolute top-0 right-0 w-1/2 h-1/2" style={{ backgroundColor: fill(dayEntries[1].person_color) }} />
|
||||
<div className="absolute bottom-0 right-0 w-1/2 h-1/2" style={{ backgroundColor: fill(dayEntries[2].person_color) }} />
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
)}
|
||||
{dayEntries.length >= 4 && (
|
||||
<div className="absolute inset-0 overflow-hidden" style={{ borderRadius: 10 }}>
|
||||
<div className="absolute top-0 left-0 w-1/2 h-1/2" style={{ backgroundColor: fill(dayEntries[0].person_color) }} />
|
||||
<div className="absolute top-0 right-0 w-1/2 h-1/2" style={{ backgroundColor: fill(dayEntries[1].person_color) }} />
|
||||
<div className="absolute bottom-0 left-0 w-1/2 h-1/2" style={{ backgroundColor: fill(dayEntries[2].person_color) }} />
|
||||
<div className="absolute bottom-0 right-0 w-1/2 h-1/2" style={{ backgroundColor: fill(dayEntries[3].person_color) }} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tripDates?.has(dateStr) && (
|
||||
<span className="absolute top-1 right-1 w-[5px] h-[5px] rounded-full z-[2] bg-[#3b82f6]" style={{ boxShadow: '0 0 0 1.5px var(--vg-surf)' }} />
|
||||
)}
|
||||
|
||||
<span className="relative z-[1]" style={{
|
||||
fontFamily: 'var(--font-subtext)',
|
||||
fontSize: 12,
|
||||
fontWeight: (hasEntries || isToday) ? 700 : 500,
|
||||
color: numColor,
|
||||
}}>
|
||||
{day}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -68,7 +68,7 @@ describe('VacayPersons', () => {
|
||||
|
||||
render(<VacayPersons />)
|
||||
|
||||
expect(document.body).toHaveTextContent('(you)')
|
||||
expect(document.body).toHaveTextContent('you')
|
||||
})
|
||||
|
||||
it('FE-COMP-VACAYPERSONS-003: Pending invite rendered with "(pending)" text', () => {
|
||||
@@ -80,7 +80,7 @@ describe('VacayPersons', () => {
|
||||
render(<VacayPersons />)
|
||||
|
||||
expect(document.body).toHaveTextContent('Bob')
|
||||
expect(document.body).toHaveTextContent('(pending)')
|
||||
expect(document.body).toHaveTextContent('pending')
|
||||
})
|
||||
|
||||
it('FE-COMP-VACAYPERSONS-004: Opens invite modal on UserPlus click', async () => {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import ReactDOM from 'react-dom'
|
||||
import { useState, useEffect } from 'react'
|
||||
import DOM from 'react-dom'
|
||||
import { UserPlus, Unlink, Check, Loader2, Clock, X } from 'lucide-react'
|
||||
import { UserPlus, Check, Loader2, Clock, X } from 'lucide-react'
|
||||
import { useVacayStore } from '../../store/vacayStore'
|
||||
import { useAuthStore } from '../../store/authStore'
|
||||
import { useTranslation } from '../../i18n'
|
||||
@@ -9,6 +8,7 @@ import { getApiErrorMessage } from '../../types'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import CustomSelect from '../shared/CustomSelect'
|
||||
import apiClient from '../../api/client'
|
||||
import VacayBadge from './VacayBadge'
|
||||
|
||||
const PRESET_COLORS = [
|
||||
'#6366f1', '#ec4899', '#14b8a6', '#8b5cf6', '#ef4444',
|
||||
@@ -55,7 +55,7 @@ export default function VacayPersons() {
|
||||
}
|
||||
}
|
||||
|
||||
const handleColorChange = async (color) => {
|
||||
const handleColorChange = async (color: string) => {
|
||||
await updateColor(color, colorEditUserId)
|
||||
setShowColorPicker(false)
|
||||
setColorEditUserId(null)
|
||||
@@ -64,37 +64,42 @@ export default function VacayPersons() {
|
||||
const editingUserColor = users.find(u => u.id === colorEditUserId)?.color || '#6366f1'
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border p-3 bg-surface-card border-edge">
|
||||
<div className="vg-card rounded-[22px]" style={{ padding: '14px 18px' }}>
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<span className="text-[11px] font-medium uppercase tracking-wider text-content-faint">{t('vacay.persons')}</span>
|
||||
<span style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.14em', color: 'var(--vg-ink3)' }}>{t('vacay.persons')}</span>
|
||||
<button onClick={() => { setShowInvite(true); loadAvailable() }}
|
||||
className="p-0.5 rounded transition-colors text-content-faint">
|
||||
<UserPlus size={14} />
|
||||
className="w-7 h-7 rounded-lg flex items-center justify-center transition-colors"
|
||||
style={{ color: 'var(--vg-ink3)' }}>
|
||||
<UserPlus size={15} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<div className="flex flex-col gap-1">
|
||||
{users.map(u => {
|
||||
const isSelected = selectedUserId === u.id
|
||||
return (
|
||||
<div key={u.id}
|
||||
onClick={() => { if (isFused) setSelectedUserId(u.id) }}
|
||||
className={`flex items-center gap-2 px-2.5 py-1.5 rounded-lg group transition-all border ${isSelected ? 'bg-surface-hover border-edge' : 'bg-transparent border-transparent'}`}
|
||||
className="flex items-center gap-2.5 group transition-colors"
|
||||
style={{
|
||||
padding: '7px 10px',
|
||||
borderRadius: 12,
|
||||
cursor: isFused ? 'pointer' : 'default',
|
||||
background: isSelected ? 'var(--vg-surf2)' : 'transparent',
|
||||
border: `1px solid ${isSelected ? 'var(--vg-line)' : 'transparent'}`,
|
||||
}}>
|
||||
<button
|
||||
onClick={(e) => { e.stopPropagation(); setColorEditUserId(u.id); setShowColorPicker(true) }}
|
||||
className="w-3.5 h-3.5 rounded-full shrink-0 transition-transform hover:scale-125"
|
||||
className="w-3 h-3 rounded-full shrink-0 transition-transform hover:scale-125"
|
||||
style={{ backgroundColor: u.color, cursor: 'pointer' }}
|
||||
title={t('vacay.changeColor')}
|
||||
/>
|
||||
<span className="text-xs font-medium flex-1 truncate text-content">
|
||||
<span className="truncate min-w-0" style={{ fontSize: 13, fontWeight: 600, color: 'var(--vg-ink)' }}>
|
||||
{u.username}
|
||||
{u.id === currentUser?.id && <span className="text-content-faint"> ({t('vacay.you')})</span>}
|
||||
</span>
|
||||
{u.id === currentUser?.id && <VacayBadge label={t('vacay.you')} />}
|
||||
{isSelected && isFused && (
|
||||
<Check size={12} className="text-content" />
|
||||
<Check size={15} strokeWidth={2.4} className="ml-auto" style={{ color: 'var(--vg-ink2)' }} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
@@ -102,14 +107,16 @@ export default function VacayPersons() {
|
||||
|
||||
{/* Pending invites */}
|
||||
{pendingInvites.map(inv => (
|
||||
<div key={inv.user_id} className="flex items-center gap-2 px-2.5 py-1.5 rounded-lg group bg-surface-secondary"
|
||||
style={{ opacity: 0.7 }}>
|
||||
<Clock size={12} className="text-content-faint" />
|
||||
<span className="text-xs flex-1 truncate text-content-muted">
|
||||
{inv.username} <span className="text-[10px]">({t('vacay.pending')})</span>
|
||||
<div key={inv.user_id} className="flex items-center gap-2.5 group"
|
||||
style={{ padding: '7px 10px', borderRadius: 12, background: 'var(--vg-surf2)', opacity: 0.7 }}>
|
||||
<Clock size={13} style={{ color: 'var(--vg-ink3)' }} />
|
||||
<span className="truncate min-w-0" style={{ fontSize: 13, color: 'var(--vg-ink2)' }}>
|
||||
{inv.username}
|
||||
</span>
|
||||
<VacayBadge label={t('vacay.pending')} tone="amber" />
|
||||
<button onClick={() => cancelInvite(inv.user_id)}
|
||||
className="opacity-0 group-hover:opacity-100 text-[10px] px-1.5 py-0.5 rounded transition-all text-content-faint">
|
||||
className="ml-auto opacity-0 group-hover:opacity-100 text-[10px] px-1.5 py-0.5 rounded transition-all"
|
||||
style={{ color: 'var(--vg-ink3)' }}>
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -138,11 +138,10 @@ describe('VacaySettings', () => {
|
||||
})
|
||||
render(<VacaySettings onClose={vi.fn()} />)
|
||||
|
||||
// Find and click the add button (has rounded-md class and is in the holidays section)
|
||||
const buttons = screen.getAllByRole('button')
|
||||
const addButton = buttons.find(b => b.className.includes('rounded-md') && b.querySelector('svg'))
|
||||
// Find and click the add button by its accessible name
|
||||
const addButton = screen.getByRole('button', { name: /addCalendar|add calendar/i })
|
||||
expect(addButton).toBeDefined()
|
||||
await user.click(addButton!)
|
||||
await user.click(addButton)
|
||||
|
||||
// After clicking, the AddCalendarForm should be visible with a label input
|
||||
const inputs = screen.getAllByRole('textbox')
|
||||
@@ -159,9 +158,8 @@ describe('VacaySettings', () => {
|
||||
render(<VacaySettings onClose={vi.fn()} />)
|
||||
|
||||
// Click the add button to show AddCalendarForm
|
||||
const buttons = screen.getAllByRole('button')
|
||||
const addButton = buttons.find(b => b.className.includes('rounded-md') && b.querySelector('svg'))
|
||||
await user.click(addButton!)
|
||||
const addButton = screen.getByRole('button', { name: /addCalendar|add calendar/i })
|
||||
await user.click(addButton)
|
||||
|
||||
// Wait for countries to load (the component fetches them on mount)
|
||||
await waitFor(() => {
|
||||
@@ -360,10 +358,8 @@ describe('VacaySettings', () => {
|
||||
render(<VacaySettings onClose={vi.fn()} />)
|
||||
|
||||
// Open the form
|
||||
const addButton = screen.getAllByRole('button').find(b =>
|
||||
b.className.includes('rounded-md') && b.querySelector('svg')
|
||||
)
|
||||
await user.click(addButton!)
|
||||
const addButton = screen.getByRole('button', { name: /addCalendar|add calendar/i })
|
||||
await user.click(addButton)
|
||||
expect(screen.getAllByRole('textbox').length).toBeGreaterThan(0)
|
||||
|
||||
// Click cancel (✕ button)
|
||||
|
||||
@@ -40,7 +40,10 @@ export default function VacaySettings({ onClose }: VacaySettingsProps) {
|
||||
const toggle = (key: string) => updatePlan({ [key]: !plan[key] })
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-5 items-stretch">
|
||||
{/* ── Column 1 · calendar rules ── */}
|
||||
<div className="rounded-2xl p-5 space-y-4" style={{ border: '1px solid var(--vg-line)', background: 'var(--vg-surf2)' }}>
|
||||
{/* Block weekends */}
|
||||
<SettingToggle
|
||||
icon={CalendarOff}
|
||||
@@ -125,7 +128,10 @@ export default function VacaySettings({ onClose }: VacaySettingsProps) {
|
||||
value={plan.carry_over_enabled}
|
||||
onChange={() => toggle('carry_over_enabled')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* ── Column 2 · holidays ── */}
|
||||
<div className="rounded-2xl p-5 space-y-4" style={{ border: '1px solid var(--vg-line)', background: 'var(--vg-surf2)' }}>
|
||||
{/* Company holidays */}
|
||||
<div>
|
||||
<SettingToggle
|
||||
@@ -137,9 +143,9 @@ export default function VacaySettings({ onClose }: VacaySettingsProps) {
|
||||
/>
|
||||
{plan.company_holidays_enabled && (
|
||||
<div className="ml-7 mt-2">
|
||||
<div className="flex items-center gap-1.5 px-2 py-1.5 rounded-md bg-surface-secondary">
|
||||
<AlertCircle size={12} className="text-content-faint" />
|
||||
<span className="text-[10px] text-content-faint">{t('vacay.companyHolidaysNoDeduct')}</span>
|
||||
<div className="flex items-center gap-1.5 px-2 py-1.5 rounded-md" style={{ background: 'var(--vg-surf)', border: '1px solid var(--vg-line)' }}>
|
||||
<AlertCircle size={12} style={{ color: 'var(--vg-ink3)' }} />
|
||||
<span className="text-[10px]" style={{ color: 'var(--vg-ink3)' }}>{t('vacay.companyHolidaysNoDeduct')}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
@@ -179,15 +185,18 @@ export default function VacaySettings({ onClose }: VacaySettingsProps) {
|
||||
) : (
|
||||
<button
|
||||
onClick={() => setShowAddForm(true)}
|
||||
className="flex items-center gap-1.5 text-xs px-2 py-1.5 rounded-md transition-colors text-content-muted bg-surface-secondary"
|
||||
className="w-full flex items-center justify-center gap-1.5 text-xs font-medium py-2.5 rounded-xl border border-dashed transition-colors"
|
||||
style={{ borderColor: 'var(--vg-line2)', background: 'var(--vg-surf)', color: 'var(--vg-ink2)' }}
|
||||
>
|
||||
<Plus size={12} />
|
||||
<Plus size={13} />
|
||||
{t('vacay.addCalendar')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Dissolve fusion */}
|
||||
{isFused && (
|
||||
@@ -284,7 +293,7 @@ function CalendarRow({ cal, countries, onUpdate, onDelete }: {
|
||||
const [showColorPicker, setShowColorPicker] = useState(false)
|
||||
|
||||
return (
|
||||
<div className="flex gap-3 items-start p-3 rounded-xl bg-surface-secondary">
|
||||
<div className="flex gap-3 items-start p-3 rounded-xl" style={{ background: 'var(--vg-surf)', border: '1px solid var(--vg-line)' }}>
|
||||
<div style={{ position: 'relative', flexShrink: 0 }}>
|
||||
<button
|
||||
onClick={() => setShowColorPicker(!showColorPicker)}
|
||||
@@ -308,7 +317,7 @@ function CalendarRow({ cal, countries, onUpdate, onDelete }: {
|
||||
onBlur={() => { const v = localLabel.trim() || null; if (v !== cal.label) onUpdate({ label: v }) }}
|
||||
onKeyDown={e => { if (e.key === 'Enter') (e.target as HTMLInputElement).blur() }}
|
||||
placeholder={t('vacay.calendarLabel')}
|
||||
style={{ width: '100%', fontSize: 'calc(12px * var(--fs-scale-body, 1))', padding: '6px 10px', borderRadius: 8, background: 'var(--bg-input)', border: '1px solid var(--border-primary)', color: 'var(--text-primary)', fontFamily: 'inherit', outline: 'none' }}
|
||||
style={{ width: '100%', fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 500, padding: '8px 14px', borderRadius: 10, background: 'var(--bg-input)', border: '1px solid var(--border-primary)', color: 'var(--text-primary)', fontFamily: 'inherit', outline: 'none' }}
|
||||
/>
|
||||
<CustomSelect
|
||||
value={selectedCountry}
|
||||
@@ -368,7 +377,7 @@ function AddCalendarForm({ countries, onAdd, onCancel }: {
|
||||
const [showColorPicker, setShowColorPicker] = useState(false)
|
||||
|
||||
return (
|
||||
<div className="flex gap-3 items-start p-3 rounded-xl border border-dashed border-edge">
|
||||
<div className="flex gap-3 items-start p-3 rounded-xl border border-dashed" style={{ borderColor: 'var(--vg-line2)', background: 'var(--vg-surf)' }}>
|
||||
<div style={{ position: 'relative', flexShrink: 0 }}>
|
||||
<button
|
||||
onClick={() => setShowColorPicker(!showColorPicker)}
|
||||
@@ -390,7 +399,7 @@ function AddCalendarForm({ countries, onAdd, onCancel }: {
|
||||
value={label}
|
||||
onChange={e => setLabel(e.target.value)}
|
||||
placeholder={t('vacay.calendarLabel')}
|
||||
style={{ width: '100%', fontSize: 'calc(12px * var(--fs-scale-body, 1))', padding: '6px 10px', borderRadius: 8, background: 'var(--bg-input)', border: '1px solid var(--border-primary)', color: 'var(--text-primary)', fontFamily: 'inherit', outline: 'none' }}
|
||||
style={{ width: '100%', fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 500, padding: '8px 14px', borderRadius: 10, background: 'var(--bg-input)', border: '1px solid var(--border-primary)', color: 'var(--text-primary)', fontFamily: 'inherit', outline: 'none' }}
|
||||
/>
|
||||
<CustomSelect
|
||||
value={selectedCountry}
|
||||
|
||||
@@ -59,7 +59,7 @@ describe('VacayStats', () => {
|
||||
seedStore(useAuthStore, { user: { id: 1 } })
|
||||
seedStore(useVacayStore, { stats: [buildStat({ user_id: 1 })] })
|
||||
render(<VacayStats />)
|
||||
expect(screen.getByText(/\(you\)/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/^you$/i)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('FE-COMP-VACAYSTATS-005: Remaining shown in green when > 3', () => {
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Briefcase, Pencil } from 'lucide-react'
|
||||
import { Pencil } from 'lucide-react'
|
||||
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'
|
||||
import VacayBadge from './VacayBadge'
|
||||
|
||||
|
||||
export default function VacayStats() {
|
||||
@@ -15,18 +16,17 @@ export default function VacayStats() {
|
||||
useEffect(() => { loadStats(selectedYear) }, [selectedYear])
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border p-3 bg-surface-card border-edge">
|
||||
<div className="flex items-center gap-1.5 mb-3">
|
||||
<Briefcase size={13} className="text-content-faint" />
|
||||
<span className="text-[11px] font-medium uppercase tracking-wider text-content-faint">
|
||||
<div className="vg-card rounded-[22px]" style={{ padding: '14px 18px' }}>
|
||||
<div className="mb-2.5">
|
||||
<span style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.14em', color: 'var(--vg-ink3)' }}>
|
||||
{t('vacay.entitlement')} {selectedYear}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{stats.length === 0 ? (
|
||||
<p className="text-[11px] text-center py-3 text-content-faint">{t('vacay.noData')}</p>
|
||||
<p className="text-[11px] text-center py-3" style={{ color: 'var(--vg-ink3)' }}>{t('vacay.noData')}</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<div className="flex flex-col gap-2">
|
||||
{stats.map(s => (
|
||||
<StatCard
|
||||
key={s.user_id}
|
||||
@@ -73,33 +73,34 @@ function StatCard({ stat: s, isMe, canEdit, selectedYear, onSave, t }: StatCardP
|
||||
}
|
||||
}
|
||||
|
||||
const remainingColor = s.remaining < 0 ? '#ef4444' : s.remaining <= 3 ? '#f59e0b' : '#22c55e'
|
||||
const tileValue = { fontFamily: 'var(--font-subtext)', fontSize: 14, fontWeight: 700, height: 16, lineHeight: '16px' } as const
|
||||
|
||||
return (
|
||||
<div className="rounded-lg p-2.5 space-y-2 border border-edge-secondary">
|
||||
<div className="flex items-center gap-2">
|
||||
<div style={{ padding: 10, borderRadius: 14, border: '1px solid var(--vg-line)' }}>
|
||||
<div className="flex items-center gap-2" style={{ marginBottom: 6 }}>
|
||||
<span className="w-2.5 h-2.5 rounded-full shrink-0" style={{ backgroundColor: s.person_color }} />
|
||||
<span className="text-xs font-semibold flex-1 truncate text-content">
|
||||
<span className="truncate min-w-0" style={{ fontSize: 13, fontWeight: 700, color: 'var(--vg-ink)' }}>
|
||||
{s.person_name}
|
||||
{isMe && <span className="text-content-faint"> ({t('vacay.you')})</span>}
|
||||
</span>
|
||||
<span className="text-[10px] tabular-nums text-content-faint">{s.used}/{s.total_available}</span>
|
||||
{isMe && <VacayBadge label={t('vacay.you')} />}
|
||||
<span className="tabular-nums ml-auto" style={{ fontFamily: 'var(--font-subtext)', fontSize: 10.5, color: 'var(--vg-ink3)' }}>{s.used}/{s.total_available}</span>
|
||||
</div>
|
||||
<div className="h-1.5 rounded-full overflow-hidden bg-surface-secondary">
|
||||
<div className="overflow-hidden" style={{ height: 6, borderRadius: 99, background: 'var(--vg-surf2)', marginBottom: 7 }}>
|
||||
<div
|
||||
className="trek-bar-fill h-full rounded-full transition-[width] duration-500 ease-[cubic-bezier(0.23,1,0.32,1)]"
|
||||
style={{ width: `${pct}%`, backgroundColor: s.person_color }}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-1.5">
|
||||
<div className="grid grid-cols-3" style={{ gap: 7 }}>
|
||||
{/* Days — editable */}
|
||||
<div
|
||||
className={`rounded-md px-2 py-2 group/days border ${canEdit ? 'bg-surface-card border-edge' : 'bg-surface-secondary border-transparent'}`}
|
||||
style={{
|
||||
cursor: canEdit ? 'pointer' : 'default',
|
||||
}}
|
||||
className="group/days"
|
||||
style={{ padding: '6px 9px', borderRadius: 10, background: 'var(--vg-surf2)', cursor: canEdit ? 'pointer' : 'default' }}
|
||||
onClick={() => { if (canEdit && !editing) setEditing(true) }}
|
||||
>
|
||||
<div className="text-[10px] mb-1 text-content-faint" style={{ height: 14, lineHeight: '14px' }}>
|
||||
{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 style={{ fontSize: 10, marginBottom: 2, color: 'var(--vg-ink3)', height: 13, lineHeight: '13px' }}>
|
||||
{t('vacay.entitlementDays')} {canEdit && !editing && <Pencil size={9} className="inline opacity-0 group-hover/days:opacity-100 transition-opacity" style={{ verticalAlign: 'middle', color: 'var(--vg-ink3)' }} />}
|
||||
</div>
|
||||
{editing ? (
|
||||
<NumericInput
|
||||
@@ -108,28 +109,26 @@ function StatCard({ stat: s, isMe, canEdit, selectedYear, onSave, t }: StatCardP
|
||||
onBlur={handleSave}
|
||||
onKeyDown={e => { if (e.key === 'Enter') handleSave(); if (e.key === 'Escape') { setEditing(false); setLocalDays(s.vacation_days) } }}
|
||||
autoFocus
|
||||
className="w-full bg-transparent text-sm font-bold outline-none p-0 m-0 [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none text-content"
|
||||
style={{ height: 18, lineHeight: '18px' }}
|
||||
className="w-full bg-transparent outline-none p-0 m-0 [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none"
|
||||
style={{ ...tileValue, color: 'var(--vg-ink)' }}
|
||||
/>
|
||||
) : (
|
||||
<div className="text-sm font-bold text-content" style={{ height: 18, lineHeight: '18px' }}>{s.vacation_days}</div>
|
||||
<div style={{ ...tileValue, color: 'var(--vg-ink)' }}>{s.vacation_days}</div>
|
||||
)}
|
||||
</div>
|
||||
{/* Used */}
|
||||
<div className="rounded-md px-2 py-2 bg-surface-secondary">
|
||||
<div className="text-[10px] mb-1 text-content-faint" style={{ height: 14, lineHeight: '14px' }}>{t('vacay.used')}</div>
|
||||
<div className="text-sm font-bold text-content" style={{ height: 18, lineHeight: '18px' }}>{s.used}</div>
|
||||
<div style={{ padding: '6px 9px', borderRadius: 10, background: 'var(--vg-surf2)' }}>
|
||||
<div style={{ fontSize: 10, marginBottom: 2, color: 'var(--vg-ink3)', height: 13, lineHeight: '13px' }}>{t('vacay.used')}</div>
|
||||
<div style={{ ...tileValue, color: 'var(--vg-ink)' }}>{s.used}</div>
|
||||
</div>
|
||||
{/* Remaining */}
|
||||
<div className="rounded-md px-2 py-2 bg-surface-secondary">
|
||||
<div className="text-[10px] mb-1 text-content-faint" style={{ height: 14, lineHeight: '14px' }}>{t('vacay.remaining')}</div>
|
||||
<div className="text-sm font-bold" style={{ color: s.remaining < 0 ? '#ef4444' : s.remaining <= 3 ? '#f59e0b' : '#22c55e', height: 18, lineHeight: '18px' }}>
|
||||
{s.remaining}
|
||||
</div>
|
||||
<div style={{ padding: '6px 9px', borderRadius: 10, background: 'var(--vg-surf2)' }}>
|
||||
<div style={{ fontSize: 10, marginBottom: 2, color: 'var(--vg-ink3)', height: 13, lineHeight: '13px' }}>{t('vacay.remaining')}</div>
|
||||
<div style={{ ...tileValue, color: remainingColor }}>{s.remaining}</div>
|
||||
</div>
|
||||
</div>
|
||||
{s.carried_over > 0 && (
|
||||
<div className="flex items-center gap-1.5 px-2 py-1 rounded-md bg-[rgba(245,158,11,0.08)] border border-[rgba(245,158,11,0.15)]">
|
||||
<div className="flex items-center gap-1.5 px-2 py-1 rounded-md bg-[rgba(245,158,11,0.08)] border border-[rgba(245,158,11,0.15)]" style={{ marginTop: 10 }}>
|
||||
<span className="text-[10px] text-[#d97706]">+{s.carried_over} {t('vacay.carriedOver', { year: selectedYear - 1 })}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { CSSProperties } from 'react'
|
||||
import MDancingTrek, { type TrekScene, type TrekMood } from '../../mobile/components/MDancingTrek'
|
||||
|
||||
/**
|
||||
* The one desktop empty state: the TREK mascot acting out the page's scene with
|
||||
* a single title beneath it — no subtitle, one uniform look everywhere.
|
||||
*
|
||||
* The mascot is monochrome and drives its colours off two mobile tokens
|
||||
* (`--m-ink` body / `--m-bg` cutouts) that only exist inside the mobile shell,
|
||||
* so we map them onto the desktop palette here. Its `.trek-*` choreography is
|
||||
* global CSS, so it animates outside the shell as-is. `surface` should match the
|
||||
* background the state sits on so the cut-out eyes read as holes (default: card).
|
||||
*/
|
||||
export default function EmptyState({
|
||||
scene = 'idle',
|
||||
mood,
|
||||
title,
|
||||
size = 104,
|
||||
surface = 'var(--bg-card)',
|
||||
className = '',
|
||||
}: {
|
||||
scene?: TrekScene
|
||||
mood?: TrekMood
|
||||
title: string
|
||||
size?: number
|
||||
surface?: string
|
||||
className?: string
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className={`flex flex-col items-center justify-center gap-3 px-6 py-12 text-center ${className}`}
|
||||
style={{ '--m-ink': 'var(--text-primary)', '--m-bg': surface } as CSSProperties}
|
||||
>
|
||||
<MDancingTrek scene={scene} mood={mood} size={size} />
|
||||
<p className="text-[15px] font-semibold text-content-secondary">{title}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import MDancingTrek, { type TrekScene } from '../../mobile/components/MDancingTrek'
|
||||
|
||||
/**
|
||||
* Trip-open splash for desktop — the same little journey the mobile splash
|
||||
* plays: the TREK mascot packs, hits the road, cruises in and drops the
|
||||
* destination pin while the trip loads. It now takes over the viewport as a
|
||||
* calm, Apple-style scene: a slowly drifting pastel gradient wash (soft
|
||||
* pink/lavender/periwinkle, toned right down) whose tiles pan and whose hue
|
||||
* gently breathes, dusted with a faint filmic grain, and the whole journey
|
||||
* floating on a frosted "liquid glass" card. Monochrome mascot tokens map onto
|
||||
* the desktop palette; the mascot's eye cut-outs (--m-bg) are pinned to the
|
||||
* card surface so they read as clean holes. Under reduced motion the background
|
||||
* freezes and the mascot parks on "loading photos". Palette + glass tint swap
|
||||
* for light/dark via the .dark class the app puts on <html>.
|
||||
*/
|
||||
const STEPS: { scene: TrekScene; key: string }[] = [
|
||||
{ scene: 'packing', key: 'trip.loadingSteps.pack' },
|
||||
{ scene: 'transport', key: 'trip.loadingSteps.road' },
|
||||
{ scene: 'dashboard', key: 'trip.loadingPhotos' },
|
||||
{ scene: 'collections', key: 'trip.loadingSteps.arrive' },
|
||||
]
|
||||
const STEP_MS = 1400
|
||||
const STILL_INDEX = 2
|
||||
|
||||
const SPLASH_CSS = `
|
||||
.m-splash-root { background: #eef0fb; }
|
||||
.dark .m-splash-root { background: #0c0c12; }
|
||||
|
||||
/* ── Drifting gradient wash ──────────────────────────────────────────────────
|
||||
A layered pastel mesh whose tiles pan on a long ease-in-out loop, so nothing
|
||||
ever snaps or races. Toned-down opacity keeps it airy rather than garish. */
|
||||
.m-splash-bg {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background-color: #eef0fb;
|
||||
background-image:
|
||||
radial-gradient(60% 60% at 50% 50%, rgba(244, 199, 221, 0.55), transparent 70%),
|
||||
radial-gradient(56% 56% at 50% 50%, rgba(206, 201, 245, 0.50), transparent 72%),
|
||||
radial-gradient(60% 60% at 50% 50%, rgba(190, 209, 247, 0.52), transparent 72%),
|
||||
radial-gradient(52% 52% at 50% 50%, rgba(238, 214, 236, 0.44), transparent 72%);
|
||||
background-repeat: no-repeat;
|
||||
background-size: 122% 122%, 132% 132%, 126% 126%, 116% 116%;
|
||||
background-position: 12% 20%, 82% 18%, 74% 82%, 22% 78%;
|
||||
animation: m-splash-drift 30s ease-in-out infinite alternate;
|
||||
will-change: background-position;
|
||||
}
|
||||
.dark .m-splash-bg {
|
||||
background-color: #0c0c12;
|
||||
background-image:
|
||||
radial-gradient(60% 60% at 50% 50%, rgba(158, 116, 192, 0.30), transparent 70%),
|
||||
radial-gradient(56% 56% at 50% 50%, rgba(112, 122, 196, 0.28), transparent 72%),
|
||||
radial-gradient(60% 60% at 50% 50%, rgba(90, 132, 194, 0.26), transparent 72%),
|
||||
radial-gradient(52% 52% at 50% 50%, rgba(164, 112, 176, 0.24), transparent 72%);
|
||||
}
|
||||
@keyframes m-splash-drift {
|
||||
0% { background-position: 12% 20%, 82% 18%, 74% 82%, 22% 78%; }
|
||||
100% { background-position: 26% 36%, 66% 30%, 58% 68%, 36% 62%; }
|
||||
}
|
||||
|
||||
/* Hue veil — a heavily blurred conic sweep that gently hue-rotates, so the
|
||||
palette breathes without any visible spinning. */
|
||||
.m-splash-veil {
|
||||
position: absolute;
|
||||
inset: -25%;
|
||||
background: conic-gradient(from 210deg at 50% 50%,
|
||||
rgba(255, 214, 232, 0), rgba(214, 205, 248, 0.16),
|
||||
rgba(198, 214, 248, 0.16), rgba(245, 214, 236, 0),
|
||||
rgba(255, 214, 232, 0));
|
||||
filter: blur(46px) hue-rotate(0deg);
|
||||
mix-blend-mode: soft-light;
|
||||
animation: m-splash-hue 26s ease-in-out infinite alternate;
|
||||
will-change: filter;
|
||||
}
|
||||
.dark .m-splash-veil { opacity: 0.55; }
|
||||
@keyframes m-splash-hue {
|
||||
from { filter: blur(46px) hue-rotate(0deg); }
|
||||
to { filter: blur(46px) hue-rotate(24deg); }
|
||||
}
|
||||
|
||||
/* Filmic grain — an inline (self-contained) fractal-noise texture at a whisper
|
||||
of opacity for that reference-shot texture. Static, so it never adds motion. */
|
||||
.m-splash-grain {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='2' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
|
||||
background-size: 160px 160px;
|
||||
opacity: 0.05;
|
||||
mix-blend-mode: overlay;
|
||||
}
|
||||
.dark .m-splash-grain { opacity: 0.09; mix-blend-mode: soft-light; }
|
||||
|
||||
/* A breath of vignette for depth. */
|
||||
.m-splash-vignette {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: radial-gradient(120% 100% at 50% 40%, transparent 55%, rgba(48, 38, 72, 0.10) 100%);
|
||||
}
|
||||
.dark .m-splash-vignette {
|
||||
background: radial-gradient(120% 100% at 50% 42%, transparent 46%, rgba(0, 0, 0, 0.42) 100%);
|
||||
}
|
||||
|
||||
/* ── Frosted "liquid glass" card ─────────────────────────────────────────────
|
||||
Translucent, blurred + saturated, a hairline light edge, soft lift, generous
|
||||
radius. Painted after the background layers so the frost blurs them. */
|
||||
.m-splash-card {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 44px 56px 40px;
|
||||
border-radius: 32px;
|
||||
background: rgba(255, 255, 255, 0.55);
|
||||
border: 1px solid rgba(255, 255, 255, 0.6);
|
||||
box-shadow:
|
||||
0 24px 70px -26px rgba(60, 48, 96, 0.38),
|
||||
0 2px 8px -4px rgba(60, 48, 96, 0.20),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.75);
|
||||
backdrop-filter: blur(30px) saturate(1.7);
|
||||
-webkit-backdrop-filter: blur(30px) saturate(1.7);
|
||||
animation: m-splash-rise 700ms cubic-bezier(0.22, 1, 0.36, 1) both;
|
||||
}
|
||||
.dark .m-splash-card {
|
||||
background: rgba(26, 24, 34, 0.52);
|
||||
border-color: rgba(255, 255, 255, 0.09);
|
||||
box-shadow:
|
||||
0 28px 80px -28px rgba(0, 0, 0, 0.65),
|
||||
0 2px 10px -4px rgba(0, 0, 0, 0.45),
|
||||
inset 0 1px 0 rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
@keyframes m-splash-rise {
|
||||
from { opacity: 0; transform: translateY(10px) scale(0.985); }
|
||||
to { opacity: 1; transform: none; }
|
||||
}
|
||||
|
||||
/* Monochrome mascot tokens live on the content wrapper. --m-bg is pinned to the
|
||||
frosted card's surface tone (not the page) so the eye cut-outs read clean. */
|
||||
.m-splash-content {
|
||||
--m-ink: var(--text-primary);
|
||||
--m-bg: #f3f1f8;
|
||||
}
|
||||
.dark .m-splash-content { --m-bg: #1b1a22; }
|
||||
|
||||
@keyframes m-trek-beat {
|
||||
from { opacity: 0; transform: translateX(20px); }
|
||||
to { opacity: 1; transform: translateX(0); }
|
||||
}
|
||||
|
||||
/* ── Motion prefs: freeze the drifting background ────────────────────────── */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.m-splash-bg,
|
||||
.m-splash-veil,
|
||||
.m-splash-card { animation: none !important; }
|
||||
}
|
||||
`
|
||||
|
||||
export default function TripLoadingSplash({ title }: { title?: string }) {
|
||||
const { t } = useTranslation()
|
||||
const reduceMotion =
|
||||
typeof window !== 'undefined' && window.matchMedia?.('(prefers-reduced-motion: reduce)').matches
|
||||
|
||||
const [index, setIndex] = useState(0)
|
||||
useEffect(() => {
|
||||
if (reduceMotion) return
|
||||
const id = setInterval(() => setIndex((n) => (n + 1) % STEPS.length), STEP_MS)
|
||||
return () => clearInterval(id)
|
||||
}, [reduceMotion])
|
||||
|
||||
const activeIndex = reduceMotion ? STILL_INDEX : index
|
||||
const step = STEPS[activeIndex]
|
||||
|
||||
return (
|
||||
<div
|
||||
className="m-splash-root fixed inset-0 z-[100] flex items-center justify-center overflow-hidden"
|
||||
role="status"
|
||||
aria-label={title || 'TREK'}
|
||||
>
|
||||
{/* Slowly drifting glass gradient — painted behind the card so the frost
|
||||
blurs it. */}
|
||||
<div className="m-splash-bg" aria-hidden="true" />
|
||||
<div className="m-splash-veil" aria-hidden="true" />
|
||||
<div className="m-splash-grain" aria-hidden="true" />
|
||||
<div className="m-splash-vignette" aria-hidden="true" />
|
||||
|
||||
<div className="m-splash-card">
|
||||
<div className="m-splash-content flex flex-col items-center justify-center">
|
||||
{/* Fixed stage so the travelling mascot never nudges the layout. */}
|
||||
<div className="mb-6 flex h-[150px] w-[160px] items-center justify-center overflow-hidden">
|
||||
<div key={step.scene} style={reduceMotion ? undefined : { animation: 'm-trek-beat 460ms cubic-bezier(.34,1.56,.64,1) both' }}>
|
||||
<MDancingTrek scene={step.scene} mood="happy" size={128} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mb-2 text-[1.25rem] font-bold tracking-[-0.3px] text-content">{title || 'TREK'}</div>
|
||||
|
||||
<div className="mb-8 flex h-4 items-center justify-center">
|
||||
<span key={step.key} className="text-[0.75rem] font-medium uppercase tracking-[2px] text-content-faint">
|
||||
{t(step.key)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Beat dots — the active stage widens into a pill. */}
|
||||
<div className="flex items-center gap-1.5">
|
||||
{STEPS.map((_, i) => (
|
||||
<span
|
||||
key={i}
|
||||
className="h-[6px] rounded-full transition-all duration-[400ms] ease-out"
|
||||
style={{ width: i === activeIndex ? 20 : 6, background: i === activeIndex ? 'var(--text-primary)' : 'var(--border-primary)' }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>{SPLASH_CSS}</style>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
import { useState, useCallback, useRef, useEffect, useMemo } from 'react'
|
||||
import { useTripStore } from '../store/tripStore'
|
||||
import { useSettingsStore } from '../store/settingsStore'
|
||||
import { calculateRouteWithLegs, withHotelBookends } from '../components/Map/RouteCalculator'
|
||||
import { calculateRouteWithLegs, withHotelBookends, type RouteProfileKey } from '../components/Map/RouteCalculator'
|
||||
import { getTransportRouteEndpoints } from '../utils/dayMerge'
|
||||
import { getDayBookendHotels, shouldDrawMorningLeg, shouldDrawEveningLeg } from '../utils/dayOrder'
|
||||
import type { TripStoreState } from '../store/tripStore'
|
||||
import type { RouteSegment, RouteResult, Accommodation } from '../types'
|
||||
import type { RouteSegment, RouteResult, RouteVia, Accommodation } from '../types'
|
||||
|
||||
const TRANSPORT_TYPES = ['flight', 'train', 'bus', 'car', 'taxi', 'bicycle', 'cruise', 'ferry', 'transit', 'transport_other']
|
||||
|
||||
@@ -16,10 +16,12 @@ const NO_ACCOMMODATIONS: Accommodation[] = []
|
||||
* day assignments, draws a straight-line route immediately, then upgrades it to real OSRM
|
||||
* road geometry with per-segment durations. Aborts in-flight requests when the day changes.
|
||||
*/
|
||||
export function useRouteCalculation(tripStore: TripStoreState, selectedDayId: number | null, enabled: boolean = true, profile: 'driving' | 'walking' | 'cycling' = 'driving', accommodations: Accommodation[] = NO_ACCOMMODATIONS) {
|
||||
export function useRouteCalculation(tripStore: TripStoreState, selectedDayId: number | null, enabled: boolean = true, profile: RouteProfileKey = 'driving', accommodations: Accommodation[] = NO_ACCOMMODATIONS) {
|
||||
const [route, setRoute] = useState<[number, number][][] | null>(null)
|
||||
const [routeInfo, setRouteInfo] = useState<RouteResult | null>(null)
|
||||
const [routeSegments, setRouteSegments] = useState<RouteSegment[]>([])
|
||||
// Charging stops / rest areas a plugin route places on the drawn line.
|
||||
const [routeVias, setRouteVias] = useState<RouteVia[]>([])
|
||||
const routeAbortRef = useRef<AbortController | null>(null)
|
||||
const reservationsForSignature = useTripStore((s) => s.reservations)
|
||||
// Draw the day's accommodation bookend legs (hotel → first stop, last stop →
|
||||
@@ -32,7 +34,7 @@ export function useRouteCalculation(tripStore: TripStoreState, selectedDayId: nu
|
||||
const updateRouteForDay = useCallback(async (dayId: number | null) => {
|
||||
if (routeAbortRef.current) routeAbortRef.current.abort()
|
||||
// Route is manual: only compute when explicitly enabled (the "show route" toggle).
|
||||
if (!dayId || !enabled) { setRoute(null); setRouteSegments([]); return }
|
||||
if (!dayId || !enabled) { setRoute(null); setRouteSegments([]); setRouteVias([]); return }
|
||||
// Read directly from store (not a render-phase ref) so callers after optimistic
|
||||
// updates or non-optimistic deletes always see the latest assignments.
|
||||
const currentAssignments = useTripStore.getState().assignments || {}
|
||||
@@ -160,32 +162,35 @@ export function useRouteCalculation(tripStore: TripStoreState, selectedDayId: nu
|
||||
const straightLines = (): [number, number][][] =>
|
||||
runsWithHotel.map(r => r.map(p => [p.lat, p.lng] as [number, number]))
|
||||
|
||||
if (runsWithHotel.length === 0) { setRoute(null); setRouteSegments([]); return }
|
||||
if (runsWithHotel.length === 0) { setRoute(null); setRouteSegments([]); setRouteVias([]); return }
|
||||
|
||||
// Draw straight lines immediately for snappiness, then upgrade to the real
|
||||
// OSRM road geometry.
|
||||
// OSRM (or plugin-provided) road geometry.
|
||||
setRoute(straightLines())
|
||||
|
||||
const tripId = useTripStore.getState().trip?.id ?? null
|
||||
const controller = new AbortController()
|
||||
routeAbortRef.current = controller
|
||||
try {
|
||||
const polylines: [number, number][][] = []
|
||||
const allLegs: RouteSegment[] = []
|
||||
const allVias: RouteVia[] = []
|
||||
for (const run of runsWithHotel) {
|
||||
try {
|
||||
const r = await calculateRouteWithLegs(run, { signal: controller.signal, profile })
|
||||
const r = await calculateRouteWithLegs(run, { signal: controller.signal, profile, tripId, dayId })
|
||||
polylines.push(r.coordinates.length >= 2 ? r.coordinates : run.map(p => [p.lat, p.lng] as [number, number]))
|
||||
allLegs.push(...r.legs)
|
||||
if (r.vias) allVias.push(...r.vias)
|
||||
} catch (err) {
|
||||
if (err instanceof Error && err.name === 'AbortError') throw err
|
||||
// OSRM failed for this run — fall back to a straight line, no times.
|
||||
// Routing failed for this run — fall back to a straight line, no times.
|
||||
polylines.push(run.map(p => [p.lat, p.lng] as [number, number]))
|
||||
}
|
||||
}
|
||||
if (!controller.signal.aborted) { setRoute(polylines); setRouteSegments(allLegs) }
|
||||
if (!controller.signal.aborted) { setRoute(polylines); setRouteSegments(allLegs); setRouteVias(allVias) }
|
||||
} catch (err: unknown) {
|
||||
// Aborted (day changed) — newer call owns the state. Anything else: keep straight lines.
|
||||
if (!(err instanceof Error) || err.name !== 'AbortError') setRouteSegments([])
|
||||
if (!(err instanceof Error) || err.name !== 'AbortError') { setRouteSegments([]); setRouteVias([]) }
|
||||
}
|
||||
}, [enabled, profile, accommodations, optimizeFromAccommodation, distanceUnit])
|
||||
|
||||
@@ -208,10 +213,10 @@ export function useRouteCalculation(tripStore: TripStoreState, selectedDayId: nu
|
||||
// Recalculate when assignments or transport positions for the SELECTED day change
|
||||
const selectedDayAssignments = selectedDayId ? tripStore.assignments?.[String(selectedDayId)] : null
|
||||
useEffect(() => {
|
||||
if (!selectedDayId) { setRoute(null); setRouteSegments([]); return }
|
||||
if (!selectedDayId) { setRoute(null); setRouteSegments([]); setRouteVias([]); return }
|
||||
updateRouteForDay(selectedDayId)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [selectedDayId, selectedDayAssignments, transportSignature, enabled, profile, accommodations, optimizeFromAccommodation, distanceUnit])
|
||||
|
||||
return { route, routeSegments, routeInfo, setRoute, setRouteInfo, updateRouteForDay }
|
||||
return { route, routeSegments, routeVias, routeInfo, setRoute, setRouteInfo, updateRouteForDay }
|
||||
}
|
||||
|
||||
@@ -562,6 +562,24 @@ input[type="number"], input[type="time"], input[type="date"], input[type="dateti
|
||||
--mood-neutral: #94928C;
|
||||
--mood-tired: #6B9BD2;
|
||||
--mood-rough: #9B8EC4;
|
||||
|
||||
/* ── Vacay "liquid glass" facelift tokens (desktop) ──────────────
|
||||
Prefixed --vg-*; only the Vacay surface consumes them. Values are
|
||||
the light palette; .dark overrides below. Kept global (not scoped)
|
||||
so the tablet sidebar drawer — which portals to <body> — still
|
||||
resolves them in dark mode. */
|
||||
--vg-ink: oklch(0.22 0.012 65);
|
||||
--vg-ink2: oklch(0.42 0.012 65);
|
||||
--vg-ink3: oklch(0.62 0.01 65);
|
||||
--vg-bg: #f8fafc;
|
||||
--vg-surf: #ffffff;
|
||||
--vg-surf2: oklch(0.968 0.003 247);
|
||||
--vg-line: oklch(0.92 0.008 70);
|
||||
--vg-line2: oklch(0.88 0.01 70);
|
||||
--vg-glass-bg: linear-gradient(135deg, oklch(1 0 0 / .72) 0%, oklch(0.99 0.006 75 / .5) 100%);
|
||||
--vg-glass-br: oklch(0.88 0.008 70 / .7);
|
||||
--vg-glass-sh: 0 1px 2px oklch(0.4 0.02 60 / .05), 0 12px 32px -14px oklch(0.3 0.02 60 / .2);
|
||||
--vg-hi: inset 0 1px 0 oklch(1 0 0 / .8);
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
@@ -630,6 +648,29 @@ input[type="number"], input[type="time"], input[type="date"], input[type="dateti
|
||||
--mood-neutral: #9a9a94;
|
||||
--mood-tired: #6db3f0;
|
||||
--mood-rough: #a9a3f0;
|
||||
|
||||
/* Vacay "liquid glass" facelift tokens (dark) */
|
||||
--vg-ink: oklch(0.96 0 0);
|
||||
--vg-ink2: oklch(0.78 0 0);
|
||||
--vg-ink3: oklch(0.6 0 0);
|
||||
--vg-bg: oklch(0.17 0 0);
|
||||
--vg-surf: oklch(0.225 0 0);
|
||||
--vg-surf2: oklch(0.255 0 0);
|
||||
--vg-line: oklch(0.32 0 0);
|
||||
--vg-line2: oklch(0.38 0 0);
|
||||
--vg-glass-bg: linear-gradient(135deg, oklch(0.31 0 0 / .58) 0%, oklch(0.25 0 0 / .42) 100%);
|
||||
--vg-glass-br: oklch(1 0 0 / .1);
|
||||
--vg-glass-sh: 0 1px 2px oklch(0 0 0 / .3), 0 12px 32px -14px oklch(0 0 0 / .55);
|
||||
--vg-hi: inset 0 1px 0 oklch(1 0 0 / .09);
|
||||
}
|
||||
|
||||
/* Vacay glass card + button helpers (consume --vg-* above). */
|
||||
.vg-card {
|
||||
background: var(--vg-glass-bg);
|
||||
border: 1px solid var(--vg-glass-br);
|
||||
box-shadow: var(--vg-glass-sh), var(--vg-hi);
|
||||
-webkit-backdrop-filter: blur(22px) saturate(1.7);
|
||||
backdrop-filter: blur(22px) saturate(1.7);
|
||||
}
|
||||
|
||||
/* ── Color schemes (data-scheme) ──────────────────────────────────
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { ReactNode } from 'react'
|
||||
import { useMatch } from 'react-router-dom'
|
||||
import BottomNav from '../components/Layout/BottomNav'
|
||||
import MBottomNav from './components/MBottomNav'
|
||||
import MToastHost from './components/MToastHost'
|
||||
import './mobile.css'
|
||||
|
||||
interface MobileShellProps {
|
||||
isPhone: boolean
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* Shell around every protected page. Below the md breakpoint it is the root
|
||||
* of the new mobile experience: scopes the --m-* design tokens, paints the
|
||||
* screen gradient, hosts the bottom dock, the sheet portal target and the
|
||||
* mobile toast presenter. From 768px up it renders the exact legacy wrapper
|
||||
* unchanged. Both branches share the div > div > children shape so pages keep
|
||||
* their state when the viewport crosses the breakpoint (rotation,
|
||||
* split-screen) instead of remounting. The content area keeps the exact
|
||||
* scroll semantics of the legacy ProtectedRoute wrapper, so not-yet-migrated
|
||||
* pages render unchanged inside.
|
||||
*/
|
||||
export default function MobileShell({ isPhone, children }: MobileShellProps) {
|
||||
// The trip planner (/trips/:id) is a full-screen takeover that ships its own
|
||||
// in-trip dock (MTripShell). The global dock must not render underneath it:
|
||||
// on iOS Safari a position:fixed nav paints THROUGH the trip overlay's higher
|
||||
// stacking context, so the wrong (global) bar shows on top of the trip screen.
|
||||
const inTripPlanner = useMatch('/trips/:id')
|
||||
|
||||
if (!isPhone) {
|
||||
return (
|
||||
<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>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="m-root flex h-dvh min-h-dvh flex-col bg-[color:var(--m-bg)] bg-[image:var(--m-scr)] text-m-ink">
|
||||
<div className="min-h-0 flex-1 overflow-y-auto">{children}</div>
|
||||
{!inTripPlanner && <MBottomNav />}
|
||||
<MToastHost />
|
||||
<div id="m-sheet-root" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useNavigate, useLocation, useMatch } from 'react-router-dom'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { ChevronRight, MoreHorizontal, Plus, Search } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { normalizeAppearance } from '@trek/shared'
|
||||
import { useNavItems, splitMobileNav } from '../../components/Layout/navItems'
|
||||
import MFab from './MFab'
|
||||
|
||||
interface NavItem { to: string; label: string; icon: LucideIcon }
|
||||
|
||||
// The centre "+" means something different per context: inside a trip it adds a
|
||||
// place, on the journey list it starts a journey (deliberate deviation from the
|
||||
// demo, which reserves the FAB for entries — the list has no journey to add
|
||||
// into yet), inside a journey it adds an entry, on the atlas it opens the
|
||||
// country search, on collections it adds a place to the active list —
|
||||
// everywhere else it creates a new trip. Pages pick the intent up from the
|
||||
// query params.
|
||||
function useCreateAction(): { label: string; run: () => void } {
|
||||
const navigate = useNavigate()
|
||||
const { t } = useTranslation()
|
||||
const inTrip = useMatch('/trips/:id')
|
||||
const inJourney = useMatch('/journey/:id')
|
||||
const onJourneyList = useMatch('/journey')
|
||||
const onAtlas = useMatch('/atlas')
|
||||
const onCollections = useMatch('/collections')
|
||||
|
||||
if (inTrip) {
|
||||
// The "+" is context-aware per active tab: Bookings → reservation,
|
||||
// Transports → transport, Costs → expense. Tabs without a create modal
|
||||
// (lists / files / collab) fall through to adding a place. #1349
|
||||
const id = inTrip.params.id
|
||||
const tripTab = typeof sessionStorage !== 'undefined' ? sessionStorage.getItem(`trip-tab-${id}`) : null
|
||||
if (tripTab === 'finanzplan') return { label: t('costs.addExpense'), run: () => navigate(`/trips/${id}?create=expense`) }
|
||||
if (tripTab === 'buchungen') return { label: t('reservations.addManual'), run: () => navigate(`/trips/${id}?create=reservation`) }
|
||||
if (tripTab === 'transports') return { label: t('transport.addManual'), run: () => navigate(`/trips/${id}?create=transport`) }
|
||||
return { label: t('places.addPlace'), run: () => navigate(`/trips/${id}?create=place`) }
|
||||
}
|
||||
if (inJourney) {
|
||||
return { label: t('journey.detail.addEntry'), run: () => navigate(`/journey/${inJourney.params.id}?create=entry`) }
|
||||
}
|
||||
if (onJourneyList) {
|
||||
return { label: t('journey.new'), run: () => navigate('/journey?create=1') }
|
||||
}
|
||||
if (onAtlas) {
|
||||
return { label: t('atlas.searchCountry'), run: () => navigate('/atlas?search=1') }
|
||||
}
|
||||
if (onCollections) {
|
||||
return { label: t('collections.addPlace'), run: () => navigate('/collections?create=place') }
|
||||
}
|
||||
return { label: t('dashboard.newTrip'), run: () => navigate('/dashboard?create=1') }
|
||||
}
|
||||
|
||||
/**
|
||||
* Floating glass dock of the mobile shell. Same tab/gating/"+" logic as the
|
||||
* legacy BottomNav (addons, ?create= contract), redesigned as the demo's icon
|
||||
* dock: 42px circles, active on the --m-act pill, Journey/Collections and page
|
||||
* plugins behind the "More" popover, and a context FAB in the middle (search
|
||||
* on the atlas, disabled logo slot on settings/admin).
|
||||
*/
|
||||
export default function MBottomNav() {
|
||||
const { t } = useTranslation()
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const create = useCreateAction()
|
||||
const [moreOpen, setMoreOpen] = useState(false)
|
||||
|
||||
// Close the popover when the route changes underneath it (browser back etc.).
|
||||
useEffect(() => setMoreOpen(false), [location.pathname])
|
||||
|
||||
// The dock split + order is user-configurable (Settings → Appearance → Mobile);
|
||||
// an un-customised account falls back to the built-in Dashboard + vacay/atlas
|
||||
// dock with everything else under "More".
|
||||
const navItems = useNavItems()
|
||||
const appearance = useSettingsStore(s => s.settings.appearance)
|
||||
const split = splitMobileNav(navItems, normalizeAppearance(appearance).mobileNav)
|
||||
|
||||
const dockItems: NavItem[] = split.bar
|
||||
const moreItems: NavItem[] = split.more
|
||||
|
||||
const isActive = (to: string) =>
|
||||
to === '/dashboard' ? location.pathname === '/dashboard' : location.pathname.startsWith(to)
|
||||
const moreActive = moreItems.some(item => isActive(item.to))
|
||||
|
||||
// The FAB gives way to a decorative logo slot on screens without an add
|
||||
// action (settings/admin, demo Z. 1372/1429).
|
||||
const logoSlot = location.pathname.startsWith('/settings') || location.pathname.startsWith('/admin')
|
||||
const searchFab = location.pathname.startsWith('/atlas')
|
||||
|
||||
// Split so the raised centre slot sits dead centre; the More slot always
|
||||
// closes the right group.
|
||||
const slotCount = dockItems.length + (moreItems.length > 0 ? 1 : 0)
|
||||
const splitAt = Math.ceil(slotCount / 2)
|
||||
const left = dockItems.slice(0, splitAt)
|
||||
const right = dockItems.slice(splitAt)
|
||||
|
||||
const circleCls = (active: boolean) =>
|
||||
`flex h-[42px] w-[42px] flex-none items-center justify-center rounded-full ${
|
||||
active ? 'bg-m-act text-m-actfg' : 'text-m-muted'
|
||||
}`
|
||||
|
||||
const renderItem = ({ to, label, icon: Icon }: NavItem) => {
|
||||
const active = isActive(to)
|
||||
// Fixed sizes per slot (demo): the dashboard grid is 18/2.1, every other
|
||||
// slot 21/1.9 — independent of the active state.
|
||||
const dash = to === '/dashboard'
|
||||
return (
|
||||
<button
|
||||
key={to}
|
||||
type="button"
|
||||
onClick={() => navigate(to)}
|
||||
aria-label={label}
|
||||
aria-current={active ? 'page' : undefined}
|
||||
className={circleCls(active)}
|
||||
>
|
||||
<Icon size={dash ? 18 : 21} strokeWidth={dash ? 2.1 : 1.9} />
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{moreOpen && (
|
||||
// Invisible scrim (the popover sits on the UI without dimming it).
|
||||
<div className="fixed inset-0 z-[60]" onClick={() => setMoreOpen(false)}>
|
||||
<div
|
||||
className="absolute left-4 right-4 flex flex-col gap-2 rounded-[26px] border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] p-[10px] shadow-[0_-8px_40px_-14px_rgba(0,0,0,.45)] backdrop-blur-[30px] backdrop-saturate-[1.8] bottom-[calc(env(safe-area-inset-bottom,0px)+86px)]"
|
||||
onClick={e => e.stopPropagation()}
|
||||
>
|
||||
{moreItems.map(({ to, label, icon: Icon }) => (
|
||||
<button
|
||||
key={to}
|
||||
type="button"
|
||||
onClick={() => { setMoreOpen(false); navigate(to) }}
|
||||
className="flex items-center gap-[13px] rounded-[18px] bg-[color:var(--m-ic)] px-4 py-[14px] text-left"
|
||||
>
|
||||
<span className="flex h-10 w-10 flex-none items-center justify-center rounded-xl bg-[color:var(--m-ic)] text-m-ink">
|
||||
<Icon size={20} strokeWidth={2} />
|
||||
</span>
|
||||
<span className="block min-w-0 flex-1 truncate text-[0.9375rem] font-extrabold text-m-ink">{label}</span>
|
||||
<ChevronRight size={17} strokeWidth={2} className="flex-none text-m-faint" />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<nav className="fixed left-4 right-4 z-40 flex h-[62px] items-center rounded-[31px] border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] px-3 shadow-[0_16px_44px_-14px_rgba(0,0,0,.35)] backdrop-blur-[30px] backdrop-saturate-[1.8] bottom-[calc(env(safe-area-inset-bottom,0px)+12px)]">
|
||||
<div className="flex min-w-0 flex-1 items-center justify-around">{left.map(renderItem)}</div>
|
||||
|
||||
{logoSlot ? (
|
||||
<span aria-hidden="true" className="mx-2 flex h-14 w-14 flex-none items-center justify-center rounded-full bg-[color:var(--m-ic)] opacity-70">
|
||||
<img src="/icons/icon-dark.svg" alt="" className="block h-6 w-6 opacity-75 dark:hidden" />
|
||||
<img src="/icons/icon-white.svg" alt="" className="hidden h-6 w-6 opacity-75 dark:block" />
|
||||
</span>
|
||||
) : (
|
||||
<MFab onClick={create.run} ariaLabel={create.label} className="mx-2">
|
||||
{searchFab ? <Search size={24} strokeWidth={2.4} /> : <Plus size={26} strokeWidth={2.4} />}
|
||||
</MFab>
|
||||
)}
|
||||
|
||||
<div className="flex min-w-0 flex-1 items-center justify-around">
|
||||
{right.map(renderItem)}
|
||||
{moreItems.length > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setMoreOpen(v => !v)}
|
||||
aria-label={t('mobileNav.more')}
|
||||
aria-expanded={moreOpen}
|
||||
aria-current={moreActive ? 'page' : undefined}
|
||||
className={circleCls(moreActive)}
|
||||
>
|
||||
<MoreHorizontal size={21} strokeWidth={1.9} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</nav>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { ReactNode } from 'react'
|
||||
|
||||
interface MChipProps {
|
||||
active?: boolean
|
||||
onClick?: () => void
|
||||
className?: string
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
/** Small pill chip: --m-act when active, neutral --m-ic surface otherwise. */
|
||||
export default function MChip({ active = false, onClick, className = '', children }: MChipProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className={`inline-flex flex-none items-center gap-[6px] rounded-full px-3 py-[7px] text-[0.75rem] font-semibold ${
|
||||
active
|
||||
? 'bg-m-act text-m-actfg'
|
||||
: 'border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] text-m-ink'
|
||||
} ${className}`}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
import { useState } from 'react'
|
||||
|
||||
/**
|
||||
* The TREK mascot — an empty-state character that IS the TREK mark: the logo is
|
||||
* the whole body, no arms, no legs. Two eyes give it life; a soft idle keeps it
|
||||
* breathing and blinking, and a ground shadow anchors it. Monochrome
|
||||
* (currentColor, theme-driven) and it holds a single pose under reduced motion.
|
||||
*
|
||||
* Two orthogonal props drive personality:
|
||||
* - `scene` picks the prop + body motion for a page (skateboard, suitcase, …).
|
||||
* - `mood` picks the facial expression (default / happy / sleepy / confused /
|
||||
* error) so loading and error states can reuse the same face. Scenes carry a
|
||||
* sensible default mood (notifications → sleepy, search → confused) that an
|
||||
* explicit `mood` overrides.
|
||||
*
|
||||
* Body motion (`.trek-bounce--<scene>`) and each prop animate independently, so
|
||||
* the mascot can react to a prop without the prop moving with it. Choreography
|
||||
* lives in mobile.css (.trek-*). Poking (tap) remounts the svg to replay the
|
||||
* entrance pop-in as a bounce.
|
||||
*/
|
||||
export type TrekScene =
|
||||
| 'idle'
|
||||
| 'chat'
|
||||
| 'transport'
|
||||
| 'bookings'
|
||||
| 'guide'
|
||||
| 'packing'
|
||||
| 'files'
|
||||
| 'notes'
|
||||
| 'polls'
|
||||
| 'journey'
|
||||
| 'collections'
|
||||
| 'dashboard'
|
||||
| 'atlas'
|
||||
| 'notifications'
|
||||
| 'costs'
|
||||
| 'search'
|
||||
| 'tasks'
|
||||
|
||||
export type TrekMood = 'default' | 'happy' | 'sleepy' | 'confused' | 'error'
|
||||
|
||||
const MARK =
|
||||
'M 855.636719 699.203125 L 222.246094 699.203125 C 197.679688 699.203125 179.90625 675.75 186.539062 652.101562 L 360.429688 32.390625 C 364.921875 16.386719 379.511719 5.328125 396.132812 5.328125 L 1029.527344 5.328125 C 1054.089844 5.328125 1071.867188 28.777344 1065.230469 52.429688 L 891.339844 672.136719 C 886.851562 688.140625 872.257812 699.203125 855.636719 699.203125 Z M 444.238281 1166.980469 L 533.773438 847.898438 C 540.410156 824.246094 522.632812 800.796875 498.070312 800.796875 L 172.472656 800.796875 C 155.851562 800.796875 141.261719 811.855469 136.769531 827.859375 L 47.234375 1146.941406 C 40.597656 1170.59375 58.375 1194.042969 82.9375 1194.042969 L 408.535156 1194.042969 C 425.15625 1194.042969 439.75 1182.984375 444.238281 1166.980469 Z M 609.003906 827.859375 L 435.113281 1447.570312 C 428.476562 1471.21875 446.253906 1494.671875 470.816406 1494.671875 L 1104.210938 1494.671875 C 1120.832031 1494.671875 1135.421875 1483.609375 1139.914062 1467.605469 L 1313.804688 847.898438 C 1320.441406 824.246094 1302.664062 800.796875 1278.101562 800.796875 L 644.707031 800.796875 C 628.085938 800.796875 613.492188 811.855469 609.003906 827.859375 Z M 1056.105469 333.019531 L 966.570312 652.101562 C 959.933594 675.75 977.710938 699.203125 1002.273438 699.203125 L 1327.871094 699.203125 C 1344.492188 699.203125 1359.085938 688.140625 1363.574219 672.136719 L 1453.109375 353.054688 C 1459.746094 329.40625 1441.96875 305.953125 1417.40625 305.953125 L 1091.808594 305.953125 C 1075.1875 305.953125 1060.597656 317.015625 1056.105469 333.019531 Z'
|
||||
|
||||
const SCENE_MOOD: Partial<Record<TrekScene, TrekMood>> = {
|
||||
notifications: 'sleepy',
|
||||
search: 'confused',
|
||||
}
|
||||
|
||||
export default function MDancingTrek({
|
||||
size = 96,
|
||||
scene = 'idle',
|
||||
mood,
|
||||
className = '',
|
||||
}: {
|
||||
size?: number
|
||||
scene?: TrekScene
|
||||
mood?: TrekMood
|
||||
className?: string
|
||||
}) {
|
||||
const face = mood ?? SCENE_MOOD[scene] ?? 'default'
|
||||
// Ground shadow sits under whatever the mascot stands on this scene.
|
||||
const shadowCy = scene === 'transport' ? 86 : 73
|
||||
// Poke to react: remounting the svg replays the entrance pop-in as a tap bounce.
|
||||
const [poke, setPoke] = useState(0)
|
||||
return (
|
||||
<svg
|
||||
key={poke}
|
||||
onClick={() => setPoke(p => p + 1)}
|
||||
width={size}
|
||||
height={(size * 96) / 88}
|
||||
viewBox="0 0 88 96"
|
||||
fill="none"
|
||||
aria-hidden="true"
|
||||
className={`trek trek--${scene} cursor-pointer text-m-ink ${className}`}
|
||||
>
|
||||
<ellipse className="trek-shadow" cx="44" cy={shadowCy} rx="19" ry="3.4" fill="currentColor" />
|
||||
<g className="trek-root">
|
||||
{/* scene prop behind / under the body — animates on its own */}
|
||||
<SceneBack scene={scene} />
|
||||
|
||||
{/* body = the TREK mark, with its own per-scene bounce (hop, nod, …) */}
|
||||
<g className={`trek-bounce trek-bounce--${scene}`}>
|
||||
<g className="trek-body">
|
||||
<g transform="translate(20.5 21.7) scale(0.0313)">
|
||||
<path fill="currentColor" d={MARK} />
|
||||
</g>
|
||||
<Eyes mood={face} />
|
||||
</g>
|
||||
</g>
|
||||
|
||||
{/* scene prop in front of the body — animates on its own */}
|
||||
<SceneFront scene={scene} />
|
||||
</g>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
/* ── Eyes ────────────────────────────────────────────────────────────────────
|
||||
Default eyes are surface-colour cutouts with ink pupils that blink and glance.
|
||||
Expression eyes are cut into the body as m-bg strokes so they read on the
|
||||
monochrome mark. */
|
||||
|
||||
function Eyes({ mood }: { mood: TrekMood }) {
|
||||
if (mood === 'happy') {
|
||||
return (
|
||||
<g fill="none" stroke="var(--m-bg)" strokeWidth="1.8" strokeLinecap="round">
|
||||
<path d="M33.7 34 Q36 31.2 38.3 34" />
|
||||
<path d="M42.7 34 Q45 31.2 47.3 34" />
|
||||
</g>
|
||||
)
|
||||
}
|
||||
if (mood === 'sleepy') {
|
||||
return (
|
||||
<g fill="none" stroke="var(--m-bg)" strokeWidth="1.8" strokeLinecap="round">
|
||||
<path d="M33.7 33 Q36 34.4 38.3 33" />
|
||||
<path d="M42.7 33 Q45 34.4 47.3 33" />
|
||||
</g>
|
||||
)
|
||||
}
|
||||
if (mood === 'error') {
|
||||
return (
|
||||
<g stroke="var(--m-bg)" strokeWidth="1.6" strokeLinecap="round">
|
||||
<path d="M34.4 31.4 L37.6 34.6 M37.6 31.4 L34.4 34.6" />
|
||||
<path d="M43.4 31.4 L46.6 34.6 M46.6 31.4 L43.4 34.6" />
|
||||
</g>
|
||||
)
|
||||
}
|
||||
if (mood === 'confused') {
|
||||
// one eye open, one a raised squint — reads puzzled
|
||||
return (
|
||||
<g className="trek-eyes">
|
||||
<circle className="trek-eye" cx="36" cy="33" r="2.3" />
|
||||
<circle cx="36.4" cy="33.3" r="1" fill="currentColor" />
|
||||
<path d="M42.7 32.6 Q45 31.4 47.3 32.6" fill="none" stroke="var(--m-bg)" strokeWidth="1.8" strokeLinecap="round" />
|
||||
</g>
|
||||
)
|
||||
}
|
||||
// default — open eyes that blink and glance around
|
||||
return (
|
||||
<g className="trek-eyes">
|
||||
<circle className="trek-eye" cx="36" cy="33" r="2.3" />
|
||||
<circle className="trek-eye" cx="45" cy="33" r="2.3" />
|
||||
<g className="trek-pupils">
|
||||
<circle cx="36.4" cy="33.3" r="1" fill="currentColor" />
|
||||
<circle cx="45.4" cy="33.3" r="1" fill="currentColor" />
|
||||
</g>
|
||||
</g>
|
||||
)
|
||||
}
|
||||
|
||||
/* ── Scene props ─────────────────────────────────────────────────────────────
|
||||
Monochrome props built from a few shapes. Animated elements never carry a
|
||||
`transform` attribute (a CSS-animation transform would override it) — any
|
||||
static rotation lives on a wrapping <g transform=…> instead. */
|
||||
|
||||
function SceneBack({ scene }: { scene: TrekScene }) {
|
||||
switch (scene) {
|
||||
case 'transport':
|
||||
// skateboard under the body — deck + two wheels spinning in place
|
||||
return (
|
||||
<g className="trek-board">
|
||||
<rect x="24" y="72" width="40" height="4" rx="2" fill="currentColor" />
|
||||
<g className="trek-wheel">
|
||||
<circle cx="32" cy="79" r="3.1" fill="currentColor" />
|
||||
<circle cx="32" cy="79" r="1.1" fill="var(--m-bg)" />
|
||||
</g>
|
||||
<g className="trek-wheel">
|
||||
<circle cx="56" cy="79" r="3.1" fill="currentColor" />
|
||||
<circle cx="56" cy="79" r="1.1" fill="var(--m-bg)" />
|
||||
</g>
|
||||
</g>
|
||||
)
|
||||
case 'guide':
|
||||
// tall staff with a big pennant fluttering near the top
|
||||
return (
|
||||
<g className="trek-guide">
|
||||
<rect x="70.4" y="26" width="2.6" height="56" rx="1.3" fill="currentColor" />
|
||||
<circle cx="71.7" cy="26" r="2.1" fill="currentColor" />
|
||||
<g className="trek-flag">
|
||||
<path d="M73 25 L90 30.5 L73 40 Z" fill="currentColor" />
|
||||
</g>
|
||||
</g>
|
||||
)
|
||||
case 'packing':
|
||||
// rolling suitcase parked beside the body — rocks on its wheels,
|
||||
// handle telescoping up and down
|
||||
return (
|
||||
<g className="trek-suitcase">
|
||||
<g className="trek-handle">
|
||||
<path d="M69 55 Q73 47.5 77 55" stroke="currentColor" strokeWidth="2" fill="none" strokeLinecap="round" />
|
||||
</g>
|
||||
<rect x="62" y="54" width="21" height="18" rx="3" fill="currentColor" />
|
||||
<rect x="62" y="60" width="21" height="2.2" fill="var(--m-bg)" />
|
||||
<rect x="70.5" y="56.4" width="4" height="2.2" rx="1" fill="var(--m-bg)" />
|
||||
<g className="trek-wheel">
|
||||
<circle cx="66" cy="73.4" r="2" fill="currentColor" />
|
||||
</g>
|
||||
<g className="trek-wheel">
|
||||
<circle cx="79" cy="73.4" r="2" fill="currentColor" />
|
||||
</g>
|
||||
</g>
|
||||
)
|
||||
case 'polls':
|
||||
// vote bars gently rising and settling like live tallies
|
||||
return (
|
||||
<g className="trek-polls">
|
||||
<rect className="trek-bar" x="66" y="60" width="5" height="12" rx="1.5" fill="currentColor" />
|
||||
<rect className="trek-bar trek-d2" x="73" y="52" width="5" height="20" rx="1.5" fill="currentColor" />
|
||||
<rect className="trek-bar trek-d3" x="80" y="56" width="5" height="16" rx="1.5" fill="currentColor" />
|
||||
</g>
|
||||
)
|
||||
case 'collections':
|
||||
// a map pin dropping in and bouncing beside the body
|
||||
return (
|
||||
<g className="trek-pin">
|
||||
<path d="M73 48 C 78 48 81.5 51.6 81.5 56.4 C 81.5 61.6 76 66 73 70 C 70 66 64.5 61.6 64.5 56.4 C 64.5 51.6 68 48 73 48 Z" fill="currentColor" />
|
||||
<circle cx="73" cy="56.2" r="2.9" fill="var(--m-bg)" />
|
||||
</g>
|
||||
)
|
||||
case 'atlas':
|
||||
// a globe beside the body, meridians drifting
|
||||
return (
|
||||
<g className="trek-globe-wrap">
|
||||
<circle cx="73" cy="60" r="11" fill="currentColor" />
|
||||
<path d="M63 57 H83 M64.5 64.5 H81.5" stroke="var(--m-bg)" strokeWidth="1.2" strokeLinecap="round" />
|
||||
<ellipse className="trek-globe" cx="73" cy="60" rx="4.6" ry="11" fill="none" stroke="var(--m-bg)" strokeWidth="1.2" />
|
||||
</g>
|
||||
)
|
||||
case 'costs':
|
||||
// a stack of coins beside the body, top one bouncing on
|
||||
return (
|
||||
<g className="trek-coins">
|
||||
<ellipse cx="74" cy="70" rx="9" ry="3.2" fill="currentColor" />
|
||||
<ellipse cx="74" cy="66" rx="9" ry="3.2" fill="currentColor" />
|
||||
<ellipse cx="74" cy="66" rx="9" ry="3.2" fill="none" stroke="var(--m-bg)" strokeWidth="1" />
|
||||
<g className="trek-coin">
|
||||
<ellipse cx="74" cy="61.5" rx="9" ry="3.2" fill="currentColor" />
|
||||
<rect x="72.7" y="58.6" width="2.6" height="5.8" rx="1.3" fill="var(--m-bg)" />
|
||||
</g>
|
||||
</g>
|
||||
)
|
||||
case 'chat':
|
||||
// a speech bubble beside the body with three typing dots pulsing in turn
|
||||
return (
|
||||
<g className="trek-chat">
|
||||
<rect x="60" y="44" width="26" height="15" rx="5.5" fill="currentColor" />
|
||||
<path d="M67 58 L63.5 64 L72 58.5 Z" fill="currentColor" />
|
||||
<circle className="trek-dot" cx="67" cy="51.5" r="1.9" fill="var(--m-bg)" />
|
||||
<circle className="trek-dot trek-d2" cx="73" cy="51.5" r="1.9" fill="var(--m-bg)" />
|
||||
<circle className="trek-dot trek-d3" cx="79" cy="51.5" r="1.9" fill="var(--m-bg)" />
|
||||
</g>
|
||||
)
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function SceneFront({ scene }: { scene: TrekScene }) {
|
||||
switch (scene) {
|
||||
// Files reuse the booking ticket per design — a card getting written on.
|
||||
case 'bookings':
|
||||
case 'files':
|
||||
return (
|
||||
<g className="trek-ticket">
|
||||
<g transform="rotate(7 70 54)">
|
||||
<rect x="60" y="41" width="20" height="26" rx="2.6" fill="currentColor" />
|
||||
<circle cx="70.5" cy="46.5" r="1.5" fill="var(--m-bg)" />
|
||||
<rect x="64" y="51" width="12" height="2.6" rx="1.3" fill="var(--m-bg)" />
|
||||
<rect className="trek-write" x="64" y="56.5" width="12" height="1.7" rx="0.85" fill="var(--m-bg)" />
|
||||
<rect className="trek-write trek-d2" x="64" y="60" width="12" height="1.7" rx="0.85" fill="var(--m-bg)" />
|
||||
<rect className="trek-write trek-d3" x="64" y="63.5" width="7" height="1.7" rx="0.85" fill="var(--m-bg)" />
|
||||
</g>
|
||||
</g>
|
||||
)
|
||||
case 'notes':
|
||||
// a paper note (surface colour) with ink lines being written and a
|
||||
// scribbling pencil — pencil is ink (light in dark theme, dark in light)
|
||||
return (
|
||||
<g className="trek-note">
|
||||
<g transform="rotate(5 70 55)">
|
||||
<rect x="60" y="44" width="20" height="24" rx="2.5" fill="var(--m-bg)" stroke="currentColor" strokeWidth="1.4" />
|
||||
<rect className="trek-write" x="63.5" y="50" width="13" height="1.7" rx="0.85" fill="currentColor" />
|
||||
<rect className="trek-write trek-d2" x="63.5" y="54.5" width="13" height="1.7" rx="0.85" fill="currentColor" />
|
||||
<rect className="trek-write trek-d3" x="63.5" y="59" width="8" height="1.7" rx="0.85" fill="currentColor" />
|
||||
</g>
|
||||
<g className="trek-pencil">
|
||||
{/* body + tip modelled vertically as one piece, then leaned together
|
||||
so the point always stays attached to the shaft */}
|
||||
<g transform="rotate(34 74.5 52)">
|
||||
<rect x="73" y="40" width="3" height="16" rx="1.3" fill="currentColor" />
|
||||
<path d="M73 56 L76 56 L74.5 60.5 Z" fill="currentColor" />
|
||||
</g>
|
||||
</g>
|
||||
</g>
|
||||
)
|
||||
case 'journey':
|
||||
// an open book with a fluttering page and a ribbon bookmark
|
||||
return (
|
||||
<g className="trek-journal">
|
||||
<path d="M58 53 Q71 49.5 71 52 L71 69 Q71 66.5 58 70 Z" fill="currentColor" />
|
||||
<path d="M84 53 Q71 49.5 71 52 L71 69 Q71 66.5 84 70 Z" fill="currentColor" />
|
||||
<path d="M60.5 56 Q66 54 70 55.5 M60.5 60 Q66 58 70 59.5 M60.5 64 Q66 62 70 63.5" stroke="var(--m-bg)" strokeWidth="1" fill="none" strokeLinecap="round" />
|
||||
<path d="M76 55.4 Q80 54 83 55.6 M76 59.4 Q80 58 83 59.6" stroke="var(--m-bg)" strokeWidth="1" fill="none" strokeLinecap="round" />
|
||||
<g className="trek-page">
|
||||
<path d="M71 52 Q78 50.5 82 52 L82 68.5 Q78 67 71 68.5 Z" fill="currentColor" />
|
||||
<path d="M74 55.4 Q78 54.2 81 55.6 M74 59.4 Q78 58.2 81 59.6" stroke="var(--m-bg)" strokeWidth="1" fill="none" strokeLinecap="round" />
|
||||
</g>
|
||||
<rect x="70" y="49.5" width="2.2" height="9" fill="var(--m-bg)" />
|
||||
</g>
|
||||
)
|
||||
case 'dashboard':
|
||||
// a little paper plane looping around, ready for a first trip
|
||||
return (
|
||||
<g className="trek-plane">
|
||||
<path d="M64 53 L87 58 L70 68 L71 60 Z" fill="currentColor" />
|
||||
<path d="M87 58 L71 60 L70 68" stroke="var(--m-bg)" strokeWidth="0.9" fill="none" strokeLinejoin="round" />
|
||||
</g>
|
||||
)
|
||||
case 'notifications':
|
||||
// all caught up — a stack of Zzz drifting up while the mascot dozes
|
||||
return (
|
||||
<g className="trek-zzz" fill="currentColor">
|
||||
<path className="trek-z trek-z1" d="M63 50 h5 l-5 6 h5" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round" strokeLinecap="round" />
|
||||
<path className="trek-z trek-z2" d="M69 42 h6 l-6 7 h6" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round" strokeLinecap="round" />
|
||||
<path className="trek-z trek-z3" d="M76 32 h7 l-7 8 h7" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round" strokeLinecap="round" />
|
||||
</g>
|
||||
)
|
||||
case 'search':
|
||||
// a magnifying glass scanning back and forth
|
||||
return (
|
||||
<g className="trek-magnifier">
|
||||
<circle cx="72" cy="56" r="8" fill="none" stroke="currentColor" strokeWidth="2.4" />
|
||||
<circle cx="72" cy="56" r="5.4" fill="var(--m-bg)" />
|
||||
<rect x="77" y="62.5" width="3" height="10" rx="1.5" fill="currentColor" transform="rotate(-45 78.5 67.5)" />
|
||||
</g>
|
||||
)
|
||||
case 'tasks':
|
||||
// a clipboard checklist with a checkmark ticking on
|
||||
return (
|
||||
<g className="trek-tasks">
|
||||
<g transform="rotate(4 71 55)">
|
||||
<rect x="60" y="43" width="22" height="25" rx="2.6" fill="currentColor" />
|
||||
<rect x="67" y="41" width="8" height="3.4" rx="1.7" fill="currentColor" />
|
||||
<rect x="63.5" y="48.4" width="4" height="4" rx="1" fill="var(--m-bg)" />
|
||||
<rect x="69.5" y="49.6" width="9" height="1.7" rx="0.85" fill="var(--m-bg)" />
|
||||
<rect x="63.5" y="55" width="4" height="4" rx="1" fill="var(--m-bg)" />
|
||||
<rect x="69.5" y="56.2" width="9" height="1.7" rx="0.85" fill="var(--m-bg)" />
|
||||
<rect x="63.5" y="61.6" width="4" height="4" rx="1" fill="var(--m-bg)" />
|
||||
<rect x="69.5" y="62.8" width="6" height="1.7" rx="0.85" fill="var(--m-bg)" />
|
||||
<path className="trek-check" d="M64 50.5 l1.3 1.4 l2.2 -2.7" fill="none" stroke="currentColor" strokeWidth="1.1" strokeLinecap="round" strokeLinejoin="round" />
|
||||
</g>
|
||||
</g>
|
||||
)
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { ReactNode } from 'react'
|
||||
|
||||
interface MDropdownPanelProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
/** Positioning classes (e.g. `top-[100px] right-4`); panel is fixed. */
|
||||
className?: string
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
/**
|
||||
* Floating popover panel (user menu, filter dropdowns): heavy glass, r20,
|
||||
* closed by a transparent full-screen backdrop — no dim, unlike sheets.
|
||||
* Layered above the scrolling content but below the bottom nav (z-40) and
|
||||
* sheets (z-60), matching the design's stacking order.
|
||||
*/
|
||||
export default function MDropdownPanel({ open, onClose, className = '', children }: MDropdownPanelProps) {
|
||||
if (!open) return null
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="fixed inset-0 z-[35]" onClick={onClose} />
|
||||
<div
|
||||
className={`m-pop-in fixed z-[36] w-[228px] rounded-[20px] border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] p-[6px] text-m-ink shadow-[0_24px_60px_-20px_rgba(0,0,0,.5)] backdrop-blur-[30px] backdrop-saturate-[1.8] ${className}`}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { ReactNode } from 'react'
|
||||
|
||||
interface MFabProps {
|
||||
onClick?: () => void
|
||||
ariaLabel: string
|
||||
className?: string
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
/** 56px round action button on the --m-act surface (bottom-nav "+", screen FABs). */
|
||||
export default function MFab({ onClick, ariaLabel, className = '', children }: MFabProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
aria-label={ariaLabel}
|
||||
className={`flex h-14 w-14 flex-none items-center justify-center rounded-full bg-m-act text-m-actfg shadow-[0_8px_20px_-6px_rgba(0,0,0,.4)] ${className}`}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { ReactNode } from 'react'
|
||||
|
||||
interface MGlassBarProps {
|
||||
/** Pins the bar below the status bar (default). Pass false to embed it in flow. */
|
||||
floating?: boolean
|
||||
className?: string
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
/** Top bar glass pill: blur 26 / saturate 1.7 on --m-glass with --m-gbr border. */
|
||||
export default function MGlassBar({ floating = true, className = '', children }: MGlassBarProps) {
|
||||
return (
|
||||
<div
|
||||
className={`flex items-center gap-[11px] rounded-full border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)] px-[14px] py-2 backdrop-blur-[26px] backdrop-saturate-[1.7] shadow-[0_14px_34px_-16px_rgba(0,0,0,.22)] ${
|
||||
floating ? 'fixed left-4 right-4 top-[var(--m-safe-top,12px)] z-30' : ''
|
||||
} ${className}`}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { ReactNode } from 'react'
|
||||
|
||||
interface MIconBtnProps {
|
||||
onClick?: () => void
|
||||
ariaLabel: string
|
||||
/** glass = topbar-style glass circle, neutral = flat --m-ic circle (sheet close) */
|
||||
variant?: 'glass' | 'neutral'
|
||||
/** Diameter in px (topbar 38, sheet close 34) */
|
||||
size?: number
|
||||
className?: string
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
/** Round icon button used in the top bar (glass) and sheet headers (neutral). */
|
||||
export default function MIconBtn({
|
||||
onClick,
|
||||
ariaLabel,
|
||||
variant = 'glass',
|
||||
size = 38,
|
||||
className = '',
|
||||
children,
|
||||
}: MIconBtnProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
aria-label={ariaLabel}
|
||||
className={`relative flex flex-none items-center justify-center rounded-full text-m-ink ${
|
||||
variant === 'glass'
|
||||
? 'border border-[color:var(--m-gbr)] bg-[color:var(--m-glass)]'
|
||||
: 'bg-[color:var(--m-ic)]'
|
||||
} ${className}`}
|
||||
style={{ width: size, height: size }}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { ReactNode } from 'react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
|
||||
interface MListRowProps {
|
||||
label: ReactNode
|
||||
icon?: LucideIcon
|
||||
trailing?: ReactNode
|
||||
danger?: boolean
|
||||
onClick?: () => void
|
||||
className?: string
|
||||
}
|
||||
|
||||
/** Menu/list row (user menu style): icon 16 in --m-muted, 13.5px semibold label. */
|
||||
export default function MListRow({
|
||||
label,
|
||||
icon: Icon,
|
||||
trailing,
|
||||
danger = false,
|
||||
onClick,
|
||||
className = '',
|
||||
}: MListRowProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className={`flex w-full items-center gap-[11px] rounded-xl px-[10px] py-[11px] text-left text-[0.84375rem] font-semibold active:bg-[color:var(--m-ic)] ${
|
||||
danger ? 'text-[color:var(--m-st-danger)]' : 'text-m-ink'
|
||||
} ${className}`}
|
||||
>
|
||||
{Icon && <Icon size={16} strokeWidth={2} className={danger ? '' : 'text-m-muted'} />}
|
||||
<span className="min-w-0 flex-1 truncate">{label}</span>
|
||||
{trailing}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
interface MProgressProps {
|
||||
/** 0–100 */
|
||||
value: number
|
||||
/** Optional data-driven fill color (bag/category colors); defaults to --m-act. */
|
||||
color?: string
|
||||
/** Bar height in px: 5 is the --m-ic track canon, 4 the spotlight bar, 6 the bag bar. */
|
||||
height?: 4 | 5 | 6
|
||||
className?: string
|
||||
}
|
||||
|
||||
const HEIGHT: Record<4 | 5 | 6, string> = {
|
||||
4: 'h-[4px]',
|
||||
5: 'h-[5px]',
|
||||
6: 'h-[6px]',
|
||||
}
|
||||
|
||||
/** Thin progress bar on the neutral --m-ic track. */
|
||||
export default function MProgress({ value, color, height = 5, className = '' }: MProgressProps) {
|
||||
const clamped = Math.max(0, Math.min(100, value))
|
||||
return (
|
||||
<div className={`${HEIGHT[height]} w-full overflow-hidden rounded-full bg-[color:var(--m-ic)] ${className}`}>
|
||||
<div
|
||||
className="h-full rounded-full bg-m-act"
|
||||
style={{ width: `${clamped}%`, ...(color ? { background: color } : undefined) }}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { ReactNode, useLayoutEffect, useRef, useState } from 'react'
|
||||
|
||||
export interface MSegmentedOption<T extends string = string> {
|
||||
value: T
|
||||
label: ReactNode
|
||||
}
|
||||
|
||||
interface MSegmentedProps<T extends string = string> {
|
||||
options: MSegmentedOption<T>[]
|
||||
value: T
|
||||
onChange: (value: T) => void
|
||||
/** stretch = equal-width segments (costs tabs), intrinsic = pill hugs its label (dashboard filter) */
|
||||
variant?: 'stretch' | 'intrinsic'
|
||||
className?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Segment pill with a sliding active indicator. Active segment reads in
|
||||
* --m-actfg on the --m-act pill, idle segments in --m-ink (Spec 07 §6).
|
||||
*/
|
||||
export default function MSegmented<T extends string = string>({
|
||||
options,
|
||||
value,
|
||||
onChange,
|
||||
variant = 'stretch',
|
||||
className = '',
|
||||
}: MSegmentedProps<T>) {
|
||||
const trackRef = useRef<HTMLDivElement>(null)
|
||||
const [indicator, setIndicator] = useState<{ left: number; width: number } | null>(null)
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const track = trackRef.current
|
||||
if (!track) return
|
||||
const measure = () => {
|
||||
const active = track.querySelector<HTMLElement>('[data-active="true"]')
|
||||
if (active) setIndicator({ left: active.offsetLeft, width: active.offsetWidth })
|
||||
}
|
||||
measure()
|
||||
const ro = new ResizeObserver(measure)
|
||||
ro.observe(track)
|
||||
return () => ro.disconnect()
|
||||
}, [value, options.length])
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={trackRef}
|
||||
role="tablist"
|
||||
className={`relative flex rounded-full bg-[color:var(--m-ic)] p-[3px] ${className}`}
|
||||
>
|
||||
{indicator && (
|
||||
<div
|
||||
className="absolute top-[3px] bottom-[3px] rounded-full bg-m-act transition-[left,width] duration-[280ms] ease-[var(--ease-drawer)]"
|
||||
style={{ left: indicator.left, width: indicator.width }}
|
||||
/>
|
||||
)}
|
||||
{options.map((opt) => {
|
||||
const active = opt.value === value
|
||||
return (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={active}
|
||||
data-active={active}
|
||||
onClick={() => onChange(opt.value)}
|
||||
className={`relative z-[1] rounded-full py-[7px] text-center ${
|
||||
variant === 'intrinsic'
|
||||
? 'whitespace-nowrap px-[13px] text-[0.75rem]'
|
||||
: 'flex-1 text-[0.71875rem]'
|
||||
} ${active ? 'font-semibold text-m-actfg' : 'font-medium text-m-ink'}`}
|
||||
>
|
||||
{opt.label}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
import React, { ReactNode, useEffect, useRef, useState } from 'react'
|
||||
import ReactDOM from 'react-dom'
|
||||
|
||||
export type MSheetVariant = 'card' | 'bottom' | 'drawer'
|
||||
export type MSheetMaterial = 'glass' | 'bar-glass' | 'opaque'
|
||||
|
||||
interface MSheetProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
/** card = centred floating card, bottom = docked panel above the nav, drawer = left drawer */
|
||||
variant?: MSheetVariant
|
||||
/**
|
||||
* glass = translucent sheet (--m-sheet), bar-glass = lighter bar glass
|
||||
* (--m-glass, default for the bottom variant), opaque = solid (--m-sheetop)
|
||||
*/
|
||||
material?: MSheetMaterial
|
||||
/** Transparent scrim (the "Mehr" sheet sits on the UI without dimming it) */
|
||||
dimTransparent?: boolean
|
||||
ariaLabel?: string
|
||||
className?: string
|
||||
children?: ReactNode
|
||||
}
|
||||
|
||||
const EXIT_MS = 280
|
||||
|
||||
const FOCUSABLE =
|
||||
'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'
|
||||
|
||||
const POSITION: Record<MSheetVariant, string> = {
|
||||
card: 'absolute left-[14px] right-[14px] top-1/2 -translate-y-1/2',
|
||||
bottom: 'absolute left-4 right-4 bottom-[calc(var(--bottom-nav-h,84px)+16px)]',
|
||||
drawer: 'absolute left-0 top-0 bottom-0 w-[78%] max-w-[320px]',
|
||||
}
|
||||
|
||||
const SHAPE: Record<MSheetVariant, string> = {
|
||||
card: 'rounded-[28px] shadow-[0_30px_80px_-24px_rgba(0,0,0,.6)] max-h-[calc(100dvh-var(--m-safe-top,12px)-96px)]',
|
||||
bottom: 'rounded-[26px] shadow-[0_-8px_40px_-14px_rgba(0,0,0,.45)] max-h-[calc(100dvh-var(--bottom-nav-h,84px)-var(--m-safe-top,12px)-72px)]',
|
||||
drawer: 'h-full shadow-[0_0_60px_-10px_rgba(0,0,0,.5)]',
|
||||
}
|
||||
|
||||
// Deliberate normalisation: the demo borders a few opaque sheets (journey
|
||||
// create/entry/settings, drawer) with --rowbr instead of --shbr; both hairlines
|
||||
// are near-identical on the solid sheet surface, so every material keeps one
|
||||
// border token here.
|
||||
const MATERIAL: Record<MSheetMaterial, string> = {
|
||||
glass:
|
||||
'bg-[color:var(--m-sheet)] backdrop-blur-[40px] backdrop-saturate-[1.8] border border-[color:var(--m-shbr)]',
|
||||
'bar-glass':
|
||||
'bg-[color:var(--m-glass)] backdrop-blur-[30px] backdrop-saturate-[1.8] border border-[color:var(--m-gbr)]',
|
||||
opaque: 'bg-[color:var(--m-sheetop)] border border-[color:var(--m-shbr)]',
|
||||
}
|
||||
|
||||
function sheetRoot(): HTMLElement {
|
||||
return document.getElementById('m-sheet-root') ?? document.body
|
||||
}
|
||||
|
||||
// Body scroll lock shared across stacked sheets: only the first lock saves the
|
||||
// original overflow and only the last unlock restores it.
|
||||
let scrollLocks = 0
|
||||
let savedBodyOverflow = ''
|
||||
|
||||
function lockBodyScroll() {
|
||||
if (scrollLocks === 0) {
|
||||
savedBodyOverflow = document.body.style.overflow
|
||||
document.body.style.overflow = 'hidden'
|
||||
}
|
||||
scrollLocks++
|
||||
}
|
||||
|
||||
function unlockBodyScroll() {
|
||||
scrollLocks = Math.max(0, scrollLocks - 1)
|
||||
if (scrollLocks === 0) document.body.style.overflow = savedBodyOverflow
|
||||
}
|
||||
|
||||
/**
|
||||
* The one sheet primitive of the mobile design system. Handles portal,
|
||||
* scrim, ESC/backdrop dismissal, body scroll lock, focus trapping, 280ms
|
||||
* enter/exit and — for the bottom variant — drag-to-dismiss on the top edge.
|
||||
*/
|
||||
export default function MSheet({
|
||||
open,
|
||||
onClose,
|
||||
variant = 'card',
|
||||
material,
|
||||
dimTransparent = false,
|
||||
ariaLabel,
|
||||
className = '',
|
||||
children,
|
||||
}: MSheetProps) {
|
||||
const [rendered, setRendered] = useState(open)
|
||||
// Once the enter animation has played it is removed again: its forwards
|
||||
// fill would otherwise override the inline drag transform for good.
|
||||
const [entered, setEntered] = useState(false)
|
||||
const [dragY, setDragY] = useState<number | null>(null)
|
||||
const panelRef = useRef<HTMLDivElement>(null)
|
||||
const dragRef = useRef<{ startY: number; lastY: number; lastT: number; velocity: number } | null>(null)
|
||||
|
||||
// Keep the sheet mounted through the exit animation.
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setRendered(true)
|
||||
return
|
||||
}
|
||||
setEntered(false)
|
||||
setDragY(null)
|
||||
const t = setTimeout(() => setRendered(false), EXIT_MS)
|
||||
return () => clearTimeout(t)
|
||||
}, [open])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') onClose()
|
||||
}
|
||||
document.addEventListener('keydown', onKey)
|
||||
return () => document.removeEventListener('keydown', onKey)
|
||||
}, [open, onClose])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
lockBodyScroll()
|
||||
return unlockBodyScroll
|
||||
}, [open])
|
||||
|
||||
// Move focus into the dialog on open, hand it back on close.
|
||||
useEffect(() => {
|
||||
if (!open || !rendered) return
|
||||
const previous = document.activeElement as HTMLElement | null
|
||||
panelRef.current?.focus()
|
||||
return () => previous?.focus()
|
||||
}, [open, rendered])
|
||||
|
||||
if (!rendered) return null
|
||||
|
||||
const handlePointerDown = (e: React.PointerEvent) => {
|
||||
;(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId)
|
||||
dragRef.current = { startY: e.clientY, lastY: e.clientY, lastT: e.timeStamp, velocity: 0 }
|
||||
setDragY(0)
|
||||
}
|
||||
|
||||
const handlePointerMove = (e: React.PointerEvent) => {
|
||||
const d = dragRef.current
|
||||
if (!d) return
|
||||
d.velocity = (e.clientY - d.lastY) / Math.max(1, e.timeStamp - d.lastT)
|
||||
d.lastY = e.clientY
|
||||
d.lastT = e.timeStamp
|
||||
setDragY(Math.max(0, e.clientY - d.startY))
|
||||
}
|
||||
|
||||
const handlePointerEnd = () => {
|
||||
const d = dragRef.current
|
||||
if (!d) return
|
||||
dragRef.current = null
|
||||
const height = panelRef.current?.offsetHeight ?? 0
|
||||
const dy = Math.max(0, d.lastY - d.startY)
|
||||
setDragY(null)
|
||||
// Past 30% of the panel or a decisive flick → dismiss.
|
||||
if ((height > 0 && dy > height * 0.3) || d.velocity > 0.6) onClose()
|
||||
}
|
||||
|
||||
// Keep Tab inside the dialog while it is open.
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key !== 'Tab') return
|
||||
const panel = panelRef.current
|
||||
if (!panel) return
|
||||
const focusable = panel.querySelectorAll<HTMLElement>(FOCUSABLE)
|
||||
if (focusable.length === 0) {
|
||||
e.preventDefault()
|
||||
return
|
||||
}
|
||||
const first = focusable[0]
|
||||
const last = focusable[focusable.length - 1]
|
||||
if (e.shiftKey && (document.activeElement === first || document.activeElement === panel)) {
|
||||
e.preventDefault()
|
||||
last.focus()
|
||||
} else if (!e.shiftKey && document.activeElement === last) {
|
||||
e.preventDefault()
|
||||
first.focus()
|
||||
}
|
||||
}
|
||||
|
||||
const enterClass = variant === 'drawer' ? 'm-drawer-in' : 'm-sheet-in'
|
||||
const exitClass = variant === 'drawer' ? 'm-drawer-out' : 'm-sheet-out'
|
||||
const animation = open ? (entered ? '' : enterClass) : exitClass
|
||||
|
||||
const resolvedMaterial = material ?? (variant === 'bottom' ? 'bar-glass' : 'glass')
|
||||
|
||||
const dragStyle: React.CSSProperties =
|
||||
dragY !== null
|
||||
? { transform: `translateY(${dragY}px)`, transition: 'none' }
|
||||
: { transition: 'transform 280ms var(--ease-drawer)' }
|
||||
|
||||
return ReactDOM.createPortal(
|
||||
// m-root on the overlay so the --m-* tokens resolve even when the portal
|
||||
// has to fall back to document.body (sheet mounted in the same commit as
|
||||
// the shell).
|
||||
// A transparent scrim skips the overlay's opacity animation: an animating
|
||||
// opacity<1 ancestor becomes a backdrop-root that cancels the sheet's own
|
||||
// backdrop-blur (the "liquid glass" frost). The sheet still slides via m-sheet-in.
|
||||
<div
|
||||
className={`m-root fixed inset-0 z-[60] ${dimTransparent ? 'bg-transparent' : `bg-[color:var(--m-dim)] ${open ? 'm-fade-in' : 'm-fade-out'}`}`}
|
||||
onClick={(e) => {
|
||||
if (e.target === e.currentTarget) onClose()
|
||||
}}
|
||||
>
|
||||
<div className={POSITION[variant]}>
|
||||
<div
|
||||
ref={panelRef}
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={ariaLabel}
|
||||
tabIndex={-1}
|
||||
className={`relative flex flex-col overflow-hidden outline-none text-m-ink ${SHAPE[variant]} ${MATERIAL[resolvedMaterial]} ${animation} ${className}`}
|
||||
style={variant === 'bottom' ? dragStyle : undefined}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
onKeyDown={handleKeyDown}
|
||||
onAnimationEnd={(e) => {
|
||||
if (e.target === e.currentTarget && open) setEntered(true)
|
||||
}}
|
||||
>
|
||||
{variant === 'bottom' && (
|
||||
// Invisible drag strip along the top edge — the design shows no
|
||||
// handle, the panel starts directly with its content.
|
||||
<div
|
||||
className="absolute inset-x-0 top-0 z-[1] h-5 cursor-grab touch-none active:cursor-grabbing"
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerMove={handlePointerMove}
|
||||
onPointerUp={handlePointerEnd}
|
||||
onPointerCancel={handlePointerEnd}
|
||||
/>
|
||||
)}
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</div>,
|
||||
sheetRoot(),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
export type MStatus = 'confirmed' | 'pending' | 'info' | 'danger' | 'neutral'
|
||||
|
||||
interface MStatusDotProps {
|
||||
status: MStatus
|
||||
/** Diameter in px */
|
||||
size?: number
|
||||
className?: string
|
||||
}
|
||||
|
||||
const STATUS_VAR: Record<MStatus, string> = {
|
||||
confirmed: 'var(--m-st-confirmed)',
|
||||
pending: 'var(--m-st-pending)',
|
||||
info: 'var(--m-st-info)',
|
||||
danger: 'var(--m-st-danger)',
|
||||
neutral: 'var(--m-st-neutral)',
|
||||
}
|
||||
|
||||
/** Status dot in the canonical status colors (confirmed/pending/info/danger/neutral). */
|
||||
export default function MStatusDot({ status, size = 7, className = '' }: MStatusDotProps) {
|
||||
return (
|
||||
<span
|
||||
aria-hidden
|
||||
className={`inline-block flex-none rounded-full ${className}`}
|
||||
style={{ width: size, height: size, background: STATUS_VAR[status] }}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import MStatusDot, { MStatus } from './MStatusDot'
|
||||
|
||||
type ToastType = 'success' | 'error' | 'warning' | 'info'
|
||||
|
||||
interface MToast {
|
||||
id: number
|
||||
message: string
|
||||
type: ToastType
|
||||
/** duration <= 0: no auto-dismiss, the pill closes on tap instead. */
|
||||
sticky: boolean
|
||||
removing: boolean
|
||||
}
|
||||
|
||||
let toastId = 0
|
||||
const EXIT_MS = 220
|
||||
|
||||
// info stays the plain act-pill; the other types get a status dot.
|
||||
const TYPE_DOT: Partial<Record<ToastType, MStatus>> = {
|
||||
success: 'confirmed',
|
||||
error: 'danger',
|
||||
warning: 'pending',
|
||||
}
|
||||
|
||||
/**
|
||||
* Mobile toast presenter. Takes over the global `window.__addToast` bridge
|
||||
* (fed by useToast / store/notify) while the mobile shell is mounted, so every
|
||||
* existing toast call renders as the design's act-pill above the bottom nav.
|
||||
* The desktop ToastContainer handler is restored on unmount.
|
||||
*/
|
||||
export default function MToastHost() {
|
||||
const [toasts, setToasts] = useState<MToast[]>([])
|
||||
const timersRef = useRef<ReturnType<typeof setTimeout>[]>([])
|
||||
|
||||
useEffect(() => {
|
||||
const timers = timersRef.current
|
||||
return () => timers.forEach(clearTimeout)
|
||||
}, [])
|
||||
|
||||
const dismissToast = useCallback((id: number) => {
|
||||
setToasts((prev) => prev.map((t) => (t.id === id ? { ...t, removing: true } : t)))
|
||||
const t = setTimeout(() => {
|
||||
setToasts((prev) => prev.filter((t) => t.id !== id))
|
||||
}, EXIT_MS)
|
||||
timersRef.current.push(t)
|
||||
}, [])
|
||||
|
||||
const addToast = useCallback(
|
||||
(message: string, type: ToastType = 'info', duration: number = 3000) => {
|
||||
const id = ++toastId
|
||||
setToasts((prev) => [...prev, { id, message, type, sticky: duration <= 0, removing: false }])
|
||||
|
||||
if (duration > 0) {
|
||||
const t = setTimeout(() => dismissToast(id), duration)
|
||||
timersRef.current.push(t)
|
||||
}
|
||||
|
||||
return id
|
||||
},
|
||||
[dismissToast],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
const previous = window.__addToast
|
||||
window.__addToast = addToast
|
||||
return () => {
|
||||
window.__addToast = previous
|
||||
}
|
||||
}, [addToast])
|
||||
|
||||
if (toasts.length === 0) return null
|
||||
|
||||
return (
|
||||
<div className="pointer-events-none fixed inset-x-0 bottom-[calc(var(--bottom-nav-h,84px)+16px)] z-[90] flex flex-col-reverse items-center gap-2 px-6">
|
||||
{toasts.map((toast) => {
|
||||
const dot = TYPE_DOT[toast.type]
|
||||
return (
|
||||
<div
|
||||
key={toast.id}
|
||||
onClick={toast.sticky ? () => dismissToast(toast.id) : undefined}
|
||||
className={`flex max-w-full items-center gap-2 rounded-full bg-m-act px-4 py-2 text-[0.75rem] font-semibold text-m-actfg shadow-[0_10px_30px_-8px_rgba(0,0,0,.5)] ${
|
||||
toast.sticky ? 'pointer-events-auto cursor-pointer' : ''
|
||||
} ${toast.removing ? 'm-toast-out' : 'm-toast-in'}`}
|
||||
>
|
||||
{dot && <MStatusDot status={dot} size={6} />}
|
||||
<span className="min-w-0 truncate">{toast.message}</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
interface MToggleProps {
|
||||
checked: boolean
|
||||
onChange: (checked: boolean) => void
|
||||
ariaLabel?: string
|
||||
disabled?: boolean
|
||||
className?: string
|
||||
}
|
||||
|
||||
/** iOS-style switch: --m-act track when on, --m-trackoff when off, 18px knob. */
|
||||
export default function MToggle({ checked, onChange, ariaLabel, disabled = false, className = '' }: MToggleProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={checked}
|
||||
aria-label={ariaLabel}
|
||||
disabled={disabled}
|
||||
onClick={() => onChange(!checked)}
|
||||
className={`box-border h-[22px] w-10 flex-none rounded-full p-[2px] transition-colors duration-[180ms] disabled:opacity-50 ${
|
||||
checked ? 'bg-m-act' : 'bg-[color:var(--m-trackoff)]'
|
||||
} ${className}`}
|
||||
>
|
||||
<span
|
||||
className={`block h-[18px] w-[18px] rounded-full bg-[color:var(--m-knob)] transition-transform duration-[180ms] ${
|
||||
checked ? 'translate-x-[18px]' : 'translate-x-0'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
/* ── Mobile rewrite design tokens ─────────────────────────────────────────────
|
||||
* Scoped to .m-root (the MobileShell wrapper) so the mobile design system
|
||||
* never leaks into desktop chrome. Values are the mobile design ground truth;
|
||||
* dark values follow the app-wide `.dark` class strategy.
|
||||
*/
|
||||
.m-root {
|
||||
--m-ink: #101013;
|
||||
--m-muted: #68686F;
|
||||
--m-faint: #9A9AA1;
|
||||
--m-bg: #F3F2EF;
|
||||
--m-scr: radial-gradient(120% 80% at 50% -10%, #FBFAF7 0%, #F1EFEA 55%, #E9E7E1 100%);
|
||||
--m-glass: rgba(255,255,255,.6);
|
||||
--m-gbr: rgba(255,255,255,.75);
|
||||
--m-card: rgba(255,255,255,.55);
|
||||
--m-cbr: rgba(255,255,255,.75);
|
||||
--m-inner: rgba(255,255,255,.68);
|
||||
--m-inbr: rgba(255,255,255,.9);
|
||||
--m-act: #101013;
|
||||
--m-actfg: #fff;
|
||||
--m-dim: rgba(16,16,19,.4);
|
||||
--m-sheet: rgba(250,250,248,.94);
|
||||
--m-sheetop: #FAFAF8;
|
||||
--m-shbr: rgba(255,255,255,.95);
|
||||
--m-ic: rgba(16,16,19,.04);
|
||||
--m-avbr: rgba(255,255,255,.9);
|
||||
--m-rowbr: rgba(16,16,19,.045);
|
||||
--m-conn: #9A9AA1;
|
||||
--m-mapb: #E8E6E1;
|
||||
--m-mapr: #FBFAF8;
|
||||
--m-mapw: #DFE2E4;
|
||||
--m-mkr: #101013;
|
||||
--m-mkfg: #fff;
|
||||
--m-trackoff: rgba(16,16,19,.14);
|
||||
|
||||
/* Toggle knob is white on both themes (off-track is translucent enough). */
|
||||
--m-knob: #fff;
|
||||
|
||||
/* Status color canon — theme independent. */
|
||||
--m-st-confirmed: #2FA37A;
|
||||
--m-st-pending: #E8A13A;
|
||||
--m-st-info: #4A7DDB;
|
||||
--m-st-danger: #D6273B;
|
||||
--m-st-neutral: #9A9AA1;
|
||||
|
||||
/* Chrome metrics. --bottom-nav-h stays the single source of truth for
|
||||
* content clearance (same value the legacy shell uses). The demo's fixed
|
||||
* 52px/26px offsets stand in for the phone status bar / home indicator, so
|
||||
* real devices derive them from the safe-area insets. */
|
||||
--bottom-nav-h: calc(84px + env(safe-area-inset-bottom, 0px));
|
||||
--m-safe-top: calc(env(safe-area-inset-top, 0px) + 12px);
|
||||
}
|
||||
|
||||
.dark .m-root {
|
||||
--m-ink: #F5F5F7;
|
||||
--m-muted: #9C9CA3;
|
||||
--m-faint: #6E6E76;
|
||||
--m-bg: #0A0A0C;
|
||||
--m-scr: radial-gradient(120% 80% at 50% -10%, #17171C 0%, #0C0C0F 55%, #08080A 100%);
|
||||
--m-glass: rgba(26,26,31,.6);
|
||||
--m-gbr: rgba(255,255,255,.12);
|
||||
--m-card: rgba(24,24,29,.55);
|
||||
--m-cbr: rgba(255,255,255,.1);
|
||||
--m-inner: rgba(255,255,255,.07);
|
||||
--m-inbr: rgba(255,255,255,.1);
|
||||
--m-act: #F5F5F7;
|
||||
--m-actfg: #101013;
|
||||
--m-dim: rgba(0,0,0,.55);
|
||||
--m-sheet: rgba(22,22,27,.94);
|
||||
--m-sheetop: #191920;
|
||||
--m-shbr: rgba(255,255,255,.14);
|
||||
--m-ic: rgba(255,255,255,.09);
|
||||
--m-avbr: rgba(255,255,255,.14);
|
||||
--m-rowbr: rgba(255,255,255,.07);
|
||||
--m-conn: #6E6E76;
|
||||
--m-mapb: #121215;
|
||||
--m-mapr: #1E1F24;
|
||||
--m-mapw: #0D1013;
|
||||
--m-mkr: #F5F5F7;
|
||||
--m-mkfg: #101013;
|
||||
--m-trackoff: rgba(255,255,255,.14);
|
||||
}
|
||||
|
||||
/* Geist "subtext" tier weight — single knob. The design's Geist labels/numbers
|
||||
* read heavy at their declared bold; render the whole tier at Medium (500) for
|
||||
* the fine, low-key look. Higher specificity than Tailwind's font-* utilities,
|
||||
* so it caps font-medium / font-semibold / font-bold / font-extrabold on any
|
||||
* .font-geist span. Retune here if a weight feels too light or heavy. */
|
||||
.m-root .font-geist { font-weight: 500; }
|
||||
|
||||
/* ── Keyframes ──────────────────────────────────────────────────────────── */
|
||||
|
||||
@keyframes m-sheet-in {
|
||||
from { opacity: 0; transform: translateY(24px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
@keyframes m-sheet-out {
|
||||
from { opacity: 1; transform: translateY(0); }
|
||||
to { opacity: 0; transform: translateY(24px); }
|
||||
}
|
||||
@keyframes m-drawer-in {
|
||||
from { transform: translateX(-100%); }
|
||||
to { transform: translateX(0); }
|
||||
}
|
||||
@keyframes m-drawer-out {
|
||||
from { transform: translateX(0); }
|
||||
to { transform: translateX(-100%); }
|
||||
}
|
||||
@keyframes m-fade-in {
|
||||
from { opacity: 0; }
|
||||
to { opacity: 1; }
|
||||
}
|
||||
@keyframes m-fade-out {
|
||||
from { opacity: 1; }
|
||||
to { opacity: 0; }
|
||||
}
|
||||
@keyframes m-pop-in {
|
||||
from { opacity: 0; transform: translateY(-6px) scale(.97); }
|
||||
to { opacity: 1; transform: translateY(0) scale(1); }
|
||||
}
|
||||
@keyframes m-toast-in {
|
||||
from { opacity: 0; transform: translateY(10px); }
|
||||
to { opacity: 1; transform: translateY(0); }
|
||||
}
|
||||
@keyframes m-toast-out {
|
||||
from { opacity: 1; transform: translateY(0); }
|
||||
to { opacity: 0; transform: translateY(6px); }
|
||||
}
|
||||
|
||||
.m-sheet-in { animation: m-sheet-in 280ms var(--ease-drawer) both; }
|
||||
.m-sheet-out { animation: m-sheet-out 280ms var(--ease-drawer) both; }
|
||||
.m-drawer-in { animation: m-drawer-in 280ms var(--ease-drawer) both; }
|
||||
.m-drawer-out { animation: m-drawer-out 280ms var(--ease-drawer) both; }
|
||||
.m-fade-in { animation: m-fade-in 280ms var(--ease-drawer) both; }
|
||||
.m-fade-out { animation: m-fade-out 280ms var(--ease-drawer) both; }
|
||||
.m-pop-in { animation: m-pop-in 220ms var(--ease-out-quint) both; }
|
||||
.m-toast-in { animation: m-toast-in 260ms var(--ease-out-quint) both; }
|
||||
.m-toast-out { animation: m-toast-out 220ms ease both; }
|
||||
|
||||
/* Reduced motion: gentler, not zero (same rule the desktop keyframes follow). */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.m-sheet-in, .m-drawer-in, .m-pop-in, .m-toast-in {
|
||||
animation: m-fade-in 120ms ease-out both;
|
||||
}
|
||||
.m-sheet-out, .m-drawer-out, .m-toast-out {
|
||||
animation: m-fade-out 120ms ease-out both;
|
||||
}
|
||||
}
|
||||
|
||||
/* ── TREK mascot (empty-state) — logo-as-body character, per-scene props ───── */
|
||||
@keyframes trek-idle { 0%, 100% { transform: translateY(0) rotate(-1.1deg); } 50% { transform: translateY(-2px) rotate(1.1deg); } }
|
||||
@keyframes trek-breathe { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.012, 1.024); } }
|
||||
@keyframes trek-shadow { 0%, 100% { transform: scaleX(1); opacity: .15; } 50% { transform: scaleX(1.05); opacity: .17; } }
|
||||
/* body hop, occasional: long rest, then anticipation squash → airborne → land → settle */
|
||||
@keyframes trek-hop {
|
||||
0%, 74%, 100% { transform: translateY(0) scale(1, 1); }
|
||||
79% { transform: translateY(1px) scale(1.05, .92); }
|
||||
87% { transform: translateY(-10px) scale(.95, 1.07); }
|
||||
94% { transform: translateY(0) scale(1.07, .93); }
|
||||
98% { transform: translateY(0) scale(.99, 1.01); }
|
||||
}
|
||||
/* body nod — a pleased look left-and-right, e.g. cheering the poll results */
|
||||
@keyframes trek-nod {
|
||||
0%, 100% { transform: translateY(0) rotate(0); }
|
||||
25% { transform: translateY(-2px) rotate(-4deg); }
|
||||
50% { transform: translateY(0) rotate(0); }
|
||||
75% { transform: translateY(-2px) rotate(4deg); }
|
||||
}
|
||||
/* slow blink: eyes squeeze shut for a couple of frames each cycle */
|
||||
@keyframes trek-blink { 0%, 90%, 100% { transform: scaleY(1); } 94%, 97% { transform: scaleY(.12); } }
|
||||
/* entrance / poke-to-react pop-in (plays on mount and on each remount/tap) */
|
||||
@keyframes trek-in {
|
||||
0% { opacity: 0; transform: translateY(7px) scale(.85); }
|
||||
60% { opacity: 1; }
|
||||
100% { opacity: 1; transform: translateY(0) scale(1); }
|
||||
}
|
||||
/* pupils glancing around — centred most of the time, occasional look down/side */
|
||||
@keyframes trek-look {
|
||||
0%, 34%, 100% { transform: translate(0, 0); }
|
||||
42%, 52% { transform: translate(0, .9px); }
|
||||
64%, 72% { transform: translate(.9px, .1px); }
|
||||
84%, 90% { transform: translate(-.8px, .2px); }
|
||||
}
|
||||
/* wheels rolling in place */
|
||||
@keyframes trek-roll { to { transform: rotate(360deg); } }
|
||||
/* skateboard ollie — body and board pop off the ground together, now and then */
|
||||
@keyframes trek-sk-body {
|
||||
0%, 68%, 100% { transform: translateY(0) scale(1, 1); }
|
||||
73% { transform: translateY(1.5px) scale(1.04, .95); }
|
||||
84% { transform: translateY(-9px) scale(.97, 1.05); }
|
||||
92% { transform: translateY(0) scale(1.05, .95); }
|
||||
96% { transform: translateY(0) scale(1, 1); }
|
||||
}
|
||||
@keyframes trek-sk-board {
|
||||
0%, 68%, 100% { transform: translateY(0) rotate(0); }
|
||||
73% { transform: translateY(0) rotate(-6deg); }
|
||||
84% { transform: translateY(-8px) rotate(7deg); }
|
||||
90% { transform: translateY(-3px) rotate(-3deg); }
|
||||
95% { transform: translateY(0) rotate(0); }
|
||||
}
|
||||
/* guide pennant fluttering — pivots at the pole */
|
||||
@keyframes trek-flag {
|
||||
0%, 100% { transform: skewY(0) scaleX(1); }
|
||||
30% { transform: skewY(-7deg) scaleX(.96); }
|
||||
60% { transform: skewY(6deg) scaleX(1.03); }
|
||||
}
|
||||
/* poll bars staying up, gently rising and settling like live tallies */
|
||||
@keyframes trek-bar { 0%, 100% { transform: scaleY(.78); } 50% { transform: scaleY(1); } }
|
||||
@keyframes trek-typing { 0%, 70%, 100% { transform: scale(.5); opacity: .4; } 35% { transform: scale(1); opacity: 1; } }
|
||||
/* card / note rocking gently */
|
||||
@keyframes trek-ticket { 0%, 100% { transform: rotate(-2.5deg); } 50% { transform: rotate(2.5deg); } }
|
||||
/* a line being written: draws in from the left, holds, then a fresh pass */
|
||||
@keyframes trek-write {
|
||||
0% { transform: scaleX(0); }
|
||||
30%, 82% { transform: scaleX(1); }
|
||||
92%, 100% { transform: scaleX(0); }
|
||||
}
|
||||
/* pencil scribbling as the lines appear */
|
||||
@keyframes trek-pencil {
|
||||
0%, 100% { transform: translate(0, 0) rotate(0); }
|
||||
20% { transform: translate(-1.5px, 1.5px) rotate(-4deg); }
|
||||
45% { transform: translate(1.5px, -.5px) rotate(3deg); }
|
||||
70% { transform: translate(-1px, 1px) rotate(-2deg); }
|
||||
}
|
||||
/* suitcase rocking on its wheels, restless to get going */
|
||||
@keyframes trek-suitcase { 0%, 100% { transform: rotate(-2.5deg); } 50% { transform: rotate(2.5deg); } }
|
||||
/* suitcase handle telescoping up and down */
|
||||
@keyframes trek-handle { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-2px); } }
|
||||
/* collections map pin bobbing */
|
||||
@keyframes trek-pin { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-4px); } }
|
||||
/* atlas globe meridian drifting to fake a slow spin */
|
||||
@keyframes trek-globe { 0%, 100% { transform: translateX(-2px); } 50% { transform: translateX(2px); } }
|
||||
/* costs top coin bouncing on */
|
||||
@keyframes trek-coin { 0%, 100% { transform: translateY(0); } 30% { transform: translateY(-5px); } 55% { transform: translateY(0); } 70% { transform: translateY(-2px); } 84% { transform: translateY(0); } }
|
||||
/* journey page turning over the spine */
|
||||
@keyframes trek-page { 0%, 55%, 100% { transform: scaleX(1); } 78% { transform: scaleX(-.9); } }
|
||||
/* dashboard paper plane bobbing in flight */
|
||||
@keyframes trek-plane { 0%, 100% { transform: translate(0, 0) rotate(0); } 25% { transform: translate(-1px, -2px) rotate(-4deg); } 50% { transform: translate(0, 0) rotate(0); } 75% { transform: translate(1px, 2px) rotate(4deg); } }
|
||||
/* notifications Zzz drifting up and fading */
|
||||
@keyframes trek-z { 0% { opacity: 0; transform: translate(0, 4px) scale(.7); } 30% { opacity: .9; } 100% { opacity: 0; transform: translate(3px, -8px) scale(1.1); } }
|
||||
/* search magnifier scanning */
|
||||
@keyframes trek-magnifier { 0%, 100% { transform: translateX(-3px) rotate(-3deg); } 50% { transform: translateX(3px) rotate(3deg); } }
|
||||
/* to-do checkmark ticking on, holding, then resetting */
|
||||
@keyframes trek-check { 0%, 8% { transform: scale(0); } 22% { transform: scale(1.2); } 32%, 88% { transform: scale(1); } 96%, 100% { transform: scale(0); } }
|
||||
|
||||
.trek { animation: trek-in 480ms cubic-bezier(.34, 1.4, .64, 1) both; transform-origin: 50% 100%; }
|
||||
.trek-root { animation: trek-idle 3.4s ease-in-out infinite; transform-box: fill-box; transform-origin: 50% 100%; }
|
||||
.trek-body { animation: trek-breathe 3.8s ease-in-out infinite; transform-box: fill-box; transform-origin: 50% 100%; }
|
||||
.trek-shadow { animation: trek-shadow 3.4s ease-in-out infinite; transform-box: fill-box; transform-origin: 50% 50%; opacity: .15; filter: blur(1px); }
|
||||
/* eyes read as cutouts in the surface behind the mascot, so they stay visible on the monochrome body */
|
||||
.trek-eye { fill: var(--m-bg); }
|
||||
.trek-eyes { animation: trek-blink 5.2s ease-in-out infinite; transform-box: fill-box; transform-origin: center; }
|
||||
.trek-pupils { animation: trek-look 7s ease-in-out infinite; transform-box: fill-box; transform-origin: center; }
|
||||
/* body bounce — per scene */
|
||||
.trek-bounce { transform-box: fill-box; transform-origin: 50% 100%; }
|
||||
.trek-bounce--idle { animation: trek-hop 4.6s ease-in-out infinite; }
|
||||
.trek-bounce--polls { animation: trek-nod 3s ease-in-out infinite; }
|
||||
.trek-bounce--transport { animation: trek-sk-body 3.6s ease-in-out infinite; }
|
||||
/* per-scene props */
|
||||
.trek-board { animation: trek-sk-board 3.6s ease-in-out infinite; transform-box: fill-box; transform-origin: 50% 65%; }
|
||||
.trek-wheel { animation: trek-roll 1.1s linear infinite; transform-box: fill-box; transform-origin: center; }
|
||||
.trek-flag { animation: trek-flag 1.8s ease-in-out infinite; transform-box: fill-box; transform-origin: 0% 50%; }
|
||||
.trek-ticket { animation: trek-ticket 3.6s ease-in-out infinite; transform-box: fill-box; transform-origin: 50% 100%; }
|
||||
.trek-note { animation: trek-ticket 3.9s ease-in-out infinite; transform-box: fill-box; transform-origin: 50% 100%; }
|
||||
.trek-pencil { animation: trek-pencil 1.15s ease-in-out infinite; transform-box: fill-box; transform-origin: center; }
|
||||
.trek-write { animation: trek-write 3.8s ease-in-out infinite; transform-box: fill-box; transform-origin: 0% 50%; }
|
||||
.trek-bar { animation: trek-bar 2.6s ease-in-out infinite; transform-box: fill-box; transform-origin: 50% 100%; }
|
||||
.trek-dot { animation: trek-typing 1.4s ease-in-out infinite; transform-box: fill-box; transform-origin: 50% 50%; }
|
||||
.trek-suitcase { animation: trek-suitcase 1.5s ease-in-out infinite; transform-box: fill-box; transform-origin: 50% 100%; }
|
||||
.trek-handle { animation: trek-handle 1.5s ease-in-out infinite; transform-box: fill-box; transform-origin: 50% 100%; }
|
||||
.trek-pin { animation: trek-pin 2.2s ease-in-out infinite; transform-box: fill-box; transform-origin: 50% 100%; }
|
||||
.trek-globe { animation: trek-globe 3s ease-in-out infinite; transform-box: fill-box; transform-origin: center; }
|
||||
.trek-coin { animation: trek-coin 2s ease-in-out infinite; transform-box: fill-box; transform-origin: 50% 100%; }
|
||||
.trek-page { animation: trek-page 3.4s ease-in-out infinite; transform-box: fill-box; transform-origin: 0% 50%; }
|
||||
.trek-plane { animation: trek-plane 3s ease-in-out infinite; transform-box: fill-box; transform-origin: center; }
|
||||
.trek-magnifier { animation: trek-magnifier 2.4s ease-in-out infinite; transform-box: fill-box; transform-origin: center; }
|
||||
.trek-z { animation: trek-z 2.8s ease-in-out infinite; transform-box: fill-box; transform-origin: center; }
|
||||
.trek-check { animation: trek-check 3s ease-in-out infinite; transform-box: fill-box; transform-origin: center; }
|
||||
/* staggered starts for written lines / poll bars / Zzz */
|
||||
.trek-d2, .trek-z2 { animation-delay: .5s; }
|
||||
.trek-d3, .trek-z3 { animation-delay: 1s; }
|
||||
|
||||
/* Mobile range slider — the --m-* twin of the desktop .trek-range. */
|
||||
.m-range {
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
width: 100%;
|
||||
height: 5px;
|
||||
border-radius: 999px;
|
||||
background: linear-gradient(to right, var(--m-act) var(--fill, 50%), var(--m-trackoff) var(--fill, 50%));
|
||||
outline: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
.m-range::-webkit-slider-thumb {
|
||||
-webkit-appearance: none;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border-radius: 50%;
|
||||
background: var(--m-knob);
|
||||
border: 1px solid var(--m-rowbr);
|
||||
box-shadow: 0 1px 4px rgba(0, 0, 0, .25);
|
||||
transition: transform .12s ease;
|
||||
}
|
||||
.m-range::-webkit-slider-thumb:hover { transform: scale(1.1); }
|
||||
.m-range::-webkit-slider-thumb:active { transform: scale(1.18); }
|
||||
.m-range::-moz-range-thumb {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border-radius: 50%;
|
||||
background: var(--m-knob);
|
||||
border: 1px solid var(--m-rowbr);
|
||||
box-shadow: 0 1px 4px rgba(0, 0, 0, .25);
|
||||
}
|
||||
.m-range::-moz-range-track { height: 5px; border-radius: 999px; background: transparent; }
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.trek, .trek-root, .trek-body, .trek-shadow, .trek-eyes, .trek-pupils,
|
||||
.trek-bounce--idle, .trek-bounce--polls, .trek-bounce--transport,
|
||||
.trek-board, .trek-wheel, .trek-flag, .trek-ticket, .trek-note, .trek-pencil, .trek-write, .trek-bar,
|
||||
.trek-suitcase, .trek-handle, .trek-pin, .trek-globe, .trek-coin, .trek-page, .trek-plane,
|
||||
.trek-magnifier, .trek-z, .trek-check { animation: none; }
|
||||
/* Zzz would sit invisible at opacity 0 without their animation — pin them visible */
|
||||
.trek-z { opacity: 1; }
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
ArrowUp,
|
||||
Bell,
|
||||
Blocks,
|
||||
Briefcase,
|
||||
Bug,
|
||||
ChevronDown,
|
||||
ChevronLeft,
|
||||
Database,
|
||||
FileText,
|
||||
Github,
|
||||
Map,
|
||||
Plug,
|
||||
Puzzle,
|
||||
ScrollText,
|
||||
Settings as SettingsIcon,
|
||||
Shield,
|
||||
SlidersHorizontal,
|
||||
UserCog,
|
||||
UserPlus,
|
||||
Users,
|
||||
} from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { adminApi } from '../../../api/client'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import { useCountUp } from '../../../hooks/useCountUp'
|
||||
import { useAdmin } from '../../../pages/admin/useAdmin'
|
||||
import MAdminAddonManager from './MAdminAddonManager'
|
||||
import MAdminMcpTokensPanel from './MAdminMcpTokensPanel'
|
||||
import MAdminPluginsPanel from './MAdminPluginsPanel'
|
||||
import MAdminAuditLogPanel from './MAdminAuditLogPanel'
|
||||
import MAdminBackupPanel from './MAdminBackupPanel'
|
||||
import MAdminCategoryManager from './MAdminCategoryManager'
|
||||
import MAdminDefaultUserSettings from './MAdminDefaultUserSettings'
|
||||
import MAdminDevNotificationsPanel from './MAdminDevNotificationsPanel'
|
||||
import MAdminGitHubPanel from './MAdminGitHubPanel'
|
||||
import MAdminPackingTemplateManager from './MAdminPackingTemplateManager'
|
||||
import MAdminNotificationsSection from './MAdminNotificationsSection'
|
||||
import MAdminSettingsSection from './MAdminSettingsSection'
|
||||
import MAdminSheets from './MAdminSheets'
|
||||
import MAdminUsersSection from './MAdminUsersSection'
|
||||
import { MAdminButton } from './MAdminUi'
|
||||
|
||||
// Stat card of the 2×2 grid (design §6.3): 34px icon tile, 19px/800 number,
|
||||
// small tracking label. Count-up animation matches the desktop stat cards.
|
||||
function MAdminStat({ label, value, icon: Icon }: { label: string; value: number; icon: LucideIcon }) {
|
||||
const animated = useCountUp(value, 900)
|
||||
return (
|
||||
<div className="flex items-center gap-[11px] rounded-2xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheetop)] px-[14px] py-[13px]">
|
||||
<span className="flex h-[34px] w-[34px] flex-none items-center justify-center rounded-[11px] bg-[color:var(--m-ic)] text-m-ink">
|
||||
<Icon size={16} strokeWidth={2} />
|
||||
</span>
|
||||
<div>
|
||||
<div className="text-[1.1875rem] font-extrabold leading-none text-m-ink">{animated}</div>
|
||||
<div className="mt-[2px] font-geist text-[0.59375rem] font-bold tracking-[0.06em] text-m-faint">{label}</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Mobile admin screen (design §6): section switcher pill with the 11-entry
|
||||
* dropdown, update banner, stats grid and the users section; every other
|
||||
* desktop admin section stays reachable through the dropdown.
|
||||
*/
|
||||
export default function MAdmin() {
|
||||
const { t, locale } = useTranslation()
|
||||
const admin = useAdmin()
|
||||
const {
|
||||
demoMode, mcpEnabled, devMode, toast, navigate,
|
||||
activeTab, setActiveTab, stats, serverTimezone,
|
||||
bagTrackingEnabled, setBagTrackingEnabled,
|
||||
collabFeatures, setCollabFeatures,
|
||||
setShowCreateUser,
|
||||
updateInfo, setShowUpdateModal,
|
||||
} = admin
|
||||
const [sectionsOpen, setSectionsOpen] = useState(false)
|
||||
|
||||
// Same sections and gating as the desktop sidebar, ordered and iconed like
|
||||
// the design's dropdown (§6.1).
|
||||
const sections: { id: string; label: string; icon: LucideIcon }[] = [
|
||||
{ id: 'users', label: t('admin.tabs.users'), icon: Users },
|
||||
{ id: 'defaults', label: t('admin.tabs.defaults'), icon: UserCog },
|
||||
{ id: 'config', label: t('admin.tabs.config'), icon: SlidersHorizontal },
|
||||
{ id: 'settings', label: t('admin.tabs.settings'), icon: SettingsIcon },
|
||||
{ id: 'addons', label: t('admin.tabs.addons'), icon: Blocks },
|
||||
{ id: 'plugins', label: t('admin.tabs.plugins'), icon: Puzzle },
|
||||
{ id: 'notifications', label: t('admin.tabs.notifications'), icon: Bell },
|
||||
...(mcpEnabled ? [{ id: 'mcp-tokens', label: t('admin.tabs.mcpTokens'), icon: Plug }] : []),
|
||||
{ id: 'github', label: t('admin.tabs.github'), icon: Github },
|
||||
{ id: 'backup', label: t('admin.tabs.backup'), icon: Database },
|
||||
{ id: 'audit', label: t('admin.tabs.audit'), icon: ScrollText },
|
||||
...(devMode ? [{ id: 'dev-notifications', label: 'Dev: Notifications', icon: Bug }] : []),
|
||||
]
|
||||
const activeSection = sections.find((s) => s.id === activeTab) ?? sections[0]
|
||||
|
||||
const saveDemoBaseline = async () => {
|
||||
try {
|
||||
await adminApi.saveDemoBaseline()
|
||||
toast.success('Baseline saved! Resets will restore to this state.')
|
||||
} catch (e) {
|
||||
toast.error(e.response?.data?.error || 'Failed to save baseline')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-full overflow-y-auto px-4 pb-[calc(var(--bottom-nav-h,84px)+16px)] pt-[var(--m-safe-top,12px)]">
|
||||
{/* Header: back · section switcher · create user */}
|
||||
<div className="mb-3 flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('common.back')}
|
||||
onClick={() => navigate('/dashboard')}
|
||||
className="flex h-[38px] w-[38px] flex-none items-center justify-center rounded-full border border-[color:var(--m-gbr)] bg-[color:var(--m-sheet)] text-m-ink shadow-[0_5px_12px_-8px_rgba(0,0,0,.18)]"
|
||||
>
|
||||
<ChevronLeft size={18} strokeWidth={2.2} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('admin.title')}
|
||||
aria-expanded={sectionsOpen}
|
||||
onClick={() => setSectionsOpen((v) => !v)}
|
||||
className="flex h-[38px] min-w-0 flex-1 items-center gap-[7px] rounded-full border border-[color:var(--m-gbr)] bg-[color:var(--m-sheet)] px-[14px] text-[0.8125rem] font-bold text-m-ink shadow-[0_5px_12px_-8px_rgba(0,0,0,.18)]"
|
||||
>
|
||||
<Shield size={14} strokeWidth={2.2} className="flex-none" />
|
||||
<span className="min-w-0 flex-1 truncate text-left">{activeSection.label}</span>
|
||||
<ChevronDown size={13} strokeWidth={2} className="flex-none text-m-faint" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('admin.createUser')}
|
||||
onClick={() => setShowCreateUser(true)}
|
||||
className="flex h-[38px] w-[38px] flex-none items-center justify-center rounded-full bg-m-act text-m-actfg shadow-[0_5px_12px_-8px_rgba(0,0,0,.3)]"
|
||||
>
|
||||
<UserPlus size={16} strokeWidth={2.2} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Section dropdown */}
|
||||
{sectionsOpen && (
|
||||
<div className="-mt-[6px] mb-3 rounded-2xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheetop)] p-[6px] shadow-[0_16px_40px_-20px_rgba(0,0,0,.4)]">
|
||||
{sections.map((section) => (
|
||||
<button
|
||||
key={section.id}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setActiveTab(section.id)
|
||||
setSectionsOpen(false)
|
||||
}}
|
||||
className={`flex w-full items-center gap-[10px] rounded-[11px] p-[10px] text-left text-[0.8125rem] font-semibold text-m-ink ${
|
||||
section.id === activeSection.id ? 'bg-[color:var(--m-ic)]' : ''
|
||||
}`}
|
||||
>
|
||||
<section.icon size={15} strokeWidth={2} />
|
||||
{section.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Update banner (§6.2) — real update check, shown on every section */}
|
||||
{updateInfo && (
|
||||
<div className="mb-3 flex items-center gap-[10px] rounded-2xl border border-[color:color-mix(in_srgb,var(--m-st-pending)_28%,transparent)] bg-[color:color-mix(in_srgb,var(--m-st-pending)_10%,transparent)] px-[14px] py-3">
|
||||
<span className="flex h-[34px] w-[34px] flex-none items-center justify-center rounded-full bg-[color:var(--m-st-pending)] text-white">
|
||||
<ArrowUp size={17} strokeWidth={2.4} />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-[0.78125rem] font-extrabold text-m-ink">{t('admin.update.available')}</div>
|
||||
<div className="font-geist text-[0.625rem] text-m-muted">
|
||||
{t('mobileAdmin.updateLine', { version: `v${updateInfo.latest}`, current: `v${updateInfo.current}` })}
|
||||
</div>
|
||||
</div>
|
||||
<MAdminButton onClick={() => setShowUpdateModal(true)}>{t('mobileAdmin.updateAction')}</MAdminButton>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Demo baseline (demo instances only) */}
|
||||
{demoMode && (
|
||||
<div className="mb-3 flex items-center gap-[10px] rounded-2xl border border-[color:color-mix(in_srgb,var(--m-st-pending)_28%,transparent)] bg-[color:color-mix(in_srgb,var(--m-st-pending)_10%,transparent)] px-[14px] py-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-[0.78125rem] font-extrabold text-m-ink">Demo Baseline</div>
|
||||
<div className="font-geist text-[0.625rem] leading-relaxed text-m-muted">
|
||||
Save current state as the hourly reset point. All admin trips and settings will be preserved.
|
||||
</div>
|
||||
</div>
|
||||
<MAdminButton onClick={saveDemoBaseline}>Save Baseline</MAdminButton>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Stats grid (§6.3) */}
|
||||
{stats && (
|
||||
<div className="mb-3 grid grid-cols-2 gap-[10px]">
|
||||
<MAdminStat label={t('admin.stats.users')} value={stats.totalUsers} icon={Users} />
|
||||
<MAdminStat label={t('admin.stats.trips')} value={stats.totalTrips} icon={Briefcase} />
|
||||
<MAdminStat label={t('admin.stats.places')} value={stats.totalPlaces} icon={Map} />
|
||||
<MAdminStat label={t('admin.stats.files')} value={stats.totalFiles || 0} icon={FileText} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Active section */}
|
||||
{activeTab === 'users' && <MAdminUsersSection admin={admin} t={t} locale={locale} />}
|
||||
{activeTab === 'settings' && <MAdminSettingsSection admin={admin} t={t} />}
|
||||
{activeTab === 'notifications' && <MAdminNotificationsSection admin={admin} t={t} />}
|
||||
{activeTab === 'defaults' && <MAdminDefaultUserSettings />}
|
||||
{activeTab === 'config' && (
|
||||
<div className="space-y-4">
|
||||
<MAdminPackingTemplateManager />
|
||||
<MAdminCategoryManager />
|
||||
</div>
|
||||
)}
|
||||
{activeTab === 'addons' && (
|
||||
<MAdminAddonManager
|
||||
bagTrackingEnabled={bagTrackingEnabled}
|
||||
onToggleBagTracking={async () => {
|
||||
const next = !bagTrackingEnabled
|
||||
setBagTrackingEnabled(next)
|
||||
try {
|
||||
await adminApi.updateBagTracking(next)
|
||||
} catch {
|
||||
setBagTrackingEnabled(!next)
|
||||
}
|
||||
}}
|
||||
collabFeatures={collabFeatures}
|
||||
onToggleCollabFeature={async (key: string) => {
|
||||
const next = { ...collabFeatures, [key]: !collabFeatures[key] }
|
||||
setCollabFeatures(next)
|
||||
try {
|
||||
await adminApi.updateCollabFeatures({ [key]: next[key] })
|
||||
} catch {
|
||||
setCollabFeatures(collabFeatures)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{activeTab === 'plugins' && <MAdminPluginsPanel />}
|
||||
{activeTab === 'mcp-tokens' && <MAdminMcpTokensPanel />}
|
||||
{activeTab === 'github' && <MAdminGitHubPanel isPrerelease={updateInfo?.is_prerelease ?? false} />}
|
||||
{activeTab === 'backup' && <MAdminBackupPanel />}
|
||||
{activeTab === 'audit' && <MAdminAuditLogPanel serverTimezone={serverTimezone} />}
|
||||
{activeTab === 'dev-notifications' && <MAdminDevNotificationsPanel />}
|
||||
|
||||
<MAdminSheets admin={admin} t={t} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,610 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { adminApi } from '../../../api/client'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import { useSettingsStore } from '../../../store/settingsStore'
|
||||
import { useAddonStore } from '../../../store/addonStore'
|
||||
import { useToast } from '../../../components/shared/Toast'
|
||||
import {
|
||||
Puzzle, ListChecks, Wallet, FileText, CalendarDays, Globe, Briefcase, Image, Terminal, Link2, Compass, BookOpen,
|
||||
MessageCircle, StickyNote, BarChart3, Sparkles, Luggage, Plane, Server, Cloud, Bookmark, Check, Loader2,
|
||||
} from 'lucide-react'
|
||||
import MToggle from '../../components/MToggle'
|
||||
import { MAdminButton, MAdminCard, MAdminField, MAdminInput, MAdminSecretInput } from './MAdminUi'
|
||||
|
||||
const ICON_MAP = {
|
||||
ListChecks, Wallet, FileText, CalendarDays, Puzzle, Globe, Briefcase, Image, Terminal, Link2, Compass, BookOpen, Plane, Bookmark,
|
||||
}
|
||||
|
||||
function ImmichIcon({ size = 14 }: { size?: number }) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" width={size} height={size} style={{ flexShrink: 0 }}>
|
||||
<path d="M11.986.27c-2.409 0-5.207 1.09-5.207 3.894v.152c1.343.597 2.935 1.663 4.412 2.971 1.571 1.391 2.838 2.882 3.653 4.287 1.4-2.503 2.336-5.478 2.347-7.373V4.164c0-2.803-2.796-3.894-5.205-3.894m7.512 4.49c-.378-.008-.775.05-1.192.186l-.144.047c-.153 1.461-.676 3.304-1.463 5.113-.837 1.924-1.863 3.59-2.947 4.799 2.813.558 5.93.527 7.736-.047l.035-.01c2.667-.866 2.84-3.863 2.096-6.154-.628-1.933-2.081-3.89-4.121-3.934m-14.996.04c-2.04.043-3.493 1.997-4.121 3.93-.744 2.291-.571 5.288 2.096 6.155l.144.046c.982-1.092 2.488-2.276 4.188-3.277 1.809-1.065 3.619-1.808 5.207-2.148-1.949-2.105-4.489-3.914-6.287-4.51l-.036-.012c-.416-.135-.813-.193-1.191-.185m4.672 6.758c-2.604 1.202-5.109 3.06-6.233 4.586l-.021.029c-1.648 2.268-.027 4.795 1.922 6.211 1.949 1.416 4.852 2.177 6.5-.092.023-.031.054-.07.09-.121-.736-1.272-1.396-3.072-1.822-4.998-.454-2.05-.603-4-.436-5.615m1.072 3.338c.339 2.848 1.332 5.804 2.436 7.344l.021.029c1.648 2.268 4.551 1.508 6.5.092 1.949-1.416 3.57-3.943 1.922-6.211-.023-.031-.052-.073-.088-.123-1.437.307-3.352.38-5.316.19-2.089-.202-3.99-.663-5.475-1.321" fill="currentColor" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
function SynologyIcon({ size = 14 }: { size?: number }) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" width={size} height={size} style={{ flexShrink: 0 }}>
|
||||
<path d="M17.895 11.927a3.196 3.196 0 0 1 .394-1.53l-.008.017a2.677 2.677 0 0 1 1.075-1.108l.014-.007a3.181 3.181 0 0 1 1.523-.382h.05-.003q1.346 0 2.2.871.854.871.86 2.203c0 .895-.29 1.635-.867 2.226s-1.306.886-2.183.886c-.566 0-1.1-.137-1.571-.379l.019.009a2.535 2.535 0 0 1-1.115-1.067l-.007-.013q-.38-.708-.381-1.726zm1.593.083c0 .591.138 1.043.42 1.349a1.365 1.365 0 0 0 2.066.002l.001-.002c.275-.307.413-.764.413-1.357s-.138-1.033-.413-1.342a1.371 1.371 0 0 0-2.066-.001l-.001.002c-.281.306-.42.758-.42 1.345zm-1.602 2.941H16.33v-3.015c0-.635-.032-1.044-.101-1.234a.876.876 0 0 0-.328-.435l-.003-.002a.938.938 0 0 0-.521-.156h-.027.001-.012c-.27 0-.521.084-.727.228l.004-.003a1.115 1.115 0 0 0-.444.576l-.002.008c-.083.248-.121.696-.121 1.359v2.673H12.5V9.027h1.439v.867c.518-.656 1.167-.98 1.952-.98h.021c.335 0 .655.067.946.189l-.016-.006c.261.105.48.268.648.475l.002.003c.141.185.247.404.304.643l.002.012c.057.278.089.597.089.924l-.002.135v-.007zM6.413 9.028h1.654l1.412 4.204 1.376-4.204h1.611l-2.067 5.693-.38 1.038a4.158 4.158 0 0 1-.4.807l.01-.017a1.637 1.637 0 0 1-.422.443l-.005.003c-.17.113-.367.203-.578.26l-.014.003c-.232.064-.499.1-.774.1h-.025.001a4.13 4.13 0 0 1-.911-.105l.028.005-.129-1.229c.198.046.426.074.659.077h.002c.36 0 .628-.106.8-.318a2.27 2.27 0 0 0 .395-.807l.004-.016zM0 12.29l1.592-.149q.147.802.586 1.181.439.379 1.192.375c.528 0 .927-.113 1.197-.335.27-.222.4-.486.4-.782v-.024a.751.751 0 0 0-.167-.474l.001.001c-.113-.132-.309-.252-.59-.347-.193-.074-.631-.191-1.312-.365-.882-.216-1.496-.486-1.85-.804A2.147 2.147 0 0 1 .3 8.936v-.019V8.908c0-.431.132-.831.358-1.163l-.005.007a2.226 2.226 0 0 1 1.003-.826l.015-.005c.442-.184.973-.281 1.602-.281q1.529 0 2.304.676c.516.457.785 1.057.811 1.809l-1.649.055c-.073-.413-.219-.714-.452-.899-.233-.185-.579-.276-1.034-.276-.476 0-.85.098-1.118.298a.59.59 0 0 0-.261.49v.011-.001.002c0 .201.095.379.242.493l.001.001c.205.179.709.36 1.507.546.798.186 1.388.387 1.769.59.374.196.678.48.893.825l.006.01c.214.345.326.786.326 1.305 0 .489-.146.944-.396 1.325l.006-.009c-.264.408-.64.724-1.084.908l-.016.006c-.475.194-1.065.298-1.772.298-1.029 0-1.819-.241-2.373-.722-.554-.481-.879-1.177-.986-2.091z" fill="currentColor" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
const PROVIDER_ICONS: Record<string, React.FC<{ size?: number }>> = {
|
||||
immich: ImmichIcon,
|
||||
synologyphotos: SynologyIcon,
|
||||
}
|
||||
|
||||
interface Addon {
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
icon: string
|
||||
type: string
|
||||
enabled: boolean
|
||||
config?: Record<string, unknown>
|
||||
}
|
||||
|
||||
interface ProviderOption {
|
||||
key: string
|
||||
label: string
|
||||
description: string
|
||||
enabled: boolean
|
||||
toggle: () => Promise<void>
|
||||
}
|
||||
|
||||
interface AddonIconProps {
|
||||
name: string
|
||||
size?: number
|
||||
}
|
||||
|
||||
function AddonIcon({ name, size = 18 }: AddonIconProps) {
|
||||
const Icon = ICON_MAP[name] || Puzzle
|
||||
return <Icon size={size} />
|
||||
}
|
||||
|
||||
interface CollabFeatures { chat: boolean; notes: boolean; polls: boolean; whatsnext: boolean }
|
||||
|
||||
const COLLAB_SUB_FEATURES = [
|
||||
{ key: 'chat', icon: MessageCircle, titleKey: 'admin.collab.chat.title', subtitleKey: 'admin.collab.chat.subtitle' },
|
||||
{ key: 'notes', icon: StickyNote, titleKey: 'admin.collab.notes.title', subtitleKey: 'admin.collab.notes.subtitle' },
|
||||
{ key: 'polls', icon: BarChart3, titleKey: 'admin.collab.polls.title', subtitleKey: 'admin.collab.polls.subtitle' },
|
||||
{ key: 'whatsnext', icon: Sparkles, titleKey: 'admin.collab.whatsnext.title', subtitleKey: 'admin.collab.whatsnext.subtitle' },
|
||||
] as const
|
||||
|
||||
export default function MAdminAddonManager({ bagTrackingEnabled, onToggleBagTracking, collabFeatures, onToggleCollabFeature }: { bagTrackingEnabled?: boolean; onToggleBagTracking?: () => void; collabFeatures?: CollabFeatures; onToggleCollabFeature?: (key: string) => void }) {
|
||||
const { t } = useTranslation()
|
||||
const dm = useSettingsStore(s => s.settings.dark_mode)
|
||||
const dark = dm === true || dm === 'dark' || (dm === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches)
|
||||
const toast = useToast()
|
||||
const refreshGlobalAddons = useAddonStore(s => s.loadAddons)
|
||||
const [addons, setAddons] = useState<Addon[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
loadAddons()
|
||||
}, [])
|
||||
|
||||
const loadAddons = async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const data = await adminApi.addons()
|
||||
setAddons(data.addons)
|
||||
} catch (err: unknown) {
|
||||
toast.error(t('admin.addons.toast.error'))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleToggle = async (addon: Addon) => {
|
||||
const newEnabled = !addon.enabled
|
||||
// Optimistic update
|
||||
setAddons(prev => prev.map(a => a.id === addon.id ? { ...a, enabled: newEnabled } : a))
|
||||
try {
|
||||
await adminApi.updateAddon(addon.id, { enabled: newEnabled })
|
||||
refreshGlobalAddons()
|
||||
toast.success(t('admin.addons.toast.updated'))
|
||||
} catch (err: unknown) {
|
||||
// Rollback
|
||||
setAddons(prev => prev.map(a => a.id === addon.id ? { ...a, enabled: !newEnabled } : a))
|
||||
toast.error(t('admin.addons.toast.error'))
|
||||
}
|
||||
}
|
||||
|
||||
const isPhotoProviderAddon = (addon: Addon) => {
|
||||
return addon.type === 'photo_provider'
|
||||
}
|
||||
|
||||
const isPhotosAddon = (addon: Addon) => {
|
||||
const haystack = `${addon.id} ${addon.name} ${addon.description}`.toLowerCase()
|
||||
return addon.type === 'trip' && (addon.icon === 'Image' || haystack.includes('photo') || haystack.includes('memories'))
|
||||
}
|
||||
|
||||
const handleTogglePhotoProvider = async (providerAddon: Addon) => {
|
||||
const enableProvider = !providerAddon.enabled
|
||||
const prev = addons
|
||||
|
||||
setAddons(current => current.map(a => a.id === providerAddon.id ? { ...a, enabled: enableProvider } : a))
|
||||
|
||||
try {
|
||||
await adminApi.updateAddon(providerAddon.id, { enabled: enableProvider })
|
||||
refreshGlobalAddons()
|
||||
toast.success(t('admin.addons.toast.updated'))
|
||||
} catch {
|
||||
setAddons(prev)
|
||||
toast.error(t('admin.addons.toast.error'))
|
||||
}
|
||||
}
|
||||
|
||||
const photoProviderAddons = addons.filter(isPhotoProviderAddon)
|
||||
const tripAddons = addons.filter(a => a.type === 'trip' && !isPhotosAddon(a))
|
||||
const globalAddons = addons.filter(a => a.type === 'global')
|
||||
const integrationAddons = addons.filter(a => a.type === 'integration')
|
||||
const providerOptions: ProviderOption[] = photoProviderAddons.map((provider) => ({
|
||||
key: provider.id,
|
||||
label: provider.name,
|
||||
description: provider.description,
|
||||
enabled: provider.enabled,
|
||||
toggle: () => handleTogglePhotoProvider(provider),
|
||||
}))
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex justify-center py-10">
|
||||
<Loader2 size={22} className="animate-spin text-m-faint" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{/* Header */}
|
||||
<MAdminCard>
|
||||
<div className="text-[0.875rem] font-extrabold text-m-ink">{t('admin.addons.title')}</div>
|
||||
<p className="mt-[2px] flex flex-wrap items-center gap-1 font-geist text-[0.625rem] leading-relaxed text-m-muted">
|
||||
{t('admin.addons.subtitleBefore')}
|
||||
<img src={dark ? '/text-light.svg' : '/text-dark.svg'} alt="TREK" style={{ height: 11, display: 'inline', verticalAlign: 'middle', opacity: 0.7 }} />
|
||||
{t('admin.addons.subtitleAfter')}
|
||||
</p>
|
||||
</MAdminCard>
|
||||
|
||||
{addons.length === 0 ? (
|
||||
<MAdminCard>
|
||||
<p className="py-6 text-center font-geist text-[0.6875rem] text-m-faint">
|
||||
{t('admin.addons.noAddons')}
|
||||
</p>
|
||||
</MAdminCard>
|
||||
) : (
|
||||
<>
|
||||
{/* Trip Addons */}
|
||||
{tripAddons.length > 0 && (
|
||||
<MAdminCard>
|
||||
<MGroupHead icon={Briefcase} label={`${t('admin.addons.type.trip')} — ${t('admin.addons.tripHint')}`} />
|
||||
{tripAddons.map((addon, i) => (
|
||||
<div key={addon.id}>
|
||||
<MAddonRow addon={addon} onToggle={handleToggle} t={t} first={i === 0} />
|
||||
{addon.id === 'packing' && addon.enabled && onToggleBagTracking && (
|
||||
<MSubRow
|
||||
icon={Luggage}
|
||||
title={t('admin.bagTracking.title')}
|
||||
subtitle={t('admin.bagTracking.subtitle')}
|
||||
enabled={!!bagTrackingEnabled}
|
||||
onToggle={onToggleBagTracking}
|
||||
/>
|
||||
)}
|
||||
{addon.id === 'collab' && addon.enabled && collabFeatures && onToggleCollabFeature && (
|
||||
<>
|
||||
{COLLAB_SUB_FEATURES.map(feat => (
|
||||
<MSubRow
|
||||
key={feat.key}
|
||||
icon={feat.icon}
|
||||
title={t(feat.titleKey)}
|
||||
subtitle={t(feat.subtitleKey)}
|
||||
enabled={collabFeatures[feat.key]}
|
||||
onToggle={() => onToggleCollabFeature(feat.key)}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</MAdminCard>
|
||||
)}
|
||||
|
||||
{/* Global Addons */}
|
||||
{globalAddons.length > 0 && (
|
||||
<MAdminCard>
|
||||
<MGroupHead icon={Globe} label={`${t('admin.addons.type.global')} — ${t('admin.addons.globalHint')}`} />
|
||||
{globalAddons.map((addon, i) => (
|
||||
<div key={addon.id}>
|
||||
<MAddonRow addon={addon} onToggle={handleToggle} t={t} first={i === 0} />
|
||||
{/* Memories providers as sub-items under Journey addon */}
|
||||
{addon.id === 'journey' && providerOptions.length > 0 && (
|
||||
<>
|
||||
{providerOptions.map(provider => {
|
||||
const ProviderIcon = PROVIDER_ICONS[provider.key]
|
||||
return (
|
||||
<MSubRow
|
||||
key={provider.key}
|
||||
providerIcon={ProviderIcon}
|
||||
title={provider.label}
|
||||
subtitle={provider.description}
|
||||
enabled={provider.enabled}
|
||||
onToggle={provider.toggle}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</MAdminCard>
|
||||
)}
|
||||
|
||||
{/* Integration Addons */}
|
||||
{integrationAddons.length > 0 && (
|
||||
<MAdminCard>
|
||||
<MGroupHead icon={Link2} label={`${t('admin.addons.type.integration')} — ${t('admin.addons.integrationHint')}`} />
|
||||
{integrationAddons.map((addon, i) => (
|
||||
<div key={addon.id}>
|
||||
<MAddonRow addon={addon} onToggle={handleToggle} t={t} first={i === 0} />
|
||||
{addon.id === 'llm_parsing' && addon.enabled && (
|
||||
<div className="mt-1 border-t border-[color:var(--m-rowbr)] pt-3">
|
||||
<LlmParsingConfig addon={addon} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</MAdminCard>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Group subheader: small icon + uppercase label, matches the desktop section band. */
|
||||
function MGroupHead({ icon: Icon, label }: { icon: typeof Briefcase; label: string }) {
|
||||
return (
|
||||
<div className="mb-1 flex items-center gap-2">
|
||||
<Icon size={13} className="flex-none text-m-muted" />
|
||||
<span className="font-geist text-[0.625rem] font-bold uppercase tracking-[0.06em] text-m-muted">{label}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function getAddonLabel(t: (key: string) => string, addon: Addon): { name: string; description: string } {
|
||||
const nameKey = `admin.addons.catalog.${addon.id}.name`
|
||||
const descKey = `admin.addons.catalog.${addon.id}.description`
|
||||
const translatedName = t(nameKey)
|
||||
const translatedDescription = t(descKey)
|
||||
|
||||
return {
|
||||
name: translatedName !== nameKey ? translatedName : addon.name,
|
||||
description: translatedDescription !== descKey ? translatedDescription : addon.description,
|
||||
}
|
||||
}
|
||||
|
||||
interface MAddonRowProps {
|
||||
addon: Addon
|
||||
onToggle: (addon: Addon) => void
|
||||
t: (key: string) => string
|
||||
first?: boolean
|
||||
}
|
||||
|
||||
/** Addon row: icon tile, name + type badge, description, MToggle. */
|
||||
function MAddonRow({ addon, onToggle, t, first }: MAddonRowProps) {
|
||||
const label = getAddonLabel(t, addon)
|
||||
const typeLabel =
|
||||
addon.type === 'global' ? t('admin.addons.type.global') : addon.type === 'integration' ? t('admin.addons.type.integration') : t('admin.addons.type.trip')
|
||||
return (
|
||||
<div className={`flex items-center gap-3 py-[11px] ${first ? '' : 'border-t border-[color:var(--m-rowbr)]'}`}>
|
||||
<span className="flex h-[38px] w-[38px] flex-none items-center justify-center rounded-[11px] bg-[color:var(--m-ic)] text-m-ink">
|
||||
<AddonIcon name={addon.icon} size={18} />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="min-w-0 truncate text-[0.8125rem] font-bold text-m-ink">{label.name}</span>
|
||||
<span className="flex-none rounded-full bg-[color:var(--m-ic)] px-[7px] py-[2px] font-geist text-[0.5625rem] font-bold text-m-muted">
|
||||
{typeLabel}
|
||||
</span>
|
||||
</div>
|
||||
<p className="mt-[1px] font-geist text-[0.625rem] leading-relaxed text-m-muted">{label.description}</p>
|
||||
</div>
|
||||
<MToggle checked={addon.enabled} ariaLabel={label.name} onChange={() => onToggle(addon)} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface MSubRowProps {
|
||||
icon?: typeof Luggage
|
||||
providerIcon?: React.FC<{ size?: number }>
|
||||
title: string
|
||||
subtitle: string
|
||||
enabled: boolean
|
||||
onToggle: () => void
|
||||
}
|
||||
|
||||
/** Indented sub-feature row (bag tracking, collab features, memory providers). */
|
||||
function MSubRow({ icon: Icon, providerIcon: ProviderIcon, title, subtitle, enabled, onToggle }: MSubRowProps) {
|
||||
return (
|
||||
<div className="flex items-center gap-3 border-t border-[color:var(--m-rowbr)] py-[9px] pl-[50px]">
|
||||
<span className="flex-none text-m-faint">
|
||||
{Icon ? <Icon size={14} /> : ProviderIcon ? <ProviderIcon size={14} /> : null}
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-[0.75rem] font-bold text-m-ink">{title}</div>
|
||||
<div className="mt-[1px] font-geist text-[0.59375rem] leading-relaxed text-m-muted">{subtitle}</div>
|
||||
</div>
|
||||
<MToggle checked={enabled} ariaLabel={title} onChange={onToggle} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const MASKED = '••••••••'
|
||||
const DEFAULT_OLLAMA_URL = 'http://localhost:11434/v1'
|
||||
|
||||
/** Curated models the local extractor is tuned for, pullable via Ollama. The router drives
|
||||
* one model per document via Ollama's grammar-constrained `format`; "thinking" is disabled
|
||||
* automatically, so the Qwen3 family works without any tuning. A host only needs one. */
|
||||
const RECOMMENDED_MODELS: { id: string; label: string; note: string; recommended: boolean; vision: boolean }[] = [
|
||||
{ id: 'qwen3:8b', label: 'Qwen3 — 8B', note: 'Recommended · best extraction quality & speed on CPU (thinking auto-disabled) · Apache-2.0', recommended: true, vision: false },
|
||||
]
|
||||
|
||||
/**
|
||||
* Instance-wide AI-parsing config. When set, applies to the whole instance and
|
||||
* overrides per-user config (see server llmConfig.ts). The API key is masked on
|
||||
* read; an unchanged mask is treated as a no-op by the server. For the local
|
||||
* provider, it also lists installed Ollama models and can pull NuExtract models.
|
||||
*/
|
||||
function LlmParsingConfig({ addon }: { addon: Addon }) {
|
||||
const toast = useToast()
|
||||
const cfg = (addon.config ?? {}) as Record<string, unknown>
|
||||
const [provider, setProvider] = useState<string>((cfg.provider as string) ?? 'local')
|
||||
const [model, setModel] = useState<string>((cfg.model as string) ?? '')
|
||||
const [baseUrl, setBaseUrl] = useState<string>((cfg.baseUrl as string) ?? '')
|
||||
const [apiKey, setApiKey] = useState<string>((cfg.apiKey as string) ?? '')
|
||||
const [saving, setSaving] = useState(false)
|
||||
|
||||
// Local-provider model management.
|
||||
const [installed, setInstalled] = useState<string[]>([])
|
||||
const [modelsErr, setModelsErr] = useState('')
|
||||
const [loadingModels, setLoadingModels] = useState(false)
|
||||
const [pulling, setPulling] = useState<string | null>(null)
|
||||
const [pullPct, setPullPct] = useState(0)
|
||||
const [pullStatus, setPullStatus] = useState('')
|
||||
|
||||
const effectiveUrl = baseUrl.trim() || DEFAULT_OLLAMA_URL
|
||||
const isInstalled = (id: string) => installed.some(n => n === id || n.startsWith(id + ':') || n.startsWith(id))
|
||||
|
||||
const loadModels = async () => {
|
||||
if (provider !== 'local') return
|
||||
setLoadingModels(true)
|
||||
setModelsErr('')
|
||||
try {
|
||||
const res = await adminApi.llmLocalModels(effectiveUrl)
|
||||
setInstalled(res.models.map(m => m.name))
|
||||
} catch (e: unknown) {
|
||||
setModelsErr(e instanceof Error ? e.message : 'Could not reach the local LLM server')
|
||||
setInstalled([])
|
||||
} finally {
|
||||
setLoadingModels(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Load installed models when the local provider is active.
|
||||
useEffect(() => {
|
||||
if (provider === 'local') loadModels()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [provider])
|
||||
|
||||
const pull = async (id: string) => {
|
||||
if (pulling) return
|
||||
setPulling(id)
|
||||
setPullPct(0)
|
||||
setPullStatus('starting…')
|
||||
try {
|
||||
await adminApi.llmLocalPull(effectiveUrl, id, (p) => {
|
||||
if (p.error) throw new Error(p.error)
|
||||
if (p.status) setPullStatus(p.status)
|
||||
if (p.total && p.completed != null) setPullPct(Math.round((p.completed / p.total) * 100))
|
||||
})
|
||||
toast.success('Model pulled')
|
||||
setModel(id)
|
||||
await loadModels()
|
||||
} catch (e: unknown) {
|
||||
toast.error(e instanceof Error ? e.message : 'Pull failed')
|
||||
} finally {
|
||||
setPulling(null)
|
||||
setPullPct(0)
|
||||
setPullStatus('')
|
||||
}
|
||||
}
|
||||
|
||||
const save = async () => {
|
||||
setSaving(true)
|
||||
try {
|
||||
// Send the masked sentinel unchanged so the server keeps the stored key.
|
||||
await adminApi.updateAddon(addon.id, { config: { provider, model: model.trim(), baseUrl: baseUrl.trim(), apiKey, multimodal: cfg.multimodal === true } })
|
||||
toast.success('Saved')
|
||||
} catch {
|
||||
toast.error('Failed to save')
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const sectionCls = 'font-geist text-[0.625rem] font-bold uppercase tracking-[0.06em] text-m-faint'
|
||||
|
||||
const providerOptions = [
|
||||
{ value: 'local', label: 'Local · OpenAI-compatible', icon: <Server size={14} />, badge: 'Ollama' },
|
||||
{ value: 'openai', label: 'OpenAI', icon: <Cloud size={14} /> },
|
||||
{ value: 'anthropic', label: 'Anthropic', icon: <Sparkles size={14} /> },
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="space-y-5 pl-[50px]">
|
||||
<p className="font-geist text-[0.625rem] leading-relaxed text-m-faint">
|
||||
Set instance-wide config (applies to all users). Leave blank to let each user configure their own provider.
|
||||
</p>
|
||||
|
||||
{/* Connection */}
|
||||
<section className="space-y-3">
|
||||
<div className={sectionCls}>Connection</div>
|
||||
<MAdminField label="Provider">
|
||||
<div className="space-y-[6px]">
|
||||
{providerOptions.map((opt) => {
|
||||
const active = provider === opt.value
|
||||
return (
|
||||
<button
|
||||
key={opt.value}
|
||||
type="button"
|
||||
onClick={() => setProvider(opt.value)}
|
||||
className={`flex w-full items-center gap-2 rounded-xl border px-3 py-[10px] text-left ${
|
||||
active ? 'border-[color:var(--m-act)] bg-[color:var(--m-ic)]' : 'border-[color:var(--m-rowbr)]'
|
||||
}`}
|
||||
>
|
||||
<span className="flex-none text-m-muted">{opt.icon}</span>
|
||||
<span className="min-w-0 flex-1 truncate text-[0.8125rem] font-semibold text-m-ink">{opt.label}</span>
|
||||
{opt.badge && (
|
||||
<span className="flex-none rounded-full bg-[color:var(--m-ic)] px-2 py-[2px] font-geist text-[0.5625rem] font-bold text-m-muted">
|
||||
{opt.badge}
|
||||
</span>
|
||||
)}
|
||||
{active && <Check size={15} strokeWidth={2.4} className="flex-none text-m-ink" />}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</MAdminField>
|
||||
{provider !== 'anthropic' && (
|
||||
<MAdminField label="Base URL">
|
||||
<MAdminInput
|
||||
type="url"
|
||||
autoComplete="off"
|
||||
value={baseUrl}
|
||||
onChange={e => setBaseUrl(e.target.value)}
|
||||
onBlur={loadModels}
|
||||
placeholder={provider === 'local' ? 'http://localhost:11434/v1' : 'https://api.openai.com/v1'}
|
||||
/>
|
||||
</MAdminField>
|
||||
)}
|
||||
<MAdminField label="API key">
|
||||
<MAdminSecretInput
|
||||
value={apiKey}
|
||||
onChange={e => setApiKey(e.target.value)}
|
||||
placeholder={apiKey === MASKED ? MASKED : provider === 'local' ? '(often not required)' : 'sk-…'}
|
||||
/>
|
||||
</MAdminField>
|
||||
{provider === 'anthropic' && (
|
||||
<p className="font-geist text-[0.625rem] leading-relaxed text-m-faint">
|
||||
Anthropic reads PDFs (including scans) natively. Local/OpenAI models receive extracted text — scanned PDFs need Anthropic.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* Model */}
|
||||
<section className="space-y-3">
|
||||
<div className={sectionCls}>Model</div>
|
||||
<MAdminInput
|
||||
autoComplete="off"
|
||||
value={model}
|
||||
onChange={e => setModel(e.target.value)}
|
||||
placeholder={provider === 'anthropic' ? 'claude-opus-4-8' : provider === 'openai' ? 'gpt-4o' : 'select or pull below'}
|
||||
/>
|
||||
|
||||
{/* Local model management (Ollama) */}
|
||||
{provider === 'local' && (
|
||||
<div className="space-y-3 rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] p-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-[0.75rem] font-semibold text-m-ink">Installed on the server</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={loadModels}
|
||||
disabled={loadingModels}
|
||||
className="font-geist text-[0.6875rem] text-m-muted underline disabled:opacity-60"
|
||||
>
|
||||
{loadingModels ? 'Loading…' : 'Refresh'}
|
||||
</button>
|
||||
</div>
|
||||
{modelsErr && <p className="font-geist text-[0.6875rem] text-[color:var(--m-st-danger)]">{modelsErr}</p>}
|
||||
{!modelsErr && installed.length === 0 && !loadingModels && (
|
||||
<p className="font-geist text-[0.6875rem] text-m-faint">No models installed yet — pull one below.</p>
|
||||
)}
|
||||
{installed.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{installed.map(name => (
|
||||
<button
|
||||
key={name}
|
||||
type="button"
|
||||
title={name}
|
||||
onClick={() => setModel(name)}
|
||||
className={`max-w-full truncate rounded-full border px-[10px] py-[5px] text-[0.6875rem] ${
|
||||
model === name ? 'border-transparent bg-m-act text-m-actfg' : 'border-[color:var(--m-rowbr)] text-m-ink'
|
||||
}`}
|
||||
>
|
||||
{name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="border-t border-[color:var(--m-rowbr)] pt-3">
|
||||
<div className="mb-2 text-[0.75rem] font-semibold text-m-ink">Pull a recommended model</div>
|
||||
<div className="space-y-1">
|
||||
{RECOMMENDED_MODELS.map(m => {
|
||||
const installedHere = isInstalled(m.id)
|
||||
const isPulling = pulling === m.id
|
||||
const active = model === m.id
|
||||
return (
|
||||
<div
|
||||
key={m.id}
|
||||
className={`flex items-center gap-3 rounded-xl border px-3 py-2 ${
|
||||
active ? 'border-[color:var(--m-rowbr)] bg-[color:var(--m-sheetop)]' : 'border-transparent'
|
||||
}`}
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-[0.8125rem] text-m-ink">{m.label}</span>
|
||||
{m.recommended && (
|
||||
<span className="rounded-md bg-[color:color-mix(in_srgb,var(--m-st-confirmed)_15%,transparent)] px-1.5 py-px font-geist text-[0.5625rem] font-bold text-[color:var(--m-st-confirmed)]">
|
||||
Recommended
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="font-geist text-[0.625rem] leading-relaxed text-m-faint">{m.note}</div>
|
||||
{isPulling && (
|
||||
<div className="mt-1.5">
|
||||
<div className="h-1.5 w-full overflow-hidden rounded-full bg-[color:var(--m-ic)]">
|
||||
<div className="h-full bg-m-act transition-[width] duration-200" style={{ width: `${pullPct}%` }} />
|
||||
</div>
|
||||
<div className="mt-0.5 font-geist text-[0.5625rem] text-m-faint">{pullStatus}{pullPct ? ` · ${pullPct}%` : ''}</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{installedHere ? (
|
||||
<MAdminButton variant="ghost" disabled={active} onClick={() => setModel(m.id)}>
|
||||
{active ? 'Selected' : 'Use'}
|
||||
</MAdminButton>
|
||||
) : (
|
||||
<MAdminButton busy={isPulling} disabled={!!pulling} onClick={() => pull(m.id)}>
|
||||
{isPulling ? 'Pulling…' : 'Pull'}
|
||||
</MAdminButton>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<MAdminButton busy={saving} onClick={save}>
|
||||
{saving ? 'Saving…' : 'Save'}
|
||||
</MAdminButton>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
import React, { useCallback, useEffect, useState } from 'react'
|
||||
import { RefreshCw, ClipboardList } from 'lucide-react'
|
||||
import { adminApi } from '../../../api/client'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import { MAdminButton } from './MAdminUi'
|
||||
|
||||
interface AuditEntry {
|
||||
id: number
|
||||
created_at: string
|
||||
user_id: number | null
|
||||
username: string | null
|
||||
user_email: string | null
|
||||
action: string
|
||||
resource: string | null
|
||||
details: Record<string, unknown> | null
|
||||
ip: string | null
|
||||
}
|
||||
|
||||
interface AuditLogPanelProps {
|
||||
serverTimezone?: string
|
||||
}
|
||||
|
||||
export default function MAdminAuditLogPanel({ serverTimezone }: AuditLogPanelProps): React.ReactElement {
|
||||
const { t, locale } = useTranslation()
|
||||
const [entries, setEntries] = useState<AuditEntry[]>([])
|
||||
const [total, setTotal] = useState(0)
|
||||
const [offset, setOffset] = useState(0)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const limit = 100
|
||||
|
||||
const loadFirstPage = useCallback(async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const data = (await adminApi.auditLog({ limit, offset: 0 })) as {
|
||||
entries: AuditEntry[]
|
||||
total: number
|
||||
}
|
||||
setEntries(data.entries || [])
|
||||
setTotal(data.total ?? 0)
|
||||
setOffset(0)
|
||||
} catch {
|
||||
setEntries([])
|
||||
setTotal(0)
|
||||
setOffset(0)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const loadMore = useCallback(async () => {
|
||||
const nextOffset = offset + limit
|
||||
setLoading(true)
|
||||
try {
|
||||
const data = (await adminApi.auditLog({ limit, offset: nextOffset })) as {
|
||||
entries: AuditEntry[]
|
||||
total: number
|
||||
}
|
||||
setEntries((prev) => [...prev, ...(data.entries || [])])
|
||||
setTotal(data.total ?? 0)
|
||||
setOffset(nextOffset)
|
||||
} catch {
|
||||
/* keep existing */
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [offset])
|
||||
|
||||
useEffect(() => {
|
||||
loadFirstPage()
|
||||
}, [loadFirstPage])
|
||||
|
||||
const fmtTime = (iso: string) => {
|
||||
try {
|
||||
return new Date(iso.endsWith('Z') ? iso : iso + 'Z').toLocaleString(locale, {
|
||||
dateStyle: 'short',
|
||||
timeStyle: 'medium',
|
||||
timeZone: serverTimezone || undefined,
|
||||
})
|
||||
} catch {
|
||||
return iso
|
||||
}
|
||||
}
|
||||
|
||||
const fmtDetails = (d: Record<string, unknown> | null) => {
|
||||
if (!d || Object.keys(d).length === 0) return '—'
|
||||
try {
|
||||
return JSON.stringify(d)
|
||||
} catch {
|
||||
return '—'
|
||||
}
|
||||
}
|
||||
|
||||
const userLabel = (e: AuditEntry) => {
|
||||
if (e.username) return e.username
|
||||
if (e.user_email) return e.user_email
|
||||
if (e.user_id != null) return `#${e.user_id}`
|
||||
return '—'
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{/* Header: title + subtitle + refresh */}
|
||||
<div className="flex items-start gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2 text-[0.9375rem] font-extrabold text-m-ink">
|
||||
<ClipboardList size={18} strokeWidth={2.2} className="flex-none" />
|
||||
{t('admin.tabs.audit')}
|
||||
</div>
|
||||
<p className="mt-[3px] font-geist text-[0.625rem] leading-relaxed text-m-muted">
|
||||
{t('admin.audit.subtitle')}
|
||||
</p>
|
||||
</div>
|
||||
<MAdminButton variant="ghost" busy={loading} onClick={() => loadFirstPage()}>
|
||||
{!loading && <RefreshCw size={12} strokeWidth={2.2} />}
|
||||
{t('admin.audit.refresh')}
|
||||
</MAdminButton>
|
||||
</div>
|
||||
|
||||
<p className="font-geist text-[0.59375rem] font-bold tracking-[0.02em] text-m-faint">
|
||||
{t('admin.audit.showing', { count: entries.length, total })}
|
||||
</p>
|
||||
|
||||
{loading && entries.length === 0 ? (
|
||||
<div className="py-12 text-center text-[0.8125rem] text-m-muted">{t('common.loading')}</div>
|
||||
) : entries.length === 0 ? (
|
||||
<div className="py-12 text-center text-[0.8125rem] text-m-muted">{t('admin.audit.empty')}</div>
|
||||
) : (
|
||||
<div className="space-y-[10px]">
|
||||
{entries.map((e) => (
|
||||
<div
|
||||
key={e.id}
|
||||
className="rounded-2xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheetop)] p-[13px]"
|
||||
>
|
||||
{/* Action + time */}
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<span className="min-w-0 flex-1 break-all font-mono text-[0.75rem] font-bold text-m-ink">
|
||||
{e.action}
|
||||
</span>
|
||||
<span className="flex-none whitespace-nowrap font-mono text-[0.59375rem] text-m-faint">
|
||||
{fmtTime(e.created_at)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* User */}
|
||||
<div className="mt-[6px] flex items-baseline gap-2">
|
||||
<span className="flex-none font-geist text-[0.5625rem] font-bold uppercase tracking-[0.06em] text-m-faint">
|
||||
{t('admin.audit.col.user')}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 break-all text-[0.75rem] text-m-ink">{userLabel(e)}</span>
|
||||
</div>
|
||||
|
||||
{/* Resource */}
|
||||
<div className="mt-[4px] flex items-baseline gap-2">
|
||||
<span className="flex-none font-geist text-[0.5625rem] font-bold uppercase tracking-[0.06em] text-m-faint">
|
||||
{t('admin.audit.col.resource')}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 break-all font-mono text-[0.6875rem] text-m-muted">
|
||||
{e.resource || '—'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* IP */}
|
||||
<div className="mt-[4px] flex items-baseline gap-2">
|
||||
<span className="flex-none font-geist text-[0.5625rem] font-bold uppercase tracking-[0.06em] text-m-faint">
|
||||
{t('admin.audit.col.ip')}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 break-all font-mono text-[0.6875rem] text-m-muted">
|
||||
{e.ip || '—'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Details */}
|
||||
<div className="mt-[4px] flex items-baseline gap-2">
|
||||
<span className="flex-none font-geist text-[0.5625rem] font-bold uppercase tracking-[0.06em] text-m-faint">
|
||||
{t('admin.audit.col.details')}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 break-all font-mono text-[0.6875rem] text-m-faint">
|
||||
{fmtDetails(e.details)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{entries.length < total && (
|
||||
<div className="flex justify-center pt-1">
|
||||
<MAdminButton variant="ghost" busy={loading} onClick={() => loadMore()}>
|
||||
{t('admin.audit.loadMore')}
|
||||
</MAdminButton>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,503 @@
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import {
|
||||
Check,
|
||||
Clock,
|
||||
Download,
|
||||
HardDrive,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
RotateCcw,
|
||||
Trash2,
|
||||
Upload,
|
||||
} from 'lucide-react'
|
||||
import { backupApi } from '../../../api/client'
|
||||
import { useToast } from '../../../components/shared/Toast'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import { useSettingsStore } from '../../../store/settingsStore'
|
||||
import { getApiErrorMessage } from '../../../types'
|
||||
import MChip from '../../components/MChip'
|
||||
import MToggle from '../../components/MToggle'
|
||||
import MConfirmSheet from '../settings/MConfirmSheet'
|
||||
import { MAdminButton, MAdminCard, MAdminCardHead, MAdminField, MAdminRow } from './MAdminUi'
|
||||
|
||||
const INTERVAL_OPTIONS = [
|
||||
{ value: 'hourly', labelKey: 'backup.interval.hourly' },
|
||||
{ value: 'daily', labelKey: 'backup.interval.daily' },
|
||||
{ value: 'weekly', labelKey: 'backup.interval.weekly' },
|
||||
{ value: 'monthly', labelKey: 'backup.interval.monthly' },
|
||||
]
|
||||
|
||||
const KEEP_OPTIONS = [
|
||||
{ value: 1, labelKey: 'backup.keep.1day' },
|
||||
{ value: 3, labelKey: 'backup.keep.3days' },
|
||||
{ value: 7, labelKey: 'backup.keep.7days' },
|
||||
{ value: 14, labelKey: 'backup.keep.14days' },
|
||||
{ value: 30, labelKey: 'backup.keep.30days' },
|
||||
{ value: 0, labelKey: 'backup.keep.forever' },
|
||||
]
|
||||
|
||||
const DAYS_OF_WEEK = [
|
||||
{ value: 0, labelKey: 'backup.dow.sunday' },
|
||||
{ value: 1, labelKey: 'backup.dow.monday' },
|
||||
{ value: 2, labelKey: 'backup.dow.tuesday' },
|
||||
{ value: 3, labelKey: 'backup.dow.wednesday' },
|
||||
{ value: 4, labelKey: 'backup.dow.thursday' },
|
||||
{ value: 5, labelKey: 'backup.dow.friday' },
|
||||
{ value: 6, labelKey: 'backup.dow.saturday' },
|
||||
]
|
||||
|
||||
const HOURS = Array.from({ length: 24 }, (_, i) => i)
|
||||
|
||||
const DAYS_OF_MONTH = Array.from({ length: 28 }, (_, i) => i + 1)
|
||||
|
||||
const SELECT_CLASS =
|
||||
'h-[42px] w-full rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-3 text-[0.84375rem] text-m-ink outline-none focus:border-[color:var(--m-faint)]'
|
||||
|
||||
export default function MAdminBackupPanel() {
|
||||
const [backups, setBackups] = useState([])
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [isCreating, setIsCreating] = useState(false)
|
||||
const [restoringFile, setRestoringFile] = useState(null)
|
||||
const [isUploading, setIsUploading] = useState(false)
|
||||
const [autoSettings, setAutoSettings] = useState({ enabled: false, interval: 'daily', keep_days: 7, hour: 2, day_of_week: 0, day_of_month: 1 })
|
||||
const [autoSettingsSaving, setAutoSettingsSaving] = useState(false)
|
||||
const [autoSettingsDirty, setAutoSettingsDirty] = useState(false)
|
||||
const [serverTimezone, setServerTimezone] = useState('')
|
||||
const [restoreConfirm, setRestoreConfirm] = useState(null) // { type: 'file'|'upload', filename, file? }
|
||||
const [deleteConfirm, setDeleteConfirm] = useState(null) // filename pending deletion
|
||||
const fileInputRef = useRef(null)
|
||||
const toast = useToast()
|
||||
const { t, locale } = useTranslation()
|
||||
const is12h = useSettingsStore(s => s.settings.time_format) === '12h'
|
||||
|
||||
const loadBackups = async () => {
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const data = await backupApi.list()
|
||||
setBackups(data.backups || [])
|
||||
} catch {
|
||||
toast.error(t('backup.toast.loadError'))
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const loadAutoSettings = async () => {
|
||||
try {
|
||||
const data = await backupApi.getAutoSettings()
|
||||
setAutoSettings(data.settings)
|
||||
if (data.timezone) setServerTimezone(data.timezone)
|
||||
} catch {}
|
||||
}
|
||||
|
||||
useEffect(() => { loadBackups(); loadAutoSettings() }, [])
|
||||
|
||||
const handleCreate = async () => {
|
||||
setIsCreating(true)
|
||||
try {
|
||||
await backupApi.create()
|
||||
toast.success(t('backup.toast.created'))
|
||||
await loadBackups()
|
||||
} catch {
|
||||
toast.error(t('backup.toast.createError'))
|
||||
} finally {
|
||||
setIsCreating(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleRestore = (filename) => {
|
||||
setRestoreConfirm({ type: 'file', filename })
|
||||
}
|
||||
|
||||
const handleUploadRestore = (e) => {
|
||||
const file = (e.target as HTMLInputElement).files?.[0]
|
||||
if (!file) return
|
||||
e.target.value = ''
|
||||
setRestoreConfirm({ type: 'upload', filename: file.name, file })
|
||||
}
|
||||
|
||||
const executeRestore = async () => {
|
||||
if (!restoreConfirm) return
|
||||
const { type, filename, file } = restoreConfirm
|
||||
setRestoreConfirm(null)
|
||||
|
||||
if (type === 'file') {
|
||||
setRestoringFile(filename)
|
||||
try {
|
||||
await backupApi.restore(filename)
|
||||
toast.success(t('backup.toast.restored'))
|
||||
setTimeout(() => window.location.reload(), 1500)
|
||||
} catch (err: unknown) {
|
||||
toast.error(getApiErrorMessage(err, t('backup.toast.restoreError')))
|
||||
setRestoringFile(null)
|
||||
}
|
||||
} else {
|
||||
setIsUploading(true)
|
||||
try {
|
||||
await backupApi.uploadRestore(file)
|
||||
toast.success(t('backup.toast.restored'))
|
||||
setTimeout(() => window.location.reload(), 1500)
|
||||
} catch (err: unknown) {
|
||||
toast.error(getApiErrorMessage(err, t('backup.toast.uploadError')))
|
||||
setIsUploading(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = (filename) => {
|
||||
setDeleteConfirm(filename)
|
||||
}
|
||||
|
||||
const executeDelete = async () => {
|
||||
const filename = deleteConfirm
|
||||
setDeleteConfirm(null)
|
||||
if (!filename) return
|
||||
try {
|
||||
await backupApi.delete(filename)
|
||||
toast.success(t('backup.toast.deleted'))
|
||||
setBackups(prev => prev.filter(b => b.filename !== filename))
|
||||
} catch {
|
||||
toast.error(t('backup.toast.deleteError'))
|
||||
}
|
||||
}
|
||||
|
||||
const handleAutoSettingsChange = (key, value) => {
|
||||
setAutoSettings(prev => ({ ...prev, [key]: value }))
|
||||
setAutoSettingsDirty(true)
|
||||
}
|
||||
|
||||
const handleSaveAutoSettings = async () => {
|
||||
setAutoSettingsSaving(true)
|
||||
try {
|
||||
const data = await backupApi.setAutoSettings(autoSettings)
|
||||
setAutoSettings(data.settings)
|
||||
setAutoSettingsDirty(false)
|
||||
toast.success(t('backup.toast.settingsSaved'))
|
||||
} catch {
|
||||
toast.error(t('backup.toast.settingsError'))
|
||||
} finally {
|
||||
setAutoSettingsSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const formatSize = (bytes) => {
|
||||
if (!bytes) return '-'
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
|
||||
return `${(bytes / 1024 / 1024).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
const formatDate = (dateStr) => {
|
||||
if (!dateStr) return '-'
|
||||
try {
|
||||
const opts: Intl.DateTimeFormatOptions = {
|
||||
day: '2-digit', month: '2-digit', year: 'numeric',
|
||||
hour: '2-digit', minute: '2-digit',
|
||||
}
|
||||
if (serverTimezone) opts.timeZone = serverTimezone
|
||||
return new Date(dateStr).toLocaleString(locale, opts)
|
||||
} catch { return dateStr }
|
||||
}
|
||||
|
||||
const isAuto = (filename) => filename.startsWith('auto-backup-')
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
|
||||
{/* Manual Backups */}
|
||||
<MAdminCard>
|
||||
<MAdminCardHead
|
||||
title={
|
||||
<span className="flex items-center gap-2">
|
||||
<HardDrive size={15} strokeWidth={2.2} className="flex-none text-m-faint" />
|
||||
{t('backup.title')}
|
||||
</span>
|
||||
}
|
||||
hint={t('backup.subtitle')}
|
||||
trailing={
|
||||
<button
|
||||
type="button"
|
||||
onClick={loadBackups}
|
||||
disabled={isLoading}
|
||||
title={t('backup.refresh')}
|
||||
aria-label={t('backup.refresh')}
|
||||
className="flex h-[34px] w-[34px] flex-none items-center justify-center rounded-full border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] text-m-ink disabled:opacity-50"
|
||||
>
|
||||
<RefreshCw size={15} strokeWidth={2.2} className={isLoading ? 'animate-spin' : ''} />
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Upload & Create actions */}
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".zip"
|
||||
className="hidden"
|
||||
onChange={handleUploadRestore}
|
||||
/>
|
||||
<div className="mb-2 flex items-center gap-2">
|
||||
<MAdminButton
|
||||
variant="ghost"
|
||||
busy={isUploading}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
title={isUploading ? t('backup.uploading') : t('backup.upload')}
|
||||
>
|
||||
{!isUploading && <Upload size={12} strokeWidth={2.2} />}
|
||||
{isUploading ? t('backup.uploading') : t('backup.upload')}
|
||||
</MAdminButton>
|
||||
<MAdminButton
|
||||
busy={isCreating}
|
||||
onClick={handleCreate}
|
||||
title={isCreating ? t('backup.creating') : t('backup.create')}
|
||||
>
|
||||
{!isCreating && <Plus size={12} strokeWidth={2.2} />}
|
||||
{isCreating ? t('backup.creating') : t('backup.create')}
|
||||
</MAdminButton>
|
||||
</div>
|
||||
|
||||
{isLoading && backups.length === 0 ? (
|
||||
<div className="flex items-center justify-center gap-2 py-10 text-[0.8125rem] text-m-muted">
|
||||
<div className="h-5 w-5 rounded-full border-2 border-[color:var(--m-rowbr)] border-t-[color:var(--m-ink)] animate-spin" />
|
||||
{t('common.loading')}
|
||||
</div>
|
||||
) : backups.length === 0 ? (
|
||||
<div className="py-10 text-center text-m-muted">
|
||||
<HardDrive size={38} strokeWidth={1.6} className="mx-auto mb-3 opacity-40" />
|
||||
<p className="text-[0.8125rem]">{t('backup.empty')}</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleCreate}
|
||||
className="mt-3 text-[0.8125rem] font-bold text-m-ink underline"
|
||||
>
|
||||
{t('backup.createFirst')}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
{backups.map((backup, i) => (
|
||||
<div
|
||||
key={backup.filename}
|
||||
className={`flex flex-col gap-2 py-3 ${i === 0 ? '' : 'border-t border-[color:var(--m-rowbr)]'}`}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="flex h-9 w-9 flex-none items-center justify-center rounded-xl bg-[color:var(--m-ic)]">
|
||||
{isAuto(backup.filename)
|
||||
? <RefreshCw size={16} strokeWidth={2.2} className="text-[color:var(--m-st-info)]" />
|
||||
: <HardDrive size={16} strokeWidth={2.2} className="text-m-muted" />
|
||||
}
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<p className="min-w-0 truncate text-[0.8125rem] font-bold text-m-ink">{backup.filename}</p>
|
||||
{isAuto(backup.filename) && (
|
||||
<span className="flex-none rounded-full bg-[color:color-mix(in_srgb,var(--m-st-info)_14%,transparent)] px-2 py-[2px] font-geist text-[0.5625rem] font-bold text-[color:var(--m-st-info)]">
|
||||
Auto
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-[2px] flex items-center gap-3 font-geist text-[0.625rem] text-m-faint">
|
||||
<span>{formatDate(backup.created_at)}</span>
|
||||
<span>{formatSize(backup.size)}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 pl-12">
|
||||
<MAdminButton
|
||||
variant="ghost"
|
||||
onClick={() => backupApi.download(backup.filename).catch(() => toast.error(t('backup.toast.downloadError')))}
|
||||
>
|
||||
<Download size={12} strokeWidth={2.2} />
|
||||
{t('backup.download')}
|
||||
</MAdminButton>
|
||||
<MAdminButton
|
||||
variant="ghost"
|
||||
busy={restoringFile === backup.filename}
|
||||
onClick={() => handleRestore(backup.filename)}
|
||||
className="text-[color:var(--m-st-pending)]"
|
||||
>
|
||||
{restoringFile !== backup.filename && <RotateCcw size={12} strokeWidth={2.2} />}
|
||||
{t('backup.restore')}
|
||||
</MAdminButton>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleDelete(backup.filename)}
|
||||
aria-label={t('common.delete')}
|
||||
className="ml-auto flex h-8 w-8 flex-none items-center justify-center rounded-full text-m-faint"
|
||||
>
|
||||
<Trash2 size={16} strokeWidth={2.2} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</MAdminCard>
|
||||
|
||||
{/* Auto-Backup Settings */}
|
||||
<MAdminCard>
|
||||
<MAdminCardHead
|
||||
title={
|
||||
<span className="flex items-center gap-2">
|
||||
<Clock size={15} strokeWidth={2.2} className="flex-none text-m-faint" />
|
||||
{t('backup.auto.title')}
|
||||
</span>
|
||||
}
|
||||
hint={t('backup.auto.subtitle')}
|
||||
/>
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* Enable toggle */}
|
||||
<MAdminRow
|
||||
first
|
||||
title={t('backup.auto.enable')}
|
||||
hint={t('backup.auto.enableHint')}
|
||||
trailing={
|
||||
<MToggle
|
||||
checked={autoSettings.enabled}
|
||||
ariaLabel={t('backup.auto.enable')}
|
||||
onChange={(v) => handleAutoSettingsChange('enabled', v)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
{autoSettings.enabled && (
|
||||
<>
|
||||
{/* Interval */}
|
||||
<MAdminField label={t('backup.auto.interval')}>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{INTERVAL_OPTIONS.map(opt => (
|
||||
<MChip
|
||||
key={opt.value}
|
||||
active={autoSettings.interval === opt.value}
|
||||
onClick={() => handleAutoSettingsChange('interval', opt.value)}
|
||||
>
|
||||
{t(opt.labelKey)}
|
||||
</MChip>
|
||||
))}
|
||||
</div>
|
||||
</MAdminField>
|
||||
|
||||
{/* Hour picker (for daily, weekly, monthly) */}
|
||||
{autoSettings.interval !== 'hourly' && (
|
||||
<MAdminField
|
||||
label={t('backup.auto.hour')}
|
||||
hint={`${t('backup.auto.hourHint', { format: is12h ? '12h' : '24h' })}${serverTimezone ? ` (Timezone: ${serverTimezone})` : ''}`}
|
||||
>
|
||||
<select
|
||||
value={String(autoSettings.hour)}
|
||||
onChange={e => handleAutoSettingsChange('hour', parseInt(e.target.value, 10))}
|
||||
className={SELECT_CLASS}
|
||||
>
|
||||
{HOURS.map(h => {
|
||||
let label: string
|
||||
if (is12h) {
|
||||
const period = h >= 12 ? 'PM' : 'AM'
|
||||
const h12 = h === 0 ? 12 : h > 12 ? h - 12 : h
|
||||
label = `${h12}:00 ${period}`
|
||||
} else {
|
||||
label = `${String(h).padStart(2, '0')}:00`
|
||||
}
|
||||
return <option key={h} value={String(h)}>{label}</option>
|
||||
})}
|
||||
</select>
|
||||
</MAdminField>
|
||||
)}
|
||||
|
||||
{/* Day of week (for weekly) */}
|
||||
{autoSettings.interval === 'weekly' && (
|
||||
<MAdminField label={t('backup.auto.dayOfWeek')}>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{DAYS_OF_WEEK.map(opt => (
|
||||
<MChip
|
||||
key={opt.value}
|
||||
active={autoSettings.day_of_week === opt.value}
|
||||
onClick={() => handleAutoSettingsChange('day_of_week', opt.value)}
|
||||
>
|
||||
{t(opt.labelKey)}
|
||||
</MChip>
|
||||
))}
|
||||
</div>
|
||||
</MAdminField>
|
||||
)}
|
||||
|
||||
{/* Day of month (for monthly) */}
|
||||
{autoSettings.interval === 'monthly' && (
|
||||
<MAdminField label={t('backup.auto.dayOfMonth')} hint={t('backup.auto.dayOfMonthHint')}>
|
||||
<select
|
||||
value={String(autoSettings.day_of_month)}
|
||||
onChange={e => handleAutoSettingsChange('day_of_month', parseInt(e.target.value, 10))}
|
||||
className={SELECT_CLASS}
|
||||
>
|
||||
{DAYS_OF_MONTH.map(d => (
|
||||
<option key={d} value={String(d)}>{String(d)}</option>
|
||||
))}
|
||||
</select>
|
||||
</MAdminField>
|
||||
)}
|
||||
|
||||
{/* Keep duration */}
|
||||
<MAdminField label={t('backup.auto.keepLabel')}>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{KEEP_OPTIONS.map(opt => (
|
||||
<MChip
|
||||
key={opt.value}
|
||||
active={autoSettings.keep_days === opt.value}
|
||||
onClick={() => handleAutoSettingsChange('keep_days', opt.value)}
|
||||
>
|
||||
{t(opt.labelKey)}
|
||||
</MChip>
|
||||
))}
|
||||
</div>
|
||||
</MAdminField>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Save button */}
|
||||
<div className="flex justify-end border-t border-[color:var(--m-rowbr)] pt-3">
|
||||
<MAdminButton
|
||||
busy={autoSettingsSaving}
|
||||
disabled={autoSettingsSaving || !autoSettingsDirty}
|
||||
onClick={handleSaveAutoSettings}
|
||||
>
|
||||
{!autoSettingsSaving && <Check size={12} strokeWidth={2.2} />}
|
||||
{autoSettingsSaving ? t('common.saving') : t('common.save')}
|
||||
</MAdminButton>
|
||||
</div>
|
||||
</div>
|
||||
</MAdminCard>
|
||||
|
||||
{/* Restore Warning */}
|
||||
<MConfirmSheet
|
||||
open={!!restoreConfirm}
|
||||
onClose={() => setRestoreConfirm(null)}
|
||||
title={t('backup.restoreConfirmTitle')}
|
||||
message={
|
||||
<>
|
||||
<span className="block font-bold text-m-ink">{restoreConfirm?.filename}</span>
|
||||
<span className="mt-2 block">{t('backup.restoreWarning')}</span>
|
||||
</>
|
||||
}
|
||||
confirmLabel={t('backup.restoreConfirm')}
|
||||
cancelLabel={t('common.cancel')}
|
||||
danger
|
||||
onConfirm={executeRestore}
|
||||
>
|
||||
<div className="mt-3 rounded-xl border border-[color:color-mix(in_srgb,var(--m-st-danger)_28%,transparent)] bg-[color:color-mix(in_srgb,var(--m-st-danger)_10%,transparent)] px-3 py-2 font-geist text-[0.625rem] leading-relaxed text-[color:var(--m-st-danger)]">
|
||||
{t('backup.restoreTip')}
|
||||
</div>
|
||||
</MConfirmSheet>
|
||||
|
||||
{/* Delete confirm */}
|
||||
<MConfirmSheet
|
||||
open={!!deleteConfirm}
|
||||
onClose={() => setDeleteConfirm(null)}
|
||||
title={t('common.delete')}
|
||||
message={t('backup.confirm.delete', { name: deleteConfirm ?? '' })}
|
||||
confirmLabel={t('common.delete')}
|
||||
cancelLabel={t('common.cancel')}
|
||||
danger
|
||||
onConfirm={executeDelete}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { Plus, Edit2, Trash2, Pipette } from 'lucide-react'
|
||||
import { categoriesApi } from '../../../api/client'
|
||||
import { useToast } from '../../../components/shared/Toast'
|
||||
import { CATEGORY_ICON_MAP, ICON_LABELS, getCategoryIcon } from '../../../components/shared/categoryIcons'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import { getApiErrorMessage } from '../../../types'
|
||||
import MConfirmSheet from '../settings/MConfirmSheet'
|
||||
import { MAdminButton, MAdminCard, MAdminCardHead } from './MAdminUi'
|
||||
|
||||
const PRESET_COLORS = [
|
||||
'#6366f1', '#8b5cf6', '#ec4899', '#ef4444', '#f97316',
|
||||
'#f59e0b', '#10b981', '#06b6d4', '#3b82f6', '#84cc16',
|
||||
'#6b7280', '#1f2937',
|
||||
]
|
||||
|
||||
const ICON_NAMES = Object.keys(CATEGORY_ICON_MAP)
|
||||
|
||||
export default function MAdminCategoryManager() {
|
||||
const [categories, setCategories] = useState([])
|
||||
const [showForm, setShowForm] = useState(false)
|
||||
const [editingId, setEditingId] = useState(null)
|
||||
const [form, setForm] = useState({ name: '', color: '#6366f1', icon: 'MapPin' })
|
||||
const [isSaving, setIsSaving] = useState(false)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [deleteId, setDeleteId] = useState(null)
|
||||
const [isDeleting, setIsDeleting] = useState(false)
|
||||
const colorInputRef = useRef(null)
|
||||
const toast = useToast()
|
||||
const { t } = useTranslation()
|
||||
|
||||
useEffect(() => { loadCategories() }, [])
|
||||
|
||||
const loadCategories = async () => {
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const data = await categoriesApi.list()
|
||||
setCategories(data.categories || [])
|
||||
} catch (err: unknown) {
|
||||
toast.error(t('categories.toast.loadError'))
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleStartEdit = (cat) => {
|
||||
setEditingId(cat.id)
|
||||
setForm({ name: cat.name, color: cat.color || '#6366f1', icon: cat.icon || 'MapPin' })
|
||||
setShowForm(false)
|
||||
}
|
||||
|
||||
const handleStartCreate = () => {
|
||||
setEditingId(null)
|
||||
setForm({ name: '', color: '#6366f1', icon: 'MapPin' })
|
||||
setShowForm(true)
|
||||
}
|
||||
|
||||
const handleCancel = () => {
|
||||
setShowForm(false)
|
||||
setEditingId(null)
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!form.name.trim()) { toast.error(t('categories.toast.nameRequired')); return }
|
||||
setIsSaving(true)
|
||||
try {
|
||||
if (editingId) {
|
||||
const result = await categoriesApi.update(editingId, form)
|
||||
setCategories(prev => prev.map(c => c.id === editingId ? result.category : c))
|
||||
setEditingId(null)
|
||||
toast.success(t('categories.toast.updated'))
|
||||
} else {
|
||||
const result = await categoriesApi.create(form)
|
||||
setCategories(prev => [...prev, result.category])
|
||||
setShowForm(false)
|
||||
toast.success(t('categories.toast.created'))
|
||||
}
|
||||
setForm({ name: '', color: '#6366f1', icon: 'MapPin' })
|
||||
} catch (err: unknown) {
|
||||
toast.error(getApiErrorMessage(err, t('categories.toast.saveError')))
|
||||
} finally {
|
||||
setIsSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (id) => {
|
||||
setIsDeleting(true)
|
||||
try {
|
||||
await categoriesApi.delete(id)
|
||||
setCategories(prev => prev.filter(c => c.id !== id))
|
||||
toast.success(t('categories.toast.deleted'))
|
||||
setDeleteId(null)
|
||||
} catch (err: unknown) {
|
||||
toast.error(getApiErrorMessage(err, t('categories.toast.deleteError')))
|
||||
} finally {
|
||||
setIsDeleting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const isPresetColor = PRESET_COLORS.includes(form.color)
|
||||
const PreviewIcon = getCategoryIcon(form.icon)
|
||||
|
||||
const categoryForm = (
|
||||
<div className="space-y-3 rounded-2xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] p-4">
|
||||
<input
|
||||
type="text"
|
||||
value={form.name}
|
||||
onChange={e => setForm(prev => ({ ...prev, name: e.target.value }))}
|
||||
placeholder={t('categories.namePlaceholder')}
|
||||
className="h-[42px] w-full rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheetop)] px-3 text-[0.84375rem] text-m-ink outline-none placeholder:text-m-faint focus:border-[color:var(--m-faint)]"
|
||||
autoFocus
|
||||
/>
|
||||
|
||||
<div>
|
||||
<div className="mb-[6px] text-[0.75rem] font-semibold text-m-ink">{t('categories.icon')}</div>
|
||||
<div className="max-h-48 overflow-y-auto">
|
||||
<div className="flex flex-wrap gap-1.5 px-1.5 py-1.5">
|
||||
{ICON_NAMES.map(name => {
|
||||
const Icon = CATEGORY_ICON_MAP[name]
|
||||
const isSelected = form.icon === name
|
||||
return (
|
||||
<button
|
||||
key={name}
|
||||
type="button"
|
||||
title={ICON_LABELS[name] || name}
|
||||
onClick={() => setForm(prev => ({ ...prev, icon: name }))}
|
||||
className={`flex h-9 w-9 items-center justify-center rounded-lg border-2 transition-colors ${
|
||||
isSelected ? '' : 'border-transparent hover:bg-[color:var(--m-sheetop)]'
|
||||
}`}
|
||||
style={isSelected ? { background: `${form.color}1f`, borderColor: form.color } : undefined}
|
||||
>
|
||||
<span className={isSelected ? '' : 'text-m-faint'}>
|
||||
<Icon size={17} strokeWidth={1.8} color={isSelected ? form.color : undefined} />
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div className="mb-[6px] text-[0.75rem] font-semibold text-m-ink">{t('categories.color')}</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{PRESET_COLORS.map(color => (
|
||||
<button key={color} type="button" onClick={() => setForm(prev => ({ ...prev, color }))}
|
||||
className={`h-7 w-7 rounded-full transition-transform hover:scale-110 ${
|
||||
form.color === color
|
||||
? 'scale-110 ring-2 ring-[color:var(--m-faint)] ring-offset-2 ring-offset-[color:var(--m-ic)]'
|
||||
: ''
|
||||
}`}
|
||||
style={{ backgroundColor: color }} />
|
||||
))}
|
||||
|
||||
{/* Custom color button */}
|
||||
<input
|
||||
ref={colorInputRef}
|
||||
type="color"
|
||||
value={form.color}
|
||||
onChange={e => setForm(prev => ({ ...prev, color: e.target.value }))}
|
||||
className="sr-only"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
title={t('categories.customColor')}
|
||||
onClick={() => colorInputRef.current?.click()}
|
||||
className={`flex h-7 w-7 items-center justify-center rounded-full border-2 transition-transform hover:scale-110 ${
|
||||
!isPresetColor
|
||||
? 'scale-110 border-transparent ring-2 ring-[color:var(--m-faint)] ring-offset-2 ring-offset-[color:var(--m-ic)]'
|
||||
: 'border-dashed border-[color:var(--m-rowbr)]'
|
||||
}`}
|
||||
style={!isPresetColor ? { backgroundColor: form.color } : undefined}
|
||||
>
|
||||
{isPresetColor && <Pipette className="h-3 w-3 text-m-faint" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-[0.6875rem] text-m-muted">{t('categories.preview')}:</span>
|
||||
<span className="inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[0.8125rem] font-medium"
|
||||
style={{ backgroundColor: `${form.color}20`, color: form.color }}>
|
||||
<PreviewIcon size={14} strokeWidth={1.8} />
|
||||
{form.name || t('categories.defaultName')}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<MAdminButton variant="ghost" onClick={handleCancel}>
|
||||
{t('common.cancel')}
|
||||
</MAdminButton>
|
||||
<MAdminButton busy={isSaving} disabled={isSaving || !form.name.trim()} onClick={handleSave}>
|
||||
{isSaving ? t('common.saving') : editingId ? t('categories.update') : t('categories.create')}
|
||||
</MAdminButton>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
return (
|
||||
<MAdminCard>
|
||||
<MAdminCardHead
|
||||
title={t('categories.title')}
|
||||
hint={t('categories.subtitle')}
|
||||
trailing={
|
||||
<MAdminButton onClick={handleStartCreate}>
|
||||
<Plus size={12} strokeWidth={2.4} />
|
||||
{t('categories.new')}
|
||||
</MAdminButton>
|
||||
}
|
||||
/>
|
||||
|
||||
{showForm && <div className="mb-3 mt-1">{categoryForm}</div>}
|
||||
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-8 text-m-faint">
|
||||
<div className="h-6 w-6 animate-spin rounded-full border-2 border-[color:var(--m-rowbr)] border-t-[color:var(--m-ink)]" />
|
||||
</div>
|
||||
) : categories.length === 0 ? (
|
||||
<div className="py-8 text-center text-m-faint">
|
||||
<p className="text-[0.8125rem]">{t('categories.empty')}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="mt-1 space-y-2">
|
||||
{categories.map(cat => {
|
||||
const Icon = getCategoryIcon(cat.icon)
|
||||
return (
|
||||
<div key={cat.id}>
|
||||
{editingId === cat.id ? (
|
||||
<div className="mb-2">{categoryForm}</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-3 rounded-xl border border-[color:var(--m-rowbr)] p-3">
|
||||
<div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl"
|
||||
style={{ backgroundColor: `${cat.color}20` }}>
|
||||
<Icon size={18} strokeWidth={1.8} color={cat.color} />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="text-[0.8125rem] font-bold text-m-ink">{cat.name}</span>
|
||||
<span className="rounded-full px-2 py-0.5 text-[0.625rem] font-geist"
|
||||
style={{ backgroundColor: `${cat.color}20`, color: cat.color }}>
|
||||
{cat.color}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-none items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('common.edit')}
|
||||
onClick={() => handleStartEdit(cat)}
|
||||
className="flex h-8 w-8 items-center justify-center rounded-lg text-m-faint hover:bg-[color:var(--m-ic)] hover:text-m-ink"
|
||||
>
|
||||
<Edit2 className="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('common.delete')}
|
||||
onClick={() => setDeleteId(cat.id)}
|
||||
className="flex h-8 w-8 items-center justify-center rounded-lg text-m-faint hover:bg-[color:color-mix(in_srgb,var(--m-st-danger)_12%,transparent)] hover:text-[color:var(--m-st-danger)]"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<MConfirmSheet
|
||||
open={deleteId !== null}
|
||||
onClose={() => setDeleteId(null)}
|
||||
title={t('categories.title')}
|
||||
message={t('categories.confirm.delete')}
|
||||
confirmLabel={t('common.delete')}
|
||||
cancelLabel={t('common.cancel')}
|
||||
danger
|
||||
busy={isDeleting}
|
||||
onConfirm={() => deleteId !== null && handleDelete(deleteId)}
|
||||
/>
|
||||
</MAdminCard>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
import React, { useEffect, useMemo, useState } from 'react'
|
||||
import { ChevronDown, Settings2 } from 'lucide-react'
|
||||
import { adminApi } from '../../../api/client'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import { useToast } from '../../../components/shared/Toast'
|
||||
import { MapView } from '../../../components/Map/MapView'
|
||||
import { SYMBOLS, currenciesWith } from '../../../components/Budget/BudgetPanel.constants'
|
||||
import type { DistanceUnit, Place } from '../../../types'
|
||||
import {
|
||||
MAPBOX_DEFAULT_STYLE,
|
||||
defaultStyleForProvider,
|
||||
getStylePresets,
|
||||
isOpenFreeMapStyle,
|
||||
normalizeStyleForProvider,
|
||||
styleSettingKey,
|
||||
type GlMapProvider,
|
||||
} from '../../../components/Map/glProviders'
|
||||
import MToggle from '../../components/MToggle'
|
||||
import MSegmented from '../../components/MSegmented'
|
||||
import { MAdminCard, MAdminCardHead, MAdminField, MAdminInput, MAdminRow } from './MAdminUi'
|
||||
import { MSetSelectRow } from '../settings/MSettingsUi'
|
||||
import MSetPickerSheet from '../settings/MSetPickerSheet'
|
||||
|
||||
const MAP_PRESETS = [
|
||||
{ name: 'OpenStreetMap', url: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' },
|
||||
{ name: 'OpenStreetMap DE', url: 'https://tile.openstreetmap.de/{z}/{x}/{y}.png' },
|
||||
{ name: 'CartoDB Light', url: 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png' },
|
||||
{ name: 'CartoDB Dark', url: 'https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png' },
|
||||
{ name: 'Stadia Smooth', url: 'https://tiles.stadiamaps.com/tiles/alidade_smooth/{z}/{x}/{y}{r}.png' },
|
||||
]
|
||||
|
||||
type Defaults = {
|
||||
temperature_unit?: string
|
||||
distance_unit?: DistanceUnit
|
||||
dark_mode?: string | boolean
|
||||
time_format?: string
|
||||
default_currency?: string
|
||||
blur_booking_codes?: boolean
|
||||
map_tile_url?: string
|
||||
map_provider?: string
|
||||
mapbox_access_token?: string
|
||||
mapbox_style?: string
|
||||
maplibre_style?: string
|
||||
mapbox_3d_enabled?: boolean
|
||||
mapbox_quality_mode?: boolean
|
||||
}
|
||||
|
||||
type MapProvider = 'leaflet' | GlMapProvider
|
||||
|
||||
function normalizeProvider(value: unknown): MapProvider {
|
||||
return value === 'mapbox-gl' || value === 'maplibre-gl' ? value : 'leaflet'
|
||||
}
|
||||
|
||||
function styleForProvider(provider: MapProvider, style?: string | null): string {
|
||||
if (provider === 'leaflet') return style || MAPBOX_DEFAULT_STYLE
|
||||
if (provider === 'mapbox-gl' && isOpenFreeMapStyle(style)) return MAPBOX_DEFAULT_STYLE
|
||||
return normalizeStyleForProvider(provider, style)
|
||||
}
|
||||
|
||||
// Mobile-native rebuild of the desktop DefaultUserSettingsTab. Identical data
|
||||
// layer (adminApi defaults, per-change auto-save, reset-to-built-in) — only the
|
||||
// presentation is relaid on the admin mobile design system.
|
||||
export default function MAdminDefaultUserSettings(): React.ReactElement {
|
||||
const { t } = useTranslation()
|
||||
const toast = useToast()
|
||||
const [defaults, setDefaults] = useState<Defaults>({})
|
||||
const [loaded, setLoaded] = useState(false)
|
||||
const [mapTileUrl, setMapTileUrl] = useState('')
|
||||
const [mapboxToken, setMapboxToken] = useState('')
|
||||
const [mapboxStyle, setMapboxStyle] = useState('')
|
||||
const [currencyOpen, setCurrencyOpen] = useState(false)
|
||||
const [presetOpen, setPresetOpen] = useState(false)
|
||||
const [styleOpen, setStyleOpen] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
adminApi.getDefaultUserSettings().then((data: Defaults) => {
|
||||
const provider = normalizeProvider(data.map_provider)
|
||||
setDefaults(data)
|
||||
setMapTileUrl(data.map_tile_url || '')
|
||||
setMapboxToken(data.mapbox_access_token || '')
|
||||
setMapboxStyle(provider === 'leaflet' ? (data.mapbox_style || '') : styleForProvider(provider, provider === 'maplibre-gl' ? data.maplibre_style : data.mapbox_style))
|
||||
setLoaded(true)
|
||||
}).catch(() => setLoaded(true))
|
||||
}, [])
|
||||
|
||||
const save = async (patch: Partial<Defaults>) => {
|
||||
try {
|
||||
const updated = await adminApi.updateDefaultUserSettings(patch as Record<string, unknown>)
|
||||
setDefaults(updated)
|
||||
toast.success(t('admin.defaultSettings.saved'))
|
||||
} catch (err: unknown) {
|
||||
toast.error(err instanceof Error ? err.message : t('common.error'))
|
||||
}
|
||||
}
|
||||
|
||||
const reset = async (key: keyof Defaults) => {
|
||||
try {
|
||||
const updated = await adminApi.updateDefaultUserSettings({ [key]: null })
|
||||
setDefaults(updated)
|
||||
if (key === 'map_tile_url') setMapTileUrl('')
|
||||
if (key === 'mapbox_access_token') setMapboxToken('')
|
||||
if (key === 'mapbox_style' || key === 'maplibre_style') {
|
||||
const provider = normalizeProvider(defaults.map_provider)
|
||||
setMapboxStyle(provider === 'leaflet' ? '' : defaultStyleForProvider(provider))
|
||||
}
|
||||
toast.success(t('admin.defaultSettings.reset'))
|
||||
} catch (err: unknown) {
|
||||
toast.error(err instanceof Error ? err.message : t('common.error'))
|
||||
}
|
||||
}
|
||||
|
||||
const isSet = (key: keyof Defaults) => defaults[key] !== undefined
|
||||
|
||||
const ResetButton = ({ field }: { field: keyof Defaults }) =>
|
||||
isSet(field) ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => reset(field)}
|
||||
className="ml-2 font-geist text-[0.625rem] font-medium text-m-faint underline"
|
||||
>
|
||||
{t('admin.defaultSettings.resetToBuiltIn')}
|
||||
</button>
|
||||
) : null
|
||||
|
||||
const mapPreviewPlaces = useMemo((): Place[] => [{
|
||||
id: 1,
|
||||
trip_id: 1,
|
||||
name: 'Preview center',
|
||||
description: null,
|
||||
notes: null,
|
||||
lat: 48.8566,
|
||||
lng: 2.3522,
|
||||
address: null,
|
||||
category_id: null,
|
||||
price: null,
|
||||
currency: null,
|
||||
image_url: null,
|
||||
google_place_id: null,
|
||||
osm_id: null,
|
||||
route_geometry: null,
|
||||
place_time: null,
|
||||
end_time: null,
|
||||
duration_minutes: null,
|
||||
transport_mode: null,
|
||||
website: null,
|
||||
phone: null,
|
||||
created_at: Date(),
|
||||
}], [])
|
||||
|
||||
if (!loaded) {
|
||||
return (
|
||||
<MAdminCard>
|
||||
<p className="font-geist text-[0.75rem] italic text-m-faint">Loading…</p>
|
||||
</MAdminCard>
|
||||
)
|
||||
}
|
||||
|
||||
const darkMode = defaults.dark_mode
|
||||
const mapProvider = normalizeProvider(defaults.map_provider)
|
||||
const glStylePresets = mapProvider === 'leaflet' ? [] : getStylePresets(mapProvider)
|
||||
const styleKey: keyof Defaults = mapProvider === 'maplibre-gl' ? 'maplibre_style' : 'mapbox_style'
|
||||
const saveMapProvider = (nextProvider: MapProvider) => {
|
||||
const patch: Partial<Defaults> = { map_provider: nextProvider }
|
||||
if (nextProvider !== 'leaflet') {
|
||||
// Load + save the new provider's own style slot so the other provider's style is kept.
|
||||
const slot = nextProvider === 'maplibre-gl' ? defaults.maplibre_style : defaults.mapbox_style
|
||||
const nextStyle = styleForProvider(nextProvider, slot)
|
||||
setMapboxStyle(nextStyle)
|
||||
patch[styleSettingKey(nextProvider)] = nextStyle
|
||||
}
|
||||
save(patch)
|
||||
}
|
||||
|
||||
// No active value when the setting is unset → segmented shows no pill, matching
|
||||
// the desktop tab (which only highlights a button once a default is chosen).
|
||||
const colorModeValue =
|
||||
darkMode === 'dark' || darkMode === true
|
||||
? 'dark'
|
||||
: darkMode === 'light' || darkMode === false
|
||||
? 'light'
|
||||
: darkMode === 'auto'
|
||||
? 'auto'
|
||||
: ''
|
||||
|
||||
const modeOptions: { value: string; label: React.ReactNode }[] = [
|
||||
{ value: 'light', label: t('settings.light') },
|
||||
{ value: 'dark', label: t('settings.dark') },
|
||||
{ value: 'auto', label: t('settings.auto') },
|
||||
]
|
||||
const tempOptions: { value: string; label: React.ReactNode }[] = [
|
||||
{ value: 'celsius', label: '°C Celsius' },
|
||||
{ value: 'fahrenheit', label: '°F Fahrenheit' },
|
||||
]
|
||||
const distanceOptions: { value: string; label: React.ReactNode }[] = [
|
||||
{ value: 'metric', label: 'km Metric' },
|
||||
{ value: 'imperial', label: 'mi Imperial' },
|
||||
]
|
||||
const timeOptions: { value: string; label: React.ReactNode }[] = [
|
||||
{ value: '24h', label: '24h (14:30)' },
|
||||
{ value: '12h', label: '12h (2:30 PM)' },
|
||||
]
|
||||
const providerOptions: { value: string; label: React.ReactNode }[] = [
|
||||
{ value: 'leaflet', label: t('admin.defaultSettings.providerLeaflet') },
|
||||
{ value: 'mapbox-gl', label: t('admin.defaultSettings.providerMapbox') },
|
||||
{ value: 'maplibre-gl', label: t('admin.defaultSettings.providerMapLibre') },
|
||||
]
|
||||
|
||||
const currencyLabel = defaults.default_currency
|
||||
? (SYMBOLS[defaults.default_currency] ? `${defaults.default_currency} ${SYMBOLS[defaults.default_currency]}` : defaults.default_currency)
|
||||
: t('settings.currency')
|
||||
const tilePresetLabel = MAP_PRESETS.find((p) => p.url === mapTileUrl)?.name || t('settings.mapTemplatePlaceholder.select')
|
||||
const stylePresetLabel = glStylePresets.find((p) => p.url === mapboxStyle)?.name || t('admin.defaultSettings.mapboxStylePlaceholder')
|
||||
const chevron = <ChevronDown size={13} strokeWidth={2} className="flex-none text-m-faint" />
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{/* Display + regional defaults */}
|
||||
<MAdminCard>
|
||||
<MAdminCardHead title={t('admin.defaultSettings.title')} hint={t('admin.defaultSettings.description')} />
|
||||
|
||||
<div className="mt-2 space-y-[14px]">
|
||||
{/* Color Mode */}
|
||||
<MAdminField label={<>{t('settings.colorMode')} <ResetButton field="dark_mode" /></>}>
|
||||
<MSegmented value={colorModeValue} onChange={(v) => save({ dark_mode: v })} options={modeOptions} />
|
||||
</MAdminField>
|
||||
|
||||
{/* Temperature */}
|
||||
<MAdminField label={<>{t('settings.temperature')} <ResetButton field="temperature_unit" /></>}>
|
||||
<MSegmented value={defaults.temperature_unit || ''} onChange={(v) => save({ temperature_unit: v })} options={tempOptions} />
|
||||
</MAdminField>
|
||||
|
||||
{/* Distance */}
|
||||
<MAdminField label={<>{t('settings.distance')} <ResetButton field="distance_unit" /></>}>
|
||||
<MSegmented value={defaults.distance_unit || ''} onChange={(v) => save({ distance_unit: v as DistanceUnit })} options={distanceOptions} />
|
||||
</MAdminField>
|
||||
|
||||
{/* Time Format */}
|
||||
<MAdminField label={<>{t('settings.timeFormat')} <ResetButton field="time_format" /></>}>
|
||||
<MSegmented value={defaults.time_format || ''} onChange={(v) => save({ time_format: v })} options={timeOptions} />
|
||||
</MAdminField>
|
||||
|
||||
{/* Default Currency */}
|
||||
<MAdminField
|
||||
label={<>{t('settings.currency')} <ResetButton field="default_currency" /></>}
|
||||
hint={t('settings.currencyHint')}
|
||||
>
|
||||
<MSetSelectRow label={currencyLabel} trailing={chevron} onClick={() => setCurrencyOpen(true)} />
|
||||
</MAdminField>
|
||||
|
||||
{/* Blur Booking Codes */}
|
||||
<MAdminRow
|
||||
first
|
||||
title={<>{t('settings.blurBookingCodes')} <ResetButton field="blur_booking_codes" /></>}
|
||||
trailing={
|
||||
<MToggle
|
||||
checked={defaults.blur_booking_codes === true}
|
||||
ariaLabel={t('settings.blurBookingCodes')}
|
||||
onChange={(v) => save({ blur_booking_codes: v })}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</MAdminCard>
|
||||
|
||||
{/* Map */}
|
||||
<MAdminCard>
|
||||
<div className="mb-1 flex items-center gap-2 text-[0.875rem] font-extrabold text-m-ink">
|
||||
<Settings2 size={16} strokeWidth={2.2} className="flex-none" />
|
||||
<span className="min-w-0 flex-1 truncate">{t('settings.mapTemplate')}</span>
|
||||
</div>
|
||||
|
||||
<div className="mt-2 space-y-[14px]">
|
||||
{/* Map Tile URL */}
|
||||
<MAdminField
|
||||
label={<>{t('settings.mapTemplate')} <ResetButton field="map_tile_url" /></>}
|
||||
hint={t('settings.mapDefaultHint')}
|
||||
>
|
||||
<MSetSelectRow label={tilePresetLabel} trailing={chevron} onClick={() => setPresetOpen(true)} />
|
||||
<MAdminInput
|
||||
type="text"
|
||||
className="mt-[6px]"
|
||||
value={mapTileUrl}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setMapTileUrl(e.target.value)}
|
||||
onBlur={() => save({ map_tile_url: mapTileUrl })}
|
||||
placeholder="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
|
||||
/>
|
||||
</MAdminField>
|
||||
|
||||
{/* Live tile preview */}
|
||||
<div className="relative h-[200px] w-full overflow-hidden rounded-xl">
|
||||
{/* eslint-disable-next-line @typescript-eslint/no-explicit-any */}
|
||||
{React.createElement(MapView as any, {
|
||||
places: mapPreviewPlaces,
|
||||
dayPlaces: [],
|
||||
route: null,
|
||||
routeSegments: null,
|
||||
selectedPlaceId: null,
|
||||
onMarkerClick: null,
|
||||
onMapClick: null,
|
||||
onMapContextMenu: null,
|
||||
center: [48.8566, 2.3522],
|
||||
zoom: 10,
|
||||
tileUrl: mapTileUrl,
|
||||
fitKey: null,
|
||||
dayOrderMap: [],
|
||||
leftWidth: 0,
|
||||
rightWidth: 0,
|
||||
hasInspector: false,
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Map provider */}
|
||||
<div className="border-t border-[color:var(--m-rowbr)] pt-[14px]">
|
||||
<MAdminField
|
||||
label={<>{t('admin.defaultSettings.mapProvider')} <ResetButton field="map_provider" /></>}
|
||||
hint={t('admin.defaultSettings.mapProviderHint')}
|
||||
>
|
||||
<MSegmented value={mapProvider} onChange={(v) => saveMapProvider(v as MapProvider)} options={providerOptions} />
|
||||
</MAdminField>
|
||||
</div>
|
||||
|
||||
{mapProvider !== 'leaflet' && (
|
||||
<div className="space-y-[14px]">
|
||||
{mapProvider === 'mapbox-gl' && (
|
||||
<MAdminField
|
||||
label={<>{t('admin.defaultSettings.mapboxToken')} <ResetButton field="mapbox_access_token" /></>}
|
||||
hint={t('admin.defaultSettings.mapboxTokenHint')}
|
||||
>
|
||||
<MAdminInput
|
||||
type="text"
|
||||
value={mapboxToken}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setMapboxToken(e.target.value)}
|
||||
onBlur={() => save({ mapbox_access_token: mapboxToken })}
|
||||
placeholder="pk.eyJ…"
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
/>
|
||||
</MAdminField>
|
||||
)}
|
||||
|
||||
<MAdminField label={<>{t('admin.defaultSettings.mapboxStyle')} <ResetButton field={styleKey} /></>}>
|
||||
<MSetSelectRow label={stylePresetLabel} trailing={chevron} onClick={() => setStyleOpen(true)} />
|
||||
<MAdminInput
|
||||
type="text"
|
||||
className="mt-[6px]"
|
||||
value={mapboxStyle}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setMapboxStyle(e.target.value)}
|
||||
onBlur={() => {
|
||||
const nextStyle = normalizeStyleForProvider(mapProvider, mapboxStyle)
|
||||
setMapboxStyle(nextStyle)
|
||||
save({ [styleKey]: nextStyle })
|
||||
}}
|
||||
placeholder={defaultStyleForProvider(mapProvider)}
|
||||
/>
|
||||
</MAdminField>
|
||||
|
||||
{mapProvider === 'mapbox-gl' && (
|
||||
<div>
|
||||
<MAdminRow
|
||||
first
|
||||
title={<>{t('admin.defaultSettings.mapbox3d')} <ResetButton field="mapbox_3d_enabled" /></>}
|
||||
trailing={
|
||||
<MToggle
|
||||
checked={defaults.mapbox_3d_enabled ?? true}
|
||||
ariaLabel={t('admin.defaultSettings.mapbox3d')}
|
||||
onChange={(v) => save({ mapbox_3d_enabled: v })}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<MAdminRow
|
||||
title={<>{t('admin.defaultSettings.mapboxQuality')} <ResetButton field="mapbox_quality_mode" /></>}
|
||||
trailing={
|
||||
<MToggle
|
||||
checked={defaults.mapbox_quality_mode ?? false}
|
||||
ariaLabel={t('admin.defaultSettings.mapboxQuality')}
|
||||
onChange={(v) => save({ mapbox_quality_mode: v })}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</MAdminCard>
|
||||
|
||||
{/* Pickers */}
|
||||
<MSetPickerSheet
|
||||
open={currencyOpen}
|
||||
onClose={() => setCurrencyOpen(false)}
|
||||
title={t('settings.currency')}
|
||||
value={defaults.default_currency || ''}
|
||||
onSelect={(value) => { if (value) save({ default_currency: value }) }}
|
||||
options={currenciesWith(defaults.default_currency).map((c) => ({ value: c, label: SYMBOLS[c] ? `${c} ${SYMBOLS[c]}` : c }))}
|
||||
/>
|
||||
|
||||
<MSetPickerSheet
|
||||
open={presetOpen}
|
||||
onClose={() => setPresetOpen(false)}
|
||||
title={t('settings.mapTemplate')}
|
||||
value={mapTileUrl}
|
||||
onSelect={(value) => { if (value) { setMapTileUrl(value); save({ map_tile_url: value }) } }}
|
||||
options={MAP_PRESETS.map((p) => ({ value: p.url, label: p.name }))}
|
||||
/>
|
||||
|
||||
<MSetPickerSheet
|
||||
open={styleOpen}
|
||||
onClose={() => setStyleOpen(false)}
|
||||
title={t('admin.defaultSettings.mapboxStyle')}
|
||||
value={mapboxStyle}
|
||||
onSelect={(value) => { if (value) { setMapboxStyle(value); save({ [styleKey]: value }) } }}
|
||||
options={glStylePresets.map((p) => ({ value: p.url, label: p.name }))}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
import React, { useState, useEffect } from 'react'
|
||||
import {
|
||||
Bell, Zap, CheckCircle, Navigation, Calendar, Clock, Image,
|
||||
MessageSquare, Tag, UserPlus, Download, MapPin, Loader2,
|
||||
} from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import { adminApi, tripsApi } from '../../../api/client'
|
||||
import { useAuthStore } from '../../../store/authStore'
|
||||
import { useToast } from '../../../components/shared/Toast'
|
||||
import { MAdminCard, MAdminCardHead } from './MAdminUi'
|
||||
|
||||
interface Trip {
|
||||
id: number
|
||||
title: string
|
||||
}
|
||||
|
||||
interface AppUser {
|
||||
id: number
|
||||
username: string
|
||||
email: string
|
||||
}
|
||||
|
||||
// Dev-only notification testing panel, re-skinned to the mobile admin system.
|
||||
// All state, fetches and fire() payloads are ported verbatim from the desktop
|
||||
// DevNotificationsPanel — only the presentation layer changes.
|
||||
export default function MAdminDevNotificationsPanel(): React.ReactElement {
|
||||
const toast = useToast()
|
||||
const user = useAuthStore(s => s.user)
|
||||
const [sending, setSending] = useState<string | null>(null)
|
||||
const [trips, setTrips] = useState<Trip[]>([])
|
||||
const [selectedTripId, setSelectedTripId] = useState<number | null>(null)
|
||||
const [users, setUsers] = useState<AppUser[]>([])
|
||||
const [selectedUserId, setSelectedUserId] = useState<number | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
tripsApi.list().then(data => {
|
||||
const list = (data.trips || data || []) as Trip[]
|
||||
setTrips(list)
|
||||
if (list.length > 0) setSelectedTripId(list[0].id)
|
||||
}).catch(() => {})
|
||||
adminApi.users().then(data => {
|
||||
const list = (data.users || data || []) as AppUser[]
|
||||
setUsers(list)
|
||||
if (list.length > 0) setSelectedUserId(list[0].id)
|
||||
}).catch(() => {})
|
||||
}, [])
|
||||
|
||||
const fire = async (label: string, payload: Record<string, unknown>) => {
|
||||
setSending(label)
|
||||
try {
|
||||
await adminApi.sendTestNotification(payload)
|
||||
toast.success(`Sent: ${label}`)
|
||||
} catch (err: any) {
|
||||
toast.error(err.message || 'Failed')
|
||||
} finally {
|
||||
setSending(null)
|
||||
}
|
||||
}
|
||||
|
||||
const selectedTrip = trips.find(t => t.id === selectedTripId)
|
||||
const selectedUser = users.find(u => u.id === selectedUserId)
|
||||
const username = user?.username || 'Admin'
|
||||
const tripTitle = selectedTrip?.title || 'Test Trip'
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────
|
||||
|
||||
const Btn = ({
|
||||
id, label, sub, icon: Icon, color, onClick,
|
||||
}: {
|
||||
id: string; label: string; sub: string; icon: LucideIcon; color: string; onClick: () => void
|
||||
}) => (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
disabled={sending !== null}
|
||||
className="flex w-full items-center gap-3 rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-3 py-[11px] text-left disabled:opacity-50"
|
||||
>
|
||||
<span
|
||||
className="flex h-8 w-8 flex-none items-center justify-center rounded-[10px]"
|
||||
style={{ background: `${color}20`, color }}
|
||||
>
|
||||
<Icon className="h-4 w-4" />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-[0.8125rem] font-bold text-m-ink">{label}</p>
|
||||
<p className="truncate font-geist text-[0.625rem] text-m-faint">{sub}</p>
|
||||
</div>
|
||||
{sending === id && <Loader2 size={14} className="flex-none animate-spin text-m-faint" />}
|
||||
</button>
|
||||
)
|
||||
|
||||
const TripSelector = () => (
|
||||
<select
|
||||
value={selectedTripId ?? ''}
|
||||
onChange={e => setSelectedTripId(Number(e.target.value))}
|
||||
className="mb-2 h-[42px] w-full rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-3 text-[0.84375rem] text-m-ink outline-none focus:border-[color:var(--m-faint)]"
|
||||
>
|
||||
{trips.map(trip => <option key={trip.id} value={trip.id}>{trip.title}</option>)}
|
||||
</select>
|
||||
)
|
||||
|
||||
const UserSelector = () => (
|
||||
<select
|
||||
value={selectedUserId ?? ''}
|
||||
onChange={e => setSelectedUserId(Number(e.target.value))}
|
||||
className="mb-2 h-[42px] w-full rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-3 text-[0.84375rem] text-m-ink outline-none focus:border-[color:var(--m-faint)]"
|
||||
>
|
||||
{users.map(u => <option key={u.id} value={u.id}>{u.username} ({u.email})</option>)}
|
||||
</select>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{/* Dev header */}
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="rounded px-2 py-[3px] font-mono text-[0.625rem] font-bold bg-[color:var(--m-st-pending)] text-white">
|
||||
DEV ONLY
|
||||
</span>
|
||||
<span className="text-[0.8125rem] font-bold text-m-ink">
|
||||
Notification Testing
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* ── Type Testing ─────────────────────────────────────────────────── */}
|
||||
<MAdminCard>
|
||||
<MAdminCardHead
|
||||
title="Type Testing"
|
||||
hint="Test how each in-app notification type renders, sent to yourself."
|
||||
/>
|
||||
<div className="mt-2 grid grid-cols-1 gap-2">
|
||||
<Btn id="simple-me" label="Simple → Me" sub="test_simple · user" icon={Bell} color="#6366f1"
|
||||
onClick={() => fire('simple-me', {
|
||||
event: 'test_simple',
|
||||
scope: 'user',
|
||||
targetId: user?.id,
|
||||
params: {},
|
||||
})}
|
||||
/>
|
||||
<Btn id="boolean-me" label="Boolean → Me" sub="test_boolean · user" icon={CheckCircle} color="#10b981"
|
||||
onClick={() => fire('boolean-me', {
|
||||
event: 'test_boolean',
|
||||
scope: 'user',
|
||||
targetId: user?.id,
|
||||
params: {},
|
||||
inApp: {
|
||||
type: 'boolean',
|
||||
positiveCallback: { action: 'test_approve', payload: {} },
|
||||
negativeCallback: { action: 'test_deny', payload: {} },
|
||||
},
|
||||
})}
|
||||
/>
|
||||
<Btn id="navigate-me" label="Navigate → Me" sub="test_navigate · user" icon={Navigation} color="#f59e0b"
|
||||
onClick={() => fire('navigate-me', {
|
||||
event: 'test_navigate',
|
||||
scope: 'user',
|
||||
targetId: user?.id,
|
||||
params: {},
|
||||
})}
|
||||
/>
|
||||
<Btn id="simple-admins" label="Simple → All Admins" sub="test_simple · admin" icon={Zap} color="#ef4444"
|
||||
onClick={() => fire('simple-admins', {
|
||||
event: 'test_simple',
|
||||
scope: 'admin',
|
||||
targetId: 0,
|
||||
params: {},
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
</MAdminCard>
|
||||
|
||||
{/* ── Trip-Scoped Events ───────────────────────────────────────────── */}
|
||||
{trips.length > 0 && (
|
||||
<MAdminCard>
|
||||
<MAdminCardHead
|
||||
title="Trip-Scoped Events"
|
||||
hint="Fires each trip event to all members of the selected trip (excluding yourself)."
|
||||
/>
|
||||
<div className="mt-2">
|
||||
<TripSelector />
|
||||
<div className="grid grid-cols-1 gap-2">
|
||||
<Btn id="booking_change" label="booking_change" sub="navigate · trip" icon={Calendar} color="#6366f1"
|
||||
onClick={() => selectedTripId && fire('booking_change', {
|
||||
event: 'booking_change',
|
||||
scope: 'trip',
|
||||
targetId: selectedTripId,
|
||||
params: { actor: username, trip: tripTitle, booking: 'Test Hotel', type: 'hotel', tripId: String(selectedTripId) },
|
||||
})}
|
||||
/>
|
||||
<Btn id="trip_reminder" label="trip_reminder" sub="navigate · trip" icon={Clock} color="#10b981"
|
||||
onClick={() => selectedTripId && fire('trip_reminder', {
|
||||
event: 'trip_reminder',
|
||||
scope: 'trip',
|
||||
targetId: selectedTripId,
|
||||
params: { trip: tripTitle, tripId: String(selectedTripId) },
|
||||
})}
|
||||
/>
|
||||
<Btn id="photos_shared" label="photos_shared" sub="navigate · trip" icon={Image} color="#f59e0b"
|
||||
onClick={() => selectedTripId && fire('photos_shared', {
|
||||
event: 'photos_shared',
|
||||
scope: 'trip',
|
||||
targetId: selectedTripId,
|
||||
params: { actor: username, trip: tripTitle, count: '5', tripId: String(selectedTripId) },
|
||||
})}
|
||||
/>
|
||||
<Btn id="collab_message" label="collab_message" sub="navigate · trip" icon={MessageSquare} color="#8b5cf6"
|
||||
onClick={() => selectedTripId && fire('collab_message', {
|
||||
event: 'collab_message',
|
||||
scope: 'trip',
|
||||
targetId: selectedTripId,
|
||||
params: { actor: username, trip: tripTitle, preview: 'This is a test message preview.', tripId: String(selectedTripId) },
|
||||
})}
|
||||
/>
|
||||
<Btn id="packing_tagged" label="packing_tagged" sub="navigate · trip" icon={Tag} color="#ec4899"
|
||||
onClick={() => selectedTripId && fire('packing_tagged', {
|
||||
event: 'packing_tagged',
|
||||
scope: 'trip',
|
||||
targetId: selectedTripId,
|
||||
params: { actor: username, trip: tripTitle, category: 'Clothing', tripId: String(selectedTripId) },
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</MAdminCard>
|
||||
)}
|
||||
|
||||
{/* ── User-Scoped Events ───────────────────────────────────────────── */}
|
||||
{users.length > 0 && (
|
||||
<MAdminCard>
|
||||
<MAdminCardHead
|
||||
title="User-Scoped Events"
|
||||
hint="Fires each user event to the selected recipient."
|
||||
/>
|
||||
<div className="mt-2">
|
||||
<UserSelector />
|
||||
<div className="grid grid-cols-1 gap-2">
|
||||
<Btn
|
||||
id={`trip_invite-${selectedUserId}`}
|
||||
label="trip_invite"
|
||||
sub="navigate · user"
|
||||
icon={UserPlus}
|
||||
color="#06b6d4"
|
||||
onClick={() => selectedUserId && fire(`trip_invite-${selectedUserId}`, {
|
||||
event: 'trip_invite',
|
||||
scope: 'user',
|
||||
targetId: selectedUserId,
|
||||
params: { actor: username, trip: tripTitle, invitee: selectedUser?.email || '', tripId: String(selectedTripId ?? 0) },
|
||||
})}
|
||||
/>
|
||||
<Btn
|
||||
id={`vacay_invite-${selectedUserId}`}
|
||||
label="vacay_invite"
|
||||
sub="navigate · user"
|
||||
icon={MapPin}
|
||||
color="#f97316"
|
||||
onClick={() => selectedUserId && fire(`vacay_invite-${selectedUserId}`, {
|
||||
event: 'vacay_invite',
|
||||
scope: 'user',
|
||||
targetId: selectedUserId,
|
||||
params: { actor: username, planId: '1' },
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</MAdminCard>
|
||||
)}
|
||||
|
||||
{/* ── Admin-Scoped Events ──────────────────────────────────────────── */}
|
||||
<MAdminCard>
|
||||
<MAdminCardHead
|
||||
title="Admin-Scoped Events"
|
||||
hint="Fires to all admin users."
|
||||
/>
|
||||
<div className="mt-2 grid grid-cols-1 gap-2">
|
||||
<Btn id="version_available" label="version_available" sub="navigate · admin" icon={Download} color="#64748b"
|
||||
onClick={() => fire('version_available', {
|
||||
event: 'version_available',
|
||||
scope: 'admin',
|
||||
targetId: 0,
|
||||
params: { version: '9.9.9-test' },
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
</MAdminCard>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
import { useState, useEffect, type ReactNode } from 'react'
|
||||
import { Tag, Calendar, ExternalLink, ChevronDown, ChevronUp, Loader2, Heart, Coffee, Bug, Lightbulb, BookOpen } from 'lucide-react'
|
||||
import { getLocaleForLanguage, useTranslation } from '../../../i18n'
|
||||
import apiClient from '../../../api/client'
|
||||
import { MAdminButton, MAdminCard } from './MAdminUi'
|
||||
|
||||
const REPO = 'mauriceboe/TREK'
|
||||
const PER_PAGE = 10
|
||||
|
||||
interface GithubRelease {
|
||||
id: number
|
||||
prerelease: boolean
|
||||
tag_name: string
|
||||
name: string | null
|
||||
body: string | null
|
||||
published_at: string | null
|
||||
created_at: string
|
||||
author: { login: string } | null
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
// Support / community link cards (design: brand-tinted icon tile + title/sub).
|
||||
// Brand hex stays as content identity; every surface/border uses --m-* tokens.
|
||||
interface LinkCard {
|
||||
href: string
|
||||
color: string
|
||||
icon: ReactNode
|
||||
title: string
|
||||
sub: string
|
||||
}
|
||||
|
||||
export default function MAdminGitHubPanel({ isPrerelease = false }: { isPrerelease?: boolean }) {
|
||||
const { t, language } = useTranslation()
|
||||
const [releases, setReleases] = useState<GithubRelease[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [expanded, setExpanded] = useState<Record<number, boolean>>({})
|
||||
const [page, setPage] = useState(1)
|
||||
const [hasMore, setHasMore] = useState(true)
|
||||
const [loadingMore, setLoadingMore] = useState(false)
|
||||
|
||||
const fetchReleases = async (pageNum = 1, append = false) => {
|
||||
try {
|
||||
const res = await apiClient.get(`/admin/github-releases`, { params: { per_page: PER_PAGE, page: pageNum } })
|
||||
const data = Array.isArray(res.data) ? res.data : []
|
||||
setReleases(prev => append ? [...prev, ...data] : data)
|
||||
setHasMore(data.length === PER_PAGE)
|
||||
} catch (err: unknown) {
|
||||
setError(err instanceof Error ? err.message : 'Unknown error')
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
setLoading(true)
|
||||
fetchReleases(1).finally(() => setLoading(false))
|
||||
}, [])
|
||||
|
||||
const handleLoadMore = async () => {
|
||||
const next = page + 1
|
||||
setLoadingMore(true)
|
||||
await fetchReleases(next, true)
|
||||
setPage(next)
|
||||
setLoadingMore(false)
|
||||
}
|
||||
|
||||
const toggleExpand = (id: number) => {
|
||||
setExpanded(prev => ({ ...prev, [id]: !prev[id] }))
|
||||
}
|
||||
|
||||
const formatDate = (dateStr: string) => {
|
||||
const d = new Date(dateStr)
|
||||
return d.toLocaleDateString(getLocaleForLanguage(language), { day: 'numeric', month: 'short', year: 'numeric' })
|
||||
}
|
||||
|
||||
// Simple markdown-to-html for release notes (handles headers, bold, lists, links)
|
||||
const renderBody = (body: string | null) => {
|
||||
if (!body) return null
|
||||
const lines = body.split('\n')
|
||||
const elements: ReactNode[] = []
|
||||
let listItems: string[] = []
|
||||
|
||||
const flushList = () => {
|
||||
if (listItems.length > 0) {
|
||||
elements.push(
|
||||
<ul key={`ul-${elements.length}`} className="space-y-1 my-2">
|
||||
{listItems.map((item, i) => (
|
||||
<li key={i} className="flex gap-2 text-xs text-m-muted">
|
||||
<span className="mt-1.5 w-1 h-1 rounded-full flex-shrink-0" style={{ background: 'var(--m-faint)' }} />
|
||||
<span dangerouslySetInnerHTML={{ __html: inlineFormat(item) }} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
listItems = []
|
||||
}
|
||||
}
|
||||
|
||||
const escapeHtml = (str: string) => str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
|
||||
const inlineFormat = (text: string) => {
|
||||
return escapeHtml(text)
|
||||
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
|
||||
.replace(/`(.+?)`/g, '<code style="font-size:11px;padding:1px 4px;border-radius:4px;background:var(--m-ic)">$1</code>')
|
||||
.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, label, url) => {
|
||||
const safeUrl = url.startsWith('http://') || url.startsWith('https://') ? url : '#'
|
||||
return `<a href="${escapeHtml(safeUrl)}" target="_blank" rel="noopener noreferrer" style="color:var(--m-st-info);text-decoration:underline">${label}</a>`
|
||||
})
|
||||
}
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim()
|
||||
if (!trimmed) { flushList(); continue }
|
||||
|
||||
if (trimmed.startsWith('### ')) {
|
||||
flushList()
|
||||
elements.push(
|
||||
<h4 key={elements.length} className="text-xs font-semibold mt-3 mb-1 text-m-ink">
|
||||
{trimmed.slice(4)}
|
||||
</h4>
|
||||
)
|
||||
} else if (trimmed.startsWith('## ')) {
|
||||
flushList()
|
||||
elements.push(
|
||||
<h3 key={elements.length} className="text-sm font-semibold mt-3 mb-1 text-m-ink">
|
||||
{trimmed.slice(3)}
|
||||
</h3>
|
||||
)
|
||||
} else if (/^[-*] /.test(trimmed)) {
|
||||
listItems.push(trimmed.slice(2))
|
||||
} else {
|
||||
flushList()
|
||||
elements.push(
|
||||
<p key={elements.length} className="text-xs my-1 text-m-muted"
|
||||
dangerouslySetInnerHTML={{ __html: inlineFormat(trimmed) }}
|
||||
/>
|
||||
)
|
||||
}
|
||||
}
|
||||
flushList()
|
||||
return elements
|
||||
}
|
||||
|
||||
const discordIcon = (
|
||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="#5865F2"><path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028c.462-.63.874-1.295 1.226-1.994a.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.095 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z"/></svg>
|
||||
)
|
||||
|
||||
const cards: LinkCard[] = [
|
||||
{ href: 'https://ko-fi.com/mauriceboe', color: '#ff5e5b', icon: <Coffee size={18} className="text-[#ff5e5b]" />, title: 'Ko-fi', sub: t('admin.github.support') },
|
||||
{ href: 'https://buymeacoffee.com/mauriceboe', color: '#ffdd00', icon: <Heart size={18} className="text-[#ffdd00]" />, title: 'Buy Me a Coffee', sub: t('admin.github.support') },
|
||||
{ href: 'https://discord.gg/NhZBDSd4qW', color: '#5865F2', icon: discordIcon, title: 'Discord', sub: 'Join the community' },
|
||||
{ href: 'https://github.com/mauriceboe/TREK/issues/new?template=bug_report.yml', color: '#ef4444', icon: <Bug size={18} className="text-[#ef4444]" />, title: t('settings.about.reportBug'), sub: t('settings.about.reportBugHint') },
|
||||
{ href: 'https://github.com/mauriceboe/TREK/discussions/new?category=feature-requests', color: '#f59e0b', icon: <Lightbulb size={18} className="text-[#f59e0b]" />, title: t('settings.about.featureRequest'), sub: t('settings.about.featureRequestHint') },
|
||||
{ href: 'https://github.com/mauriceboe/TREK/wiki', color: '#6366f1', icon: <BookOpen size={18} className="text-[#6366f1]" />, title: 'Wiki', sub: t('settings.about.wikiHint') },
|
||||
]
|
||||
|
||||
const shownReleases = isPrerelease ? releases : releases.filter(r => !r.prerelease)
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{/* Support / community cards */}
|
||||
<div className="grid grid-cols-1 gap-[10px]">
|
||||
{cards.map((card) => (
|
||||
<a
|
||||
key={card.href}
|
||||
href={card.href}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-3 rounded-[18px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheetop)] px-[14px] py-3 no-underline"
|
||||
>
|
||||
<span
|
||||
className="flex h-10 w-10 flex-none items-center justify-center rounded-[11px]"
|
||||
style={{ background: `${card.color}22` }}
|
||||
>
|
||||
{card.icon}
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-[0.8125rem] font-bold text-m-ink">{card.title}</div>
|
||||
<div className="mt-[1px] truncate font-geist text-[0.625rem] text-m-faint">{card.sub}</div>
|
||||
</div>
|
||||
<ExternalLink size={14} className="ml-auto flex-none text-m-faint" />
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Loading / Error / Releases */}
|
||||
{loading ? (
|
||||
<MAdminCard>
|
||||
<div className="flex items-center justify-center py-6">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-m-muted" />
|
||||
</div>
|
||||
</MAdminCard>
|
||||
) : error ? (
|
||||
<MAdminCard>
|
||||
<div className="py-4 text-center">
|
||||
<p className="text-[0.8125rem] text-m-muted">{t('admin.github.error')}</p>
|
||||
<p className="mt-1 font-geist text-[0.625rem] text-m-faint">{error}</p>
|
||||
</div>
|
||||
</MAdminCard>
|
||||
) : (
|
||||
<div className="overflow-hidden rounded-[18px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheetop)]">
|
||||
<div className="flex items-center justify-between gap-2 border-b border-[color:var(--m-rowbr)] px-[14px] py-[13px]">
|
||||
<div className="min-w-0 flex-1">
|
||||
<h2 className="text-[0.875rem] font-extrabold text-m-ink">{t('admin.github.title')}</h2>
|
||||
<p className="mt-[2px] truncate font-geist text-[0.625rem] text-m-faint">
|
||||
{t('admin.github.subtitle').replace('{repo}', REPO)}
|
||||
</p>
|
||||
</div>
|
||||
<a
|
||||
href={`https://github.com/${REPO}/releases`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex flex-none items-center gap-[5px] rounded-full border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-3 py-[7px] text-[0.6875rem] font-bold text-m-ink no-underline"
|
||||
>
|
||||
<ExternalLink size={12} />
|
||||
GitHub
|
||||
</a>
|
||||
</div>
|
||||
|
||||
{/* Timeline */}
|
||||
<div className="px-[14px] py-3">
|
||||
<div className="relative">
|
||||
{/* Timeline line */}
|
||||
<div className="absolute left-[11px] top-3 bottom-3 w-px" style={{ background: 'var(--m-rowbr)' }} />
|
||||
|
||||
<div className="space-y-0">
|
||||
{shownReleases.map((release, idx) => {
|
||||
const isLatest = idx === 0
|
||||
const isExpanded = expanded[release.id]
|
||||
|
||||
return (
|
||||
<div key={release.id} className="relative pb-5 pl-8">
|
||||
{/* Timeline dot */}
|
||||
<div
|
||||
className="absolute left-0 top-1 flex h-[23px] w-[23px] items-center justify-center rounded-full border-2"
|
||||
style={{
|
||||
background: isLatest ? 'var(--m-ink)' : 'var(--m-sheetop)',
|
||||
borderColor: isLatest ? 'var(--m-ink)' : 'var(--m-rowbr)',
|
||||
}}
|
||||
>
|
||||
<Tag size={10} style={{ color: isLatest ? 'var(--m-sheetop)' : 'var(--m-faint)' }} />
|
||||
</div>
|
||||
|
||||
{/* Release content */}
|
||||
<div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="text-[0.875rem] font-bold text-m-ink">
|
||||
{release.tag_name}
|
||||
</span>
|
||||
{isLatest && (
|
||||
<span className="rounded-full bg-[color:color-mix(in_srgb,var(--m-st-confirmed)_14%,transparent)] px-2 py-[2px] text-[0.625rem] font-bold text-[color:var(--m-st-confirmed)]">
|
||||
{t('admin.github.latest')}
|
||||
</span>
|
||||
)}
|
||||
{release.prerelease && (
|
||||
<span className="rounded-full bg-[color:color-mix(in_srgb,var(--m-st-pending)_14%,transparent)] px-2 py-[2px] text-[0.625rem] font-bold text-[color:var(--m-st-pending)]">
|
||||
{t('admin.github.prerelease')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{release.name && release.name !== release.tag_name && (
|
||||
<p className="mt-[2px] text-xs font-medium text-m-muted">
|
||||
{release.name}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="mt-1 flex items-center gap-3">
|
||||
<span className="flex items-center gap-1 text-[0.6875rem] text-m-faint">
|
||||
<Calendar size={10} />
|
||||
{formatDate(release.published_at || release.created_at)}
|
||||
</span>
|
||||
{release.author && (
|
||||
<span className="text-[0.6875rem] text-m-faint">
|
||||
{t('admin.github.by')} {release.author.login}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Expandable body */}
|
||||
{release.body && (
|
||||
<div className="mt-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggleExpand(release.id)}
|
||||
className="flex items-center gap-1 text-[0.6875rem] font-medium text-m-muted"
|
||||
>
|
||||
{isExpanded ? <ChevronUp size={12} /> : <ChevronDown size={12} />}
|
||||
{isExpanded ? t('admin.github.hideDetails') : t('admin.github.showDetails')}
|
||||
</button>
|
||||
|
||||
{isExpanded && (
|
||||
<div className="mt-2 rounded-lg bg-[color:var(--m-ic)] p-3">
|
||||
{renderBody(release.body)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Load more */}
|
||||
{hasMore && (
|
||||
<div className="pt-1 text-center">
|
||||
<MAdminButton variant="ghost" busy={loadingMore} onClick={handleLoadMore}>
|
||||
{!loadingMore && <ChevronDown size={12} />}
|
||||
{loadingMore ? t('admin.github.loading') : t('admin.github.loadMore')}
|
||||
</MAdminButton>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Key, Trash2, User, Loader2, Shield } from 'lucide-react'
|
||||
import { adminApi } from '../../../api/client'
|
||||
import { useToast } from '../../../components/shared/Toast'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import { MAdminCard } from './MAdminUi'
|
||||
import MConfirmSheet from '../settings/MConfirmSheet'
|
||||
|
||||
interface AdminOAuthSession {
|
||||
id: number
|
||||
client_id: string
|
||||
client_name: string
|
||||
user_id: number
|
||||
username: string
|
||||
scopes: string[]
|
||||
access_token_expires_at: string
|
||||
refresh_token_expires_at: string
|
||||
created_at: string
|
||||
}
|
||||
|
||||
interface AdminMcpToken {
|
||||
id: number
|
||||
name: string
|
||||
token_prefix: string
|
||||
created_at: string
|
||||
last_used_at: string | null
|
||||
user_id: number
|
||||
username: string
|
||||
}
|
||||
|
||||
const SCOPES_PREVIEW = 6
|
||||
|
||||
// Mobile MCP tokens admin section: OAuth sessions + long-lived MCP tokens, each
|
||||
// as a card list with loading/empty states, expandable scope chips and a
|
||||
// delete confirm sheet. Drop-in for the desktop AdminMcpTokensPanel — no props,
|
||||
// same adminApi calls and state machine, only the presentation is mobile.
|
||||
export default function MAdminMcpTokensPanel() {
|
||||
const [sessions, setSessions] = useState<AdminOAuthSession[]>([])
|
||||
const [sessionsLoading, setSessionsLoading] = useState(true)
|
||||
const [tokens, setTokens] = useState<AdminMcpToken[]>([])
|
||||
const [tokensLoading, setTokensLoading] = useState(true)
|
||||
const [expandedScopes, setExpandedScopes] = useState<Set<number>>(new Set())
|
||||
const [revokeConfirmId, setRevokeConfirmId] = useState<number | null>(null)
|
||||
const [deleteConfirmId, setDeleteConfirmId] = useState<number | null>(null)
|
||||
|
||||
const toggleScopes = (id: number) =>
|
||||
setExpandedScopes(prev => {
|
||||
const next = new Set(prev)
|
||||
next.has(id) ? next.delete(id) : next.add(id)
|
||||
return next
|
||||
})
|
||||
const toast = useToast()
|
||||
const { t, locale } = useTranslation()
|
||||
|
||||
useEffect(() => {
|
||||
adminApi.oauthSessions()
|
||||
.then(d => setSessions(d.sessions || []))
|
||||
.catch(() => toast.error(t('admin.oauthSessions.loadError')))
|
||||
.finally(() => setSessionsLoading(false))
|
||||
|
||||
adminApi.mcpTokens()
|
||||
.then(d => setTokens(d.tokens || []))
|
||||
.catch(() => toast.error(t('admin.mcpTokens.loadError')))
|
||||
.finally(() => setTokensLoading(false))
|
||||
}, [])
|
||||
|
||||
const handleRevoke = async (id: number) => {
|
||||
try {
|
||||
await adminApi.revokeOAuthSession(id)
|
||||
setSessions(prev => prev.filter(s => s.id !== id))
|
||||
setRevokeConfirmId(null)
|
||||
toast.success(t('admin.oauthSessions.revokeSuccess'))
|
||||
} catch {
|
||||
toast.error(t('admin.oauthSessions.revokeError'))
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
try {
|
||||
await adminApi.deleteMcpToken(id)
|
||||
setTokens(prev => prev.filter(tk => tk.id !== id))
|
||||
setDeleteConfirmId(null)
|
||||
toast.success(t('admin.mcpTokens.deleteSuccess'))
|
||||
} catch {
|
||||
toast.error(t('admin.mcpTokens.deleteError'))
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{/* Section title */}
|
||||
<div>
|
||||
<div className="text-[0.875rem] font-extrabold text-m-ink">{t('admin.mcpTokens.title')}</div>
|
||||
<div className="mt-[2px] font-geist text-[0.625rem] leading-relaxed text-m-muted">
|
||||
{t('admin.mcpTokens.subtitle')}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* OAuth Sessions */}
|
||||
<div>
|
||||
<div className="mb-2 px-1 font-geist text-[0.625rem] font-bold uppercase tracking-[0.06em] text-m-faint">
|
||||
{t('admin.oauthSessions.sectionTitle')}
|
||||
</div>
|
||||
<MAdminCard>
|
||||
{sessionsLoading ? (
|
||||
<div className="flex items-center justify-center py-10">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-m-faint" />
|
||||
</div>
|
||||
) : sessions.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center gap-2 py-10">
|
||||
<Shield className="h-8 w-8 text-m-faint" />
|
||||
<p className="font-geist text-[0.6875rem] text-m-muted">{t('admin.oauthSessions.empty')}</p>
|
||||
</div>
|
||||
) : (
|
||||
sessions.map((session, i) => {
|
||||
const expanded = expandedScopes.has(session.id)
|
||||
const visible = expanded ? session.scopes : session.scopes.slice(0, SCOPES_PREVIEW)
|
||||
const hidden = session.scopes.length - SCOPES_PREVIEW
|
||||
return (
|
||||
<div
|
||||
key={session.id}
|
||||
className={`flex items-start gap-2 py-[11px] ${i === 0 ? '' : 'border-t border-[color:var(--m-rowbr)]'}`}
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-[0.8125rem] font-bold text-m-ink">{session.client_name}</div>
|
||||
<div className="mt-[3px] flex flex-wrap items-center gap-x-2 gap-y-[2px] font-geist text-[0.625rem] text-m-muted">
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<User size={11} strokeWidth={2.2} className="flex-none" />
|
||||
{session.username}
|
||||
</span>
|
||||
<span className="text-m-faint">·</span>
|
||||
<span>{new Date(session.created_at).toLocaleDateString(locale)}</span>
|
||||
</div>
|
||||
<div className="mt-[6px] flex flex-wrap gap-1">
|
||||
{visible.map(scope => (
|
||||
<span
|
||||
key={scope}
|
||||
className="inline-flex items-center rounded-md border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-1.5 py-0.5 font-mono text-[0.5625rem] text-m-muted"
|
||||
>
|
||||
{scope}
|
||||
</span>
|
||||
))}
|
||||
{!expanded && hidden > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggleScopes(session.id)}
|
||||
className="inline-flex items-center rounded-md border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-1.5 py-0.5 font-geist text-[0.5625rem] font-bold text-m-ink"
|
||||
>
|
||||
+{hidden} more
|
||||
</button>
|
||||
)}
|
||||
{expanded && hidden > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggleScopes(session.id)}
|
||||
className="inline-flex items-center rounded-md border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-1.5 py-0.5 font-geist text-[0.5625rem] font-bold text-m-ink"
|
||||
>
|
||||
show less
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setRevokeConfirmId(session.id)}
|
||||
aria-label={t('common.delete')}
|
||||
title={t('common.delete')}
|
||||
className="flex h-8 w-8 flex-none items-center justify-center rounded-full bg-[color:color-mix(in_srgb,var(--m-st-danger)_12%,transparent)] text-[color:var(--m-st-danger)]"
|
||||
>
|
||||
<Trash2 size={14} strokeWidth={2.2} />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</MAdminCard>
|
||||
</div>
|
||||
|
||||
{/* MCP Tokens */}
|
||||
<div>
|
||||
<div className="mb-2 px-1 font-geist text-[0.625rem] font-bold uppercase tracking-[0.06em] text-m-faint">
|
||||
{t('admin.mcpTokens.sectionTitle')}
|
||||
</div>
|
||||
<MAdminCard>
|
||||
{tokensLoading ? (
|
||||
<div className="flex items-center justify-center py-10">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-m-faint" />
|
||||
</div>
|
||||
) : tokens.length === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center gap-2 py-10">
|
||||
<Key className="h-8 w-8 text-m-faint" />
|
||||
<p className="font-geist text-[0.6875rem] text-m-muted">{t('admin.mcpTokens.empty')}</p>
|
||||
</div>
|
||||
) : (
|
||||
tokens.map((token, i) => (
|
||||
<div
|
||||
key={token.id}
|
||||
className={`flex items-start gap-2 py-[11px] ${i === 0 ? '' : 'border-t border-[color:var(--m-rowbr)]'}`}
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-[0.8125rem] font-bold text-m-ink">{token.name}</div>
|
||||
<div className="mt-[2px] font-mono text-[0.625rem] text-m-faint">{token.token_prefix}...</div>
|
||||
<div className="mt-[3px] flex flex-wrap items-center gap-x-2 gap-y-[2px] font-geist text-[0.625rem] text-m-muted">
|
||||
<span className="inline-flex items-center gap-1">
|
||||
<User size={11} strokeWidth={2.2} className="flex-none" />
|
||||
{token.username}
|
||||
</span>
|
||||
<span className="text-m-faint">·</span>
|
||||
<span>{new Date(token.created_at).toLocaleDateString(locale)}</span>
|
||||
<span className="text-m-faint">·</span>
|
||||
<span>
|
||||
{token.last_used_at
|
||||
? new Date(token.last_used_at).toLocaleDateString(locale)
|
||||
: t('admin.mcpTokens.never')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDeleteConfirmId(token.id)}
|
||||
aria-label={t('common.delete')}
|
||||
title={t('common.delete')}
|
||||
className="flex h-8 w-8 flex-none items-center justify-center rounded-full bg-[color:color-mix(in_srgb,var(--m-st-danger)_12%,transparent)] text-[color:var(--m-st-danger)]"
|
||||
>
|
||||
<Trash2 size={14} strokeWidth={2.2} />
|
||||
</button>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</MAdminCard>
|
||||
</div>
|
||||
|
||||
{/* Revoke OAuth session confirm */}
|
||||
<MConfirmSheet
|
||||
open={revokeConfirmId !== null}
|
||||
onClose={() => setRevokeConfirmId(null)}
|
||||
title={t('admin.oauthSessions.revokeTitle')}
|
||||
message={t('admin.oauthSessions.revokeMessage')}
|
||||
confirmLabel={t('common.delete')}
|
||||
cancelLabel={t('common.cancel')}
|
||||
danger
|
||||
onConfirm={() => revokeConfirmId !== null && handleRevoke(revokeConfirmId)}
|
||||
/>
|
||||
|
||||
{/* Delete MCP token confirm */}
|
||||
<MConfirmSheet
|
||||
open={deleteConfirmId !== null}
|
||||
onClose={() => setDeleteConfirmId(null)}
|
||||
title={t('admin.mcpTokens.deleteTitle')}
|
||||
message={t('admin.mcpTokens.deleteMessage')}
|
||||
confirmLabel={t('common.delete')}
|
||||
cancelLabel={t('common.cancel')}
|
||||
danger
|
||||
onConfirm={() => deleteConfirmId !== null && handleDelete(deleteConfirmId)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
import { authApi, notificationsApi } from '../../../api/client'
|
||||
import type { TranslationFn } from '../../../types'
|
||||
import type { useAdmin } from '../../../pages/admin/useAdmin'
|
||||
import MToggle from '../../components/MToggle'
|
||||
import MAdminNotifyMatrix from './MAdminNotifyMatrix'
|
||||
import { MAdminButton, MAdminCard, MAdminCardHead, MAdminField, MAdminInput, MAdminRow } from './MAdminUi'
|
||||
|
||||
interface MAdminNotificationsSectionProps {
|
||||
admin: ReturnType<typeof useAdmin>
|
||||
t: TranslationFn
|
||||
}
|
||||
|
||||
const SMTP_FIELDS = [
|
||||
{ key: 'smtp_host', label: 'SMTP Host', placeholder: 'mail.example.com' },
|
||||
{ key: 'smtp_port', label: 'SMTP Port', placeholder: '587' },
|
||||
{ key: 'smtp_user', label: 'SMTP User', placeholder: 'trek@example.com' },
|
||||
{ key: 'smtp_pass', label: 'SMTP Password', placeholder: '••••••••', type: 'password' },
|
||||
{ key: 'smtp_from', label: 'From Address', placeholder: 'trek@example.com' },
|
||||
]
|
||||
|
||||
// Notifications section: channel toggles (email/webhook/ntfy/in-app), SMTP
|
||||
// credentials, trip reminders, admin webhook + ntfy targets and the per-event
|
||||
// preference matrix — the desktop notifications tab in mobile cards.
|
||||
export default function MAdminNotificationsSection({ admin, t }: MAdminNotificationsSectionProps) {
|
||||
const { toast, smtpValues, setSmtpValues, smtpLoaded, setTripRemindersEnabled } = admin
|
||||
|
||||
// Derive active channels from notification_channels (plural) with fallback
|
||||
// to notification_channel (singular) for existing installs.
|
||||
const rawChannels = smtpValues.notification_channels ?? smtpValues.notification_channel ?? 'none'
|
||||
const activeChans = rawChannels === 'none' ? [] : rawChannels.split(',').map((c: string) => c.trim())
|
||||
const emailActive = activeChans.includes('email')
|
||||
const webhookActive = activeChans.includes('webhook')
|
||||
const ntfyActive = activeChans.includes('ntfy')
|
||||
const tripRemindersActive = smtpValues.notify_trip_reminder !== 'false'
|
||||
const smtpConfigured = !!smtpValues.smtp_host?.trim()
|
||||
|
||||
const setChannels = async (email: boolean, webhook: boolean, ntfy: boolean) => {
|
||||
// Preserve channel ids this toggle doesn't know about instead of
|
||||
// rebuilding the CSV from just these three booleans.
|
||||
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 {
|
||||
const reverted =
|
||||
[emailActive && 'email', webhookActive && 'webhook', ntfyActive && 'ntfy', ...others].filter(Boolean).join(',') ||
|
||||
'none'
|
||||
setSmtpValues((prev) => ({ ...prev, notification_channels: reverted }))
|
||||
toast.error(t('common.error'))
|
||||
}
|
||||
}
|
||||
|
||||
const saveSmtp = async () => {
|
||||
// Saves credentials only — channel activation is auto-saved by the toggle.
|
||||
const notifKeys = ['smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_from', 'smtp_skip_tls_verify']
|
||||
const payload: Record<string, string> = {}
|
||||
for (const k of notifKeys) {
|
||||
if (smtpValues[k] !== undefined) payload[k] = smtpValues[k]
|
||||
}
|
||||
try {
|
||||
await authApi.updateAppSettings(payload)
|
||||
toast.success(t('admin.notifications.saved'))
|
||||
authApi
|
||||
.getAppConfig()
|
||||
.then((c: { trip_reminders_enabled?: boolean }) => {
|
||||
if (c?.trip_reminders_enabled !== undefined) setTripRemindersEnabled(c.trip_reminders_enabled)
|
||||
})
|
||||
.catch(() => {})
|
||||
} catch {
|
||||
toast.error(t('common.error'))
|
||||
}
|
||||
}
|
||||
|
||||
const testSmtp = async () => {
|
||||
const smtpKeys = ['smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_from', 'smtp_skip_tls_verify']
|
||||
const payload: Record<string, string> = {}
|
||||
for (const k of smtpKeys) {
|
||||
if (smtpValues[k] !== undefined) payload[k] = smtpValues[k]
|
||||
}
|
||||
await authApi.updateAppSettings(payload).catch(() => {})
|
||||
try {
|
||||
const result = await notificationsApi.testSmtp()
|
||||
if (result.success) toast.success(t('admin.smtp.testSuccess'))
|
||||
else toast.error(result.error || t('admin.smtp.testFailed'))
|
||||
} catch {
|
||||
toast.error(t('admin.smtp.testFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
const toggleTripReminders = async () => {
|
||||
const next = !tripRemindersActive
|
||||
setSmtpValues((prev) => ({ ...prev, notify_trip_reminder: next ? 'true' : 'false' }))
|
||||
try {
|
||||
await authApi.updateAppSettings({ notify_trip_reminder: next ? 'true' : 'false' })
|
||||
toast.success(
|
||||
next ? t('admin.notifications.tripReminders.enabled') : t('admin.notifications.tripReminders.disabled'),
|
||||
)
|
||||
authApi
|
||||
.getAppConfig()
|
||||
.then((c: { trip_reminders_enabled?: boolean }) => {
|
||||
if (c?.trip_reminders_enabled !== undefined) setTripRemindersEnabled(c.trip_reminders_enabled)
|
||||
})
|
||||
.catch(() => {})
|
||||
} catch {
|
||||
setSmtpValues((prev) => ({ ...prev, notify_trip_reminder: tripRemindersActive ? 'true' : 'false' }))
|
||||
toast.error(t('common.error'))
|
||||
}
|
||||
}
|
||||
|
||||
const saveAdminWebhook = async () => {
|
||||
try {
|
||||
await authApi.updateAppSettings({ admin_webhook_url: smtpValues.admin_webhook_url || '' })
|
||||
toast.success(t('admin.notifications.adminWebhookPanel.saved'))
|
||||
} catch {
|
||||
toast.error(t('common.error'))
|
||||
}
|
||||
}
|
||||
|
||||
const testAdminWebhook = async () => {
|
||||
const url = smtpValues.admin_webhook_url === '••••••••' ? undefined : smtpValues.admin_webhook_url
|
||||
if (!url && smtpValues.admin_webhook_url !== '••••••••') return
|
||||
try {
|
||||
if (url) await authApi.updateAppSettings({ admin_webhook_url: url }).catch(() => {})
|
||||
const result = await notificationsApi.testWebhook(url)
|
||||
if (result.success) toast.success(t('admin.notifications.adminWebhookPanel.testSuccess'))
|
||||
else toast.error(result.error || t('admin.notifications.adminWebhookPanel.testFailed'))
|
||||
} catch {
|
||||
toast.error(t('admin.notifications.adminWebhookPanel.testFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
const saveAdminNtfy = async () => {
|
||||
try {
|
||||
await authApi.updateAppSettings({
|
||||
admin_ntfy_server: smtpValues.admin_ntfy_server || '',
|
||||
admin_ntfy_topic: smtpValues.admin_ntfy_topic || '',
|
||||
...(smtpValues.admin_ntfy_token && smtpValues.admin_ntfy_token !== '••••••••'
|
||||
? { admin_ntfy_token: smtpValues.admin_ntfy_token }
|
||||
: {}),
|
||||
})
|
||||
toast.success(t('admin.notifications.adminNtfyPanel.saved'))
|
||||
} catch {
|
||||
toast.error(t('common.error'))
|
||||
}
|
||||
}
|
||||
|
||||
const testAdminNtfy = async () => {
|
||||
const topic = smtpValues.admin_ntfy_topic?.trim()
|
||||
if (!topic) return
|
||||
try {
|
||||
const token =
|
||||
smtpValues.admin_ntfy_token && smtpValues.admin_ntfy_token !== '••••••••' ? smtpValues.admin_ntfy_token : null
|
||||
const result = await notificationsApi.testNtfy({ topic, server: smtpValues.admin_ntfy_server || null, token })
|
||||
if (result.success) toast.success(t('admin.notifications.adminNtfyPanel.testSuccess'))
|
||||
else toast.error(result.error || t('admin.notifications.adminNtfyPanel.testFailed'))
|
||||
} catch {
|
||||
toast.error(t('admin.notifications.adminNtfyPanel.testFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
const clearNtfyToken = async () => {
|
||||
try {
|
||||
await authApi.updateAppSettings({ admin_ntfy_token: '' })
|
||||
setSmtpValues((prev) => ({ ...prev, admin_ntfy_token: '' }))
|
||||
toast.success(t('admin.notifications.adminNtfyPanel.tokenCleared'))
|
||||
} catch {
|
||||
toast.error(t('common.error'))
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{/* Email (SMTP) */}
|
||||
<MAdminCard>
|
||||
<MAdminCardHead
|
||||
title={t('admin.notifications.emailPanel.title')}
|
||||
hint={t('admin.smtp.hint')}
|
||||
trailing={
|
||||
<MToggle
|
||||
checked={emailActive}
|
||||
ariaLabel={t('admin.notifications.emailPanel.title')}
|
||||
onChange={() => setChannels(!emailActive, webhookActive, ntfyActive)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<div className={`space-y-3 ${!emailActive ? 'pointer-events-none opacity-50' : ''}`}>
|
||||
{smtpLoaded &&
|
||||
SMTP_FIELDS.map((field) => (
|
||||
<MAdminField key={field.key} label={field.label}>
|
||||
<MAdminInput
|
||||
type={field.type || 'text'}
|
||||
value={smtpValues[field.key] || ''}
|
||||
onChange={(e) => setSmtpValues((prev) => ({ ...prev, [field.key]: e.target.value }))}
|
||||
placeholder={field.placeholder}
|
||||
/>
|
||||
</MAdminField>
|
||||
))}
|
||||
<MAdminRow
|
||||
first
|
||||
title="Skip TLS certificate check"
|
||||
hint="Enable for self-signed certificates on local mail servers"
|
||||
trailing={
|
||||
<MToggle
|
||||
checked={smtpValues.smtp_skip_tls_verify === 'true'}
|
||||
ariaLabel="Skip TLS certificate check"
|
||||
onChange={(v) => setSmtpValues((prev) => ({ ...prev, smtp_skip_tls_verify: v ? 'true' : 'false' }))}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-2 flex items-center gap-2 border-t border-[color:var(--m-rowbr)] pt-3">
|
||||
<MAdminButton onClick={saveSmtp}>{t('common.save')}</MAdminButton>
|
||||
<MAdminButton variant="ghost" disabled={!smtpConfigured} onClick={testSmtp}>
|
||||
{t('admin.smtp.testButton')}
|
||||
</MAdminButton>
|
||||
</div>
|
||||
</MAdminCard>
|
||||
|
||||
{/* Webhook */}
|
||||
<MAdminCard>
|
||||
<MAdminCardHead
|
||||
title={t('admin.notifications.webhookPanel.title')}
|
||||
hint={t('admin.webhook.hint')}
|
||||
trailing={
|
||||
<MToggle
|
||||
checked={webhookActive}
|
||||
ariaLabel={t('admin.notifications.webhookPanel.title')}
|
||||
onChange={() => setChannels(emailActive, !webhookActive, ntfyActive)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</MAdminCard>
|
||||
|
||||
{/* Ntfy */}
|
||||
<MAdminCard>
|
||||
<MAdminCardHead
|
||||
title={t('admin.notifications.ntfy')}
|
||||
hint={t('admin.ntfy.hint')}
|
||||
trailing={
|
||||
<MToggle
|
||||
checked={ntfyActive}
|
||||
ariaLabel={t('admin.notifications.ntfy')}
|
||||
onChange={() => setChannels(emailActive, webhookActive, !ntfyActive)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</MAdminCard>
|
||||
|
||||
{/* In-App (always on) */}
|
||||
<MAdminCard>
|
||||
<MAdminCardHead
|
||||
title={t('admin.notifications.inappPanel.title')}
|
||||
hint={t('admin.notifications.inappPanel.hint')}
|
||||
trailing={<MToggle checked disabled ariaLabel={t('admin.notifications.inappPanel.title')} onChange={() => {}} />}
|
||||
/>
|
||||
</MAdminCard>
|
||||
|
||||
{/* Trip reminders */}
|
||||
<MAdminCard>
|
||||
<MAdminCardHead
|
||||
title={t('admin.notifications.tripReminders.title')}
|
||||
hint={t('admin.notifications.tripReminders.hint')}
|
||||
trailing={
|
||||
<MToggle
|
||||
checked={tripRemindersActive}
|
||||
ariaLabel={t('admin.notifications.tripReminders.title')}
|
||||
onChange={toggleTripReminders}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</MAdminCard>
|
||||
|
||||
{/* Admin webhook */}
|
||||
<MAdminCard>
|
||||
<MAdminCardHead
|
||||
title={t('admin.notifications.adminWebhookPanel.title')}
|
||||
hint={t('admin.notifications.adminWebhookPanel.hint')}
|
||||
/>
|
||||
{smtpLoaded && (
|
||||
<div className="mb-3">
|
||||
<MAdminInput
|
||||
type="text"
|
||||
value={smtpValues.admin_webhook_url === '••••••••' ? '' : smtpValues.admin_webhook_url || ''}
|
||||
onChange={(e) => setSmtpValues((prev) => ({ ...prev, admin_webhook_url: e.target.value }))}
|
||||
placeholder={smtpValues.admin_webhook_url === '••••••••' ? '••••••••' : 'https://discord.com/api/webhooks/...'}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-2 border-t border-[color:var(--m-rowbr)] pt-3">
|
||||
<MAdminButton onClick={saveAdminWebhook}>{t('common.save')}</MAdminButton>
|
||||
<MAdminButton variant="ghost" disabled={!smtpValues.admin_webhook_url?.trim()} onClick={testAdminWebhook}>
|
||||
{t('admin.notifications.testWebhook')}
|
||||
</MAdminButton>
|
||||
</div>
|
||||
</MAdminCard>
|
||||
|
||||
{/* Admin ntfy */}
|
||||
<MAdminCard>
|
||||
<MAdminCardHead
|
||||
title={t('admin.notifications.adminNtfyPanel.title')}
|
||||
hint={t('admin.notifications.adminNtfyPanel.hint')}
|
||||
/>
|
||||
{smtpLoaded && (
|
||||
<div className="mb-3 space-y-3">
|
||||
<MAdminField
|
||||
label={t('admin.notifications.adminNtfyPanel.serverLabel')}
|
||||
hint={t('admin.notifications.adminNtfyPanel.serverHint')}
|
||||
>
|
||||
<MAdminInput
|
||||
type="text"
|
||||
value={smtpValues.admin_ntfy_server || ''}
|
||||
onChange={(e) => setSmtpValues((prev) => ({ ...prev, admin_ntfy_server: e.target.value }))}
|
||||
placeholder={t('admin.notifications.adminNtfyPanel.serverPlaceholder')}
|
||||
/>
|
||||
</MAdminField>
|
||||
<MAdminField label={t('admin.notifications.adminNtfyPanel.topicLabel')}>
|
||||
<MAdminInput
|
||||
type="text"
|
||||
value={smtpValues.admin_ntfy_topic || ''}
|
||||
onChange={(e) => setSmtpValues((prev) => ({ ...prev, admin_ntfy_topic: e.target.value }))}
|
||||
placeholder={t('admin.notifications.adminNtfyPanel.topicPlaceholder')}
|
||||
/>
|
||||
</MAdminField>
|
||||
<MAdminField label={t('admin.notifications.adminNtfyPanel.tokenLabel')}>
|
||||
<div className="flex gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<MAdminInput
|
||||
type="password"
|
||||
value={smtpValues.admin_ntfy_token === '••••••••' ? '' : smtpValues.admin_ntfy_token || ''}
|
||||
onChange={(e) => setSmtpValues((prev) => ({ ...prev, admin_ntfy_token: e.target.value }))}
|
||||
placeholder={smtpValues.admin_ntfy_token === '••••••••' ? '••••••••' : ''}
|
||||
/>
|
||||
</div>
|
||||
{smtpValues.admin_ntfy_token === '••••••••' && (
|
||||
<MAdminButton variant="danger" className="h-[42px]" onClick={clearNtfyToken}>
|
||||
{t('common.clear')}
|
||||
</MAdminButton>
|
||||
)}
|
||||
</div>
|
||||
</MAdminField>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-2 border-t border-[color:var(--m-rowbr)] pt-3">
|
||||
<MAdminButton onClick={saveAdminNtfy}>{t('common.save')}</MAdminButton>
|
||||
<MAdminButton variant="ghost" disabled={!smtpValues.admin_ntfy_topic?.trim()} onClick={testAdminNtfy}>
|
||||
{t('admin.notifications.adminNtfyPanel.test')}
|
||||
</MAdminButton>
|
||||
</div>
|
||||
</MAdminCard>
|
||||
|
||||
<MAdminNotifyMatrix t={t} toast={toast} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { adminApi } from '../../../api/client'
|
||||
import type { TranslationFn } from '../../../types'
|
||||
import type { useToast } from '../../../components/shared/Toast'
|
||||
import { ADMIN_EVENT_LABEL_KEYS, ADMIN_CHANNEL_LABEL_KEYS } from '../../../pages/admin/AdminPage.constants'
|
||||
import MToggle from '../../components/MToggle'
|
||||
import { MAdminCard, MAdminCardHead } from './MAdminUi'
|
||||
|
||||
interface ChannelInfo {
|
||||
id: string
|
||||
active: boolean
|
||||
}
|
||||
|
||||
interface MatrixData {
|
||||
event_types: string[]
|
||||
channels?: ChannelInfo[]
|
||||
implemented_combos: Record<string, string[]>
|
||||
preferences: Record<string, Record<string, boolean>>
|
||||
}
|
||||
|
||||
const BUILTIN_CHANNELS = ['inapp', 'email', 'webhook', 'ntfy'] as const
|
||||
|
||||
// Per-event × per-channel admin notification matrix — the mobile layout of
|
||||
// AdminNotificationsPanel. Loads its own data and auto-saves each toggle.
|
||||
export default function MAdminNotifyMatrix({ t, toast }: { t: TranslationFn; toast: ReturnType<typeof useToast> }) {
|
||||
const [matrix, setMatrix] = useState<MatrixData | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
adminApi.getNotificationPreferences().then((data: MatrixData) => setMatrix(data)).catch(() => {})
|
||||
}, [])
|
||||
|
||||
if (!matrix) {
|
||||
return (
|
||||
<MAdminCard>
|
||||
<p className="font-geist text-[0.6875rem] text-m-faint">{t('common.loading')}</p>
|
||||
</MAdminCard>
|
||||
)
|
||||
}
|
||||
|
||||
if (matrix.event_types.length === 0) {
|
||||
return (
|
||||
<MAdminCard>
|
||||
<p className="font-geist text-[0.6875rem] text-m-faint">{t('settings.notificationPreferences.noChannels')}</p>
|
||||
</MAdminCard>
|
||||
)
|
||||
}
|
||||
|
||||
// Admin-scoped events only go out over the built-in channels (plugin
|
||||
// channels are user-scoped), same rule as the desktop panel.
|
||||
const isActive = (id: string) => matrix.channels?.some((c) => c.id === id && c.active) ?? false
|
||||
const visibleChannels = BUILTIN_CHANNELS.filter(
|
||||
(ch) => isActive(ch) && matrix.event_types.some((evt) => matrix.implemented_combos[evt]?.includes(ch)),
|
||||
)
|
||||
|
||||
const toggle = async (eventType: string, channel: string) => {
|
||||
const current = matrix.preferences[eventType]?.[channel] ?? true
|
||||
const updated = {
|
||||
...matrix.preferences,
|
||||
[eventType]: { ...matrix.preferences[eventType], [channel]: !current },
|
||||
}
|
||||
setMatrix((m) => (m ? { ...m, preferences: updated } : m))
|
||||
try {
|
||||
await adminApi.updateNotificationPreferences(updated)
|
||||
} catch {
|
||||
setMatrix((m) => (m ? { ...m, preferences: matrix.preferences } : m))
|
||||
toast.error(t('common.error'))
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<MAdminCard>
|
||||
<MAdminCardHead title={t('admin.tabs.notifications')} hint={t('admin.notifications.adminNotificationsHint')} />
|
||||
<div className="flex items-center gap-1 border-b border-[color:var(--m-rowbr)] pb-2">
|
||||
<span className="min-w-0 flex-1" />
|
||||
{visibleChannels.map((ch) => (
|
||||
<span
|
||||
key={ch}
|
||||
className="w-[44px] flex-none text-center font-geist text-[0.5625rem] font-bold uppercase tracking-[0.04em] text-m-faint"
|
||||
>
|
||||
{t(ADMIN_CHANNEL_LABEL_KEYS[ch]) || ch}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
{matrix.event_types.map((eventType) => {
|
||||
const implemented = matrix.implemented_combos[eventType] ?? []
|
||||
return (
|
||||
<div key={eventType} className="flex items-center gap-1 border-b border-[color:var(--m-rowbr)] py-2">
|
||||
<span className="min-w-0 flex-1 truncate text-[0.8125rem] text-m-ink">
|
||||
{t(ADMIN_EVENT_LABEL_KEYS[eventType]) || eventType}
|
||||
</span>
|
||||
{visibleChannels.map((ch) => (
|
||||
<span key={ch} className="flex w-[44px] flex-none justify-center">
|
||||
{implemented.includes(ch) ? (
|
||||
<MToggle
|
||||
checked={matrix.preferences[eventType]?.[ch] ?? true}
|
||||
ariaLabel={`${eventType} ${ch}`}
|
||||
onChange={() => toggle(eventType, ch)}
|
||||
/>
|
||||
) : (
|
||||
<span className="font-geist text-[0.75rem] text-m-faint">—</span>
|
||||
)}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</MAdminCard>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,410 @@
|
||||
import { useState, useEffect, useRef, ReactNode } from 'react'
|
||||
import { adminApi } from '../../../api/client'
|
||||
import { useToast } from '../../../components/shared/Toast'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import { Plus, Trash2, Edit2, Package, X, Check, ChevronDown, ChevronRight, FolderPlus } from 'lucide-react'
|
||||
import { MAdminButton, MAdminCard, MAdminCardHead, MAdminInput } from './MAdminUi'
|
||||
|
||||
interface TemplateCategory { id: number; template_id: number; name: string; sort_order: number }
|
||||
interface TemplateItem { id: number; category_id: number; name: string; sort_order: number }
|
||||
interface Template { id: number; name: string; item_count: number; category_count: number; created_by_name: string }
|
||||
|
||||
// Small round icon action button in the mobile admin idiom (flat --m-ic circle).
|
||||
function PkIconBtn({
|
||||
onClick,
|
||||
ariaLabel,
|
||||
variant = 'neutral',
|
||||
size = 32,
|
||||
disabled = false,
|
||||
children,
|
||||
}: {
|
||||
onClick: () => void
|
||||
ariaLabel: string
|
||||
variant?: 'neutral' | 'danger' | 'accent'
|
||||
size?: number
|
||||
disabled?: boolean
|
||||
children: ReactNode
|
||||
}) {
|
||||
const look =
|
||||
variant === 'accent'
|
||||
? 'bg-m-act text-m-actfg'
|
||||
: variant === 'danger'
|
||||
? 'bg-[color:var(--m-ic)] text-[color:var(--m-st-danger)]'
|
||||
: 'bg-[color:var(--m-ic)] text-m-muted'
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
aria-label={ariaLabel}
|
||||
disabled={disabled}
|
||||
className={`flex flex-none items-center justify-center rounded-full disabled:opacity-40 ${look}`}
|
||||
style={{ width: size, height: size }}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
// Compact inline field matching MAdminInput, used where a native ref is needed
|
||||
// (the add-item input focuses itself after each add).
|
||||
const inlineFieldCls =
|
||||
'h-[38px] w-full rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-3 text-[0.84375rem] text-m-ink outline-none placeholder:text-m-faint focus:border-[color:var(--m-faint)]'
|
||||
|
||||
/**
|
||||
* Mobile-native re-skin of the admin Packing Template Manager: create/rename/
|
||||
* delete templates, expand a template to manage its categories and items. All
|
||||
* state, effects and adminApi mutations are preserved from the desktop version.
|
||||
*/
|
||||
export default function MAdminPackingTemplateManager() {
|
||||
const [templates, setTemplates] = useState<Template[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [showCreate, setShowCreate] = useState(false)
|
||||
const [createName, setCreateName] = useState('')
|
||||
|
||||
// Expanded template state
|
||||
const [expandedId, setExpandedId] = useState<number | null>(null)
|
||||
const [categories, setCategories] = useState<TemplateCategory[]>([])
|
||||
const [items, setItems] = useState<TemplateItem[]>([])
|
||||
|
||||
// Editing states
|
||||
const [editingTemplate, setEditingTemplate] = useState<number | null>(null)
|
||||
const [editTemplateName, setEditTemplateName] = useState('')
|
||||
const [editingCatId, setEditingCatId] = useState<number | null>(null)
|
||||
const [editCatName, setEditCatName] = useState('')
|
||||
const [editingItemId, setEditingItemId] = useState<number | null>(null)
|
||||
const [editItemName, setEditItemName] = useState('')
|
||||
|
||||
// Adding states
|
||||
const [addingCategory, setAddingCategory] = useState(false)
|
||||
const [newCatName, setNewCatName] = useState('')
|
||||
const [addingItemToCatId, setAddingItemToCatId] = useState<number | null>(null)
|
||||
const [newItemName, setNewItemName] = useState('')
|
||||
const addItemRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const toast = useToast()
|
||||
const { t } = useTranslation()
|
||||
|
||||
useEffect(() => { loadTemplates() }, [])
|
||||
|
||||
const loadTemplates = async () => {
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const data = await adminApi.packingTemplates()
|
||||
setTemplates(data.templates || [])
|
||||
} catch { toast.error(t('admin.packingTemplates.loadError')) }
|
||||
finally { setIsLoading(false) }
|
||||
}
|
||||
|
||||
const toggleExpand = async (id: number) => {
|
||||
if (expandedId === id) { setExpandedId(null); return }
|
||||
setExpandedId(id)
|
||||
setAddingCategory(false)
|
||||
setAddingItemToCatId(null)
|
||||
try {
|
||||
const data = await adminApi.getPackingTemplate(id)
|
||||
setCategories(data.categories || [])
|
||||
setItems(data.items || [])
|
||||
} catch { toast.error(t('admin.packingTemplates.loadError')) }
|
||||
}
|
||||
|
||||
// Template CRUD
|
||||
const handleCreateTemplate = async () => {
|
||||
if (!createName.trim()) return
|
||||
try {
|
||||
const data = await adminApi.createPackingTemplate({ name: createName.trim() })
|
||||
setTemplates(prev => [{ ...data.template, item_count: 0, category_count: 0 }, ...prev])
|
||||
setCreateName(''); setShowCreate(false)
|
||||
setExpandedId(data.template.id); setCategories([]); setItems([])
|
||||
toast.success(t('admin.packingTemplates.created'))
|
||||
} catch { toast.error(t('admin.packingTemplates.createError')) }
|
||||
}
|
||||
|
||||
const handleDeleteTemplate = async (id: number) => {
|
||||
try {
|
||||
await adminApi.deletePackingTemplate(id)
|
||||
setTemplates(prev => prev.filter(t => t.id !== id))
|
||||
if (expandedId === id) setExpandedId(null)
|
||||
toast.success(t('admin.packingTemplates.deleted'))
|
||||
} catch { toast.error(t('admin.packingTemplates.deleteError')) }
|
||||
}
|
||||
|
||||
const handleRenameTemplate = async (id: number) => {
|
||||
if (!editTemplateName.trim()) { setEditingTemplate(null); return }
|
||||
try {
|
||||
await adminApi.updatePackingTemplate(id, { name: editTemplateName.trim() })
|
||||
setTemplates(prev => prev.map(t => t.id === id ? { ...t, name: editTemplateName.trim() } : t))
|
||||
setEditingTemplate(null)
|
||||
} catch { toast.error(t('admin.packingTemplates.saveError')) }
|
||||
}
|
||||
|
||||
// Category CRUD
|
||||
const handleAddCategory = async () => {
|
||||
if (!newCatName.trim() || !expandedId) return
|
||||
try {
|
||||
const data = await adminApi.addTemplateCategory(expandedId, { name: newCatName.trim() })
|
||||
setCategories(prev => [...prev, data.category])
|
||||
setNewCatName(''); setAddingCategory(false)
|
||||
} catch { toast.error(t('admin.packingTemplates.saveError')) }
|
||||
}
|
||||
|
||||
const handleRenameCategory = async (catId: number) => {
|
||||
if (!editCatName.trim() || !expandedId) { setEditingCatId(null); return }
|
||||
try {
|
||||
await adminApi.updateTemplateCategory(expandedId, catId, { name: editCatName.trim() })
|
||||
setCategories(prev => prev.map(c => c.id === catId ? { ...c, name: editCatName.trim() } : c))
|
||||
setEditingCatId(null)
|
||||
} catch { toast.error(t('admin.packingTemplates.saveError')) }
|
||||
}
|
||||
|
||||
const handleDeleteCategory = async (catId: number) => {
|
||||
if (!expandedId) return
|
||||
try {
|
||||
await adminApi.deleteTemplateCategory(expandedId, catId)
|
||||
setCategories(prev => prev.filter(c => c.id !== catId))
|
||||
setItems(prev => prev.filter(i => i.category_id !== catId))
|
||||
} catch { toast.error(t('admin.packingTemplates.deleteError')) }
|
||||
}
|
||||
|
||||
// Item CRUD
|
||||
const handleAddItem = async (catId: number) => {
|
||||
if (!newItemName.trim() || !expandedId) return
|
||||
try {
|
||||
const data = await adminApi.addTemplateItem(expandedId, catId, { name: newItemName.trim() })
|
||||
setItems(prev => [...prev, data.item])
|
||||
setNewItemName('')
|
||||
setTimeout(() => addItemRef.current?.focus(), 30)
|
||||
} catch { toast.error(t('admin.packingTemplates.saveError')) }
|
||||
}
|
||||
|
||||
const handleRenameItem = async (itemId: number) => {
|
||||
if (!editItemName.trim() || !expandedId) { setEditingItemId(null); return }
|
||||
try {
|
||||
await adminApi.updateTemplateItem(expandedId, itemId, { name: editItemName.trim() })
|
||||
setItems(prev => prev.map(i => i.id === itemId ? { ...i, name: editItemName.trim() } : i))
|
||||
setEditingItemId(null)
|
||||
} catch { toast.error(t('admin.packingTemplates.saveError')) }
|
||||
}
|
||||
|
||||
const handleDeleteItem = async (itemId: number) => {
|
||||
if (!expandedId) return
|
||||
try {
|
||||
await adminApi.deleteTemplateItem(expandedId, itemId)
|
||||
setItems(prev => prev.filter(i => i.id !== itemId))
|
||||
} catch { toast.error(t('admin.packingTemplates.deleteError')) }
|
||||
}
|
||||
|
||||
return (
|
||||
<MAdminCard>
|
||||
{/* Header */}
|
||||
<MAdminCardHead
|
||||
title={t('admin.packingTemplates.title')}
|
||||
hint={t('admin.packingTemplates.subtitle')}
|
||||
trailing={
|
||||
<MAdminButton onClick={() => setShowCreate(true)}>
|
||||
<Plus size={13} strokeWidth={2.4} />
|
||||
{t('admin.packingTemplates.create')}
|
||||
</MAdminButton>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Create template */}
|
||||
{showCreate && (
|
||||
<div className="mt-2 flex items-center gap-2">
|
||||
<Package size={16} className="flex-none text-m-faint" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<MAdminInput
|
||||
autoFocus
|
||||
value={createName}
|
||||
onChange={e => setCreateName(e.target.value)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') handleCreateTemplate(); if (e.key === 'Escape') setShowCreate(false) }}
|
||||
placeholder={t('admin.packingTemplates.namePlaceholder')}
|
||||
/>
|
||||
</div>
|
||||
<PkIconBtn ariaLabel={t('common.save')} variant="accent" onClick={handleCreateTemplate}><Check size={15} /></PkIconBtn>
|
||||
<PkIconBtn ariaLabel={t('common.cancel')} onClick={() => setShowCreate(false)}><X size={15} /></PkIconBtn>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Template list */}
|
||||
{isLoading ? (
|
||||
<div className="py-8 text-center">
|
||||
<span className="inline-block h-7 w-7 animate-spin rounded-full border-2 border-[color:var(--m-rowbr)] border-t-[color:var(--m-ink)]" />
|
||||
</div>
|
||||
) : templates.length === 0 ? (
|
||||
<div className="py-8 text-center font-geist text-[0.75rem] text-m-faint">{t('admin.packingTemplates.empty')}</div>
|
||||
) : (
|
||||
<div className="mt-1">
|
||||
{templates.map(tmpl => (
|
||||
<div key={tmpl.id} className="border-t border-[color:var(--m-rowbr)] first:border-t-0">
|
||||
{/* Template row */}
|
||||
<div className="flex items-center gap-2 py-[11px]">
|
||||
<button
|
||||
type="button"
|
||||
aria-label={expandedId === tmpl.id ? t('common.collapse') : t('common.expand')}
|
||||
onClick={() => toggleExpand(tmpl.id)}
|
||||
className="flex-none text-m-faint"
|
||||
>
|
||||
{expandedId === tmpl.id ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
|
||||
</button>
|
||||
<Package size={16} className="flex-none text-m-faint" />
|
||||
{editingTemplate === tmpl.id ? (
|
||||
<div className="min-w-0 flex-1">
|
||||
<MAdminInput
|
||||
autoFocus
|
||||
value={editTemplateName}
|
||||
onChange={e => setEditTemplateName(e.target.value)}
|
||||
onBlur={() => handleRenameTemplate(tmpl.id)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') handleRenameTemplate(tmpl.id); if (e.key === 'Escape') setEditingTemplate(null) }}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="min-w-0 flex-1" onClick={() => toggleExpand(tmpl.id)}>
|
||||
<div className="truncate text-[0.8125rem] font-bold text-m-ink">{tmpl.name}</div>
|
||||
<div className="mt-[1px] font-geist text-[0.59375rem] text-m-faint">
|
||||
{tmpl.category_count} {t('admin.packingTemplates.categories')} · {tmpl.item_count} {t('admin.packingTemplates.items')}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<PkIconBtn
|
||||
ariaLabel={t('common.edit')}
|
||||
onClick={() => { setEditingTemplate(tmpl.id); setEditTemplateName(tmpl.name) }}
|
||||
><Edit2 size={14} /></PkIconBtn>
|
||||
<PkIconBtn
|
||||
ariaLabel={t('common.delete')}
|
||||
variant="danger"
|
||||
onClick={() => handleDeleteTemplate(tmpl.id)}
|
||||
><Trash2 size={14} /></PkIconBtn>
|
||||
</div>
|
||||
|
||||
{/* Expanded content */}
|
||||
{expandedId === tmpl.id && (
|
||||
<div className="space-y-2 pb-3 pl-6">
|
||||
{categories.map(cat => {
|
||||
const catItems = items.filter(i => i.category_id === cat.id)
|
||||
return (
|
||||
<div key={cat.id} className="overflow-hidden rounded-xl border border-[color:var(--m-rowbr)]">
|
||||
{/* Category header */}
|
||||
<div className="flex items-center gap-1.5 bg-[color:var(--m-ic)] px-3 py-2">
|
||||
{editingCatId === cat.id ? (
|
||||
<div className="min-w-0 flex-1">
|
||||
<MAdminInput
|
||||
autoFocus
|
||||
value={editCatName}
|
||||
onChange={e => setEditCatName(e.target.value)}
|
||||
onBlur={() => handleRenameCategory(cat.id)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') handleRenameCategory(cat.id); if (e.key === 'Escape') setEditingCatId(null) }}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<span className="min-w-0 flex-1 truncate font-geist text-[0.625rem] font-bold uppercase tracking-wider text-m-muted">{cat.name}</span>
|
||||
)}
|
||||
<span className="flex-none font-geist text-[0.625rem] text-m-faint">{catItems.length}</span>
|
||||
<PkIconBtn
|
||||
size={28}
|
||||
ariaLabel={t('admin.packingTemplates.itemName')}
|
||||
onClick={() => { setAddingItemToCatId(addingItemToCatId === cat.id ? null : cat.id); setNewItemName(''); setTimeout(() => addItemRef.current?.focus(), 30) }}
|
||||
><Plus size={14} /></PkIconBtn>
|
||||
<PkIconBtn
|
||||
size={28}
|
||||
ariaLabel={t('common.edit')}
|
||||
onClick={() => { setEditingCatId(cat.id); setEditCatName(cat.name) }}
|
||||
><Edit2 size={13} /></PkIconBtn>
|
||||
<PkIconBtn
|
||||
size={28}
|
||||
variant="danger"
|
||||
ariaLabel={t('common.delete')}
|
||||
onClick={() => handleDeleteCategory(cat.id)}
|
||||
><Trash2 size={13} /></PkIconBtn>
|
||||
</div>
|
||||
|
||||
{/* Items */}
|
||||
{(catItems.length > 0 || addingItemToCatId === cat.id) && (
|
||||
<div className="divide-y divide-[color:var(--m-rowbr)]">
|
||||
{catItems.map(item => (
|
||||
<div key={item.id} className="flex items-center gap-2 px-3 py-2">
|
||||
{editingItemId === item.id ? (
|
||||
<>
|
||||
<div className="min-w-0 flex-1">
|
||||
<MAdminInput
|
||||
autoFocus
|
||||
value={editItemName}
|
||||
onChange={e => setEditItemName(e.target.value)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') handleRenameItem(item.id); if (e.key === 'Escape') setEditingItemId(null) }}
|
||||
/>
|
||||
</div>
|
||||
<PkIconBtn size={28} variant="accent" ariaLabel={t('common.save')} onClick={() => handleRenameItem(item.id)}><Check size={13} /></PkIconBtn>
|
||||
<PkIconBtn size={28} ariaLabel={t('common.cancel')} onClick={() => setEditingItemId(null)}><X size={13} /></PkIconBtn>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span className="min-w-0 flex-1 truncate text-[0.8125rem] text-m-ink">{item.name}</span>
|
||||
<PkIconBtn
|
||||
size={28}
|
||||
ariaLabel={t('common.edit')}
|
||||
onClick={() => { setEditingItemId(item.id); setEditItemName(item.name) }}
|
||||
><Edit2 size={12} /></PkIconBtn>
|
||||
<PkIconBtn
|
||||
size={28}
|
||||
variant="danger"
|
||||
ariaLabel={t('common.delete')}
|
||||
onClick={() => handleDeleteItem(item.id)}
|
||||
><Trash2 size={12} /></PkIconBtn>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Add item inline */}
|
||||
{addingItemToCatId === cat.id && (
|
||||
<div className="flex items-center gap-2 px-3 py-2">
|
||||
<input
|
||||
ref={addItemRef}
|
||||
value={newItemName}
|
||||
onChange={e => setNewItemName(e.target.value)}
|
||||
onKeyDown={e => { if (e.key === 'Enter' && newItemName.trim()) handleAddItem(cat.id); if (e.key === 'Escape') { setAddingItemToCatId(null); setNewItemName('') } }}
|
||||
placeholder={t('admin.packingTemplates.itemName')}
|
||||
className={inlineFieldCls}
|
||||
/>
|
||||
<PkIconBtn size={28} variant="accent" disabled={!newItemName.trim()} ariaLabel={t('admin.packingTemplates.itemName')} onClick={() => handleAddItem(cat.id)}><Plus size={13} /></PkIconBtn>
|
||||
<PkIconBtn size={28} ariaLabel={t('common.cancel')} onClick={() => { setAddingItemToCatId(null); setNewItemName('') }}><X size={13} /></PkIconBtn>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
|
||||
{/* Add category */}
|
||||
{addingCategory ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<MAdminInput
|
||||
autoFocus
|
||||
value={newCatName}
|
||||
onChange={e => setNewCatName(e.target.value)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') handleAddCategory(); if (e.key === 'Escape') { setAddingCategory(false); setNewCatName('') } }}
|
||||
placeholder={t('admin.packingTemplates.categoryName')}
|
||||
/>
|
||||
</div>
|
||||
<PkIconBtn variant="accent" ariaLabel={t('common.save')} onClick={handleAddCategory}><Check size={15} /></PkIconBtn>
|
||||
<PkIconBtn ariaLabel={t('common.cancel')} onClick={() => { setAddingCategory(false); setNewCatName('') }}><X size={15} /></PkIconBtn>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setAddingCategory(true)}
|
||||
className="flex w-full items-center justify-center gap-2 rounded-xl border border-dashed border-[color:var(--m-rowbr)] px-3 py-[10px] font-geist text-[0.75rem] font-semibold text-m-muted"
|
||||
>
|
||||
<FolderPlus size={14} /> {t('admin.packingTemplates.addCategory')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</MAdminCard>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
import React, { useEffect, useState, useMemo } from 'react'
|
||||
import { adminApi } from '../../../api/client'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import { usePermissionsStore, PermissionLevel } from '../../../store/permissionsStore'
|
||||
import { useToast } from '../../../components/shared/Toast'
|
||||
import { Save, RotateCcw } from 'lucide-react'
|
||||
import { MAdminButton, MAdminCard } from './MAdminUi'
|
||||
|
||||
interface PermissionEntry {
|
||||
key: string
|
||||
level: PermissionLevel
|
||||
defaultLevel: PermissionLevel
|
||||
allowedLevels: PermissionLevel[]
|
||||
}
|
||||
|
||||
const LEVEL_LABELS: Record<string, string> = {
|
||||
admin: 'perm.level.admin',
|
||||
trip_owner: 'perm.level.tripOwner',
|
||||
trip_member: 'perm.level.tripMember',
|
||||
everybody: 'perm.level.everybody',
|
||||
}
|
||||
|
||||
const CATEGORIES = [
|
||||
{ id: 'trip', keys: ['trip_create', 'trip_edit', 'trip_delete', 'trip_archive', 'trip_cover_upload'] },
|
||||
{ id: 'members', keys: ['member_manage'] },
|
||||
{ id: 'files', keys: ['file_upload', 'file_edit', 'file_delete'] },
|
||||
{ id: 'content', keys: ['place_edit', 'day_edit', 'reservation_edit'] },
|
||||
{ id: 'extras', keys: ['budget_edit', 'packing_edit', 'collab_edit', 'share_manage'] },
|
||||
]
|
||||
|
||||
export default function MAdminPermissionsPanel(): React.ReactElement {
|
||||
const { t } = useTranslation()
|
||||
const toast = useToast()
|
||||
const [entries, setEntries] = useState<PermissionEntry[]>([])
|
||||
const [values, setValues] = useState<Record<string, PermissionLevel>>({})
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [dirty, setDirty] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
loadPermissions()
|
||||
}, [])
|
||||
|
||||
const loadPermissions = async () => {
|
||||
setLoading(true)
|
||||
try {
|
||||
const data = await adminApi.getPermissions()
|
||||
setEntries(data.permissions)
|
||||
const vals: Record<string, PermissionLevel> = {}
|
||||
for (const p of data.permissions) vals[p.key] = p.level
|
||||
setValues(vals)
|
||||
setDirty(false)
|
||||
} catch {
|
||||
toast.error(t('common.error'))
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleChange = (key: string, level: PermissionLevel) => {
|
||||
setValues(prev => ({ ...prev, [key]: level }))
|
||||
setDirty(true)
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true)
|
||||
try {
|
||||
const data = await adminApi.updatePermissions(values)
|
||||
if (data.permissions) {
|
||||
usePermissionsStore.getState().setPermissions(data.permissions)
|
||||
}
|
||||
setDirty(false)
|
||||
toast.success(t('perm.saved'))
|
||||
} catch {
|
||||
toast.error(t('common.error'))
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleReset = () => {
|
||||
const defaults: Record<string, PermissionLevel> = {}
|
||||
for (const p of entries) defaults[p.key] = p.defaultLevel
|
||||
setValues(defaults)
|
||||
setDirty(true)
|
||||
}
|
||||
|
||||
const entryMap = useMemo(() => new Map(entries.map(e => [e.key, e])), [entries])
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<MAdminCard>
|
||||
<div className="flex justify-center py-6">
|
||||
<div className="h-8 w-8 animate-spin rounded-full border-2 border-[color:var(--m-rowbr)] border-t-[color:var(--m-ink)]" />
|
||||
</div>
|
||||
</MAdminCard>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<MAdminCard>
|
||||
<div className="mb-1 flex items-center gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-[0.875rem] font-extrabold text-m-ink">{t('perm.title')}</div>
|
||||
<div className="mt-[2px] font-geist text-[0.625rem] leading-relaxed text-m-muted">{t('perm.subtitle')}</div>
|
||||
</div>
|
||||
<MAdminButton
|
||||
variant="ghost"
|
||||
disabled={saving}
|
||||
title={t('perm.resetDefaults')}
|
||||
onClick={handleReset}
|
||||
>
|
||||
<RotateCcw size={12} strokeWidth={2.2} />
|
||||
</MAdminButton>
|
||||
<MAdminButton busy={saving} disabled={saving || !dirty} onClick={handleSave}>
|
||||
{!saving && <Save size={12} strokeWidth={2.2} />}
|
||||
{t('common.save')}
|
||||
</MAdminButton>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
{CATEGORIES.map(cat => (
|
||||
<div key={cat.id} className="border-t border-[color:var(--m-rowbr)] pt-3 mt-3">
|
||||
<div className="mb-2 font-geist text-[0.5625rem] font-extrabold uppercase tracking-wider text-m-faint">
|
||||
{t(`perm.cat.${cat.id}`)}
|
||||
</div>
|
||||
<div className="space-y-3">
|
||||
{cat.keys.map(key => {
|
||||
const entry = entryMap.get(key)
|
||||
if (!entry) return null
|
||||
const currentLevel = values[key] || entry.defaultLevel
|
||||
const isDefault = currentLevel === entry.defaultLevel
|
||||
return (
|
||||
<div key={key}>
|
||||
<div className="mb-[6px] flex items-start gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-[0.8125rem] font-bold text-m-ink">{t(`perm.action.${key}`)}</div>
|
||||
<div className="mt-[1px] font-geist text-[0.625rem] leading-relaxed text-m-muted">
|
||||
{t(`perm.actionHint.${key}`)}
|
||||
</div>
|
||||
</div>
|
||||
{!isDefault && (
|
||||
<span className="mt-[1px] flex-none rounded-full bg-[color:color-mix(in_srgb,var(--m-st-pending)_14%,transparent)] px-[7px] py-[2px] font-geist text-[0.5625rem] font-bold text-[color:var(--m-st-pending)]">
|
||||
{t('perm.customized')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<select
|
||||
value={currentLevel}
|
||||
onChange={(e) => handleChange(key, e.target.value as PermissionLevel)}
|
||||
aria-label={t(`perm.action.${key}`)}
|
||||
className="h-[42px] w-full rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-3 text-[0.84375rem] text-m-ink outline-none"
|
||||
>
|
||||
{entry.allowedLevels.map(l => (
|
||||
<option key={l} value={l}>
|
||||
{t(LEVEL_LABELS[l] || l)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</MAdminCard>
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,436 @@
|
||||
import { AlertTriangle, RefreshCw, Sun } from 'lucide-react'
|
||||
import { adminApi, authApi } from '../../../api/client'
|
||||
import { getApiErrorMessage } from '../../../types'
|
||||
import type { TranslationFn } from '../../../types'
|
||||
import type { useAdmin } from '../../../pages/admin/useAdmin'
|
||||
import MToggle from '../../components/MToggle'
|
||||
import {
|
||||
MAdminButton,
|
||||
MAdminCard,
|
||||
MAdminCardHead,
|
||||
MAdminField,
|
||||
MAdminInput,
|
||||
MAdminRow,
|
||||
MAdminSecretInput,
|
||||
} from './MAdminUi'
|
||||
|
||||
interface MAdminSettingsSectionProps {
|
||||
admin: ReturnType<typeof useAdmin>
|
||||
t: TranslationFn
|
||||
}
|
||||
|
||||
// Settings section: auth methods, passkey login, require-MFA, allowed file
|
||||
// types, API keys, OIDC and the danger zone — the full desktop settings tab
|
||||
// relaid as mobile cards. All state and mutations come from useAdmin.
|
||||
export default function MAdminSettingsSection({ admin, t }: MAdminSettingsSectionProps) {
|
||||
const {
|
||||
toast,
|
||||
setPlacesPhotosEnabled, setPlacesAutocompleteEnabled, setPlacesDetailsEnabled,
|
||||
placesPhotosEnabled, setPlacesPhotosEnabledState,
|
||||
placesAutocompleteEnabled, setPlacesAutocompleteEnabledState,
|
||||
placesDetailsEnabled, setPlacesDetailsEnabledState,
|
||||
oidcConfig, setOidcConfig, savingOidc, setSavingOidc,
|
||||
passwordLogin, setPasswordLogin, passwordRegistration, setPasswordRegistration,
|
||||
oidcLogin, setOidcLogin, oidcRegistration, setOidcRegistration,
|
||||
envOverrideOidcOnly, oidcConfigured, requireMfa,
|
||||
passkeyLogin, setPasskeyLogin, passkeyConfigured,
|
||||
webauthnRpId, setWebauthnRpId, webauthnOrigins, setWebauthnOrigins, savingWebauthn, handleSaveWebauthn,
|
||||
allowedFileTypes, setAllowedFileTypes, savingFileTypes, setSavingFileTypes,
|
||||
mapsKey, setMapsKey, unsplashKey, setUnsplashKey, savingKeys, validating, validation,
|
||||
setShowRotateJwtModal,
|
||||
handleToggleAuthSetting, handleToggleRequireMfa,
|
||||
handleSaveApiKeys, handleValidateKey,
|
||||
} = admin
|
||||
|
||||
const saveFileTypes = async () => {
|
||||
setSavingFileTypes(true)
|
||||
try {
|
||||
await authApi.updateAppSettings({ allowed_file_types: allowedFileTypes })
|
||||
toast.success(t('admin.fileTypesSaved'))
|
||||
} catch {
|
||||
toast.error(t('common.error'))
|
||||
} finally {
|
||||
setSavingFileTypes(false)
|
||||
}
|
||||
}
|
||||
|
||||
const saveOidc = async () => {
|
||||
setSavingOidc(true)
|
||||
try {
|
||||
const payload: Record<string, unknown> = {
|
||||
issuer: oidcConfig.issuer,
|
||||
client_id: oidcConfig.client_id,
|
||||
display_name: oidcConfig.display_name,
|
||||
discovery_url: oidcConfig.discovery_url,
|
||||
}
|
||||
if (oidcConfig.client_secret) payload.client_secret = oidcConfig.client_secret
|
||||
await adminApi.updateOidc(payload)
|
||||
toast.success(t('admin.oidcSaved'))
|
||||
} catch (err: unknown) {
|
||||
toast.error(getApiErrorMessage(err, t('common.error')))
|
||||
} finally {
|
||||
setSavingOidc(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{/* Authentication methods */}
|
||||
<MAdminCard>
|
||||
<MAdminCardHead title={t('admin.authMethods')} />
|
||||
{envOverrideOidcOnly && (
|
||||
<p className="mb-2 rounded-xl border border-[color:color-mix(in_srgb,var(--m-st-pending)_28%,transparent)] bg-[color:color-mix(in_srgb,var(--m-st-pending)_10%,transparent)] px-3 py-2 font-geist text-[0.625rem] leading-relaxed text-m-ink">
|
||||
{t('admin.envOverrideHint')}
|
||||
</p>
|
||||
)}
|
||||
<MAdminRow
|
||||
title={t('admin.passwordLogin')}
|
||||
hint={t('admin.passwordLoginHint')}
|
||||
trailing={
|
||||
<MToggle
|
||||
checked={passwordLogin}
|
||||
disabled={envOverrideOidcOnly || (!passwordLogin && !oidcLogin)}
|
||||
ariaLabel={t('admin.passwordLogin')}
|
||||
onChange={(v) => handleToggleAuthSetting('password_login', v, setPasswordLogin)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<MAdminRow
|
||||
title={t('admin.passwordRegistration')}
|
||||
hint={t('admin.passwordRegistrationHint')}
|
||||
trailing={
|
||||
<MToggle
|
||||
checked={passwordRegistration}
|
||||
disabled={envOverrideOidcOnly}
|
||||
ariaLabel={t('admin.passwordRegistration')}
|
||||
onChange={(v) => handleToggleAuthSetting('password_registration', v, setPasswordRegistration)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{oidcConfigured && (
|
||||
<MAdminRow
|
||||
title={t('admin.oidcLogin')}
|
||||
hint={t('admin.oidcLoginHint')}
|
||||
trailing={
|
||||
<MToggle
|
||||
checked={oidcLogin}
|
||||
disabled={!passwordLogin && oidcLogin}
|
||||
ariaLabel={t('admin.oidcLogin')}
|
||||
onChange={(v) => handleToggleAuthSetting('oidc_login', v, setOidcLogin)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{oidcConfigured && (
|
||||
<MAdminRow
|
||||
title={t('admin.oidcRegistration')}
|
||||
hint={t('admin.oidcRegistrationHint')}
|
||||
trailing={
|
||||
<MToggle
|
||||
checked={oidcRegistration}
|
||||
ariaLabel={t('admin.oidcRegistration')}
|
||||
onChange={(v) => handleToggleAuthSetting('oidc_registration', v, setOidcRegistration)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</MAdminCard>
|
||||
|
||||
{/* Passkey login */}
|
||||
<MAdminCard>
|
||||
<MAdminCardHead title={t('admin.passkey.title')} hint={t('admin.passkey.cardHint')} />
|
||||
<MAdminRow
|
||||
title={t('admin.passkey.login')}
|
||||
hint={t('admin.passkey.loginHint')}
|
||||
trailing={
|
||||
<MToggle
|
||||
checked={passkeyLogin}
|
||||
ariaLabel={t('admin.passkey.login')}
|
||||
onChange={(v) => handleToggleAuthSetting('passkey_login', v, setPasskeyLogin)}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{passkeyLogin && !passkeyConfigured && (
|
||||
<p className="mb-3 flex items-start gap-2 rounded-xl border border-[color:color-mix(in_srgb,var(--m-st-pending)_28%,transparent)] bg-[color:color-mix(in_srgb,var(--m-st-pending)_10%,transparent)] px-3 py-2 font-geist text-[0.625rem] leading-relaxed text-m-ink">
|
||||
<AlertTriangle size={14} className="mt-[1px] flex-none text-[color:var(--m-st-pending)]" />
|
||||
{t('admin.passkey.notConfigured')}
|
||||
</p>
|
||||
)}
|
||||
<div className="space-y-3">
|
||||
<MAdminField label={t('admin.passkey.rpId')} hint={t('admin.passkey.rpIdHint')}>
|
||||
<MAdminInput
|
||||
type="text"
|
||||
value={webauthnRpId}
|
||||
onChange={(e) => setWebauthnRpId(e.target.value)}
|
||||
placeholder="trek.example.org"
|
||||
/>
|
||||
</MAdminField>
|
||||
<MAdminField label={t('admin.passkey.origins')} hint={t('admin.passkey.originsHint')}>
|
||||
<MAdminInput
|
||||
type="text"
|
||||
value={webauthnOrigins}
|
||||
onChange={(e) => setWebauthnOrigins(e.target.value)}
|
||||
placeholder="https://trek.example.org"
|
||||
/>
|
||||
</MAdminField>
|
||||
<MAdminButton busy={savingWebauthn} onClick={handleSaveWebauthn}>
|
||||
{t('common.save')}
|
||||
</MAdminButton>
|
||||
</div>
|
||||
</MAdminCard>
|
||||
|
||||
{/* Require 2FA */}
|
||||
<MAdminCard>
|
||||
<MAdminRow
|
||||
first
|
||||
title={t('admin.requireMfa')}
|
||||
hint={t('admin.requireMfaHint')}
|
||||
trailing={
|
||||
<MToggle checked={requireMfa} ariaLabel={t('admin.requireMfa')} onChange={handleToggleRequireMfa} />
|
||||
}
|
||||
/>
|
||||
</MAdminCard>
|
||||
|
||||
{/* Allowed file types */}
|
||||
<MAdminCard>
|
||||
<MAdminCardHead title={t('admin.fileTypes')} hint={t('admin.fileTypesHint')} />
|
||||
<div className="space-y-3">
|
||||
<MAdminField label={t('admin.fileTypes')} hint={t('admin.fileTypesFormat')}>
|
||||
<MAdminInput
|
||||
type="text"
|
||||
value={allowedFileTypes}
|
||||
onChange={(e) => setAllowedFileTypes(e.target.value)}
|
||||
placeholder="jpg,png,pdf,doc,docx,xls,xlsx,txt,csv"
|
||||
/>
|
||||
</MAdminField>
|
||||
<MAdminButton busy={savingFileTypes} onClick={saveFileTypes}>
|
||||
{t('common.save')}
|
||||
</MAdminButton>
|
||||
</div>
|
||||
</MAdminCard>
|
||||
|
||||
{/* API keys */}
|
||||
<MAdminCard>
|
||||
<MAdminCardHead title={t('admin.apiKeys')} hint={t('admin.apiKeysHint')} />
|
||||
<div className="space-y-3">
|
||||
<MAdminField
|
||||
label={
|
||||
<span className="flex items-center gap-2">
|
||||
{t('admin.mapsKey')}
|
||||
<span className="rounded-full bg-[color:color-mix(in_srgb,var(--m-st-confirmed)_14%,transparent)] px-[7px] py-[2px] font-geist text-[0.5625rem] font-bold text-[color:var(--m-st-confirmed)]">
|
||||
{t('admin.recommended')}
|
||||
</span>
|
||||
</span>
|
||||
}
|
||||
hint={t('admin.mapsKeyHintLong')}
|
||||
>
|
||||
<div className="flex gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<MAdminSecretInput
|
||||
value={mapsKey}
|
||||
onChange={(e) => setMapsKey(e.target.value)}
|
||||
placeholder={t('settings.keyPlaceholder')}
|
||||
/>
|
||||
</div>
|
||||
<MAdminButton
|
||||
variant="ghost"
|
||||
disabled={!mapsKey}
|
||||
busy={!!validating.maps}
|
||||
onClick={() => handleValidateKey('maps')}
|
||||
className="h-[42px]"
|
||||
>
|
||||
{t('admin.validateKey')}
|
||||
</MAdminButton>
|
||||
</div>
|
||||
{validation.maps === true && (
|
||||
<p className="mt-1 font-geist text-[0.625rem] font-bold text-[color:var(--m-st-confirmed)]">
|
||||
{t('admin.keyValid')}
|
||||
</p>
|
||||
)}
|
||||
{validation.maps === false && (
|
||||
<p className="mt-1 font-geist text-[0.625rem] font-bold text-[color:var(--m-st-danger)]">
|
||||
{t('admin.keyInvalid')}
|
||||
</p>
|
||||
)}
|
||||
</MAdminField>
|
||||
|
||||
<MAdminField label={t('admin.unsplashKey')} hint={t('admin.unsplashKeyHint')}>
|
||||
<MAdminSecretInput
|
||||
value={unsplashKey}
|
||||
onChange={(e) => setUnsplashKey(e.target.value)}
|
||||
placeholder={t('settings.keyPlaceholder')}
|
||||
/>
|
||||
</MAdminField>
|
||||
|
||||
<div>
|
||||
<MAdminRow
|
||||
title={t('admin.placesPhotos.title')}
|
||||
hint={t('admin.placesPhotos.subtitle')}
|
||||
trailing={
|
||||
<MToggle
|
||||
checked={placesPhotosEnabled}
|
||||
ariaLabel={t('admin.placesPhotos.title')}
|
||||
onChange={async (next) => {
|
||||
setPlacesPhotosEnabledState(next)
|
||||
setPlacesPhotosEnabled(next)
|
||||
try {
|
||||
await adminApi.updatePlacesPhotos(next)
|
||||
} catch {
|
||||
setPlacesPhotosEnabledState(!next)
|
||||
setPlacesPhotosEnabled(!next)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<MAdminRow
|
||||
title={t('admin.placesAutocomplete.title')}
|
||||
hint={t('admin.placesAutocomplete.subtitle')}
|
||||
trailing={
|
||||
<MToggle
|
||||
checked={placesAutocompleteEnabled}
|
||||
ariaLabel={t('admin.placesAutocomplete.title')}
|
||||
onChange={async (next) => {
|
||||
setPlacesAutocompleteEnabledState(next)
|
||||
setPlacesAutocompleteEnabled(next)
|
||||
try {
|
||||
await adminApi.updatePlacesAutocomplete(next)
|
||||
} catch {
|
||||
setPlacesAutocompleteEnabledState(!next)
|
||||
setPlacesAutocompleteEnabled(!next)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<MAdminRow
|
||||
title={t('admin.placesDetails.title')}
|
||||
hint={t('admin.placesDetails.subtitle')}
|
||||
trailing={
|
||||
<MToggle
|
||||
checked={placesDetailsEnabled}
|
||||
ariaLabel={t('admin.placesDetails.title')}
|
||||
onChange={async (next) => {
|
||||
setPlacesDetailsEnabledState(next)
|
||||
setPlacesDetailsEnabled(next)
|
||||
try {
|
||||
await adminApi.updatePlacesDetails(next)
|
||||
} catch {
|
||||
setPlacesDetailsEnabledState(!next)
|
||||
setPlacesDetailsEnabled(!next)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Open-Meteo weather info */}
|
||||
<div className="rounded-2xl border border-[color:color-mix(in_srgb,var(--m-st-confirmed)_28%,transparent)] bg-[color:color-mix(in_srgb,var(--m-st-confirmed)_10%,transparent)] p-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="flex h-7 w-7 flex-none items-center justify-center rounded-lg bg-[color:var(--m-st-confirmed)] text-white">
|
||||
<Sun size={14} strokeWidth={2.2} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate text-[0.78125rem] font-extrabold text-m-ink">
|
||||
{t('admin.weather.title')}
|
||||
</span>
|
||||
<span className="flex-none rounded-full bg-[color:color-mix(in_srgb,var(--m-st-confirmed)_14%,transparent)] px-2 py-[2px] font-geist text-[0.5625rem] font-bold text-[color:var(--m-st-confirmed)]">
|
||||
{t('admin.weather.badge')}
|
||||
</span>
|
||||
</div>
|
||||
<p className="mt-2 font-geist text-[0.625rem] leading-relaxed text-m-muted">
|
||||
{t('admin.weather.description')}
|
||||
</p>
|
||||
<p className="mt-1 font-geist text-[0.59375rem] leading-relaxed text-m-faint">
|
||||
{t('admin.weather.locationHint')}
|
||||
</p>
|
||||
<div className="mt-2 space-y-[6px]">
|
||||
{[
|
||||
{ title: t('admin.weather.forecast'), desc: t('admin.weather.forecastDesc') },
|
||||
{ title: t('admin.weather.climate'), desc: t('admin.weather.climateDesc') },
|
||||
{ title: t('admin.weather.requests'), desc: t('admin.weather.requestsDesc') },
|
||||
].map((row) => (
|
||||
<div key={row.title} className="rounded-xl bg-[color:var(--m-ic)] px-3 py-2">
|
||||
<p className="text-[0.6875rem] font-bold text-m-ink">{row.title}</p>
|
||||
<p className="mt-[1px] font-geist text-[0.59375rem] text-m-muted">{row.desc}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<MAdminButton busy={savingKeys} onClick={handleSaveApiKeys}>
|
||||
{t('common.save')}
|
||||
</MAdminButton>
|
||||
</div>
|
||||
</MAdminCard>
|
||||
|
||||
{/* OIDC / SSO */}
|
||||
<MAdminCard>
|
||||
<MAdminCardHead title={t('admin.oidcTitle')} hint={t('admin.oidcSubtitle')} />
|
||||
<div className="space-y-3">
|
||||
<MAdminField label={t('admin.oidcDisplayName')}>
|
||||
<MAdminInput
|
||||
type="text"
|
||||
value={oidcConfig.display_name}
|
||||
onChange={(e) => setOidcConfig((c) => ({ ...c, display_name: e.target.value }))}
|
||||
placeholder="z.B. Google, Authentik, Keycloak"
|
||||
/>
|
||||
</MAdminField>
|
||||
<MAdminField label={t('admin.oidcIssuer')} hint={t('admin.oidcIssuerHint')}>
|
||||
<MAdminInput
|
||||
type="url"
|
||||
value={oidcConfig.issuer}
|
||||
onChange={(e) => setOidcConfig((c) => ({ ...c, issuer: e.target.value }))}
|
||||
placeholder="https://accounts.google.com"
|
||||
/>
|
||||
</MAdminField>
|
||||
<MAdminField label="Discovery URL" hint="Override the auto-constructed discovery URL. Required for providers like Authentik where the endpoint is not at <issuer>/.well-known/openid-configuration.">
|
||||
<MAdminInput
|
||||
type="url"
|
||||
value={oidcConfig.discovery_url}
|
||||
onChange={(e) => setOidcConfig((c) => ({ ...c, discovery_url: e.target.value }))}
|
||||
placeholder="https://auth.example.com/application/o/trek/.well-known/openid-configuration"
|
||||
/>
|
||||
</MAdminField>
|
||||
<MAdminField label="Client ID">
|
||||
<MAdminInput
|
||||
type="text"
|
||||
value={oidcConfig.client_id}
|
||||
onChange={(e) => setOidcConfig((c) => ({ ...c, client_id: e.target.value }))}
|
||||
/>
|
||||
</MAdminField>
|
||||
<MAdminField label="Client Secret">
|
||||
<MAdminInput
|
||||
type="password"
|
||||
value={oidcConfig.client_secret}
|
||||
onChange={(e) => setOidcConfig((c) => ({ ...c, client_secret: e.target.value }))}
|
||||
placeholder={oidcConfig.client_secret_set ? '••••••••' : ''}
|
||||
/>
|
||||
</MAdminField>
|
||||
<MAdminButton busy={savingOidc} onClick={saveOidc}>
|
||||
{t('common.save')}
|
||||
</MAdminButton>
|
||||
</div>
|
||||
</MAdminCard>
|
||||
|
||||
{/* Danger zone */}
|
||||
<MAdminCard className="border-[color:color-mix(in_srgb,var(--m-st-danger)_28%,transparent)]">
|
||||
<div className="mb-1 flex items-center gap-2 text-[color:var(--m-st-danger)]">
|
||||
<AlertTriangle size={14} strokeWidth={2.2} />
|
||||
<span className="text-[0.875rem] font-extrabold">Danger Zone</span>
|
||||
</div>
|
||||
<MAdminRow
|
||||
first
|
||||
title="Rotate JWT Secret"
|
||||
hint="Generate a new JWT signing secret. All active sessions will be invalidated immediately."
|
||||
trailing={
|
||||
<MAdminButton variant="danger" onClick={() => setShowRotateJwtModal(true)}>
|
||||
<RefreshCw size={12} strokeWidth={2.2} />
|
||||
Rotate
|
||||
</MAdminButton>
|
||||
}
|
||||
/>
|
||||
</MAdminCard>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
import { useState } from 'react'
|
||||
import { AlertTriangle, CheckCircle, ExternalLink, Fingerprint, Trash2 } from 'lucide-react'
|
||||
import { adminApi } from '../../../api/client'
|
||||
import type { TranslationFn } from '../../../types'
|
||||
import type { useAdmin } from '../../../pages/admin/useAdmin'
|
||||
import MSheet from '../../components/MSheet'
|
||||
import MSegmented from '../../components/MSegmented'
|
||||
import { MAdminButton, MAdminField, MAdminInput, MAdminSecretInput, MAdminSheetFrame } from './MAdminUi'
|
||||
|
||||
interface MAdminSheetsProps {
|
||||
admin: ReturnType<typeof useAdmin>
|
||||
t: TranslationFn
|
||||
}
|
||||
|
||||
const DOCKER_UPDATE_COMMANDS = `docker pull mauriceboe/trek:latest
|
||||
docker stop trek && docker rm trek
|
||||
docker run -d --name trek \\
|
||||
-p 3000:3000 \\
|
||||
-v /opt/trek/data:/app/data \\
|
||||
-v /opt/trek/uploads:/app/uploads \\
|
||||
--restart unless-stopped \\
|
||||
mauriceboe/trek:latest`
|
||||
|
||||
// The admin screen's sheet layer: create user, edit user (incl. passkey reset
|
||||
// and delete), the "how to update" instructions and the rotate-JWT confirm.
|
||||
export default function MAdminSheets({ admin, t }: MAdminSheetsProps) {
|
||||
const {
|
||||
logout, navigate, toast, currentUser,
|
||||
editingUser, setEditingUser, editForm, setEditForm,
|
||||
showCreateUser, setShowCreateUser, createForm, setCreateForm,
|
||||
updateInfo, showUpdateModal, setShowUpdateModal,
|
||||
showRotateJwtModal, setShowRotateJwtModal, rotatingJwt, setRotatingJwt,
|
||||
handleCreateUser, handleSaveUser, handleDeleteUser,
|
||||
} = admin
|
||||
|
||||
const roleOptions = [
|
||||
{ value: 'user', label: t('settings.roleUser') },
|
||||
{ value: 'admin', label: t('settings.roleAdmin') },
|
||||
]
|
||||
|
||||
const [showResetPasskeys, setShowResetPasskeys] = useState(false)
|
||||
const [resettingPk, setResettingPk] = useState(false)
|
||||
|
||||
const resetPasskeys = async () => {
|
||||
if (!editingUser) return
|
||||
setResettingPk(true)
|
||||
try {
|
||||
const r = await adminApi.resetUserPasskeys(editingUser.id)
|
||||
toast.success(t('admin.passkey.resetDone', { count: r.deleted ?? 0 }))
|
||||
setShowResetPasskeys(false)
|
||||
} catch {
|
||||
toast.error(t('common.error'))
|
||||
} finally {
|
||||
setResettingPk(false)
|
||||
}
|
||||
}
|
||||
|
||||
const rotateJwt = async () => {
|
||||
setRotatingJwt(true)
|
||||
try {
|
||||
await adminApi.rotateJwtSecret()
|
||||
setShowRotateJwtModal(false)
|
||||
logout()
|
||||
navigate('/login', { state: { noRedirect: true } })
|
||||
} catch {
|
||||
toast.error(t('common.error'))
|
||||
setRotatingJwt(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Create user */}
|
||||
<MSheet open={showCreateUser} onClose={() => setShowCreateUser(false)} ariaLabel={t('admin.createUser')}>
|
||||
<MAdminSheetFrame
|
||||
title={t('admin.createUser')}
|
||||
onClose={() => setShowCreateUser(false)}
|
||||
footer={
|
||||
<>
|
||||
<MAdminButton variant="ghost" onClick={() => setShowCreateUser(false)}>
|
||||
{t('common.cancel')}
|
||||
</MAdminButton>
|
||||
<MAdminButton onClick={handleCreateUser}>{t('admin.createUser')}</MAdminButton>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="space-y-3">
|
||||
<MAdminField label={`${t('settings.username')} *`}>
|
||||
<MAdminInput
|
||||
type="text"
|
||||
value={createForm.username}
|
||||
onChange={(e) => setCreateForm((f) => ({ ...f, username: e.target.value }))}
|
||||
placeholder={t('settings.username')}
|
||||
/>
|
||||
</MAdminField>
|
||||
<MAdminField label={`${t('common.email')} *`}>
|
||||
<MAdminInput
|
||||
type="email"
|
||||
value={createForm.email}
|
||||
onChange={(e) => setCreateForm((f) => ({ ...f, email: e.target.value }))}
|
||||
placeholder={t('common.email')}
|
||||
/>
|
||||
</MAdminField>
|
||||
<MAdminField label={`${t('common.password')} *`}>
|
||||
<MAdminSecretInput
|
||||
value={createForm.password}
|
||||
onChange={(e) => setCreateForm((f) => ({ ...f, password: e.target.value }))}
|
||||
placeholder={t('common.password')}
|
||||
/>
|
||||
</MAdminField>
|
||||
<MAdminField label={t('settings.role')}>
|
||||
<MSegmented
|
||||
options={roleOptions}
|
||||
value={createForm.role}
|
||||
onChange={(role) => setCreateForm((f) => ({ ...f, role }))}
|
||||
/>
|
||||
</MAdminField>
|
||||
</div>
|
||||
</MAdminSheetFrame>
|
||||
</MSheet>
|
||||
|
||||
{/* Edit user */}
|
||||
<MSheet open={!!editingUser} onClose={() => setEditingUser(null)} ariaLabel={t('admin.editUser')}>
|
||||
<MAdminSheetFrame
|
||||
title={t('admin.editUser')}
|
||||
onClose={() => setEditingUser(null)}
|
||||
footer={
|
||||
<>
|
||||
<MAdminButton variant="ghost" onClick={() => setEditingUser(null)}>
|
||||
{t('common.cancel')}
|
||||
</MAdminButton>
|
||||
<MAdminButton onClick={handleSaveUser}>{t('common.save')}</MAdminButton>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{editingUser && (
|
||||
<div className="space-y-3">
|
||||
<MAdminField label={t('settings.username')}>
|
||||
<MAdminInput
|
||||
type="text"
|
||||
value={editForm.username}
|
||||
onChange={(e) => setEditForm((f) => ({ ...f, username: e.target.value }))}
|
||||
/>
|
||||
</MAdminField>
|
||||
<MAdminField label={t('common.email')}>
|
||||
<MAdminInput
|
||||
type="email"
|
||||
value={editForm.email}
|
||||
onChange={(e) => setEditForm((f) => ({ ...f, email: e.target.value }))}
|
||||
/>
|
||||
</MAdminField>
|
||||
<MAdminField label={t('admin.newPassword')} hint={t('admin.newPasswordHint')}>
|
||||
<MAdminSecretInput
|
||||
value={editForm.password}
|
||||
onChange={(e) => setEditForm((f) => ({ ...f, password: e.target.value }))}
|
||||
placeholder={t('admin.newPasswordPlaceholder')}
|
||||
/>
|
||||
</MAdminField>
|
||||
<MAdminField label={t('settings.role')}>
|
||||
<MSegmented
|
||||
options={roleOptions}
|
||||
value={editForm.role}
|
||||
onChange={(role) => setEditForm((f) => ({ ...f, role }))}
|
||||
/>
|
||||
</MAdminField>
|
||||
<div className="border-t border-[color:var(--m-rowbr)] pt-3">
|
||||
<p className="mb-2 font-geist text-[0.625rem] leading-relaxed text-m-muted">
|
||||
{t('admin.passkey.resetHint')}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<MAdminButton variant="ghost" className="text-[color:var(--m-st-danger)]" onClick={() => setShowResetPasskeys(true)}>
|
||||
<Fingerprint size={12} strokeWidth={2.2} />
|
||||
{t('admin.passkey.reset')}
|
||||
</MAdminButton>
|
||||
<MAdminButton
|
||||
variant="danger"
|
||||
disabled={editingUser.id === currentUser?.id}
|
||||
onClick={() => {
|
||||
const user = editingUser
|
||||
setEditingUser(null)
|
||||
handleDeleteUser(user)
|
||||
}}
|
||||
>
|
||||
<Trash2 size={12} strokeWidth={2.2} />
|
||||
{t('admin.deleteUserTitle')}
|
||||
</MAdminButton>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</MAdminSheetFrame>
|
||||
</MSheet>
|
||||
|
||||
{/* How to update */}
|
||||
<MSheet open={showUpdateModal} onClose={() => setShowUpdateModal(false)} ariaLabel={t('admin.update.howTo')}>
|
||||
<MAdminSheetFrame
|
||||
title={t('admin.update.howTo')}
|
||||
onClose={() => setShowUpdateModal(false)}
|
||||
footer={<MAdminButton onClick={() => setShowUpdateModal(false)}>{t('common.close')}</MAdminButton>}
|
||||
>
|
||||
<div className="space-y-3">
|
||||
<p className="font-geist text-[0.625rem] text-m-muted">
|
||||
v{updateInfo?.current} → v{updateInfo?.latest}
|
||||
</p>
|
||||
<p className="text-[0.8125rem] leading-relaxed text-m-ink">
|
||||
{(updateInfo?.is_docker === false ? t('admin.update.nonDockerText') : t('admin.update.dockerText')).replace(
|
||||
'{version}',
|
||||
`v${updateInfo?.latest ?? ''}`,
|
||||
)}
|
||||
</p>
|
||||
{updateInfo?.is_docker === false ? (
|
||||
<a
|
||||
href="https://github.com/mauriceboe/TREK/wiki/Updating"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-2 rounded-xl bg-[color:var(--m-ic)] px-3 py-3 text-[0.8125rem] font-bold text-m-ink underline"
|
||||
>
|
||||
<ExternalLink size={14} className="flex-none" />
|
||||
{t('admin.update.wikiLink')}
|
||||
</a>
|
||||
) : (
|
||||
<pre className="whitespace-pre-wrap break-all rounded-xl bg-m-act p-3 font-mono text-[0.6875rem] leading-relaxed text-m-actfg">
|
||||
{DOCKER_UPDATE_COMMANDS}
|
||||
</pre>
|
||||
)}
|
||||
<div className="flex items-start gap-2 rounded-xl border border-[color:color-mix(in_srgb,var(--m-st-confirmed)_28%,transparent)] bg-[color:color-mix(in_srgb,var(--m-st-confirmed)_10%,transparent)] px-3 py-2 font-geist text-[0.625rem] leading-relaxed text-m-ink">
|
||||
<CheckCircle size={13} className="mt-[1px] flex-none text-[color:var(--m-st-confirmed)]" />
|
||||
<span>{t('admin.update.dataInfo')}</span>
|
||||
</div>
|
||||
{updateInfo?.release_url && (
|
||||
<a
|
||||
href={updateInfo.release_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center gap-2 rounded-xl border border-[color:color-mix(in_srgb,var(--m-st-info)_28%,transparent)] bg-[color:color-mix(in_srgb,var(--m-st-info)_10%,transparent)] px-3 py-2 font-geist text-[0.625rem] font-bold text-[color:var(--m-st-info)] underline"
|
||||
>
|
||||
<ExternalLink size={13} className="flex-none" />
|
||||
{t('admin.update.button')}
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</MAdminSheetFrame>
|
||||
</MSheet>
|
||||
|
||||
{/* Reset passkeys confirm */}
|
||||
<MSheet open={showResetPasskeys} onClose={() => setShowResetPasskeys(false)} ariaLabel={t('admin.passkey.reset')}>
|
||||
<MAdminSheetFrame
|
||||
title={t('admin.passkey.reset')}
|
||||
onClose={() => setShowResetPasskeys(false)}
|
||||
footer={
|
||||
<>
|
||||
<MAdminButton variant="ghost" disabled={resettingPk} onClick={() => setShowResetPasskeys(false)}>
|
||||
{t('common.cancel')}
|
||||
</MAdminButton>
|
||||
<MAdminButton variant="danger" busy={resettingPk} onClick={resetPasskeys}>
|
||||
{t('admin.passkey.reset')}
|
||||
</MAdminButton>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="flex gap-3">
|
||||
<span className="flex h-10 w-10 flex-none items-center justify-center rounded-full bg-[color:color-mix(in_srgb,var(--m-st-danger)_12%,transparent)] text-[color:var(--m-st-danger)]">
|
||||
<Fingerprint size={18} strokeWidth={2.2} />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-[0.8125rem] font-bold text-m-ink">
|
||||
{t('admin.passkey.resetConfirm', { name: editingUser?.username ?? '' })}
|
||||
</p>
|
||||
<p className="mt-1 font-geist text-[0.625rem] leading-relaxed text-m-muted">
|
||||
{t('admin.passkey.resetHint')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</MAdminSheetFrame>
|
||||
</MSheet>
|
||||
|
||||
{/* Rotate JWT confirm */}
|
||||
<MSheet open={showRotateJwtModal} onClose={() => setShowRotateJwtModal(false)} ariaLabel="Rotate JWT Secret">
|
||||
<MAdminSheetFrame
|
||||
title="Rotate JWT Secret"
|
||||
onClose={() => setShowRotateJwtModal(false)}
|
||||
footer={
|
||||
<>
|
||||
<MAdminButton variant="ghost" disabled={rotatingJwt} onClick={() => setShowRotateJwtModal(false)}>
|
||||
{t('common.cancel')}
|
||||
</MAdminButton>
|
||||
<MAdminButton variant="danger" busy={rotatingJwt} onClick={rotateJwt}>
|
||||
Rotate & Log out
|
||||
</MAdminButton>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="flex gap-3">
|
||||
<span className="flex h-10 w-10 flex-none items-center justify-center rounded-full bg-[color:color-mix(in_srgb,var(--m-st-danger)_12%,transparent)] text-[color:var(--m-st-danger)]">
|
||||
<AlertTriangle size={18} strokeWidth={2.2} />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-[0.8125rem] font-bold text-m-ink">
|
||||
Warning, this will invalidate all sessions and log you out.
|
||||
</p>
|
||||
<p className="mt-1 font-geist text-[0.625rem] leading-relaxed text-m-muted">
|
||||
A new JWT secret will be generated immediately. Every logged-in user — including you — will be signed
|
||||
out and will need to log in again.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</MAdminSheetFrame>
|
||||
</MSheet>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import { InputHTMLAttributes, ReactNode, useState } from 'react'
|
||||
import { Eye, EyeOff, Loader2, X } from 'lucide-react'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import MIconBtn from '../../components/MIconBtn'
|
||||
|
||||
/** Opaque content card of the admin screen (r18, --m-sheetop on --m-rowbr). */
|
||||
export function MAdminCard({ className = '', children }: { className?: string; children: ReactNode }) {
|
||||
return (
|
||||
<div className={`rounded-[18px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheetop)] p-[14px] ${className}`}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Card header: 14px/800 title, small Geist hint, optional trailing control. */
|
||||
export function MAdminCardHead({
|
||||
title,
|
||||
hint,
|
||||
trailing,
|
||||
}: {
|
||||
title: ReactNode
|
||||
hint?: ReactNode
|
||||
trailing?: ReactNode
|
||||
}) {
|
||||
return (
|
||||
<div className="mb-1 flex items-center gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-[0.875rem] font-extrabold text-m-ink">{title}</div>
|
||||
{hint && <div className="mt-[2px] font-geist text-[0.625rem] leading-relaxed text-m-muted">{hint}</div>}
|
||||
</div>
|
||||
{trailing}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Settings row: bold 13px title + Geist hint on the left, control on the right. */
|
||||
export function MAdminRow({
|
||||
title,
|
||||
hint,
|
||||
trailing,
|
||||
first = false,
|
||||
}: {
|
||||
title: ReactNode
|
||||
hint?: ReactNode
|
||||
trailing?: ReactNode
|
||||
first?: boolean
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
className={`flex items-center justify-between gap-3 py-[11px] ${
|
||||
first ? '' : 'border-t border-[color:var(--m-rowbr)]'
|
||||
}`}
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-[0.8125rem] font-bold text-m-ink">{title}</div>
|
||||
{hint && <div className="mt-[1px] font-geist text-[0.625rem] leading-relaxed text-m-muted">{hint}</div>}
|
||||
</div>
|
||||
{trailing}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Labelled form field with an optional hint line under the control. */
|
||||
export function MAdminField({ label, hint, children }: { label: ReactNode; hint?: ReactNode; children: ReactNode }) {
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-[6px] text-[0.75rem] font-semibold text-m-ink">{label}</div>
|
||||
{children}
|
||||
{hint && <div className="mt-[5px] font-geist text-[0.625rem] leading-relaxed text-m-muted">{hint}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function MAdminInput({ className = '', ...props }: InputHTMLAttributes<HTMLInputElement>) {
|
||||
return (
|
||||
<input
|
||||
{...props}
|
||||
className={`h-[42px] w-full rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-3 text-[0.84375rem] text-m-ink outline-none placeholder:text-m-faint focus:border-[color:var(--m-faint)] ${className}`}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
/** Password-style input with the show/hide eye of the desktop admin forms. */
|
||||
export function MAdminSecretInput({ className = '', ...props }: InputHTMLAttributes<HTMLInputElement>) {
|
||||
const [show, setShow] = useState(false)
|
||||
return (
|
||||
<div className="relative">
|
||||
<MAdminInput {...props} type={show ? 'text' : 'password'} className={`pr-10 ${className}`} />
|
||||
<button
|
||||
type="button"
|
||||
tabIndex={-1}
|
||||
aria-label="Show or hide"
|
||||
onClick={() => setShow((v) => !v)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-m-faint"
|
||||
>
|
||||
{show ? <EyeOff size={16} /> : <Eye size={16} />}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface MAdminButtonProps {
|
||||
variant?: 'primary' | 'ghost' | 'danger'
|
||||
busy?: boolean
|
||||
disabled?: boolean
|
||||
onClick?: () => void
|
||||
title?: string
|
||||
className?: string
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
/** Pill action button (design: r999, --m-act surface, 11px/700). */
|
||||
export function MAdminButton({
|
||||
variant = 'primary',
|
||||
busy = false,
|
||||
disabled = false,
|
||||
onClick,
|
||||
title,
|
||||
className = '',
|
||||
children,
|
||||
}: MAdminButtonProps) {
|
||||
const look =
|
||||
variant === 'primary'
|
||||
? 'bg-m-act text-m-actfg'
|
||||
: variant === 'danger'
|
||||
? 'bg-[color:var(--m-st-danger)] text-white'
|
||||
: 'border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] text-m-ink'
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
disabled={disabled || busy}
|
||||
title={title}
|
||||
className={`inline-flex flex-none items-center justify-center gap-[5px] whitespace-nowrap rounded-full px-3 py-[7px] text-[0.6875rem] font-bold disabled:opacity-50 ${look} ${className}`}
|
||||
>
|
||||
{busy && <Loader2 size={12} className="animate-spin" />}
|
||||
{children}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
/** Sheet body frame: title row + close, scrollable content, optional footer. */
|
||||
export function MAdminSheetFrame({
|
||||
title,
|
||||
onClose,
|
||||
footer,
|
||||
children,
|
||||
}: {
|
||||
title: ReactNode
|
||||
onClose: () => void
|
||||
footer?: ReactNode
|
||||
children: ReactNode
|
||||
}) {
|
||||
const { t } = useTranslation()
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-none items-center gap-2 px-4 pb-2 pt-4">
|
||||
<div className="min-w-0 flex-1 truncate text-[0.9375rem] font-extrabold text-m-ink">{title}</div>
|
||||
<MIconBtn variant="neutral" size={34} ariaLabel={t('common.close')} onClick={onClose}>
|
||||
<X size={16} strokeWidth={2.2} />
|
||||
</MIconBtn>
|
||||
</div>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-4 pb-4">{children}</div>
|
||||
{footer && (
|
||||
<div className="flex flex-none items-center justify-end gap-2 border-t border-[color:var(--m-rowbr)] px-4 py-3">
|
||||
{footer}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
import { Copy, Link2, Trash2, UserPlus } from 'lucide-react'
|
||||
import type { TranslationFn } from '../../../types'
|
||||
import type { useAdmin } from '../../../pages/admin/useAdmin'
|
||||
import MAdminPermissionsPanel from './MAdminPermissionsPanel'
|
||||
import MSheet from '../../components/MSheet'
|
||||
import MChip from '../../components/MChip'
|
||||
import { MAdminButton, MAdminCard, MAdminField, MAdminSheetFrame } from './MAdminUi'
|
||||
|
||||
interface MAdminUsersSectionProps {
|
||||
admin: ReturnType<typeof useAdmin>
|
||||
t: TranslationFn
|
||||
locale: string
|
||||
}
|
||||
|
||||
const INVITE_USES = [1, 2, 3, 4, 5, 0]
|
||||
const INVITE_EXPIRY: { value: number | ''; label: string }[] = [
|
||||
{ value: 1, label: '1d' },
|
||||
{ value: 3, label: '3d' },
|
||||
{ value: 7, label: '7d' },
|
||||
{ value: 14, label: '14d' },
|
||||
{ value: '', label: '∞' },
|
||||
]
|
||||
|
||||
// Users section: user list with role badges (design §6.4), invite links and the
|
||||
// permissions matrix. Rows open the edit sheet; Create opens the create sheet.
|
||||
export default function MAdminUsersSection({ admin, t, locale }: MAdminUsersSectionProps) {
|
||||
const {
|
||||
currentUser, users, isLoading,
|
||||
setShowCreateUser, handleEditUser,
|
||||
invites, inviteTrips, showCreateInvite, setShowCreateInvite, inviteForm, setInviteForm,
|
||||
copyInviteLink, handleCreateInvite, handleDeleteInvite,
|
||||
} = admin
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<MAdminCard>
|
||||
<div className="mb-1 flex items-center gap-2">
|
||||
<span className="text-[0.875rem] font-extrabold text-m-ink">{t('admin.tabs.users')}</span>
|
||||
<span className="font-geist text-[0.625rem] font-bold text-m-faint">
|
||||
{users.length} {t('admin.stats.users').toLowerCase()}
|
||||
</span>
|
||||
<MAdminButton className="ml-auto" onClick={() => setShowCreateUser(true)}>
|
||||
<UserPlus size={12} strokeWidth={2.2} />
|
||||
{t('mobileAdmin.create')}
|
||||
</MAdminButton>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="flex justify-center py-6">
|
||||
<div className="h-8 w-8 animate-spin rounded-full border-2 border-[color:var(--m-rowbr)] border-t-[color:var(--m-ink)]" />
|
||||
</div>
|
||||
) : (
|
||||
users.map((u) => (
|
||||
<button
|
||||
key={u.id}
|
||||
type="button"
|
||||
onClick={() => handleEditUser(u)}
|
||||
className="flex w-full items-center gap-[11px] border-t border-[color:var(--m-rowbr)] py-[11px] text-left"
|
||||
>
|
||||
{u.avatar_url ? (
|
||||
<img src={u.avatar_url} alt="" className="h-[34px] w-[34px] flex-none rounded-full object-cover" />
|
||||
) : (
|
||||
<span className="flex h-[34px] w-[34px] flex-none items-center justify-center rounded-full bg-[color:var(--m-ic)] text-[0.75rem] font-extrabold text-m-ink">
|
||||
{u.username.charAt(0).toUpperCase()}
|
||||
</span>
|
||||
)}
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="flex items-center gap-[5px]">
|
||||
<span className="truncate text-[0.8125rem] font-bold text-m-ink">{u.username}</span>
|
||||
{u.id === currentUser?.id && (
|
||||
<span className="font-geist text-[0.5625rem] text-m-faint">{t('admin.you')}</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="block truncate font-geist text-[0.625rem] text-m-muted">{u.email}</span>
|
||||
</span>
|
||||
<span
|
||||
className={`flex-none whitespace-nowrap rounded-full px-[9px] py-[3px] font-geist text-[0.5625rem] font-extrabold ${
|
||||
u.role === 'admin'
|
||||
? 'bg-[color:color-mix(in_srgb,var(--m-st-danger)_12%,transparent)] text-[color:var(--m-st-danger)]'
|
||||
: 'bg-[color:var(--m-ic)] text-m-muted'
|
||||
}`}
|
||||
>
|
||||
{u.role === 'admin' ? t('settings.roleAdmin') : t('settings.roleUser')}
|
||||
</span>
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</MAdminCard>
|
||||
|
||||
<MAdminCard>
|
||||
<div className="mb-1 flex items-center gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-[0.875rem] font-extrabold text-m-ink">{t('admin.invite.title')}</div>
|
||||
<div className="mt-[2px] font-geist text-[0.625rem] text-m-muted">{t('admin.invite.subtitle')}</div>
|
||||
</div>
|
||||
<MAdminButton onClick={() => setShowCreateInvite(true)}>{t('admin.invite.create')}</MAdminButton>
|
||||
</div>
|
||||
|
||||
{invites.length === 0 ? (
|
||||
<div className="py-4 text-center font-geist text-[0.6875rem] text-m-faint">{t('admin.invite.empty')}</div>
|
||||
) : (
|
||||
invites.map((inv) => {
|
||||
const isExpired = inv.expires_at && new Date(inv.expires_at) < new Date()
|
||||
const isUsedUp = inv.max_uses > 0 && inv.used_count >= inv.max_uses
|
||||
const isActive = !isExpired && !isUsedUp
|
||||
return (
|
||||
<div
|
||||
key={inv.id}
|
||||
className="flex items-center gap-[10px] border-t border-[color:var(--m-rowbr)] py-[11px]"
|
||||
>
|
||||
<Link2 size={14} strokeWidth={2} className={`flex-none ${isActive ? 'text-m-ink' : 'text-m-faint'}`} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-[6px]">
|
||||
<code className="truncate font-geist text-[0.6875rem] text-m-ink">{inv.token.slice(0, 12)}…</code>
|
||||
<span
|
||||
className={`flex-none rounded-full px-[7px] py-[2px] font-geist text-[0.5625rem] font-extrabold ${
|
||||
isActive
|
||||
? 'bg-[color:color-mix(in_srgb,var(--m-st-confirmed)_12%,transparent)] text-[color:var(--m-st-confirmed)]'
|
||||
: 'bg-[color:var(--m-ic)] text-m-faint'
|
||||
}`}
|
||||
>
|
||||
{isUsedUp ? t('admin.invite.usedUp') : isExpired ? t('admin.invite.expired') : t('admin.invite.active')}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-[2px] truncate font-geist text-[0.59375rem] text-m-muted">
|
||||
{inv.used_count}/{inv.max_uses === 0 ? '∞' : inv.max_uses} {t('admin.invite.uses')}
|
||||
{inv.expires_at && ` · ${t('admin.invite.expiresAt')} ${new Date(inv.expires_at).toLocaleDateString(locale)}`}
|
||||
{inv.trip_title && ` · ${t('admin.invite.boundTo', { trip: inv.trip_title })}`}
|
||||
{` · ${t('admin.invite.createdBy')} ${inv.created_by_name}`}
|
||||
</div>
|
||||
</div>
|
||||
{isActive && (
|
||||
<button
|
||||
type="button"
|
||||
title={t('admin.invite.copyLink')}
|
||||
onClick={() => copyInviteLink(inv.token)}
|
||||
className="flex h-8 w-8 flex-none items-center justify-center rounded-full bg-[color:var(--m-ic)] text-m-muted"
|
||||
>
|
||||
<Copy size={13} strokeWidth={2} />
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
title={t('common.delete')}
|
||||
onClick={() => handleDeleteInvite(inv.id)}
|
||||
className="flex h-8 w-8 flex-none items-center justify-center rounded-full bg-[color:var(--m-ic)] text-[color:var(--m-st-danger)]"
|
||||
>
|
||||
<Trash2 size={13} strokeWidth={2} />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
)}
|
||||
</MAdminCard>
|
||||
|
||||
<MAdminPermissionsPanel />
|
||||
|
||||
{/* Create invite sheet */}
|
||||
<MSheet open={showCreateInvite} onClose={() => setShowCreateInvite(false)} ariaLabel={t('admin.invite.create')}>
|
||||
<MAdminSheetFrame
|
||||
title={t('admin.invite.create')}
|
||||
onClose={() => setShowCreateInvite(false)}
|
||||
footer={
|
||||
<>
|
||||
<MAdminButton variant="ghost" onClick={() => setShowCreateInvite(false)}>
|
||||
{t('common.cancel')}
|
||||
</MAdminButton>
|
||||
<MAdminButton onClick={handleCreateInvite}>{t('admin.invite.createAndCopy')}</MAdminButton>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<MAdminField label={t('admin.invite.maxUses')}>
|
||||
<div className="flex flex-wrap gap-[6px]">
|
||||
{INVITE_USES.map((n) => (
|
||||
<MChip
|
||||
key={n}
|
||||
active={inviteForm.max_uses === n}
|
||||
onClick={() => setInviteForm((f) => ({ ...f, max_uses: n }))}
|
||||
>
|
||||
{n === 0 ? '∞' : `${n}×`}
|
||||
</MChip>
|
||||
))}
|
||||
</div>
|
||||
</MAdminField>
|
||||
<MAdminField label={t('admin.invite.expiry')}>
|
||||
<div className="flex flex-wrap gap-[6px]">
|
||||
{INVITE_EXPIRY.map((opt) => (
|
||||
<MChip
|
||||
key={String(opt.value)}
|
||||
active={inviteForm.expires_in_days === opt.value}
|
||||
onClick={() => setInviteForm((f) => ({ ...f, expires_in_days: opt.value }))}
|
||||
>
|
||||
{opt.label}
|
||||
</MChip>
|
||||
))}
|
||||
</div>
|
||||
</MAdminField>
|
||||
{inviteTrips.length > 0 && (
|
||||
<MAdminField label={t('admin.invite.tripLabel')} hint={t('admin.invite.tripHint')}>
|
||||
<select
|
||||
value={inviteForm.trip_id}
|
||||
onChange={(e) =>
|
||||
setInviteForm((f) => ({ ...f, trip_id: e.target.value === '' ? '' : Number(e.target.value) }))
|
||||
}
|
||||
className="h-[42px] w-full rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-3 text-[0.84375rem] text-m-ink outline-none"
|
||||
>
|
||||
<option value="">{t('admin.invite.tripNone')}</option>
|
||||
{inviteTrips.map((tr) => (
|
||||
<option key={tr.id} value={tr.id}>
|
||||
{tr.title}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</MAdminField>
|
||||
)}
|
||||
</div>
|
||||
</MAdminSheetFrame>
|
||||
</MSheet>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useSearchParams } from 'react-router-dom'
|
||||
import { X } from 'lucide-react'
|
||||
import { useAtlas } from '../../../pages/atlas/useAtlas'
|
||||
import MIconBtn from '../../components/MIconBtn'
|
||||
import MSheet from '../../components/MSheet'
|
||||
import MChip from '../../components/MChip'
|
||||
import MAtlasStatsCard from './MAtlasStatsCard'
|
||||
import MAtlasSearch from './MAtlasSearch'
|
||||
import MAtlasCountryPopup from './MAtlasCountryPopup'
|
||||
import MAtlasBucketSheet from './MAtlasBucketSheet'
|
||||
|
||||
const removeBtnCls = 'mt-4 w-full rounded-full bg-[rgba(214,39,59,.12)] py-[11px] text-center text-[0.8125rem] font-bold text-[color:var(--m-st-danger)]' // theme-lint-disable — fixed status-danger tint
|
||||
|
||||
/**
|
||||
* Mobile atlas screen: the interactive world map fills the viewport, the
|
||||
* five-column stats card floats above the bottom nav and the search overlay
|
||||
* flies the map to a country. All map/data logic comes from the shared
|
||||
* useAtlas hook — this file is presentation and wiring only.
|
||||
*/
|
||||
export default function MAtlas() {
|
||||
const atlas = useAtlas()
|
||||
const {
|
||||
t,
|
||||
navigate,
|
||||
resolveName,
|
||||
loading,
|
||||
mapRef,
|
||||
regionTooltipRef,
|
||||
stats,
|
||||
countries,
|
||||
bucketList,
|
||||
selectedCountry,
|
||||
countryDetail,
|
||||
handleUnmarkCountry,
|
||||
select_country_from_search,
|
||||
atlas_country_options,
|
||||
} = atlas
|
||||
const [searchOpen, setSearchOpen] = useState(false)
|
||||
const [bucketOpen, setBucketOpen] = useState(false)
|
||||
const [detailOpen, setDetailOpen] = useState(false)
|
||||
|
||||
// The dock FAB is the search button on this screen (demo Z. 1099) and hands
|
||||
// off via ?search=1, mirroring the ?create= contract of the other pages.
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
useEffect(() => {
|
||||
if (searchParams.get('search') == null) return
|
||||
const next = new URLSearchParams(searchParams)
|
||||
next.delete('search')
|
||||
setSearchParams(next, { replace: true })
|
||||
setSearchOpen(true)
|
||||
}, [searchParams, setSearchParams])
|
||||
|
||||
// A search fly-to on a visited country loads its detail — surface it as a sheet.
|
||||
useEffect(() => {
|
||||
if (selectedCountry && countryDetail) setDetailOpen(true)
|
||||
}, [selectedCountry, countryDetail])
|
||||
|
||||
// Suggestions for the empty search field: recently visited countries first,
|
||||
// then countries already on the bucket list.
|
||||
const suggestions = useMemo(() => {
|
||||
const seen = new Set<string>()
|
||||
const list: { code: string; label: string }[] = []
|
||||
const visited = [...countries].sort((a, b) => (b.lastVisit || '').localeCompare(a.lastVisit || ''))
|
||||
for (const c of visited) {
|
||||
if (seen.has(c.code)) continue
|
||||
seen.add(c.code)
|
||||
list.push({ code: c.code, label: resolveName(c.code) })
|
||||
}
|
||||
for (const item of bucketList) {
|
||||
const code = item.country_code
|
||||
if (!code || code.length !== 2 || seen.has(code)) continue
|
||||
seen.add(code)
|
||||
list.push({ code, label: resolveName(code) })
|
||||
}
|
||||
return list.slice(0, 5)
|
||||
}, [countries, bucketList, resolveName])
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="relative h-full">
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<div className="h-8 w-8 animate-spin rounded-full border-2 border-[color:var(--m-rowbr)] border-t-m-ink" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative h-full overflow-hidden">
|
||||
<div ref={mapRef} className="absolute inset-0 z-[1] bg-[color:var(--m-mapb)] [&_.leaflet-control-zoom]:hidden" />
|
||||
{/* Region hover tooltip — positioned imperatively by useAtlas. */}
|
||||
<div
|
||||
ref={regionTooltipRef}
|
||||
style={{ display: 'none' }}
|
||||
className="pointer-events-none fixed z-[80] min-w-[120px] rounded-[10px] border border-[color:var(--m-shbr)] bg-[color:var(--m-sheetop)] px-[14px] py-[10px] text-[0.75rem] text-m-ink shadow-[0_4px_16px_rgba(0,0,0,.18)]"
|
||||
/>
|
||||
|
||||
{/* Full-width bucket-list button. The bottom nav makes a back button
|
||||
redundant on this main-nav screen, so the header spans the width. */}
|
||||
<div className="absolute left-4 right-4 top-[var(--m-safe-top,12px)] z-[5]">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setBucketOpen(true)}
|
||||
className="flex h-[38px] w-full items-center justify-center rounded-full border border-[color:var(--m-gbr)] bg-[color:var(--m-sheet)] px-4 text-[0.78125rem] font-bold text-m-ink shadow-[0_5px_12px_-8px_rgba(0,0,0,.18)]"
|
||||
>
|
||||
{t('atlas.bucketTab')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<MAtlasStatsCard stats={stats} />
|
||||
|
||||
<MAtlasSearch
|
||||
open={searchOpen}
|
||||
onClose={() => setSearchOpen(false)}
|
||||
options={atlas_country_options}
|
||||
suggestions={suggestions}
|
||||
isVisited={(code) => countries.some((c) => c.code === code)}
|
||||
isOnBucketList={(code) => bucketList.some((b) => b.country_code === code)}
|
||||
onSelect={(code) => {
|
||||
setSearchOpen(false)
|
||||
select_country_from_search(code)
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Country detail sheet (visited country with trips/places). */}
|
||||
<MSheet
|
||||
open={detailOpen}
|
||||
onClose={() => setDetailOpen(false)}
|
||||
variant="card"
|
||||
ariaLabel={selectedCountry ? resolveName(selectedCountry) : undefined}
|
||||
>
|
||||
{selectedCountry && countryDetail && (
|
||||
<div className="p-5">
|
||||
<div className="flex items-center gap-3">
|
||||
<img
|
||||
src={`https://flagcdn.com/w80/${selectedCountry.toLowerCase()}.png`}
|
||||
alt=""
|
||||
className="h-[30px] w-[42px] flex-none rounded-[6px] object-cover shadow-[0_1px_3px_rgba(0,0,0,.25)]"
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-[1.0625rem] font-extrabold text-m-ink">{resolveName(selectedCountry)}</div>
|
||||
<div className="mt-[2px] font-geist text-[0.6875rem] text-m-muted">
|
||||
{countryDetail.places.length} {t('atlas.places')} · {countryDetail.trips.length} {t('atlas.trips')}
|
||||
</div>
|
||||
</div>
|
||||
<MIconBtn variant="neutral" size={34} onClick={() => setDetailOpen(false)} ariaLabel={t('common.close')}>
|
||||
<X size={16} strokeWidth={2.2} />
|
||||
</MIconBtn>
|
||||
</div>
|
||||
{countryDetail.trips.length > 0 && (
|
||||
<div className="mt-4 flex flex-wrap gap-[6px]">
|
||||
{countryDetail.trips.slice(0, 6).map((trip) => (
|
||||
<MChip key={trip.id} onClick={() => navigate(`/trips/${trip.id}`)}>
|
||||
{trip.title}
|
||||
</MChip>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{countryDetail.manually_marked && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setDetailOpen(false)
|
||||
handleUnmarkCountry(selectedCountry)
|
||||
}}
|
||||
className={removeBtnCls}
|
||||
>
|
||||
{t('atlas.unmark')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</MSheet>
|
||||
|
||||
<MAtlasBucketSheet atlas={atlas} open={bucketOpen} onClose={() => setBucketOpen(false)} />
|
||||
<MAtlasCountryPopup atlas={atlas} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
import { useState } from 'react'
|
||||
import { Calendar, ChevronDown, ChevronLeft, ChevronRight, MapPin, Plus, Search, Star, Trash2, X } from 'lucide-react'
|
||||
import MSheet from '../../components/MSheet'
|
||||
import MIconBtn from '../../components/MIconBtn'
|
||||
import { A2_TO_A3 } from '../../../pages/atlas/atlasModel'
|
||||
import type { BucketItem } from '../../../pages/atlas/atlasModel'
|
||||
import type { AtlasController } from './atlasController'
|
||||
|
||||
interface MAtlasBucketSheetProps {
|
||||
atlas: AtlasController
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
const inputCls =
|
||||
'w-full rounded-[14px] border border-[color:var(--m-inbr)] bg-[color:var(--m-inner)] px-[14px] py-[11px] text-[0.84375rem] font-medium text-m-ink outline-none placeholder:text-m-faint'
|
||||
|
||||
function itemCountryA2(item: BucketItem): string | null {
|
||||
const code = item.country_code
|
||||
if (!code) return null
|
||||
if (code.length === 2) return code
|
||||
return Object.entries(A2_TO_A3).find(([, v]) => v === code)?.[0] ?? null
|
||||
}
|
||||
|
||||
/**
|
||||
* Bucket-list sheet, entered via the chip on the stats card. Lists every
|
||||
* bucket item with country, target month, coordinates and notes, and carries
|
||||
* the full add flow (POI search or free name, notes, target month).
|
||||
*/
|
||||
export default function MAtlasBucketSheet({ atlas, open, onClose }: MAtlasBucketSheetProps) {
|
||||
const {
|
||||
t,
|
||||
language,
|
||||
resolveName,
|
||||
bucketList,
|
||||
showBucketAdd,
|
||||
setShowBucketAdd,
|
||||
bucketForm,
|
||||
setBucketForm,
|
||||
bucketSearch,
|
||||
setBucketSearch,
|
||||
bucketSearchResults,
|
||||
setBucketSearchResults,
|
||||
bucketSearching,
|
||||
handleBucketPoiSearch,
|
||||
handleAddBucketItem,
|
||||
handleDeleteBucketItem,
|
||||
} = atlas
|
||||
|
||||
const resetForm = (): void => {
|
||||
setShowBucketAdd(false)
|
||||
setBucketForm({ name: '', notes: '', lat: '', lng: '', target_date: '' })
|
||||
setBucketSearch('')
|
||||
setBucketSearchResults([])
|
||||
}
|
||||
|
||||
const close = (): void => {
|
||||
resetForm()
|
||||
onClose()
|
||||
}
|
||||
|
||||
// Own POI pick instead of the hook's handleSelectBucketPoi: keeps the notes
|
||||
// and target month the user may already have typed into the form.
|
||||
const pickPoi = (result: { name?: string; lat?: number; lng?: number }): void => {
|
||||
setBucketForm({ ...bucketForm, name: result.name || bucketSearch, lat: String(result.lat ?? ''), lng: String(result.lng ?? '') })
|
||||
setBucketSearchResults([])
|
||||
setBucketSearch('')
|
||||
}
|
||||
|
||||
const fmtTarget = (targetDate: string): string => {
|
||||
const [y, m] = targetDate.split('-')
|
||||
return m ? new Date(Number(y), Number(m) - 1).toLocaleDateString(language, { month: 'short', year: 'numeric' }) : y
|
||||
}
|
||||
|
||||
const itemSub = (item: BucketItem): string => {
|
||||
const a2 = itemCountryA2(item)
|
||||
return [
|
||||
a2 ? resolveName(a2) : null,
|
||||
item.target_date ? fmtTarget(item.target_date) : null,
|
||||
item.lat != null && item.lng != null ? `${item.lat.toFixed(2)}, ${item.lng.toFixed(2)}` : null,
|
||||
item.notes || null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' · ')
|
||||
}
|
||||
|
||||
return (
|
||||
<MSheet open={open} onClose={close} variant="bottom" material="glass" ariaLabel={t('atlas.bucketTab')}>
|
||||
<div className="flex min-h-0 flex-col p-4">
|
||||
<div className="flex items-center gap-[10px] px-1 pb-3">
|
||||
<Star size={17} strokeWidth={2.2} className="flex-none text-[color:var(--m-st-pending)]" />
|
||||
<div className="min-w-0 flex-1 truncate text-[0.9375rem] font-extrabold text-m-ink">
|
||||
{t('atlas.bucketTab')}
|
||||
{bucketList.length > 0 && (
|
||||
<span className="ml-[6px] font-geist text-[0.75rem] font-semibold tabular-nums text-m-faint">{bucketList.length}</span>
|
||||
)}
|
||||
</div>
|
||||
<MIconBtn variant="neutral" size={34} onClick={close} ariaLabel={t('common.close')}>
|
||||
<X size={16} strokeWidth={2.2} />
|
||||
</MIconBtn>
|
||||
</div>
|
||||
|
||||
<div className="min-h-0 flex-1 space-y-2 overflow-y-auto">
|
||||
{bucketList.length === 0 && !showBucketAdd && (
|
||||
<div className="px-4 py-8 text-center">
|
||||
<div className="text-[0.84375rem] font-semibold text-m-muted">{t('atlas.bucketEmpty')}</div>
|
||||
<div className="mt-1 font-geist text-[0.6875rem] text-m-faint">{t('atlas.bucketEmptyHint')}</div>
|
||||
</div>
|
||||
)}
|
||||
{bucketList.map((item) => {
|
||||
const a2 = itemCountryA2(item)
|
||||
const sub = itemSub(item)
|
||||
return (
|
||||
<div key={item.id} className="flex items-center gap-3 rounded-[18px] bg-[color:var(--m-ic)] px-[14px] py-[11px]">
|
||||
{a2 ? (
|
||||
<img
|
||||
src={`https://flagcdn.com/w40/${a2.toLowerCase()}.png`}
|
||||
alt=""
|
||||
className="h-[17px] w-6 flex-none rounded-[3px] object-cover shadow-[0_1px_3px_rgba(0,0,0,.25)]"
|
||||
/>
|
||||
) : (
|
||||
<Star size={16} strokeWidth={2.2} className="flex-none text-[color:var(--m-st-pending)]" />
|
||||
)}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-[0.84375rem] font-semibold text-m-ink">{item.name}</div>
|
||||
{sub && <div className="mt-[1px] truncate font-geist text-[0.6875rem] text-m-muted">{sub}</div>}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleDeleteBucketItem(item.id)}
|
||||
aria-label={t('atlas.unmark')}
|
||||
className="flex h-[30px] w-[30px] flex-none items-center justify-center rounded-full text-m-faint active:bg-[color:var(--m-ic)]"
|
||||
>
|
||||
<Trash2 size={15} strokeWidth={2} />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{showBucketAdd ? (
|
||||
<div className="space-y-2 pt-3">
|
||||
<div className="relative">
|
||||
<div className="flex gap-2">
|
||||
<input
|
||||
autoFocus
|
||||
value={bucketForm.name || bucketSearch}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value
|
||||
if (bucketForm.name) setBucketForm({ ...bucketForm, name: v })
|
||||
else setBucketSearch(v)
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key !== 'Enter') return
|
||||
if (bucketForm.name) handleAddBucketItem()
|
||||
else handleBucketPoiSearch()
|
||||
}}
|
||||
placeholder={t('atlas.bucketNamePlaceholder')}
|
||||
className={`${inputCls} min-w-0 flex-1`}
|
||||
/>
|
||||
{bucketForm.name ? (
|
||||
<MIconBtn
|
||||
variant="neutral"
|
||||
size={40}
|
||||
onClick={() => {
|
||||
setBucketForm({ ...bucketForm, name: '', lat: '', lng: '' })
|
||||
setBucketSearch('')
|
||||
}}
|
||||
ariaLabel={t('common.cancel')}
|
||||
>
|
||||
<X size={15} strokeWidth={2.2} />
|
||||
</MIconBtn>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleBucketPoiSearch}
|
||||
disabled={bucketSearching}
|
||||
aria-label={t('common.search')}
|
||||
className="flex h-10 w-10 flex-none items-center justify-center rounded-[14px] bg-m-act text-m-actfg disabled:opacity-50"
|
||||
>
|
||||
<Search size={16} strokeWidth={2.2} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{bucketSearchResults.length > 0 && (
|
||||
<div className="absolute bottom-full left-0 right-0 z-10 mb-2 max-h-40 divide-y divide-[color:var(--m-rowbr)] overflow-y-auto rounded-[16px] border border-[color:var(--m-shbr)] bg-[color:var(--m-sheetop)] shadow-[0_12px_30px_-14px_rgba(0,0,0,.4)]">
|
||||
{bucketSearchResults.slice(0, 6).map((result, i) => (
|
||||
<button key={i} type="button" onClick={() => pickPoi(result)} className="flex w-full flex-col px-[14px] py-[9px] text-left active:bg-[color:var(--m-ic)]">
|
||||
<span className="text-[0.8125rem] font-semibold text-m-ink">{result.name}</span>
|
||||
{result.address && <span className="font-geist text-[0.625rem] text-m-faint">{result.address}</span>}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{bucketForm.lat && bucketForm.lng && (
|
||||
<div className="flex items-center gap-1 px-1 font-geist text-[0.625rem] text-m-faint">
|
||||
<MapPin size={10} strokeWidth={2.2} />
|
||||
{Number(bucketForm.lat).toFixed(4)}, {Number(bucketForm.lng).toFixed(4)}
|
||||
</div>
|
||||
)}
|
||||
<input
|
||||
value={bucketForm.notes}
|
||||
onChange={(e) => setBucketForm({ ...bucketForm, notes: e.target.value })}
|
||||
placeholder={t('atlas.bucketNotesPlaceholder')}
|
||||
className={inputCls}
|
||||
/>
|
||||
<MMonthYearField
|
||||
value={bucketForm.target_date}
|
||||
onChange={(v) => setBucketForm({ ...bucketForm, target_date: v })}
|
||||
placeholder={t('atlas.bucketWhen')}
|
||||
language={language}
|
||||
t={t}
|
||||
/>
|
||||
<div className="flex gap-2 pt-1">
|
||||
<button type="button" onClick={resetForm} className="flex-1 rounded-full bg-[color:var(--m-ic)] py-[11px] text-[0.8125rem] font-bold text-m-ink">
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleAddBucketItem}
|
||||
disabled={!bucketForm.name.trim()}
|
||||
className="flex-1 rounded-full bg-m-act py-[11px] text-[0.8125rem] font-bold text-m-actfg disabled:opacity-50"
|
||||
>
|
||||
{t('common.add')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowBucketAdd(true)}
|
||||
className="mt-3 flex w-full flex-none items-center justify-center gap-[6px] rounded-full border border-dashed border-[color:var(--m-rowbr)] py-[10px] font-geist text-[0.75rem] font-semibold text-m-muted"
|
||||
>
|
||||
<Plus size={13} strokeWidth={2.4} />
|
||||
{t('atlas.addPoi')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</MSheet>
|
||||
)
|
||||
}
|
||||
|
||||
/** Custom month/year picker replacing the native <input type="month">: a year
|
||||
* stepper over a 12-month grid, opening upward so it clears the docked sheet. */
|
||||
function MMonthYearField({ value, onChange, placeholder, language, t }: {
|
||||
value: string
|
||||
onChange: (v: string) => void
|
||||
placeholder: string
|
||||
language: string
|
||||
t: AtlasController['t']
|
||||
}) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const selYear = value ? Number(value.split('-')[0]) : null
|
||||
const selMonth = value ? Number(value.split('-')[1]) : null
|
||||
const [year, setYear] = useState(selYear ?? new Date().getFullYear())
|
||||
|
||||
const display = selYear
|
||||
? new Date(selYear, (selMonth ?? 1) - 1).toLocaleDateString(language, { month: 'long', year: 'numeric' })
|
||||
: ''
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<button type="button" onClick={() => setOpen(o => !o)} aria-expanded={open} className={`${inputCls} flex items-center gap-2 text-left`}>
|
||||
<Calendar size={15} strokeWidth={2.2} className="flex-none text-m-muted" />
|
||||
<span className={`min-w-0 flex-1 truncate ${display ? '' : 'text-m-faint'}`}>{display || placeholder}</span>
|
||||
<ChevronDown size={15} strokeWidth={2} className={`flex-none text-m-faint transition-transform ${open ? 'rotate-180' : ''}`} />
|
||||
</button>
|
||||
{open && (
|
||||
<div className="absolute bottom-full left-0 right-0 z-10 mb-2 rounded-[16px] border border-[color:var(--m-shbr)] bg-[color:var(--m-sheetop)] p-3 shadow-[0_12px_30px_-14px_rgba(0,0,0,.4)]">
|
||||
<div className="mb-[10px] flex items-center justify-between">
|
||||
<button type="button" onClick={() => setYear(y => y - 1)} aria-label={t('mobileVacay.prevYear')} className="flex h-8 w-8 flex-none items-center justify-center rounded-full bg-[color:var(--m-ic)] text-m-muted">
|
||||
<ChevronLeft size={16} strokeWidth={2.2} />
|
||||
</button>
|
||||
<span className="text-[0.9375rem] font-extrabold tabular-nums text-m-ink">{year}</span>
|
||||
<button type="button" onClick={() => setYear(y => y + 1)} aria-label={t('mobileVacay.nextYear')} className="flex h-8 w-8 flex-none items-center justify-center rounded-full bg-[color:var(--m-ic)] text-m-muted">
|
||||
<ChevronRight size={16} strokeWidth={2.2} />
|
||||
</button>
|
||||
</div>
|
||||
<div className="grid grid-cols-4 gap-[6px]">
|
||||
{Array.from({ length: 12 }, (_, m) => {
|
||||
const on = selYear === year && selMonth === m + 1
|
||||
return (
|
||||
<button
|
||||
key={m}
|
||||
type="button"
|
||||
onClick={() => { onChange(`${year}-${String(m + 1).padStart(2, '0')}`); setOpen(false) }}
|
||||
className={`rounded-[10px] py-2 text-[0.71875rem] font-bold capitalize ${on ? 'bg-m-act text-m-actfg' : 'bg-[color:var(--m-ic)] text-m-ink'}`}
|
||||
>
|
||||
{new Date(2000, m, 1).toLocaleDateString(language, { month: 'short' })}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
{value && (
|
||||
<button type="button" onClick={() => { onChange(''); setOpen(false) }} className="mt-[10px] w-full rounded-[10px] py-[7px] text-[0.6875rem] font-bold text-m-muted">
|
||||
{t('common.reset')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { ChevronRight, MapPin, Star } from 'lucide-react'
|
||||
import type { LucideIcon } from 'lucide-react'
|
||||
import apiClient from '../../../api/client'
|
||||
import { continentForCountry } from '@trek/shared'
|
||||
import { getApiErrorMessage } from '../../../types'
|
||||
import { useToast } from '../../../components/shared/Toast'
|
||||
import { countryCodeToFlag } from '../../../pages/atlas/atlasModel'
|
||||
import MSheet from '../../components/MSheet'
|
||||
import type { AtlasController } from './atlasController'
|
||||
|
||||
const markTint = 'bg-[rgba(47,163,122,.16)] text-[color:var(--m-st-confirmed)]' // theme-lint-disable — fixed tint from the design's option rows
|
||||
const bucketTint = 'bg-[rgba(232,161,58,.16)] text-[color:var(--m-st-pending)]' // theme-lint-disable — fixed tint from the design's option rows
|
||||
|
||||
const btnBase = 'flex-1 rounded-full py-[11px] text-[0.8125rem] font-bold'
|
||||
const cancelBtn = `${btnBase} bg-[color:var(--m-ic)] text-m-ink`
|
||||
const dangerBtn = `${btnBase} bg-[color:var(--m-st-danger)] text-white`
|
||||
const actBtn = `${btnBase} bg-m-act text-m-actfg`
|
||||
|
||||
const inputCls =
|
||||
'mt-2 w-full rounded-[14px] border border-[color:var(--m-inbr)] bg-[color:var(--m-inner)] px-[14px] py-[11px] text-[0.84375rem] font-medium text-m-ink outline-none'
|
||||
|
||||
interface OptionRowProps {
|
||||
icon: LucideIcon
|
||||
tint: string
|
||||
title: string
|
||||
hint: string
|
||||
onClick: () => void
|
||||
}
|
||||
|
||||
function OptionRow({ icon: Icon, tint, title, hint, onClick }: OptionRowProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className="flex w-full items-center gap-[13px] rounded-[18px] bg-[color:var(--m-ic)] px-4 py-[14px] text-left"
|
||||
>
|
||||
<span className={`flex h-10 w-10 flex-none items-center justify-center rounded-xl ${tint}`}>
|
||||
<Icon size={20} strokeWidth={2} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block text-[0.9375rem] font-extrabold text-m-ink">{title}</span>
|
||||
<span className="mt-[1px] block font-geist text-[0.6875rem] text-m-muted">{hint}</span>
|
||||
</span>
|
||||
<ChevronRight size={17} strokeWidth={2} className="flex-none text-m-faint" />
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
interface MAtlasCountryPopupProps {
|
||||
atlas: AtlasController
|
||||
}
|
||||
|
||||
/**
|
||||
* Country/region tap popup: mark visited, add to bucket list (with target
|
||||
* month) or remove again. Same flows and API calls as the desktop popup,
|
||||
* rendered as the mobile card sheet.
|
||||
*/
|
||||
export default function MAtlasCountryPopup({ atlas }: MAtlasCountryPopupProps) {
|
||||
const {
|
||||
t,
|
||||
confirmAction,
|
||||
setConfirmAction,
|
||||
executeConfirmAction,
|
||||
setData,
|
||||
setVisitedRegions,
|
||||
setBucketList,
|
||||
visitedRegions,
|
||||
} = atlas
|
||||
const toast = useToast()
|
||||
const [bucketDate, setBucketDate] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
if (!confirmAction) setBucketDate('')
|
||||
}, [confirmAction])
|
||||
|
||||
const markCountry = async (): Promise<void> => {
|
||||
if (!confirmAction) return
|
||||
const { code } = confirmAction
|
||||
try {
|
||||
await apiClient.post(`/addons/atlas/country/${code}/mark`)
|
||||
setData((prev) => {
|
||||
if (!prev || prev.countries.find((c) => c.code === code)) return prev
|
||||
const cont = continentForCountry(code)
|
||||
return {
|
||||
...prev,
|
||||
countries: [...prev.countries, { code, placeCount: 0, tripCount: 0, firstVisit: null, lastVisit: null }],
|
||||
stats: { ...prev.stats, totalCountries: prev.stats.totalCountries + 1 },
|
||||
continents: { ...prev.continents, [cont]: (prev.continents?.[cont] || 0) + 1 },
|
||||
}
|
||||
})
|
||||
} catch (err) {
|
||||
toast.error(getApiErrorMessage(err, t('common.error')))
|
||||
}
|
||||
setConfirmAction(null)
|
||||
}
|
||||
|
||||
const markRegion = async (): Promise<void> => {
|
||||
if (!confirmAction) return
|
||||
const { code: countryCode, name: regionName, regionCode } = confirmAction
|
||||
if (!regionCode) return
|
||||
try {
|
||||
await apiClient.post(`/addons/atlas/region/${regionCode}/mark`, { name: regionName, country_code: countryCode })
|
||||
setVisitedRegions((prev) => {
|
||||
const existing = prev[countryCode] || []
|
||||
if (existing.find((r) => r.code === regionCode)) return prev
|
||||
return { ...prev, [countryCode]: [...existing, { code: regionCode, name: regionName, placeCount: 0, manuallyMarked: true }] }
|
||||
})
|
||||
setData((prev) => {
|
||||
if (!prev || prev.countries.find((c) => c.code === countryCode)) return prev
|
||||
const cont = continentForCountry(countryCode)
|
||||
return {
|
||||
...prev,
|
||||
countries: [...prev.countries, { code: countryCode, placeCount: 0, tripCount: 0, firstVisit: null, lastVisit: null }],
|
||||
stats: { ...prev.stats, totalCountries: prev.stats.totalCountries + 1 },
|
||||
continents: { ...prev.continents, [cont]: (prev.continents?.[cont] || 0) + 1 },
|
||||
}
|
||||
})
|
||||
} catch (err) {
|
||||
toast.error(getApiErrorMessage(err, t('common.error')))
|
||||
}
|
||||
setConfirmAction(null)
|
||||
}
|
||||
|
||||
const unmarkRegion = async (): Promise<void> => {
|
||||
if (!confirmAction) return
|
||||
const { code: countryCode, regionCode } = confirmAction
|
||||
if (!regionCode) return
|
||||
try {
|
||||
await apiClient.delete(`/addons/atlas/region/${regionCode}/mark`)
|
||||
setVisitedRegions((prev) => {
|
||||
const remaining = (prev[countryCode] || []).filter((r) => r.code !== regionCode)
|
||||
const next = { ...prev, [countryCode]: remaining }
|
||||
if (remaining.length === 0) delete next[countryCode]
|
||||
return next
|
||||
})
|
||||
// Drop the country too once no manually-marked region and no trip/place keeps it.
|
||||
setData((prev) => {
|
||||
if (!prev) return prev
|
||||
const c = prev.countries.find((c) => c.code === countryCode)
|
||||
if (!c || c.placeCount > 0 || c.tripCount > 0) return prev
|
||||
const remainingRegions = (visitedRegions[countryCode] || []).filter((r) => r.code !== regionCode && r.manuallyMarked)
|
||||
if (remainingRegions.length > 0) return prev
|
||||
const cont = continentForCountry(countryCode)
|
||||
return {
|
||||
...prev,
|
||||
countries: prev.countries.filter((c) => c.code !== countryCode),
|
||||
stats: { ...prev.stats, totalCountries: Math.max(0, prev.stats.totalCountries - 1) },
|
||||
continents: { ...prev.continents, [cont]: Math.max(0, (prev.continents?.[cont] || 0) - 1) },
|
||||
}
|
||||
})
|
||||
} catch (err) {
|
||||
toast.error(getApiErrorMessage(err, t('common.error')))
|
||||
}
|
||||
setConfirmAction(null)
|
||||
}
|
||||
|
||||
const addBucket = async (): Promise<void> => {
|
||||
if (!confirmAction) return
|
||||
try {
|
||||
const r = await apiClient.post('/addons/atlas/bucket-list', {
|
||||
name: confirmAction.name,
|
||||
country_code: confirmAction.code,
|
||||
target_date: bucketDate || null,
|
||||
})
|
||||
setBucketList((prev) => [r.data.item, ...prev])
|
||||
} catch (err) {
|
||||
toast.error(getApiErrorMessage(err, t('common.error')))
|
||||
}
|
||||
setConfirmAction(null)
|
||||
}
|
||||
|
||||
const a = confirmAction
|
||||
|
||||
return (
|
||||
<MSheet open={!!a} onClose={() => setConfirmAction(null)} variant="card" ariaLabel={a?.name}>
|
||||
{a && (
|
||||
<div className="flex flex-col gap-2 p-5">
|
||||
<div className="flex flex-col items-center pb-2 text-center">
|
||||
{a.code.length === 2 ? (
|
||||
<img
|
||||
src={`https://flagcdn.com/w80/${a.code.toLowerCase()}.png`}
|
||||
alt=""
|
||||
className="h-[34px] w-12 rounded-[6px] object-cover shadow-[0_1px_3px_rgba(0,0,0,.25)]"
|
||||
/>
|
||||
) : (
|
||||
<span className="text-[2.25rem] leading-none">{countryCodeToFlag(a.code)}</span>
|
||||
)}
|
||||
<div className="mt-3 text-[1.0625rem] font-extrabold text-m-ink">{a.name}</div>
|
||||
{a.countryName && (a.type === 'choose-region' || a.type === 'unmark-region') && (
|
||||
<div className="mt-[2px] font-geist text-[0.6875rem] text-m-muted">{a.countryName}</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{a.type === 'choose' && (
|
||||
<>
|
||||
<OptionRow icon={MapPin} tint={markTint} title={t('atlas.markVisited')} hint={t('atlas.markVisitedHint')} onClick={markCountry} />
|
||||
<OptionRow
|
||||
icon={Star}
|
||||
tint={bucketTint}
|
||||
title={t('atlas.addToBucket')}
|
||||
hint={t('atlas.addToBucketHint')}
|
||||
onClick={() => setConfirmAction({ ...a, type: 'bucket' })}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{a.type === 'choose-region' && (
|
||||
<>
|
||||
<OptionRow icon={MapPin} tint={markTint} title={t('atlas.markVisited')} hint={t('atlas.markRegionVisitedHint')} onClick={markRegion} />
|
||||
<OptionRow
|
||||
icon={Star}
|
||||
tint={bucketTint}
|
||||
title={t('atlas.addToBucket')}
|
||||
hint={t('atlas.addToBucketHint')}
|
||||
onClick={() => setConfirmAction({ ...a, type: 'bucket' })}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{a.type === 'mark' && (
|
||||
<>
|
||||
<p className="pb-2 text-center text-[0.8125rem] text-m-muted">{t('atlas.confirmMark')}</p>
|
||||
<div className="flex gap-2">
|
||||
<button type="button" onClick={() => setConfirmAction(null)} className={cancelBtn}>
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
<button type="button" onClick={executeConfirmAction} className={actBtn}>
|
||||
{t('atlas.markVisited')}
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{a.type === 'unmark' && (
|
||||
<>
|
||||
<p className="pb-2 text-center text-[0.8125rem] text-m-muted">{t('atlas.confirmUnmark')}</p>
|
||||
<div className="flex gap-2">
|
||||
<button type="button" onClick={() => setConfirmAction(null)} className={cancelBtn}>
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
<button type="button" onClick={executeConfirmAction} className={dangerBtn}>
|
||||
{t('atlas.unmark')}
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{a.type === 'unmark-region' && (
|
||||
<>
|
||||
<p className="pb-2 text-center text-[0.8125rem] text-m-muted">{t('atlas.confirmUnmarkRegion')}</p>
|
||||
<div className="flex gap-2">
|
||||
<button type="button" onClick={() => setConfirmAction(null)} className={cancelBtn}>
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
<button type="button" onClick={unmarkRegion} className={dangerBtn}>
|
||||
{t('atlas.unmark')}
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{a.type === 'bucket' && (
|
||||
<>
|
||||
<label className="block text-left">
|
||||
<span className="font-geist text-[0.6875rem] font-bold text-m-muted">{t('atlas.bucketWhen')}</span>
|
||||
<input type="month" value={bucketDate} onChange={(e) => setBucketDate(e.target.value)} className={inputCls} />
|
||||
</label>
|
||||
<div className="mt-2 flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setConfirmAction({ ...a, type: a.regionCode ? 'choose-region' : 'choose' })}
|
||||
className={cancelBtn}
|
||||
>
|
||||
{t('common.back')}
|
||||
</button>
|
||||
<button type="button" onClick={addBucket} className={actBtn}>
|
||||
{t('atlas.addToBucket')}
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</MSheet>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { ChevronRight, Search } from 'lucide-react'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
|
||||
interface CountryOption {
|
||||
code: string
|
||||
label: string
|
||||
}
|
||||
|
||||
interface MAtlasSearchProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
/** All searchable countries (code + localized label). */
|
||||
options: CountryOption[]
|
||||
/** Shown while the query is empty: recently visited + bucket countries. */
|
||||
suggestions: CountryOption[]
|
||||
isVisited: (code: string) => boolean
|
||||
isOnBucketList: (code: string) => boolean
|
||||
onSelect: (code: string) => void
|
||||
}
|
||||
|
||||
const statusCls = 'flex-none font-geist text-[0.625rem] font-bold uppercase tracking-[.04em] text-m-faint'
|
||||
|
||||
/**
|
||||
* Full-screen country search on a blurred scrim. Typing filters the country
|
||||
* list; while empty the suggestion list (visited + bucket countries) fills
|
||||
* the result card. Selecting a row flies the map to the country.
|
||||
*/
|
||||
export default function MAtlasSearch({
|
||||
open,
|
||||
onClose,
|
||||
options,
|
||||
suggestions,
|
||||
isVisited,
|
||||
isOnBucketList,
|
||||
onSelect,
|
||||
}: MAtlasSearchProps) {
|
||||
const { t } = useTranslation()
|
||||
const [query, setQuery] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) setQuery('')
|
||||
}, [open])
|
||||
|
||||
if (!open) return null
|
||||
|
||||
const q = query.trim().toLowerCase()
|
||||
const rows = q ? options.filter((o) => o.label.toLowerCase().includes(q)).slice(0, 6) : suggestions
|
||||
|
||||
const scrimCls = 'm-fade-in fixed inset-0 z-[70] flex flex-col bg-[rgba(16,16,19,.28)] px-[18px] pt-[calc(var(--m-safe-top,12px)+12px)] backdrop-blur-[22px] backdrop-saturate-[1.6]' // theme-lint-disable — fixed scrim value from the design
|
||||
|
||||
return (
|
||||
<div className={scrimCls} onClick={onClose}>
|
||||
<div className="flex items-center gap-[10px]" onClick={(e) => e.stopPropagation()}>
|
||||
<label className="flex min-w-0 flex-1 items-center gap-[10px] rounded-[18px] border border-[color:var(--m-gbr)] bg-[color:var(--m-sheetop)] px-4 py-[14px] shadow-[0_12px_30px_-14px_rgba(0,0,0,.4)]">
|
||||
<Search size={18} strokeWidth={2.2} className="flex-none text-m-muted" />
|
||||
<input
|
||||
autoFocus
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Escape') onClose()
|
||||
if (e.key === 'Enter' && rows.length > 0) onSelect(rows[0].code)
|
||||
}}
|
||||
placeholder={t('atlas.searchCountry')}
|
||||
className="min-w-0 flex-1 bg-transparent font-geist text-[0.9375rem] font-semibold text-m-ink outline-none placeholder:font-normal placeholder:text-m-faint"
|
||||
/>
|
||||
</label>
|
||||
<button type="button" onClick={onClose} className="flex-none px-1 font-geist text-[0.9375rem] font-semibold text-white">
|
||||
{t('common.cancel')}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{rows.length > 0 && (
|
||||
<div
|
||||
className="m-pop-in mt-[14px] divide-y divide-[color:var(--m-rowbr)] overflow-hidden rounded-[20px] border border-[color:var(--m-gbr)] bg-[color:var(--m-sheetop)] shadow-[0_20px_44px_-18px_rgba(0,0,0,.4)]"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{rows.map((r) => (
|
||||
<button
|
||||
key={r.code}
|
||||
type="button"
|
||||
onClick={() => onSelect(r.code)}
|
||||
className="flex w-full items-center gap-3 px-4 py-[14px] text-left active:bg-[color:var(--m-ic)]"
|
||||
>
|
||||
<img
|
||||
src={`https://flagcdn.com/w40/${r.code.toLowerCase()}.png`}
|
||||
alt=""
|
||||
className="h-6 w-[34px] flex-none rounded-[5px] object-cover shadow-[0_1px_3px_rgba(0,0,0,.25)]"
|
||||
/>
|
||||
<span className="min-w-0 flex-1 truncate text-[0.9375rem] font-extrabold text-m-ink">{r.label}</span>
|
||||
{isVisited(r.code) ? (
|
||||
<span className={statusCls}>{t('mobileAtlas.visited')}</span>
|
||||
) : isOnBucketList(r.code) ? (
|
||||
<span className={statusCls}>{t('atlas.bucketTab')}</span>
|
||||
) : null}
|
||||
<ChevronRight size={17} strokeWidth={2} className="flex-none text-m-faint" />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import type { AtlasStats } from '../../../pages/atlas/atlasModel'
|
||||
|
||||
interface MAtlasStatsCardProps {
|
||||
stats: AtlasStats
|
||||
}
|
||||
|
||||
/**
|
||||
* Floating stats card above the bottom nav: five stat columns straight from the
|
||||
* design. The bucket-list entry now lives in the full-width top header, so this
|
||||
* card is stats only.
|
||||
*/
|
||||
export default function MAtlasStatsCard({ stats }: MAtlasStatsCardProps) {
|
||||
const { t } = useTranslation()
|
||||
const cols: [number, string][] = [
|
||||
[stats.totalCountries, t('atlas.countries')],
|
||||
[stats.totalTrips, t('atlas.trips')],
|
||||
[stats.totalPlaces, t('atlas.places')],
|
||||
[stats.totalCities || 0, t('atlas.cities')],
|
||||
[stats.totalDays, t('atlas.days')],
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="absolute bottom-[calc(var(--bottom-nav-h,84px)+16px)] left-4 right-4 z-[5]">
|
||||
<div className="flex w-full rounded-[22px] border border-[color:var(--m-shbr)] bg-[color:var(--m-sheet)] px-3 py-[14px] shadow-[0_18px_44px_-20px_rgba(0,0,0,.4)]">
|
||||
{cols.map(([n, l]) => (
|
||||
<div key={l} className="flex-1 text-center">
|
||||
<div className="text-[1.375rem] font-extrabold leading-none tabular-nums text-m-ink">{n}</div>
|
||||
<div className="mt-1 font-geist text-[0.53125rem] font-bold uppercase tracking-[.06em] text-m-faint">{l}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { useAtlas } from '../../../pages/atlas/useAtlas'
|
||||
|
||||
/**
|
||||
* Full surface of the shared atlas hook. The mobile screen calls useAtlas()
|
||||
* once and hands the controller down to its sheets, so map state, bucket list
|
||||
* and the mark/unmark flows stay in a single instance.
|
||||
*/
|
||||
export type AtlasController = ReturnType<typeof useAtlas>
|
||||
@@ -0,0 +1,239 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Check, Loader2, MapPin, Search, X } from 'lucide-react'
|
||||
import type { CollectionStatus } from '@trek/shared'
|
||||
import type { Category, TranslationFn } from '../../../types'
|
||||
import { mapsApi } from '../../../api/client'
|
||||
import { collectionsApi } from '../../../api/collections'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import { useToast } from '../../../components/shared/Toast'
|
||||
import { getApiErrorMessage } from '../../../types'
|
||||
import { STATUS_ORDER } from '../../../pages/collections/collectionsModel'
|
||||
import MSheet from '../../components/MSheet'
|
||||
import MCollCategoryPicker from './MCollCategoryPicker'
|
||||
import { STATUS_SPEC } from './collectionsMobileModel'
|
||||
import { CancelPill, Eyebrow, INPUT_CLS, PrimaryPill, SheetFooter, SheetHeader, TEXTAREA_CLS } from './MCollSheetKit'
|
||||
|
||||
type MapsPlace = Record<string, unknown>
|
||||
const str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined)
|
||||
const num = (v: unknown): number | undefined => (typeof v === 'number' ? v : typeof v === 'string' && v !== '' ? Number(v) : undefined)
|
||||
|
||||
interface MCollAddSheetProps {
|
||||
open: boolean
|
||||
collectionId: number | null
|
||||
collectionName: string
|
||||
/** Pickable target lists — used when opened without a fixed collectionId. */
|
||||
lists: { id: number; name: string; color?: string | null }[]
|
||||
categories: Category[]
|
||||
onClose: () => void
|
||||
onAdded: () => void
|
||||
t: TranslationFn
|
||||
}
|
||||
|
||||
/**
|
||||
* "Add a place": maps search that fills the location, then name / category /
|
||||
* status / description before saving into the active list (duplicates are
|
||||
* reported by the server and surfaced as a toast).
|
||||
*/
|
||||
export default function MCollAddSheet({ open, collectionId, collectionName, lists, categories, onClose, onAdded, t }: MCollAddSheetProps) {
|
||||
const { language } = useTranslation()
|
||||
const toast = useToast()
|
||||
const [query, setQuery] = useState('')
|
||||
const [results, setResults] = useState<MapsPlace[]>([])
|
||||
const [searching, setSearching] = useState(false)
|
||||
const [picked, setPicked] = useState<MapsPlace | null>(null)
|
||||
const [name, setName] = useState('')
|
||||
const [categoryId, setCategoryId] = useState<number | null>(null)
|
||||
const [status, setStatus] = useState<CollectionStatus>('idea')
|
||||
const [description, setDescription] = useState('')
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [targetId, setTargetId] = useState<number | null>(collectionId)
|
||||
|
||||
useEffect(() => {
|
||||
if (open) return
|
||||
setQuery(''); setResults([]); setPicked(null); setName(''); setCategoryId(null); setStatus('idea'); setDescription('')
|
||||
}, [open])
|
||||
|
||||
// Opened from a specific list → target is fixed; from "All Saved" (no active
|
||||
// list) → default to the sole list if there is one, else pick it in-sheet.
|
||||
useEffect(() => {
|
||||
if (open) setTargetId(collectionId ?? (lists.length === 1 ? lists[0].id : null))
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [open, collectionId])
|
||||
|
||||
const search = async () => {
|
||||
if (!query.trim() || searching) return
|
||||
setSearching(true)
|
||||
try {
|
||||
const res = await mapsApi.search(query, language)
|
||||
setResults((res.places as MapsPlace[]) || [])
|
||||
} catch (err) {
|
||||
toast.error(getApiErrorMessage(err, t('places.mapsSearchError')))
|
||||
} finally {
|
||||
setSearching(false)
|
||||
}
|
||||
}
|
||||
|
||||
const pick = (r: MapsPlace) => {
|
||||
setPicked(r)
|
||||
setName(str(r.name) ?? '')
|
||||
setResults([])
|
||||
setQuery(str(r.name) ?? query)
|
||||
}
|
||||
|
||||
const save = async () => {
|
||||
const cleanName = name.trim()
|
||||
if (!cleanName || targetId == null || saving) return
|
||||
setSaving(true)
|
||||
try {
|
||||
const res = await collectionsApi.savePlace({
|
||||
collection_id: targetId,
|
||||
name: cleanName,
|
||||
address: (picked && str(picked.address)) ?? null,
|
||||
lat: (picked && num(picked.lat)) ?? null,
|
||||
lng: (picked && num(picked.lng)) ?? null,
|
||||
google_place_id: (picked && str(picked.google_place_id)) ?? null,
|
||||
google_ftid: (picked && str(picked.google_ftid)) ?? null,
|
||||
osm_id: (picked && str(picked.osm_id)) ?? null,
|
||||
website: (picked && str(picked.website)) ?? null,
|
||||
phone: (picked && str(picked.phone)) ?? null,
|
||||
category_id: categoryId,
|
||||
description: description.trim() || null,
|
||||
status,
|
||||
force: true,
|
||||
})
|
||||
if (res.duplicate) toast.info(t('collections.duplicateWarning'))
|
||||
else {
|
||||
toast.success(t('collections.addedToList', { name: lists.find(l => l.id === targetId)?.name ?? collectionName }))
|
||||
onAdded()
|
||||
}
|
||||
onClose()
|
||||
} catch (err) {
|
||||
toast.error(getApiErrorMessage(err, t('common.error')))
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const address = picked ? str(picked.address) : undefined
|
||||
|
||||
return (
|
||||
<MSheet open={open} onClose={onClose} material="opaque" ariaLabel={t('collections.addPlace')}>
|
||||
<SheetHeader title={t('collections.addPlace')} onClose={onClose} closeLabel={t('common.close')} />
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-[18px] py-[14px]">
|
||||
{/* List picker — only when opened without a fixed target list */}
|
||||
{collectionId == null && (
|
||||
<div className="mb-[14px]">
|
||||
<Eyebrow className="mb-[6px]">{t('collections.pickList').toUpperCase()}</Eyebrow>
|
||||
{lists.length === 0 ? (
|
||||
<p className="font-geist text-[0.6875rem] text-m-muted">{t('collections.noListsYet')}</p>
|
||||
) : (
|
||||
<div className="flex flex-wrap gap-[6px]">
|
||||
{lists.map(l => {
|
||||
const on = targetId === l.id
|
||||
return (
|
||||
<button
|
||||
key={l.id}
|
||||
type="button"
|
||||
onClick={() => setTargetId(l.id)}
|
||||
aria-pressed={on}
|
||||
className={`flex items-center gap-[6px] rounded-full px-3 py-2 text-[0.71875rem] font-bold ${
|
||||
on ? 'bg-m-act text-m-actfg' : 'border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] text-m-ink'
|
||||
}`}
|
||||
>
|
||||
<span className="h-[8px] w-[8px] flex-none rounded-full" style={{ background: l.color || '#6366F1' }} />
|
||||
{l.name}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{/* Search — picking a result fills the location */}
|
||||
<div className="flex items-center gap-2 rounded-[14px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheet)] py-1 pl-[13px] pr-[6px]">
|
||||
<Search size={15} strokeWidth={2.2} className="flex-none text-m-muted" />
|
||||
<input
|
||||
value={query}
|
||||
onChange={e => setQuery(e.target.value)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); search() } }}
|
||||
placeholder={t('collections.addPlaceSearch')}
|
||||
className="min-w-0 flex-1 bg-transparent py-2 font-[inherit] text-[0.8125rem] text-m-ink outline-none placeholder:text-m-faint"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={search}
|
||||
disabled={!query.trim() || searching}
|
||||
className="flex h-8 flex-none items-center gap-[5px] rounded-[10px] bg-m-act px-[14px] text-[0.75rem] font-bold text-m-actfg disabled:opacity-40"
|
||||
>
|
||||
{searching ? <Loader2 size={13} className="animate-spin" /> : null}
|
||||
{t('common.search')}
|
||||
</button>
|
||||
</div>
|
||||
{results.length > 0 && (
|
||||
<div className="mt-[6px] max-h-[210px] overflow-y-auto rounded-[14px] border border-[color:var(--m-rowbr)] bg-m-sheetop shadow-[0_20px_44px_-18px_rgba(0,0,0,.45)]">
|
||||
<div className="flex items-center justify-between px-[13px] pt-2">
|
||||
<Eyebrow>{t('common.search').toUpperCase()}</Eyebrow>
|
||||
<button type="button" onClick={() => setResults([])} aria-label={t('common.close')} className="text-m-faint">
|
||||
<X size={13} strokeWidth={2.2} />
|
||||
</button>
|
||||
</div>
|
||||
{results.map((r, i) => (
|
||||
<button key={i} type="button" onClick={() => pick(r)} className="flex w-full items-center gap-[10px] px-[13px] py-[10px] text-left">
|
||||
<span className="flex h-[26px] w-[26px] flex-none items-center justify-center rounded-lg bg-[color:var(--m-ic)] text-m-faint">
|
||||
<MapPin size={14} strokeWidth={2.2} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-[0.8125rem] font-semibold text-m-ink">{str(r.name)}</span>
|
||||
{str(r.address) && <span className="block truncate font-geist text-[0.625rem] text-m-muted">{str(r.address)}</span>}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Eyebrow className="mb-[6px] mt-4">{t('common.name').toUpperCase()}</Eyebrow>
|
||||
<input value={name} onChange={e => setName(e.target.value)} placeholder={t('common.name')} className={INPUT_CLS} />
|
||||
{address && (
|
||||
<div className="mt-[6px] flex items-center gap-[5px] font-geist text-[0.6875rem] text-m-muted">
|
||||
<MapPin size={11} strokeWidth={2.2} className="flex-none" /> <span className="truncate">{address}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Eyebrow className="mb-[6px] mt-[14px]">{t('collections.category').toUpperCase()}</Eyebrow>
|
||||
<MCollCategoryPicker categories={categories} value={categoryId} onChange={setCategoryId} t={t} />
|
||||
|
||||
<Eyebrow className="mb-[6px] mt-[14px]">{t('mobileCollections.status').toUpperCase()}</Eyebrow>
|
||||
<div className="flex gap-[6px]">
|
||||
{STATUS_ORDER.map(s => {
|
||||
const meta = STATUS_SPEC[s]
|
||||
const Icon = meta.icon
|
||||
const on = status === s
|
||||
return (
|
||||
<button
|
||||
key={s}
|
||||
type="button"
|
||||
onClick={() => setStatus(s)}
|
||||
aria-pressed={on}
|
||||
className={`flex flex-1 items-center justify-center gap-[5px] rounded-full py-2 text-[0.71875rem] font-bold ${
|
||||
on ? 'bg-m-act text-m-actfg' : 'border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] text-m-ink'
|
||||
}`}
|
||||
>
|
||||
<Icon size={13} strokeWidth={2.2} style={on ? undefined : { color: meta.color }} />
|
||||
<span className="truncate">{t(meta.labelKey)}</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
<Eyebrow className="mb-[6px] mt-[14px]">{t('collections.description').toUpperCase()}</Eyebrow>
|
||||
<textarea rows={2} value={description} onChange={e => setDescription(e.target.value)} placeholder={t('collections.descriptionPlaceholder')} className={TEXTAREA_CLS} />
|
||||
</div>
|
||||
<SheetFooter>
|
||||
<CancelPill className="ml-auto" onClick={onClose}>{t('common.cancel')}</CancelPill>
|
||||
<PrimaryPill onClick={save} disabled={saving || !name.trim() || targetId == null}>
|
||||
{saving ? <Loader2 size={14} className="animate-spin" /> : <Check size={14} strokeWidth={2.4} />} {t('common.add')}
|
||||
</PrimaryPill>
|
||||
</SheetFooter>
|
||||
</MSheet>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { useState } from 'react'
|
||||
import { Check, ChevronDown, ChevronUp } from 'lucide-react'
|
||||
import type { Category, TranslationFn } from '../../../types'
|
||||
import { categoryMeta, NO_CATEGORY_META, tint } from './collectionsMobileModel'
|
||||
|
||||
interface MCollCategoryPickerProps {
|
||||
categories: Category[]
|
||||
value: number | null
|
||||
onChange: (id: number | null) => void
|
||||
t: TranslationFn
|
||||
}
|
||||
|
||||
/**
|
||||
* Category dropdown of the add/edit-place sheets: a trigger row with the tinted
|
||||
* 26px icon chip and an overlay list of "No category" + the admin categories.
|
||||
*/
|
||||
export default function MCollCategoryPicker({ categories, value, onChange, t }: MCollCategoryPickerProps) {
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
const selected = value != null ? categories.find(c => c.id === value) ?? null : null
|
||||
const selectedMeta = (selected && categoryMeta(selected)) || NO_CATEGORY_META
|
||||
const SelectedIcon = selectedMeta.icon
|
||||
const Chevron = open ? ChevronUp : ChevronDown
|
||||
|
||||
const options: { id: number | null; name: string }[] = [
|
||||
{ id: null, name: t('collections.noCategory') },
|
||||
...categories.map(c => ({ id: c.id, name: c.name })),
|
||||
]
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen(v => !v)}
|
||||
className="flex w-full items-center gap-[9px] rounded-[12px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheet)] px-[13px] py-[11px] text-left"
|
||||
>
|
||||
<span
|
||||
className="flex h-[26px] w-[26px] flex-none items-center justify-center rounded-lg"
|
||||
style={{ background: tint(selectedMeta.color, '1f'), color: selectedMeta.color }}
|
||||
>
|
||||
<SelectedIcon size={14} strokeWidth={2.2} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate text-[0.8125rem] font-semibold text-m-ink">
|
||||
{selected?.name ?? t('collections.noCategory')}
|
||||
</span>
|
||||
<Chevron size={15} strokeWidth={2.2} className="flex-none text-m-faint" />
|
||||
</button>
|
||||
{open && (
|
||||
<div className="absolute left-0 right-0 top-[calc(100%+6px)] z-[5] max-h-[210px] overflow-y-auto rounded-[14px] border border-[color:var(--m-rowbr)] bg-m-sheetop shadow-[0_20px_44px_-18px_rgba(0,0,0,.45)]">
|
||||
{options.map((opt, i) => {
|
||||
const cat = opt.id != null ? categories.find(c => c.id === opt.id) ?? null : null
|
||||
const meta = (cat && categoryMeta(cat)) || NO_CATEGORY_META
|
||||
const Icon = meta.icon
|
||||
const sel = value === opt.id
|
||||
return (
|
||||
<button
|
||||
key={opt.id ?? 'none'}
|
||||
type="button"
|
||||
onClick={() => { onChange(opt.id); setOpen(false) }}
|
||||
className={`flex w-full items-center gap-[10px] px-[13px] py-[10px] text-left ${i > 0 ? 'border-t border-[color:var(--m-rowbr)]' : ''}`}
|
||||
style={sel ? { background: tint(meta.color, '10') } : undefined}
|
||||
>
|
||||
<span
|
||||
className="flex h-[26px] w-[26px] flex-none items-center justify-center rounded-lg"
|
||||
style={{ background: tint(meta.color, '1f'), color: meta.color }}
|
||||
>
|
||||
<Icon size={14} strokeWidth={2.2} />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 truncate text-[0.8125rem] font-semibold text-m-ink">{opt.name}</span>
|
||||
{sel && <Check size={15} strokeWidth={2.6} style={{ color: meta.color }} />}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { Image, Loader2, Search, Trash2 } from 'lucide-react'
|
||||
import type { Collection, CollectionLink } from '@trek/shared'
|
||||
import type { TranslationFn } from '../../../types'
|
||||
import { tripsApi } from '../../../api/client'
|
||||
import { useCollectionStore } from '../../../store/collectionStore'
|
||||
import { useToast } from '../../../components/shared/Toast'
|
||||
import { getApiErrorMessage } from '../../../types'
|
||||
import { normalizeLinkUrl } from '../../../pages/collections/collectionsModel'
|
||||
import MSheet from '../../components/MSheet'
|
||||
import MCollLinksEditor from './MCollLinksEditor'
|
||||
import { listCoverGradient, SWATCH_COLORS } from './collectionsMobileModel'
|
||||
import { CancelPill, PrimaryPill, SheetFooter, SheetHeader, TEXTAREA_CLS } from './MCollSheetKit'
|
||||
|
||||
interface CoverSearchPhoto {
|
||||
id: string
|
||||
url: string
|
||||
thumb: string
|
||||
description?: string | null
|
||||
photographer?: string | null
|
||||
}
|
||||
|
||||
// Scrims over the cover photo / Unsplash thumbs — fixed dark overlays in both themes.
|
||||
const COVER_OVERLAY =
|
||||
'absolute inset-0 flex items-center justify-center gap-[6px] bg-[rgba(0,0,0,.28)] text-[0.78125rem] font-bold text-white' // theme-lint-disable
|
||||
const PHOTO_CREDIT =
|
||||
'absolute inset-x-0 bottom-0 truncate bg-[rgba(0,0,0,.55)] px-[6px] py-1 text-left text-[0.625rem] text-white' // theme-lint-disable
|
||||
|
||||
interface MCollEditSheetProps {
|
||||
/** null = closed, 'new' = create, a Collection = edit that list. */
|
||||
target: Collection | 'new' | null
|
||||
onClose: () => void
|
||||
onCreated: (id: number) => void
|
||||
/** Owner-only: hands the id to the delete-confirm flow (sheet closes first). */
|
||||
onRequestDelete: (id: number) => void
|
||||
t: TranslationFn
|
||||
}
|
||||
|
||||
/**
|
||||
* Create / edit a list: cover (upload or Unsplash search), name, colour,
|
||||
* description and links. Deleting goes through the shared confirm flow.
|
||||
*/
|
||||
export default function MCollEditSheet({ target, onClose, onCreated, onRequestDelete, t }: MCollEditSheetProps) {
|
||||
const createCollection = useCollectionStore(s => s.createCollection)
|
||||
const updateCollection = useCollectionStore(s => s.updateCollection)
|
||||
const uploadCover = useCollectionStore(s => s.uploadCover)
|
||||
const toast = useToast()
|
||||
const fileRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
// Hold the last target through the exit animation.
|
||||
const [held, setHeld] = useState<Collection | 'new' | null>(target)
|
||||
if (target && target !== held) setHeld(target)
|
||||
const editing = held && held !== 'new' ? held : null
|
||||
|
||||
const [name, setName] = useState('')
|
||||
const [color, setColor] = useState(SWATCH_COLORS[0])
|
||||
const [description, setDescription] = useState('')
|
||||
const [links, setLinks] = useState<CollectionLink[]>([])
|
||||
const [coverFile, setCoverFile] = useState<File | null>(null)
|
||||
const [coverPreview, setCoverPreview] = useState<string | null>(null)
|
||||
const [pendingUnsplashUrl, setPendingUnsplashUrl] = useState<string | null>(null)
|
||||
const [coverQuery, setCoverQuery] = useState('')
|
||||
const [coverResults, setCoverResults] = useState<CoverSearchPhoto[]>([])
|
||||
const [searchingCover, setSearchingCover] = useState(false)
|
||||
const coverSeq = useRef(0)
|
||||
const [saving, setSaving] = useState(false)
|
||||
// A create that failed at the cover step keeps its id so a retry updates it.
|
||||
const [createdId, setCreatedId] = useState<number | null>(null)
|
||||
const objectUrl = useRef<string | null>(null)
|
||||
|
||||
const dropObjectUrl = () => {
|
||||
if (objectUrl.current) { URL.revokeObjectURL(objectUrl.current); objectUrl.current = null }
|
||||
}
|
||||
|
||||
// (Re)seed the form whenever the sheet opens on a target.
|
||||
useEffect(() => {
|
||||
if (!target) return
|
||||
const edit = target !== 'new' ? target : null
|
||||
setName(edit?.name ?? '')
|
||||
setColor(edit?.color ?? SWATCH_COLORS[0])
|
||||
setDescription(edit?.description ?? '')
|
||||
setLinks(edit?.links ?? [])
|
||||
setCoverFile(null)
|
||||
dropObjectUrl()
|
||||
setCoverPreview(edit?.cover_image ?? null)
|
||||
setPendingUnsplashUrl(null)
|
||||
setCoverQuery('')
|
||||
setCoverResults([])
|
||||
setCreatedId(null)
|
||||
}, [target])
|
||||
|
||||
useEffect(() => () => dropObjectUrl(), [])
|
||||
|
||||
const pickCover = (file: File | undefined) => {
|
||||
if (!file) return
|
||||
dropObjectUrl()
|
||||
const url = URL.createObjectURL(file)
|
||||
objectUrl.current = url
|
||||
setCoverFile(file)
|
||||
setCoverPreview(url)
|
||||
setPendingUnsplashUrl(null)
|
||||
}
|
||||
|
||||
const searchCover = async () => {
|
||||
const query = coverQuery.trim() || name.trim()
|
||||
if (!query) return
|
||||
const seq = ++coverSeq.current
|
||||
setSearchingCover(true)
|
||||
try {
|
||||
const data = await tripsApi.searchCoverImages(query)
|
||||
if (seq !== coverSeq.current) return
|
||||
setCoverResults(data.photos || [])
|
||||
} catch {
|
||||
if (seq === coverSeq.current) setCoverResults([])
|
||||
} finally {
|
||||
if (seq === coverSeq.current) setSearchingCover(false)
|
||||
}
|
||||
}
|
||||
|
||||
const pickUnsplash = (photo: CoverSearchPhoto) => {
|
||||
if (!photo.url) return
|
||||
dropObjectUrl()
|
||||
setCoverFile(null)
|
||||
setPendingUnsplashUrl(photo.url)
|
||||
setCoverPreview(photo.url)
|
||||
}
|
||||
|
||||
const save = async () => {
|
||||
const trimmed = name.trim()
|
||||
if (!trimmed || saving) return
|
||||
const cleanLinks = links
|
||||
.map(l => ({ label: l.label?.trim() || undefined, url: normalizeLinkUrl(l.url) }))
|
||||
.filter(l => l.url)
|
||||
const payload = {
|
||||
name: trimmed,
|
||||
color,
|
||||
description: description.trim() || null,
|
||||
links: cleanLinks,
|
||||
...(pendingUnsplashUrl ? { cover_image: pendingUnsplashUrl } : {}),
|
||||
}
|
||||
setSaving(true)
|
||||
try {
|
||||
let id = editing?.id ?? createdId
|
||||
if (id != null) {
|
||||
await updateCollection(id, payload)
|
||||
} else {
|
||||
const created = await createCollection(payload)
|
||||
id = created?.id ?? null
|
||||
setCreatedId(id)
|
||||
}
|
||||
if (id != null && coverFile) await uploadCover(id, coverFile)
|
||||
if (!editing && id != null) onCreated(id)
|
||||
onClose()
|
||||
} catch (err) {
|
||||
toast.error(getApiErrorMessage(err, t('common.error')))
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
|
||||
const label = 'mb-[5px] font-geist text-[0.6875rem] font-bold text-m-muted'
|
||||
const canDeleteList = editing != null && editing.is_owner !== false
|
||||
|
||||
return (
|
||||
<MSheet
|
||||
open={target != null}
|
||||
onClose={onClose}
|
||||
material="opaque"
|
||||
ariaLabel={editing ? t('collections.editListTitle') : t('collections.newList')}
|
||||
>
|
||||
<SheetHeader
|
||||
title={editing ? t('collections.editListTitle') : t('collections.newList')}
|
||||
onClose={onClose}
|
||||
closeLabel={t('common.close')}
|
||||
/>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-[18px] py-[14px]">
|
||||
<div className={label}>{t('collections.coverImage')}</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => fileRef.current?.click()}
|
||||
className="relative block h-[120px] w-full overflow-hidden rounded-[14px]"
|
||||
style={coverPreview ? undefined : { background: listCoverGradient(color) }}
|
||||
>
|
||||
{coverPreview && <img src={coverPreview} alt="" className="absolute inset-0 h-full w-full object-cover" />}
|
||||
<span className={COVER_OVERLAY}>
|
||||
<Image size={14} strokeWidth={2.2} /> {coverPreview ? t('collections.changeCover') : t('collections.addCover')}
|
||||
</span>
|
||||
</button>
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/gif,image/webp"
|
||||
className="hidden"
|
||||
onChange={e => pickCover(e.target.files?.[0])}
|
||||
/>
|
||||
<div className="mt-2 flex gap-2">
|
||||
<input
|
||||
value={coverQuery}
|
||||
onChange={e => setCoverQuery(e.target.value)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); searchCover() } }}
|
||||
placeholder={t('dashboard.unsplashSearchPlaceholder')}
|
||||
className="min-w-0 flex-1 rounded-[12px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheet)] px-3 py-[10px] font-geist text-[0.71875rem] text-m-ink outline-none placeholder:text-m-faint"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={searchCover}
|
||||
disabled={searchingCover || (!coverQuery.trim() && !name.trim())}
|
||||
className="flex flex-none items-center gap-[5px] rounded-[12px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheet)] px-3 py-[10px] text-[0.71875rem] font-semibold text-m-ink disabled:opacity-40"
|
||||
>
|
||||
{searchingCover ? <Loader2 size={12} className="animate-spin" /> : <Search size={12} strokeWidth={2} />} Unsplash
|
||||
</button>
|
||||
</div>
|
||||
{coverResults.length > 0 && (
|
||||
<div className="mt-2 grid grid-cols-3 gap-2">
|
||||
{coverResults.map(photo => (
|
||||
<button
|
||||
key={photo.id}
|
||||
type="button"
|
||||
onClick={() => pickUnsplash(photo)}
|
||||
aria-label={photo.photographer || 'Unsplash'}
|
||||
className="relative h-20 overflow-hidden rounded-[10px] border border-[color:var(--m-rowbr)]"
|
||||
style={coverPreview === photo.url ? { boxShadow: 'inset 0 0 0 2px var(--m-act)' } : undefined}
|
||||
>
|
||||
<img src={photo.thumb} alt={photo.description || ''} loading="lazy" className="h-full w-full object-cover" />
|
||||
{photo.photographer && (
|
||||
<span className={PHOTO_CREDIT}>
|
||||
{photo.photographer}
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className={`${label} mt-[14px]`}>{t('collections.listName')}</div>
|
||||
<input
|
||||
value={name}
|
||||
onChange={e => setName(e.target.value)}
|
||||
placeholder={t('collections.listNamePlaceholder')}
|
||||
className="w-full box-border rounded-[12px] border-[1.5px] border-[color:var(--m-rowbr)] bg-[color:var(--m-sheet)] px-[13px] py-[11px] font-[inherit] text-[0.84375rem] font-semibold text-m-ink outline-none placeholder:text-m-faint"
|
||||
/>
|
||||
|
||||
<div className={`${label} mt-[14px] mb-[6px]`}>{t('collections.listColor')}</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{SWATCH_COLORS.map(col => (
|
||||
<button
|
||||
key={col}
|
||||
type="button"
|
||||
onClick={() => setColor(col)}
|
||||
aria-label={col}
|
||||
aria-pressed={color === col}
|
||||
className={`h-[26px] w-[26px] rounded-full ${color === col ? 'outline outline-2 outline-offset-2 outline-[color:var(--m-act)]' : ''}`}
|
||||
style={{ background: col }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className={`${label} mt-[14px]`}>{t('collections.description')}</div>
|
||||
<textarea rows={2} value={description} onChange={e => setDescription(e.target.value)} placeholder={t('collections.descriptionPlaceholder')} className={TEXTAREA_CLS} />
|
||||
|
||||
<div className={`${label} mt-[14px]`}>{t('collections.links')}</div>
|
||||
<MCollLinksEditor links={links} onChange={setLinks} t={t} />
|
||||
</div>
|
||||
<SheetFooter>
|
||||
{canDeleteList && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => { onClose(); onRequestDelete(editing!.id) }}
|
||||
className="flex items-center gap-[5px] text-[0.75rem] font-bold text-[color:var(--m-st-danger)]"
|
||||
>
|
||||
<Trash2 size={13} strokeWidth={2} /> {t('collections.deleteList')}
|
||||
</button>
|
||||
)}
|
||||
<CancelPill className="ml-auto" onClick={onClose}>{t('common.cancel')}</CancelPill>
|
||||
<PrimaryPill onClick={save} disabled={!name.trim() || saving}>
|
||||
{saving && <Loader2 size={14} className="animate-spin" />}
|
||||
{editing ? t('common.save') : t('collections.create')}
|
||||
</PrimaryPill>
|
||||
</SheetFooter>
|
||||
</MSheet>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { Check, Pencil, Plus, Tag, Trash2 } from 'lucide-react'
|
||||
import type { CollectionLabelUpdateRequest } from '@trek/shared'
|
||||
import type { TranslationFn } from '../../../types'
|
||||
import type { LabelOption } from '../../../pages/collections/collectionsModel'
|
||||
import MSheet from '../../components/MSheet'
|
||||
import { SWATCH_COLORS } from './collectionsMobileModel'
|
||||
import { Eyebrow, INPUT_CLS, PrimaryPill, SheetFooter, SheetHeader } from './MCollSheetKit'
|
||||
|
||||
export type MCollLabelsMode = 'manage' | 'assign'
|
||||
|
||||
interface MCollLabelsSheetProps {
|
||||
open: boolean
|
||||
mode: MCollLabelsMode
|
||||
labels: LabelOption[]
|
||||
/** Selection size, for the assign title. */
|
||||
selectedCount: number
|
||||
onCreate: (name: string, color?: string) => Promise<void>
|
||||
onUpdate: (labelId: number, body: CollectionLabelUpdateRequest) => Promise<void>
|
||||
onDelete: (labelId: number) => Promise<void>
|
||||
onAssign: (labelIds: number[]) => Promise<void>
|
||||
onSwitchToManage: () => void
|
||||
onClose: () => void
|
||||
t: TranslationFn
|
||||
}
|
||||
|
||||
/**
|
||||
* The list's custom labels. Manage mode creates / renames / recolours /
|
||||
* deletes labels; assign mode toggles labels onto the current selection.
|
||||
*/
|
||||
export default function MCollLabelsSheet({
|
||||
open, mode, labels, selectedCount, onCreate, onUpdate, onDelete, onAssign, onSwitchToManage, onClose, t,
|
||||
}: MCollLabelsSheetProps) {
|
||||
const [name, setName] = useState('')
|
||||
const [color, setColor] = useState(SWATCH_COLORS[0])
|
||||
const [editingId, setEditingId] = useState<number | null>(null)
|
||||
const [checked, setChecked] = useState<number[]>([])
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (open) return
|
||||
setName('')
|
||||
setColor(SWATCH_COLORS[0])
|
||||
setEditingId(null)
|
||||
setChecked([])
|
||||
}, [open])
|
||||
|
||||
const startEdit = (label: LabelOption) => {
|
||||
setEditingId(label.id)
|
||||
setName(label.name)
|
||||
setColor(label.color || SWATCH_COLORS[0])
|
||||
}
|
||||
|
||||
const submit = async () => {
|
||||
const trimmed = name.trim()
|
||||
if (!trimmed || busy) return
|
||||
setBusy(true)
|
||||
try {
|
||||
if (editingId != null) await onUpdate(editingId, { name: trimmed, color })
|
||||
else await onCreate(trimmed, color)
|
||||
setName('')
|
||||
setColor(SWATCH_COLORS[0])
|
||||
setEditingId(null)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const assign = async () => {
|
||||
if (checked.length === 0 || busy) return
|
||||
setBusy(true)
|
||||
try {
|
||||
await onAssign(checked)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const toggleChecked = (id: number) =>
|
||||
setChecked(checked.includes(id) ? checked.filter(x => x !== id) : [...checked, id])
|
||||
|
||||
const title = mode === 'assign' ? t('collections.labels.assignN', { count: selectedCount }) : t('collections.labels.manage')
|
||||
|
||||
return (
|
||||
<MSheet open={open} onClose={onClose} material="opaque" ariaLabel={title}>
|
||||
<SheetHeader title={title} onClose={onClose} closeLabel={t('common.close')} />
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-[18px] pb-[18px] pt-4">
|
||||
{mode === 'manage' && (
|
||||
<>
|
||||
<Eyebrow className="mb-2">{t('collections.labels.add').toUpperCase()}</Eyebrow>
|
||||
<input
|
||||
value={name}
|
||||
onChange={e => setName(e.target.value)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') submit() }}
|
||||
placeholder={t('collections.labels.namePlaceholder')}
|
||||
className={INPUT_CLS}
|
||||
/>
|
||||
<div className="mt-[11px] flex flex-wrap gap-[9px]">
|
||||
{SWATCH_COLORS.map(col => (
|
||||
<button
|
||||
key={col}
|
||||
type="button"
|
||||
onClick={() => setColor(col)}
|
||||
aria-label={col}
|
||||
aria-pressed={color === col}
|
||||
className={`h-7 w-7 rounded-full ${color === col ? 'outline outline-2 outline-offset-2 outline-[color:var(--m-act)]' : ''}`}
|
||||
style={{ background: col }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={submit}
|
||||
disabled={!name.trim() || busy}
|
||||
className="mt-[14px] flex w-full items-center justify-center gap-[6px] rounded-[12px] bg-m-act p-[11px] text-[0.78125rem] font-bold text-m-actfg disabled:opacity-40"
|
||||
>
|
||||
{editingId != null ? <Check size={14} strokeWidth={2.4} /> : <Plus size={14} strokeWidth={2.4} />}
|
||||
{editingId != null ? t('common.save') : t('collections.labels.add')}
|
||||
</button>
|
||||
<div className="mt-4 h-px bg-[color:var(--m-rowbr)]" />
|
||||
</>
|
||||
)}
|
||||
|
||||
{labels.length === 0 ? (
|
||||
<div className="flex flex-col items-center gap-[6px] px-0 pb-1 pt-5">
|
||||
<span className="flex h-10 w-10 items-center justify-center rounded-xl bg-[color:var(--m-ic)] text-m-faint">
|
||||
<Tag size={19} strokeWidth={1.8} />
|
||||
</span>
|
||||
<div className="font-geist text-[0.71875rem] text-m-faint">{t('collections.labels.empty')}</div>
|
||||
{mode === 'assign' && (
|
||||
<div className="text-center font-geist text-[0.6875rem] text-m-faint">{t('collections.labels.emptyHint')}</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className={mode === 'manage' ? 'mt-2' : ''}>
|
||||
{labels.map(label => {
|
||||
const col = label.color || SWATCH_COLORS[0]
|
||||
const on = mode === 'assign' && checked.includes(label.id)
|
||||
return (
|
||||
<div
|
||||
key={label.id}
|
||||
className={`mb-1 flex items-center gap-[10px] rounded-[13px] px-3 py-[10px] ${editingId === label.id || on ? 'bg-[color:var(--m-ic)]' : ''}`}
|
||||
style={on ? { boxShadow: `inset 0 0 0 1.5px ${col}` } : undefined}
|
||||
onClick={mode === 'assign' ? () => toggleChecked(label.id) : undefined}
|
||||
role={mode === 'assign' ? 'checkbox' : undefined}
|
||||
aria-checked={mode === 'assign' ? on : undefined}
|
||||
>
|
||||
<span className="h-[9px] w-[9px] flex-none rounded-full" style={{ background: col }} />
|
||||
<span className="min-w-0 flex-1 truncate text-[0.8125rem] font-semibold text-m-ink">{label.name}</span>
|
||||
<span className="font-geist text-[0.6875rem] font-bold text-m-faint">{label.count}</span>
|
||||
{mode === 'manage' ? (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => startEdit(label)}
|
||||
aria-label={t('common.edit')}
|
||||
className="flex h-7 w-7 flex-none items-center justify-center rounded-full text-m-muted active:bg-[color:var(--m-ic)]"
|
||||
>
|
||||
<Pencil size={13} strokeWidth={2.2} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onDelete(label.id)}
|
||||
aria-label={t('common.delete')}
|
||||
className="flex h-7 w-7 flex-none items-center justify-center rounded-full text-[color:var(--m-st-danger)] active:bg-[color:var(--m-ic)]"
|
||||
>
|
||||
<Trash2 size={13} strokeWidth={2.2} />
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
on && <Check size={15} strokeWidth={2.6} style={{ color: col }} />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{mode === 'assign' && (
|
||||
<SheetFooter>
|
||||
<button type="button" onClick={onSwitchToManage} className="text-[0.75rem] font-bold text-m-muted">
|
||||
{t('collections.labels.manage')}
|
||||
</button>
|
||||
<PrimaryPill className="ml-auto" onClick={assign} disabled={checked.length === 0 || busy}>
|
||||
<Tag size={13} strokeWidth={2.4} /> {t('collections.labels.assign')}
|
||||
</PrimaryPill>
|
||||
</SheetFooter>
|
||||
)}
|
||||
</MSheet>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { Link2, Plus, Trash2 } from 'lucide-react'
|
||||
import type { CollectionLink } from '@trek/shared'
|
||||
import type { TranslationFn } from '../../../types'
|
||||
|
||||
interface MCollLinksEditorProps {
|
||||
links: CollectionLink[]
|
||||
onChange: (links: CollectionLink[]) => void
|
||||
t: TranslationFn
|
||||
}
|
||||
|
||||
/** Label + URL rows with a dashed add-row, for list and place links. */
|
||||
export default function MCollLinksEditor({ links, onChange, t }: MCollLinksEditorProps) {
|
||||
const setLink = (i: number, patch: Partial<CollectionLink>) =>
|
||||
onChange(links.map((l, idx) => (idx === i ? { ...l, ...patch } : l)))
|
||||
|
||||
const rowInput =
|
||||
'box-border rounded-[12px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheet)] px-[11px] py-[9px] font-[inherit] text-[0.78125rem] text-m-ink outline-none placeholder:text-m-faint'
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
{links.map((l, i) => (
|
||||
<div key={i} className="flex items-center gap-2">
|
||||
<input
|
||||
value={l.label ?? ''}
|
||||
onChange={e => setLink(i, { label: e.target.value })}
|
||||
placeholder={t('collections.linkLabel')}
|
||||
className={`w-24 flex-none ${rowInput}`}
|
||||
/>
|
||||
<input
|
||||
value={l.url}
|
||||
onChange={e => setLink(i, { url: e.target.value })}
|
||||
placeholder="https://…"
|
||||
className={`min-w-0 flex-1 ${rowInput}`}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onChange(links.filter((_, idx) => idx !== i))}
|
||||
aria-label={t('common.delete')}
|
||||
className="flex h-8 w-8 flex-none items-center justify-center rounded-[10px] text-m-faint active:bg-[color:var(--m-ic)]"
|
||||
>
|
||||
<Trash2 size={14} strokeWidth={2} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onChange([...links, { url: '' }])}
|
||||
className="flex items-center gap-2 self-start rounded-[12px] border border-dashed border-[color:var(--m-rowbr)] px-3 py-[9px] text-[0.78125rem] font-semibold text-m-muted"
|
||||
>
|
||||
<Plus size={14} strokeWidth={2.2} /> <Link2 size={13} strokeWidth={2} /> {t('collections.addLink')}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { useState } from 'react'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import type { Collection } from '@trek/shared'
|
||||
import type { TranslationFn } from '../../../types'
|
||||
import MSheet from '../../components/MSheet'
|
||||
import { SheetHeader } from './MCollSheetKit'
|
||||
|
||||
export type MCollListPickerMode = 'move' | 'copy'
|
||||
|
||||
interface MCollListPickerSheetProps {
|
||||
/** null = closed; kept mounted for the exit animation. */
|
||||
mode: MCollListPickerMode | null
|
||||
lists: Collection[]
|
||||
count: number
|
||||
onPick: (targetId: number) => Promise<void>
|
||||
onClose: () => void
|
||||
t: TranslationFn
|
||||
}
|
||||
|
||||
/** Target-list picker for moving / duplicating the selection into another list. */
|
||||
export default function MCollListPickerSheet({ mode, lists, count, onPick, onClose, t }: MCollListPickerSheetProps) {
|
||||
const [held, setHeld] = useState<MCollListPickerMode | null>(mode)
|
||||
if (mode && mode !== held) setHeld(mode)
|
||||
const [busyId, setBusyId] = useState<number | null>(null)
|
||||
|
||||
const title = held === 'move'
|
||||
? t('collections.moveToListTitle', { count })
|
||||
: t('collections.duplicateToListTitle', { count })
|
||||
|
||||
const pick = async (id: number) => {
|
||||
if (busyId != null) return
|
||||
setBusyId(id)
|
||||
try {
|
||||
await onPick(id)
|
||||
} finally {
|
||||
setBusyId(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<MSheet open={mode != null} onClose={onClose} material="opaque" ariaLabel={title}>
|
||||
<SheetHeader title={title} onClose={onClose} closeLabel={t('common.close')} />
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-[18px] pb-[18px] pt-[14px]">
|
||||
{lists.length === 0 ? (
|
||||
<div className="py-8 text-center font-geist text-[0.78125rem] text-m-faint">{t('collections.noOtherLists')}</div>
|
||||
) : (
|
||||
lists.map(list => (
|
||||
<button
|
||||
key={list.id}
|
||||
type="button"
|
||||
onClick={() => pick(list.id)}
|
||||
disabled={busyId != null}
|
||||
className="mb-1 flex w-full items-center gap-[10px] rounded-[13px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheet)] px-3 py-[11px] text-left disabled:opacity-60"
|
||||
>
|
||||
<span className="h-[9px] w-[9px] flex-none rounded-full" style={{ background: list.color || '#6366F1' }} />
|
||||
<span className="min-w-0 flex-1 truncate text-[0.84375rem] font-semibold text-m-ink">{list.name}</span>
|
||||
{busyId === list.id
|
||||
? <Loader2 size={13} className="flex-none animate-spin text-m-faint" />
|
||||
: <span className="font-geist text-[0.6875rem] font-bold text-m-faint">{list.place_count ?? 0}</span>}
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</MSheet>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import { Check, Layers, Plus, X } from 'lucide-react'
|
||||
import type { Collection } from '@trek/shared'
|
||||
import type { TranslationFn } from '../../../types'
|
||||
import type { ActiveCollectionId } from '../../../store/collectionStore'
|
||||
import type { IncomingCollectionInvite } from '../../../store/collectionStore'
|
||||
import { ALL_SAVED } from '../../../store/collectionStore'
|
||||
import MSheet from '../../components/MSheet'
|
||||
import { Eyebrow } from './MCollSheetKit'
|
||||
|
||||
interface MCollListsDrawerProps {
|
||||
open: boolean
|
||||
onClose: () => void
|
||||
ownedLists: Collection[]
|
||||
sharedLists: Collection[]
|
||||
activeId: ActiveCollectionId
|
||||
incomingInvites: IncomingCollectionInvite[]
|
||||
onSelect: (id: ActiveCollectionId) => void
|
||||
onNewList: () => void
|
||||
onAcceptInvite: (collectionId: number) => void
|
||||
onDeclineInvite: (collectionId: number) => void
|
||||
t: TranslationFn
|
||||
}
|
||||
|
||||
function ListRow({ list, active, onClick }: { list: Collection; active: boolean; onClick: () => void }) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className={`mb-1 flex w-full items-center gap-[10px] rounded-[13px] px-3 py-[11px] text-left ${active ? 'bg-[color:var(--m-ic)]' : ''}`}
|
||||
style={active ? { boxShadow: `inset 0 0 0 1.5px ${list.color || '#6366F1'}` } : undefined}
|
||||
>
|
||||
<span className="h-[9px] w-[9px] flex-none rounded-full" style={{ background: list.color || '#6366F1' }} />
|
||||
<span className="min-w-0 flex-1 truncate text-[0.84375rem] font-semibold text-m-ink">{list.name}</span>
|
||||
<span className="font-geist text-[0.6875rem] font-bold text-m-faint">{list.place_count ?? 0}</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The left lists drawer: new list, the "All saved" union, the owned and shared
|
||||
* lists, and — when present — incoming share invites with accept/decline.
|
||||
*/
|
||||
export default function MCollListsDrawer({
|
||||
open, onClose, ownedLists, sharedLists, activeId, incomingInvites,
|
||||
onSelect, onNewList, onAcceptInvite, onDeclineInvite, t,
|
||||
}: MCollListsDrawerProps) {
|
||||
return (
|
||||
<MSheet open={open} onClose={onClose} variant="drawer" material="opaque" ariaLabel={t('collections.title')}>
|
||||
<div className="flex h-full min-h-0 flex-col px-[18px] py-5">
|
||||
<div className="flex flex-none justify-end">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
aria-label={t('common.close')}
|
||||
className="flex h-8 w-8 items-center justify-center rounded-full bg-[color:var(--m-ic)] text-m-ink"
|
||||
>
|
||||
<X size={15} strokeWidth={2.2} />
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onNewList}
|
||||
className="mt-[6px] flex flex-none items-center gap-2 rounded-[14px] border border-dashed border-[color:var(--m-rowbr)] px-[14px] py-3 text-[0.8125rem] font-bold text-m-muted"
|
||||
>
|
||||
<Plus size={15} strokeWidth={2.2} /> {t('collections.newList')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onSelect(ALL_SAVED)}
|
||||
className={`mt-[10px] flex flex-none items-center gap-[9px] rounded-[11px] px-[6px] py-[10px] text-[0.84375rem] font-semibold text-m-ink ${activeId === ALL_SAVED ? 'bg-[color:var(--m-ic)]' : ''}`}
|
||||
>
|
||||
<Layers size={16} strokeWidth={2} /> {t('collections.allSaved')}
|
||||
</button>
|
||||
<div className="my-2 h-px flex-none bg-[color:var(--m-rowbr)]" />
|
||||
<div className="min-h-0 flex-1 overflow-y-auto">
|
||||
{ownedLists.map(l => (
|
||||
<ListRow key={l.id} list={l} active={activeId === l.id} onClick={() => onSelect(l.id)} />
|
||||
))}
|
||||
{sharedLists.length > 0 && (
|
||||
<>
|
||||
<Eyebrow className="mb-[6px] mt-3 px-1 uppercase">{t('collections.shared')}</Eyebrow>
|
||||
{sharedLists.map(l => (
|
||||
<ListRow key={l.id} list={l} active={activeId === l.id} onClick={() => onSelect(l.id)} />
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
{incomingInvites.length > 0 && (
|
||||
<>
|
||||
<Eyebrow className="mb-[6px] mt-3 px-1 uppercase">{t('collections.invites.title')}</Eyebrow>
|
||||
{incomingInvites.map(inv => (
|
||||
<div
|
||||
key={inv.collection_id}
|
||||
className="mb-1 flex items-center gap-[10px] rounded-[13px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-sheet)] px-3 py-[10px]"
|
||||
>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate text-[0.8125rem] font-semibold text-m-ink">{inv.name}</span>
|
||||
<span className="block truncate font-geist text-[0.625rem] text-m-muted">
|
||||
{t('collections.invites.from')} {inv.from.username}
|
||||
</span>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onAcceptInvite(inv.collection_id)}
|
||||
aria-label={t('collections.invites.accept')}
|
||||
className="flex h-7 w-7 flex-none items-center justify-center rounded-full bg-m-act text-m-actfg"
|
||||
>
|
||||
<Check size={13} strokeWidth={2.6} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onDeclineInvite(inv.collection_id)}
|
||||
aria-label={t('collections.invites.decline')}
|
||||
className="flex h-7 w-7 flex-none items-center justify-center rounded-full bg-[color:var(--m-ic)] text-m-ink"
|
||||
>
|
||||
<X size={13} strokeWidth={2.4} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</MSheet>
|
||||
)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user