Compare commits

...

41 Commits

Author SHA1 Message Date
Maurice c8d09fc132 fix(ci): align place form pairs and exports
Point the paired-view manifest at the hook that now owns the desktop place form. Keep internals private and lower the unused-types baseline for the types now removed or used.
2026-12-02 23:11:25 +01:00
Maurice f5a510c78e fix(ci): repair strict types and empty dashboard card
Keep the dashboard card class when it spans all columns. Match the place form payload to the service-stop placement type and make dialog card hints optional. Document the independent receipt copy and format the files flagged by CI.
2026-12-02 23:05:12 +01:00
Maurice 86e98fde65 fix(ci): repair trip assistant checks
Fix the mobile dashboard import and align the assistant UI with client layer and lint rules. Document the OpenRouter setting, share the reservation status schema, and update coverage for external POI identifiers and the empty costs view.
2026-12-02 22:56:54 +01:00
Maurice 62a3e63f3f fix(assistant): improve trip proposals and approvals 2026-12-02 22:03:28 +01:00
Maurice 01ad13623c fix(ui): refine trip forms and planner empty states 2026-12-02 22:03:08 +01:00
Maurice 59e5c5a3c9 fix(ai): support optional OpenRouter upstream selection 2026-12-02 21:57:08 +01:00
Maurice a2cf911ce1 fix(dashboard): respect pointer type when focusing trip titles
Mark the title through the existing dialog focus mechanism so a
mouse can type right away and touch keeps focus on the dialog.
Cover creating and editing a trip in the dashboard tests.
2026-12-02 14:49:52 +01:00
Luffy 7a66a54e66 fix(dashboard): focus the title in desktop trip forms 2026-12-02 14:46:23 +01:00
Maurice 748434fc47 style(server): satisfy accommodation confirmation lint
Keep ordered writes for one linked booking in a single method. Check
that each test fixture exists before using the reservation.
2026-12-02 11:55:45 +01:00
Maurice 618f070675 fix(accommodations): keep booking confirmations in sync
Distinguish omitted references from explicit clears on stays and their
linked bookings. Reserve automatic confirmation for a new reference
with a booking code format. Announce linked changes after booking edits.

Closes #3301
2026-12-02 11:49:33 +01:00
Maurice dacf19b4d5 style(server): format the assistant proposal guard
The Server lint formatting check rejected the assistant agent and its regression test. Apply the repository Prettier configuration to those two files.
2026-12-02 10:23:11 +01:00
Maurice 103631d5fc Hold identical assistant changes only once per step 2026-12-02 10:23:11 +01:00
Maurice 10fecf4e80 fix(ci): document the exact migration filter
The metadata substring filter only finds candidates. Exact timezone comparison in the migration ensures SQLite and PostgreSQL update the same records.
2026-12-02 09:59:29 +01:00
Maurice 12483f618f fix(journey): give the public gallery a definite width
Keep both centered content layouts from collapsing before Firefox loads gallery thumbnails.

Closes #3296
2026-12-02 09:46:23 +01:00
Maurice 17c4d69e40 fix(airports): use Bahrain time for Bahrain flights
Correct the airport data and repair affected flight endpoints and metadata during upgrade. Preserve stored local flight times and legacy metadata encoding.

Closes #3294
2026-12-02 09:45:20 +01:00
Maurice d6184559e9 fix(assistant): keep OpenRouter turns in one routing session
Pass a stable conversation session to OpenRouter so turns can reuse the same provider route. Namespace locally allocated thread IDs across server processes.

Closes #3298
2026-12-02 09:45:19 +01:00
Maurice 3089aee593 fix(journey): align media validation with server checks
Validate spooled uploads in order with the shared iterator and keep media format detection in a shared utility. Adapt the controller unit fixtures and cover raster signatures, including animated PNG.
2026-12-02 09:29:33 +01:00
Maurice 24ddc3e4b0 fix(journey): validate and safely serve media uploads 2026-12-02 09:21:51 +01:00
Maurice a4cb6c69d8 chore(lint): lower the client ref-warning baseline
The plugin frame permission check now reads the store when needed. GitHub CI reports 384 react-hooks/refs warnings instead of 385.
2026-12-01 22:07:41 +01:00
Maurice 6e224cb7a4 fix(plugins): bind bridge replies to the active document
Keep pending replies tied to their original frame and verify the current permission before returning location data. Release watches when their frame detaches and preserve live replies across host context updates.
2026-12-01 22:00:45 +01:00
Maurice 56b4568a16 test(platform): cover static asset cache boundaries
Exercise the filename and path boundaries used to decide which static assets can be cached permanently, including unhashed Brotli copies.
2026-12-01 21:22:35 +01:00
Maurice 756ef14b97 fix(client): preserve explicit dialog focus and verify accessible controls
Keep the focused search for new places and title fields in explicitly opened dialogs. Assert the native ride badge button and the pointer grip tooltip in the existing tests.
2026-12-01 21:13:35 +01:00
Maurice e539860530 fix(quality): resolve reliability findings on dev
The Sonar quality gate rated new code D. Preserve focus and keyboard interaction through native controls and shared dialog behavior. Replace ambiguous regex scans with bounded parsing and make numeric coercion and initialization explicit.
2026-12-01 21:06:05 +01:00
Maurice 0d6a432967 test(server): type the hosted assistant regression on ES2022
Use the lookup overload for all addresses and drain the stream with the existing TypeScript target. Server types rejected the default lookup overload and Array.fromAsync.
2026-12-01 19:37:29 +01:00
Maurice 89035059ec fix(cloud): route the hosted assistant through its private gateway 2026-12-01 19:28:28 +01:00
Maurice 4ad926aafc fix(ci): give typed server lint more heap and patch audited dependencies
Keep the typed lint rules and ratchet intact after the 8 GiB heap was exhausted on the runner. Resolve the patched Hono adapter and cross-spawn within their existing major versions.
2026-12-01 15:21:50 +01:00
Maurice 60a30afb81 fix(deps): narrow Lucide icon types and lower the lint baseline
Keep the typed icon lookup aligned with the runtime namespace and record the three removed test assertions.
2026-12-01 13:51:32 +01:00
Maurice b77c246df4 fix(deps): keep Lucide SVG markup and Undici tests compatible
Build standalone SVG icons without a React context. Use accessible actions in tests and give the mocked dispatchers the interface the adapter expects.
2026-12-01 13:44:02 +01:00
Maurice 7f4ece2e6f chore(deps): update npm packages and adapt major upgrades
Resolve the MikroORM packages together and use the dispatcher adapter with older built-in fetch implementations. Preserve existing Lucide names and regenerate the Studio and SDK catalogs.
2026-12-01 13:32:28 +01:00
Maurice a14b6a61e6 chore(server): remove resolved plugin type errors from the baseline 2026-12-01 12:29:34 +01:00
Maurice 871135edeb refactor(plugins): generate SDK egress policy from the server 2026-12-01 12:24:32 +01:00
Maurice c22c464e68 fix: keep security checks in sync with their contracts
Mirror the egress policy in the standalone SDK and check its entire shared section. Keep entrypoint assertions aligned with the debug flag and document the mutually exclusive OIDC transactions.
2026-12-01 12:04:55 +01:00
Maurice 3c2dc51439 fix(plugins): validate stable egress options
Keep egress comparisons independent of mutable runtime methods and pass the same normalized options to validation and the socket. Restrict process signaling from plugin workers and disable signal-initiated debugging on standard server starts.
2026-12-01 11:56:24 +01:00
Maurice 28eea68559 fix(media): bound image work before public rendition
Check avatar uploads and raster fallbacks before decoding. Limit compressed bytes, decoded dimensions, GIF frames and the combined TIFF page budget.
2026-12-01 11:56:24 +01:00
Maurice 1ff8a814ae fix(oidc): verify mailbox identity before linking accounts
Preserve the provider mailbox on new accounts. For existing accounts, use the stored issuer and subject or check mailbox identity before linking. Keep the candidate lookup and identity update inside the same transaction.
2026-12-01 11:56:24 +01:00
Maurice 0d521f0930 test(transit): cover long labels in both journey details
Exercise a line with a provider colour and no foreground override on desktop and phone. Confirm that the badge can wrap and leaves room for the rest of the itinerary.
2026-12-01 11:42:31 +01:00
Maurice 7fc011408a test(transit): find mode icons on the line badge
The search test must look for the icon beside the label inside the shared badge.
2026-12-01 11:28:14 +01:00
Maurice 8f20f9f7ea test(transit): check the rendered line badge colours
The booking test checked the nested label after the badge layout changed. Assert the provider colours on the outer badge that sets them.
2026-12-01 11:21:52 +01:00
Maurice 67b65a7647 fix(transit): keep stop names readable beside long route names
Line badges could take the width of a transit row and squeeze its stops. Bound badge width across the itinerary views, wrap full labels in details, and keep compact summaries within their container.

Closes #3287
2026-12-01 11:11:53 +01:00
Luffy 82b2a530f3 fix(places): add titles to Unsplash list cover thumbnails 2026-12-01 15:31:01 +08:00
Maurice 76a3983972 Merge pull request #3284 from liketrek/fix/cloud-store-catalog
fix(native): offer Start and Plus in the TREK Cloud catalog
2026-12-01 01:04:29 +01:00
418 changed files with 9853 additions and 3762 deletions
+4 -4
View File
@@ -438,10 +438,10 @@ jobs:
- name: Lint - name: Lint
# Errors fail, and the warnings per rule may not pass # Errors fail, and the warnings per rule may not pass
# scripts/eslint-baseline.json (src, tests and eslint-disable'd # scripts/eslint-baseline.json (src, tests and eslint-disable'd
# messages counted apart). Type-aware rules build the src + tests # messages counted apart). The typed src and test programs can exhaust
# program, which outgrows Node's default ~4 GB heap on the runner. # an 8 GiB heap. Leave headroom within the runner's 16 GB of RAM.
env: env:
NODE_OPTIONS: --max-old-space-size=8192 NODE_OPTIONS: --max-old-space-size=10240
TREK_LINT_BASE: refs/remotes/lint-base TREK_LINT_BASE: refs/remotes/lint-base
run: cd server && npm run lint:warnings run: cd server && npm run lint:warnings
@@ -990,7 +990,7 @@ jobs:
# Fails on any ESLint error, like lint:check did, and on any rule # Fails on any ESLint error, like lint:check did, and on any rule
# whose warning count rises above scripts/eslint-baseline.json. # whose warning count rises above scripts/eslint-baseline.json.
# Typed linting (no-floating-promises, no-misused-promises) loads the # Typed linting (no-floating-promises, no-misused-promises) loads the
# whole TypeScript program, so it gets the heap the server lint gets. # whole TypeScript program, which exceeds Node's default heap.
env: env:
NODE_OPTIONS: --max-old-space-size=8192 NODE_OPTIONS: --max-old-space-size=8192
TREK_LINT_BASE: refs/remotes/lint-base TREK_LINT_BASE: refs/remotes/lint-base
+15 -14
View File
@@ -55,13 +55,13 @@
"dependencies": { "dependencies": {
"@assistant-ui/react": "0.15.38", "@assistant-ui/react": "0.15.38",
"@capacitor/action-sheet": "^8.1.1", "@capacitor/action-sheet": "^8.1.1",
"@capacitor/android": "^8.6.2", "@capacitor/android": "^8.6.3",
"@capacitor/app": "^8.1.1", "@capacitor/app": "^8.1.1",
"@capacitor/core": "^8.6.2", "@capacitor/core": "^8.6.3",
"@capacitor/dialog": "^8.0.1", "@capacitor/dialog": "^8.0.1",
"@capacitor/filesystem": "^8.1.3", "@capacitor/filesystem": "^8.1.6",
"@capacitor/haptics": "^8.0.2", "@capacitor/haptics": "^8.0.2",
"@capacitor/ios": "^8.6.2", "@capacitor/ios": "^8.6.3",
"@capacitor/keyboard": "^8.0.5", "@capacitor/keyboard": "^8.0.5",
"@capacitor/share": "^8.0.1", "@capacitor/share": "^8.0.1",
"@capacitor/splash-screen": "^8.0.2", "@capacitor/splash-screen": "^8.0.2",
@@ -101,6 +101,7 @@
"@fontsource/satisfy": "^5.3.0", "@fontsource/satisfy": "^5.3.0",
"@fontsource/shrikhand": "^5.3.0", "@fontsource/shrikhand": "^5.3.0",
"@fontsource/yellowtail": "^5.3.0", "@fontsource/yellowtail": "^5.3.0",
"@lucide/icons": "1.82.0",
"@maplibre/maplibre-gl-leaflet": "0.1.4", "@maplibre/maplibre-gl-leaflet": "0.1.4",
"@noble/hashes": "^2.4.0", "@noble/hashes": "^2.4.0",
"@simplewebauthn/browser": "^14.0.0", "@simplewebauthn/browser": "^14.0.0",
@@ -112,9 +113,9 @@
"heic-to": "^1.6.7", "heic-to": "^1.6.7",
"iso-3166-2": "^1.0.0", "iso-3166-2": "^1.0.0",
"leaflet": "^1.9.4", "leaflet": "^1.9.4",
"lucide-react": "^0.577.0", "lucide-react": "^1.82.0",
"mapbox-gl": "3.32.0", "mapbox-gl": "3.32.0",
"maplibre-gl": "6.19.0", "maplibre-gl": "6.20.0",
"modern-screenshot": "4.7.0", "modern-screenshot": "4.7.0",
"plyr": "^3.8.5", "plyr": "^3.8.5",
"react": "^19.3.1", "react": "^19.3.1",
@@ -123,7 +124,7 @@
"react-leaflet": "^5.0.0", "react-leaflet": "^5.0.0",
"react-leaflet-cluster": "^4.1.3", "react-leaflet-cluster": "^4.1.3",
"react-markdown": "^10.1.0", "react-markdown": "^10.1.0",
"react-router": "^7.18.4", "react-router": "^8.5.3",
"rehype-sanitize": "^6.0.0", "rehype-sanitize": "^6.0.0",
"remark-breaks": "^4.0.0", "remark-breaks": "^4.0.0",
"remark-gfm": "^4.0.1", "remark-gfm": "^4.0.1",
@@ -133,12 +134,12 @@
"zustand": "^5.0.15" "zustand": "^5.0.15"
}, },
"devDependencies": { "devDependencies": {
"@capacitor/cli": "^8.6.2", "@capacitor/cli": "^8.6.3",
"@eslint/js": "^10.0.1", "@eslint/js": "^10.0.1",
"@jscpd/core": "^4.2.5", "@jscpd/core": "^4.2.5",
"@jscpd/tokenizer": "^4.2.6", "@jscpd/tokenizer": "^4.2.6",
"@playwright/test": "^1.65.1", "@playwright/test": "^1.65.1",
"@testing-library/dom": "^10.4.1", "@testing-library/dom": "^10.4.2",
"@testing-library/jest-dom": "^8.0.0", "@testing-library/jest-dom": "^8.0.0",
"@testing-library/react": "^16.3.3", "@testing-library/react": "^16.3.3",
"@testing-library/user-event": "^14.6.13", "@testing-library/user-event": "^14.6.13",
@@ -146,22 +147,22 @@
"@types/geojson": "^7946.0.16", "@types/geojson": "^7946.0.16",
"@types/leaflet": "^1.9.23", "@types/leaflet": "^1.9.23",
"@types/node": "^26.6.11", "@types/node": "^26.6.11",
"@types/react": "^19.3.2", "@types/react": "^19.3.3",
"@types/react-dom": "^19.3.0", "@types/react-dom": "^19.3.0",
"@types/topojson-client": "^3.1.5", "@types/topojson-client": "^3.1.5",
"@types/topojson-specification": "^1.0.5", "@types/topojson-specification": "^1.0.5",
"@vitejs/plugin-react": "^6.2.1", "@vitejs/plugin-react": "^6.2.1",
"@vitest/coverage-v8": "^5.1.2", "@vitest/coverage-v8": "^5.1.2",
"autoprefixer": "^10.7.0", "autoprefixer": "^10.7.1",
"eslint": "^10.11.0", "eslint": "^10.11.0",
"eslint-config-flat-gitignore": "^2.4.0", "eslint-config-flat-gitignore": "^2.4.0",
"eslint-config-prettier": "^10.1.8", "eslint-config-prettier": "^10.1.9",
"eslint-plugin-react-hooks": "^7.1.1", "eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.8", "eslint-plugin-react-refresh": "^0.5.8",
"fake-indexeddb": "^6.2.7", "fake-indexeddb": "^6.2.7",
"jsdom": "^29.1.1", "jsdom": "^29.1.1",
"msw": "^3.0.8", "msw": "^3.0.8",
"postcss": "^8.5.33", "postcss": "^8.5.34",
"prettier": "^3.10.1", "prettier": "^3.10.1",
"prettier-plugin-organize-imports": "^4.3.0", "prettier-plugin-organize-imports": "^4.3.0",
"prettier-plugin-tailwindcss": "^0.8.1", "prettier-plugin-tailwindcss": "^0.8.1",
@@ -170,7 +171,7 @@
"tailwindcss": "^3.4.19", "tailwindcss": "^3.4.19",
"typescript": "^6.0.3", "typescript": "^6.0.3",
"typescript-eslint": "^8.74.0", "typescript-eslint": "^8.74.0",
"vite": "8.3.8", "vite": "8.4.0",
"vite-plugin-pwa": "^2.0.0", "vite-plugin-pwa": "^2.0.0",
"vitest": "^5.1.2" "vitest": "^5.1.2"
} }
+2 -2
View File
@@ -8,7 +8,7 @@
"trek/no-swallowed-catch": 124, "trek/no-swallowed-catch": 124,
"max-params": 31, "max-params": 31,
"trek/store-without-selector": 65, "trek/store-without-selector": 65,
"react-hooks/refs": 385, "react-hooks/refs": 384,
"react-hooks/set-state-in-effect": 188, "react-hooks/set-state-in-effect": 188,
"@typescript-eslint/no-floating-promises": 162, "@typescript-eslint/no-floating-promises": 162,
"react-hooks/exhaustive-deps": 112, "react-hooks/exhaustive-deps": 112,
@@ -35,7 +35,7 @@
}, },
"tests": { "tests": {
"@typescript-eslint/no-explicit-any": 484, "@typescript-eslint/no-explicit-any": 484,
"@typescript-eslint/no-non-null-assertion": 1848, "@typescript-eslint/no-non-null-assertion": 1845,
"@typescript-eslint/no-misused-promises": 22, "@typescript-eslint/no-misused-promises": 22,
"@typescript-eslint/no-unused-vars": 48, "@typescript-eslint/no-unused-vars": 48,
"@typescript-eslint/no-floating-promises": 33, "@typescript-eslint/no-floating-promises": 33,
+3 -3
View File
@@ -776,7 +776,7 @@
{ {
"feature": "Place add/edit form and maps search: usePlaceForm", "feature": "Place add/edit form and maps search: usePlaceForm",
"hooks": ["src/components/Planner/usePlaceForm.ts"], "hooks": ["src/components/Planner/usePlaceForm.ts"],
"desktop": ["src/components/Planner/PlaceFormModal.tsx"], "desktop": ["src/components/Planner/usePlaceFormModal.ts"],
"mobile": [ "mobile": [
"src/mobile/screens/trip/sheets/MPlaceEditSheet.tsx", "src/mobile/screens/trip/sheets/MPlaceEditSheet.tsx",
"src/mobile/screens/trip/sheets/PlCategoryPicker.tsx" "src/mobile/screens/trip/sheets/PlCategoryPicker.tsx"
@@ -785,13 +785,13 @@
{ {
"feature": "Place add/edit form and maps search: usePlaceSearch", "feature": "Place add/edit form and maps search: usePlaceSearch",
"hooks": ["src/components/Planner/usePlaceSearch.ts"], "hooks": ["src/components/Planner/usePlaceSearch.ts"],
"desktop": ["src/components/Planner/PlaceFormModal.tsx"], "desktop": ["src/components/Planner/usePlaceFormModal.ts"],
"mobile": ["src/mobile/screens/trip/sheets/PlPlaceSearch.tsx"] "mobile": ["src/mobile/screens/trip/sheets/PlPlaceSearch.tsx"]
}, },
{ {
"feature": "Place add/edit form: tags", "feature": "Place add/edit form: tags",
"hooks": ["src/components/Planner/usePlaceTags.ts"], "hooks": ["src/components/Planner/usePlaceTags.ts"],
"desktop": ["src/components/Planner/PlaceFormModal.tsx"], "desktop": ["src/components/Planner/usePlaceFormModal.ts"],
"mobile": ["src/mobile/screens/trip/sheets/MPlaceEditSheet.tsx"] "mobile": ["src/mobile/screens/trip/sheets/MPlaceEditSheet.tsx"]
}, },
{ {
-2
View File
@@ -640,7 +640,6 @@
"src/components/Planner/PlaceFormModal.helpers.test.ts", "src/components/Planner/PlaceFormModal.helpers.test.ts",
"src/components/Planner/PlaceFormModal.helpers.ts", "src/components/Planner/PlaceFormModal.helpers.ts",
"src/components/Planner/PlaceFormModal.test.tsx", "src/components/Planner/PlaceFormModal.test.tsx",
"src/components/Planner/PlaceFormModal.tsx",
"src/components/Planner/PlaceInspector.test.tsx", "src/components/Planner/PlaceInspector.test.tsx",
"src/components/Planner/PlaceInspector.tsx", "src/components/Planner/PlaceInspector.tsx",
"src/components/Planner/PlacesBulkCategoryModal.test.tsx", "src/components/Planner/PlacesBulkCategoryModal.test.tsx",
@@ -1426,7 +1425,6 @@
"src/mobile/screens/vacay/MVacayShareSheet.tsx", "src/mobile/screens/vacay/MVacayShareSheet.tsx",
"src/mobile/screens/vacay/useMVacay.ts", "src/mobile/screens/vacay/useMVacay.ts",
"src/mobile/screens/vacay/vacayDayModel.ts", "src/mobile/screens/vacay/vacayDayModel.ts",
"src/mobile/useIsPhone.ts",
"src/pages/AdminPage.test.tsx", "src/pages/AdminPage.test.tsx",
"src/pages/AdminPage.tsx", "src/pages/AdminPage.tsx",
"src/pages/AtlasPage.tsx", "src/pages/AtlasPage.tsx",
+1 -1
View File
@@ -4,7 +4,7 @@
"src/components/Admin/AdminPluginsPanel.test.tsx": 2704, "src/components/Admin/AdminPluginsPanel.test.tsx": 2704,
"src/components/Admin/AdminPluginsPanel.tsx": 1265, "src/components/Admin/AdminPluginsPanel.tsx": 1265,
"src/components/Budget/CostsPanel.test.tsx": 2725, "src/components/Budget/CostsPanel.test.tsx": 2725,
"src/components/Budget/CostsPanel.tsx": 1607, "src/components/Budget/CostsPanel.tsx": 1588,
"src/components/Map/MapView.tsx": 1191, "src/components/Map/MapView.tsx": 1191,
"src/components/Map/MapViewGL.test.tsx": 2919, "src/components/Map/MapViewGL.test.tsx": 2919,
"src/components/Map/MapViewGL.tsx": 2083, "src/components/Map/MapViewGL.tsx": 2083,
-1
View File
@@ -48,7 +48,6 @@
"src/components/Planner/DayPlanSidebar.tsx": 52, "src/components/Planner/DayPlanSidebar.tsx": 52,
"src/components/Planner/DayPlanSidebarNoteModal.test.tsx": 1, "src/components/Planner/DayPlanSidebarNoteModal.test.tsx": 1,
"src/components/Planner/PlaceFormModal.test.tsx": 3, "src/components/Planner/PlaceFormModal.test.tsx": 3,
"src/components/Planner/PlaceFormModal.tsx": 1,
"src/components/Planner/PlaceInspector.tsx": 16, "src/components/Planner/PlaceInspector.tsx": 16,
"src/components/Planner/PlacesBulkCategoryModal.test.tsx": 1, "src/components/Planner/PlacesBulkCategoryModal.test.tsx": 1,
"src/components/Planner/PlacesSidebar.tsx": 1, "src/components/Planner/PlacesSidebar.tsx": 1,
@@ -1,7 +1,7 @@
import { useState, type ReactNode } from 'react' import { useState, type ReactNode } from 'react'
import { import {
Blocks, AlertTriangle, RefreshCw, Trash2, Download, Bug, ShieldCheck, UploadCloud, Blocks, AlertTriangle, RefreshCw, Trash2, Download, Bug, ShieldCheck, UploadCloud,
ArrowUpCircle, Github, ExternalLink, Check, Search, Link2, KeyRound, ShieldAlert, ArrowUpCircle, ExternalLink, Check, Search, Link2, KeyRound, ShieldAlert,
SlidersHorizontal, CircleDot, Database, SlidersHorizontal, CircleDot, Database,
Globe, History, Puzzle, Bot, Loader2, Globe, History, Puzzle, Bot, Loader2,
} from 'lucide-react' } from 'lucide-react'
@@ -789,7 +789,7 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
footer={( footer={(
<DialogFooter> <DialogFooter>
<Tooltip label={t('admin.plugins.sourceRepo')}> <Tooltip label={t('admin.plugins.sourceRepo')}>
<a href={repoUrl} target="_blank" rel="noreferrer" aria-label={t('admin.plugins.sourceRepo')} className={linkClass}><Github size={15} /></a> <a href={repoUrl} target="_blank" rel="noreferrer" aria-label={t('admin.plugins.sourceRepo')} className={linkClass}><PluginIcon name="Github" size={15} /></a>
</Tooltip> </Tooltip>
<Tooltip label={t('admin.plugins.reportIssue')}> <Tooltip label={t('admin.plugins.reportIssue')}>
<a href={`${repoUrl}/issues`} target="_blank" rel="noreferrer" aria-label={t('admin.plugins.reportIssue')} className={linkClass}><CircleDot size={15} /></a> <a href={`${repoUrl}/issues`} target="_blank" rel="noreferrer" aria-label={t('admin.plugins.reportIssue')} className={linkClass}><CircleDot size={15} /></a>
@@ -210,11 +210,8 @@ describe('BackupPanel', () => {
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('backup-2025-01-15.zip')).toBeInTheDocument() expect(screen.getByText('backup-2025-01-15.zip')).toBeInTheDocument()
}) })
const trashBtn = Array.from(document.querySelectorAll('button')).find( const trashBtn = screen.getByRole('button', { name: 'Delete' })
b => b.querySelector('svg.lucide-trash2'), await user.click(trashBtn)
) as HTMLElement
expect(trashBtn).toBeTruthy()
await user.click(trashBtn!)
// The question is the shared confirm dialog now, not window.confirm // The question is the shared confirm dialog now, not window.confirm
expect(await screen.findByText('Delete backup "backup-2025-01-15.zip"?')).toBeInTheDocument() expect(await screen.findByText('Delete backup "backup-2025-01-15.zip"?')).toBeInTheDocument()
const deleteButtons = screen.getAllByRole('button', { name: 'Delete' }) const deleteButtons = screen.getAllByRole('button', { name: 'Delete' })
@@ -428,9 +425,7 @@ describe('BackupPanel', () => {
render(<><ToastContainer /><BackupPanel /></>) render(<><ToastContainer /><BackupPanel /></>)
await screen.findByText('backup-2025-01-15.zip') await screen.findByText('backup-2025-01-15.zip')
const trashBtn = Array.from(document.querySelectorAll('button')).find( const trashBtn = screen.getByRole('button', { name: 'Delete' })
b => b.querySelector('svg.lucide-trash2'),
) as HTMLElement
await user.click(trashBtn) await user.click(trashBtn)
await user.click(await screen.findByRole('button', { name: 'Cancel' })) await user.click(await screen.findByRole('button', { name: 'Cancel' }))
expect(deleteCalls).toBe(0) expect(deleteCalls).toBe(0)
@@ -1,3 +1,4 @@
import { focusRevealedEditor } from '../shared/dialogFocus'
import { useTranslation } from '../../i18n' import { useTranslation } from '../../i18n'
import { Plus, Trash2, Pencil, Package, X, Check, ChevronRight, FolderPlus, Loader2 } from 'lucide-react' import { Plus, Trash2, Pencil, Package, X, Check, ChevronRight, FolderPlus, Loader2 } from 'lucide-react'
import { fs } from '../shared/DialogShell' import { fs } from '../shared/DialogShell'
@@ -57,7 +58,7 @@ export default function PackingTemplateManager() {
{showCreate && ( {showCreate && (
<div className={COMPOSER_ROW} style={{ boxShadow: COMPOSER.boxShadow }}> <div className={COMPOSER_ROW} style={{ boxShadow: COMPOSER.boxShadow }}>
<Package size={15} className="flex-none text-content-faint" /> <Package size={15} className="flex-none text-content-faint" />
<input autoFocus value={createName} onChange={e => setCreateName(e.target.value)} <input ref={focusRevealedEditor} value={createName} onChange={e => setCreateName(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') void handleCreateTemplate(); if (e.key === 'Escape') setShowCreate(false) }} onKeyDown={e => { if (e.key === 'Enter') void handleCreateTemplate(); if (e.key === 'Escape') setShowCreate(false) }}
placeholder={t('admin.packingTemplates.namePlaceholder')} className={COMPOSER_INPUT} style={fs(13, 'body')} /> placeholder={t('admin.packingTemplates.namePlaceholder')} className={COMPOSER_INPUT} style={fs(13, 'body')} />
<Tooltip label={t('common.save')}> <Tooltip label={t('common.save')}>
@@ -101,7 +102,7 @@ export default function PackingTemplateManager() {
<Package size={15} strokeWidth={1.9} /> <Package size={15} strokeWidth={1.9} />
</span> </span>
{editingTemplate === tmpl.id ? ( {editingTemplate === tmpl.id ? (
<input autoFocus value={editTemplateName} onChange={e => setEditTemplateName(e.target.value)} <input ref={focusRevealedEditor} value={editTemplateName} onChange={e => setEditTemplateName(e.target.value)}
onBlur={() => handleRenameTemplate(tmpl.id)} onBlur={() => handleRenameTemplate(tmpl.id)}
onKeyDown={e => { if (e.key === 'Enter') void handleRenameTemplate(tmpl.id); if (e.key === 'Escape') setEditingTemplate(null) }} onKeyDown={e => { if (e.key === 'Enter') void handleRenameTemplate(tmpl.id); if (e.key === 'Escape') setEditingTemplate(null) }}
aria-label={t('common.rename')} aria-label={t('common.rename')}
@@ -132,7 +133,7 @@ export default function PackingTemplateManager() {
{/* Category header */} {/* Category header */}
<div data-row="category" className="flex items-center gap-1.5 border-b border-edge-faint bg-surface-tertiary py-1.5 ps-3 pe-1.5"> <div data-row="category" className="flex items-center gap-1.5 border-b border-edge-faint bg-surface-tertiary py-1.5 ps-3 pe-1.5">
{editingCatId === cat.id ? ( {editingCatId === cat.id ? (
<input autoFocus value={editCatName} onChange={e => setEditCatName(e.target.value)} <input ref={focusRevealedEditor} value={editCatName} onChange={e => setEditCatName(e.target.value)}
onBlur={() => handleRenameCategory(cat.id)} onBlur={() => handleRenameCategory(cat.id)}
onKeyDown={e => { if (e.key === 'Enter') void handleRenameCategory(cat.id); if (e.key === 'Escape') setEditingCatId(null) }} onKeyDown={e => { if (e.key === 'Enter') void handleRenameCategory(cat.id); if (e.key === 'Escape') setEditingCatId(null) }}
aria-label={t('common.rename')} aria-label={t('common.rename')}
@@ -162,7 +163,7 @@ export default function PackingTemplateManager() {
<div key={item.id} data-row="item" className="group flex min-h-[40px] items-center gap-2 py-1.5 ps-3 pe-1.5"> <div key={item.id} data-row="item" className="group flex min-h-[40px] items-center gap-2 py-1.5 ps-3 pe-1.5">
{editingItemId === item.id ? ( {editingItemId === item.id ? (
<> <>
<input autoFocus value={editItemName} onChange={e => setEditItemName(e.target.value)} <input ref={focusRevealedEditor} value={editItemName} onChange={e => setEditItemName(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') void handleRenameItem(item.id); if (e.key === 'Escape') setEditingItemId(null) }} onKeyDown={e => { if (e.key === 'Enter') void handleRenameItem(item.id); if (e.key === 'Escape') setEditingItemId(null) }}
aria-label={t('common.rename')} aria-label={t('common.rename')}
className={`${ROW_INPUT} flex-1`} style={fs(12.5, 'body')} /> className={`${ROW_INPUT} flex-1`} style={fs(12.5, 'body')} />
@@ -219,7 +220,7 @@ export default function PackingTemplateManager() {
{/* Add category */} {/* Add category */}
{addingCategory ? ( {addingCategory ? (
<div className={COMPOSER_ROW} style={{ boxShadow: COMPOSER.boxShadow }}> <div className={COMPOSER_ROW} style={{ boxShadow: COMPOSER.boxShadow }}>
<input autoFocus value={newCatName} onChange={e => setNewCatName(e.target.value)} <input ref={focusRevealedEditor} value={newCatName} onChange={e => setNewCatName(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') void handleAddCategory(); if (e.key === 'Escape') { setAddingCategory(false); setNewCatName('') } }} onKeyDown={e => { if (e.key === 'Enter') void handleAddCategory(); if (e.key === 'Escape') { setAddingCategory(false); setNewCatName('') } }}
placeholder={t('admin.packingTemplates.categoryName')} placeholder={t('admin.packingTemplates.categoryName')}
className={COMPOSER_INPUT} style={fs(13, 'body')} /> className={COMPOSER_INPUT} style={fs(13, 'body')} />
@@ -67,7 +67,7 @@ function Catalog() {
}}> }}>
<div className={GRID_2}> <div className={GRID_2}>
<EditorField label={t('schoolCatalog.country')} htmlFor={`${fieldId}-name`}> <EditorField label={t('schoolCatalog.country')} htmlFor={`${fieldId}-name`}>
<input id={`${fieldId}-name`} autoFocus required maxLength={100} className={INPUT} value={name} onChange={event => setName(event.target.value)} /> <input id={`${fieldId}-name`} data-initial-focus required maxLength={100} className={INPUT} value={name} onChange={event => setName(event.target.value)} />
</EditorField> </EditorField>
<EditorField label={t('schoolCatalog.code')} htmlFor={`${fieldId}-code`}> <EditorField label={t('schoolCatalog.code')} htmlFor={`${fieldId}-code`}>
<input id={`${fieldId}-code`} required pattern="[A-Z]{2}" maxLength={2} className={`${INPUT} font-geist uppercase tracking-[.08em]`} value={code} onChange={event => setCode(event.target.value.toUpperCase())} placeholder="US" /> <input id={`${fieldId}-code`} required pattern="[A-Z]{2}" maxLength={2} className={`${INPUT} font-geist uppercase tracking-[.08em]`} value={code} onChange={event => setCode(event.target.value.toUpperCase())} placeholder="US" />
@@ -62,7 +62,7 @@ export default function SchoolHolidayRegionEditor({ region, busy, offline = fals
<div className={BODY}> <div className={BODY}>
<fieldset disabled={busy || offline} className={`m-0 flex min-w-0 flex-col gap-5 border-0 p-0 ${busy ? 'opacity-60' : ''}`}> <fieldset disabled={busy || offline} className={`m-0 flex min-w-0 flex-col gap-5 border-0 p-0 ${busy ? 'opacity-60' : ''}`}>
<EditorField label={t('schoolCatalog.region')} htmlFor={`${fieldId}-region`}> <EditorField label={t('schoolCatalog.region')} htmlFor={`${fieldId}-region`}>
<input id={`${fieldId}-region`} autoFocus required maxLength={150} className={INPUT} value={name} onChange={event => setName(event.target.value)} /> <input id={`${fieldId}-region`} data-initial-focus required maxLength={150} className={INPUT} value={name} onChange={event => setName(event.target.value)} />
</EditorField> </EditorField>
<SettingsHint>{t('schoolCatalog.periodHint')}</SettingsHint> <SettingsHint>{t('schoolCatalog.periodHint')}</SettingsHint>
{holidays.map((holiday, index) => { {holidays.map((holiday, index) => {
@@ -3,7 +3,6 @@ import {
ArrowUpCircle, ArrowUpCircle,
Bug, Bug,
CircleDot, CircleDot,
Github,
Globe, Globe,
History, History,
Info, Info,
@@ -23,6 +22,7 @@ import { createPortal } from 'react-dom';
import { POPOVER } from '../../Packing/packingPopoverStyles'; import { POPOVER } from '../../Packing/packingPopoverStyles';
import ToggleSwitch from '../../Settings/ToggleSwitch'; import ToggleSwitch from '../../Settings/ToggleSwitch';
import { fs } from '../../shared/DialogShell'; import { fs } from '../../shared/DialogShell';
import { Github } from '../../shared/legacyLucideIcons';
import PluginIcon from '../../shared/PluginIcon'; import PluginIcon from '../../shared/PluginIcon';
import { Tooltip } from '../../shared/Tooltip'; import { Tooltip } from '../../shared/Tooltip';
import { deriveCaps } from '../pluginCaps'; import { deriveCaps } from '../pluginCaps';
@@ -11,12 +11,13 @@
import type { AssistantApplied, AssistantChangeEffect, AssistantChangePreview } from '@trek/shared'; import type { AssistantApplied, AssistantChangeEffect, AssistantChangePreview } from '@trek/shared';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { buildAssignment, buildDay, buildPlace, buildTrip } from '../../../tests/helpers/factories'; import { buildAssignment, buildCategory, buildDay, buildPlace, buildTrip } from '../../../tests/helpers/factories';
import { act, fireEvent, render, screen } from '../../../tests/helpers/render'; import { act, fireEvent, render, screen, within } from '../../../tests/helpers/render';
import { chatOf, useAssistantStore } from '../../store/assistantStore'; import { chatOf, useAssistantStore } from '../../store/assistantStore';
import { useTripStore } from '../../store/tripStore'; import { useTripStore } from '../../store/tripStore';
import AssistantChangeCard from './AssistantChangeCard'; import AssistantChangeCard from './AssistantChangeCard';
import AssistantCompareSwitch from './AssistantCompareSwitch'; import AssistantCompareSwitch from './AssistantCompareSwitch';
import AssistantDayPreview from './AssistantDayPreview';
import type { ChangeItem } from './assistantParts'; import type { ChangeItem } from './assistantParts';
import { type AssistantView, AssistantViewContext } from './assistantViewContext'; import { type AssistantView, AssistantViewContext } from './assistantViewContext';
@@ -168,6 +169,106 @@ describe('AssistantChangeCard: deciding', () => {
expect(screen.getByRole('button', { name: 'Apply' })).toBeDisabled(); expect(screen.getByRole('button', { name: 'Apply' })).toBeDisabled();
expect(screen.getByRole('button', { name: 'Discard' })).toBeDisabled(); expect(screen.getByRole('button', { name: 'Discard' })).toBeDisabled();
}); });
it('edits a place proposal in the full place form and previews edits before applying', async () => {
plannerHere();
const change = {
...preview('c1', 'Kinkaku-ji'),
verbKey: 'addPlaceToDay' as const,
effect: { ...PANTHEON, place: { name: 'Kinkaku-ji', lat: 48, lng: 2, categoryId: 31 } },
};
const other = { ...change, toolCallId: 'c2', subject: 'Tea house', effect: null };
useTripStore.setState({
categories: [
buildCategory({ id: 31, name: 'Temple', color: '#334455' }),
buildCategory({ id: 32, name: 'Garden', color: '#667788' }),
],
});
patchChat({
messages: [
{
id: 'm1',
role: 'assistant',
status: 'complete',
createdAt: new Date().toISOString(),
parts: [
{
type: 'tool-call',
toolCallId: 'c1',
toolName: 'create_and_assign_place',
args: {},
approval: { id: 'c1' },
},
{ type: 'data-trek-change', data: change },
{
type: 'tool-call',
toolCallId: 'c2',
toolName: 'create_and_assign_place',
args: {},
approval: { id: 'c2' },
},
{ type: 'data-trek-change', data: other },
],
},
],
});
render(<AssistantDayPreview tripId={TRIP} dayId={3} />);
renderCard([
{ ...pending('c1', 'Kinkaku-ji'), preview: change },
{ ...pending('c2', 'Tea house'), preview: other },
]);
const day = screen.getByRole('list', { name: 'Suggested by the assistant' });
const [edit] = screen.getAllByRole('button', { name: 'Edit' });
fireEvent.click(edit);
const dialog = within(await screen.findByRole('dialog', { name: 'Edit Place' }));
expect(dialog.getByRole('textbox', { name: /^Name/ })).toHaveValue('Kinkaku-ji');
expect(dialog.getByRole('textbox', { name: 'Address' })).toBeVisible();
fireEvent.change(dialog.getByRole('textbox', { name: 'Start' }), { target: { value: '12:30' } });
fireEvent.change(dialog.getByRole('textbox', { name: 'Notes for this day' }), {
target: { value: 'Use the side entrance' },
});
fireEvent.click(dialog.getByRole('button', { name: /^Category:/ }));
fireEvent.click(screen.getByRole('button', { name: /^Garden$/ }));
expect(day).toHaveTextContent('12:30');
expect(day).toHaveTextContent('Use the side entrance');
expect(within(day).getByText('Garden').parentElement).toHaveStyle({ backgroundColor: '#667788' });
expect(decide).not.toHaveBeenCalled();
fireEvent.click(dialog.getByRole('button', { name: 'Cancel' }));
expect(day).toHaveTextContent('10:30');
expect(day).toHaveTextContent('Temple');
expect(day).not.toHaveTextContent('Use the side entrance');
fireEvent.click(edit);
const reopened = within(await screen.findByRole('dialog', { name: 'Edit Place' }));
const time = reopened.getByRole('textbox', { name: 'Start' });
expect(time).toHaveValue('10:30');
fireEvent.change(time, { target: { value: '11:45' } });
fireEvent.change(reopened.getByRole('textbox', { name: /^Name/ }), { target: { value: 'Golden Pavilion' } });
fireEvent.change(reopened.getByRole('textbox', { name: 'Address' }), { target: { value: 'Kyoto, Japan' } });
expect(day).toHaveTextContent('Golden Pavilion');
fireEvent.click(reopened.getByRole('button', { name: 'Save' }));
expect(day).toHaveTextContent('11:45');
expect(decide).not.toHaveBeenCalled();
const [include] = screen.getAllByRole('button', { name: 'Include this change' });
fireEvent.click(include);
expect(day).not.toHaveTextContent('Golden Pavilion');
expect(day).toHaveTextContent('Tea house');
fireEvent.click(include);
expect(day).toHaveTextContent('Golden Pavilion');
expect(day).toHaveTextContent('11:45');
fireEvent.click(screen.getByRole('button', { name: 'Apply 2' }));
expect(decide).toHaveBeenCalledWith(TRIP, [
{
toolCallId: 'c1',
approved: true,
planEdits: { startTime: '11:45', place: { name: 'Golden Pavilion', address: 'Kyoto, Japan' } },
},
{ toolCallId: 'c2', approved: true },
]);
});
}); });
describe('AssistantChangeCard: the receipt', () => { describe('AssistantChangeCard: the receipt', () => {
@@ -1,4 +1,4 @@
import { Check, CheckCheck, ListChecks, LoaderCircle, MapPin, Undo2 } from 'lucide-react'; import { Check, CheckCheck, ChevronDown, ListChecks, LoaderCircle, MapPin, Undo2 } from 'lucide-react';
import { type ReactNode, useEffect, useMemo, useState } from 'react'; import { type ReactNode, useEffect, useMemo, useState } from 'react';
import { useTranslation } from '../../i18n'; import { useTranslation } from '../../i18n';
@@ -78,13 +78,21 @@ function dayChangesOf(items: readonly ChangeItem[], excluded: ReadonlySet<string
/** The change card's band: tinted green once everything in it is decided, what it holds and its actions. */ /** The change card's band: tinted green once everything in it is decided, what it holds and its actions. */
function CardHead({ open, count, actions }: { open: boolean; count: number; actions?: ReactNode }) { function CardHead({ open, count, actions }: { open: boolean; count: number; actions?: ReactNode }) {
const { t } = useTranslation(); const { t } = useTranslation();
const Icon = open ? ListChecks : CheckCheck;
return ( return (
<CardHeader <CardHeader
icon={open ? ListChecks : CheckCheck} icon={Icon}
tone={open ? 'info' : 'success'} tone={open ? 'info' : 'success'}
tint={open ? NEUTRAL_TINT : DONE_TINT} tint={open ? NEUTRAL_TINT : DONE_TINT}
title={t(open ? 'assistant.change.title' : 'assistant.change.doneTitle')} title={t(open ? 'assistant.change.title' : 'assistant.change.doneTitle')}
count={count} tile={
<span className="relative grid h-8 w-8 shrink-0 place-items-center rounded-[10px] bg-surface-card shadow-sm">
<Icon size={15} strokeWidth={2} className={open ? 'text-info' : 'text-success'} aria-hidden="true" />
<span className="absolute -end-1 -top-1 inline-flex h-4 min-w-4 items-center justify-center rounded-full bg-surface-card px-1 font-geist text-caption font-bold tabular-nums leading-none text-content-secondary shadow-sm ring-1 ring-edge">
{count}
</span>
</span>
}
actions={actions} actions={actions}
/> />
); );
@@ -186,11 +194,23 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
const undone = useAssistantStore((s) => chatOf(s, tripId).undone); const undone = useAssistantStore((s) => chatOf(s, tripId).undone);
const decide = useAssistantStore((s) => s.decide); const decide = useAssistantStore((s) => s.decide);
const undo = useAssistantStore((s) => s.undo); const undo = useAssistantStore((s) => s.undo);
const [excluded, setExcluded] = useChangeExclusions(items); const choices = useAssistantStore((s) => chatOf(s, tripId).changeChoices);
const choosePlanChanges = useAssistantStore((s) => s.choosePlanChanges);
const excluded = useChangeExclusions(items, choices);
const planEdits = useAssistantStore((s) => chatOf(s, tripId).planEdits);
const savePlanEdit = useAssistantStore((s) => s.savePlanEdit);
const now = useUndoClock(items); const now = useUndoClock(items);
const pending = items.filter((i) => i.state === 'pending'); const pending = items.filter((i) => i.state === 'pending');
const chosen = pending.filter((i) => !excluded.has(i.toolCallId)).length; const chosen = pending.filter((i) => !excluded.has(i.toolCallId)).length;
const invalid = pending.some((i) => !excluded.has(i.toolCallId) && planEdits[i.toolCallId]?.noteTitle?.trim() === '');
const planDayId = pending[0]?.preview?.dayId;
const planDay = useTripStore((s) => (s.trip?.id === tripId ? s.days.find((day) => day.id === planDayId) : undefined));
const groupedDay =
pending.length > 1 &&
pending.length === items.length &&
!!planDay &&
pending.every((i) => i.preview?.dayId === planDayId);
const changes = useMemo(() => dayChangesOf(items, excluded), [items, excluded]); const changes = useMemo(() => dayChangesOf(items, excluded), [items, excluded]);
const undoable = items.filter((i) => undoableNow(i, undone, now)).map((i) => i.toolCallId); const undoable = items.filter((i) => undoableNow(i, undone, now)).map((i) => i.toolCallId);
@@ -199,27 +219,17 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
// A plan over a week reads from its grid; the single changes wait behind one line. // A plan over a week reads from its grid; the single changes wait behind one line.
const folded = week.length > 0 && !showAll; const folded = week.length > 0 && !showAll;
const toggleDay = (ids: readonly string[], include: boolean) => const toggleDay = (ids: readonly string[], include: boolean) => choosePlanChanges(tripId, ids, include);
setExcluded((prev) => { const toggle = (toolCallId: string) => toggleDay([toolCallId], excluded.has(toolCallId));
const next = new Set(prev);
for (const id of ids) {
if (include) next.delete(id);
else next.add(id);
}
return next;
});
const toggle = (toolCallId: string) =>
setExcluded((prev) => {
const next = new Set(prev);
if (!next.delete(toolCallId)) next.add(toolCallId);
return next;
});
const submit = (applyChosen: boolean) => const submit = (applyChosen: boolean) =>
decide( decide(
tripId, tripId,
pending.map((i) => ({ toolCallId: i.toolCallId, approved: applyChosen && !excluded.has(i.toolCallId) })) pending.map((i) => {
const approved = applyChosen && !excluded.has(i.toolCallId);
const edits = approved ? planEdits[i.toolCallId] : undefined;
return { toolCallId: i.toolCallId, approved, ...(edits ? { planEdits: edits } : {}) };
})
); );
// An undone change reads as undone from the store; only what stays needs a word. // An undone change reads as undone from the store; only what stays needs a word.
@@ -230,6 +240,21 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
}; };
const open = pending.length > 0; const open = pending.length > 0;
const rows = (
<ChangeRows
items={items}
folded={folded}
excluded={excluded}
disabled={isRunning}
undone={undone}
undoable={undoable}
onToggle={toggle}
onUndo={(toolCallId) => void runUndo(toolCallId)}
groupedDay={groupedDay}
planEdits={planEdits}
onEdit={(id, patch) => savePlanEdit(tripId, id, patch)}
/>
);
return ( return (
<section className="trek-popover-enter overflow-hidden rounded-[16px] border border-edge-faint bg-surface-card px-3.5 pb-3 pt-3 shadow-card"> <section className="trek-popover-enter overflow-hidden rounded-[16px] border border-edge-faint bg-surface-card px-3.5 pb-3 pt-3 shadow-card">
<CardHead <CardHead
@@ -249,16 +274,31 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
{t('assistant.week.showAll', { count: pending.length })} {t('assistant.week.showAll', { count: pending.length })}
</button> </button>
)} )}
<ChangeRows {!folded && groupedDay && planDay ? (
items={items} <details open className="group/day mt-1">
folded={folded} <summary className="-mx-1.5 flex min-w-0 cursor-pointer list-none items-center gap-2.5 rounded-xl bg-surface-tertiary py-2 pe-3.5 ps-1.5 text-start hover:bg-surface-hover focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-accent [&::-webkit-details-marker]:hidden">
excluded={excluded} <span
disabled={isRunning} aria-hidden="true"
undone={undone} className="grid h-8 w-8 shrink-0 place-items-center rounded-[10px] bg-surface-card font-geist text-caption font-bold tabular-nums text-content-muted shadow-sm"
undoable={undoable} >
onToggle={toggle} {planDay.day_number}
onUndo={(toolCallId) => void runUndo(toolCallId)} </span>
/> <span className="shrink-0 text-body font-bold text-content">
{t('assistant.week.day')} {planDay.day_number}
</span>
{planDay.title && <bdi className="min-w-0 truncate text-caption text-content-muted">{planDay.title}</bdi>}
<ChevronDown
size={15}
strokeWidth={2}
aria-hidden="true"
className="ms-auto shrink-0 -rotate-90 text-content-muted group-open/day:rotate-0"
/>
</summary>
{rows}
</details>
) : (
rows
)}
{open && ( {open && (
<> <>
<p className="sr-only" role="status"> <p className="sr-only" role="status">
@@ -270,7 +310,7 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
</DialogButton> </DialogButton>
<DialogButton <DialogButton
variant="primary" variant="primary"
disabled={isRunning || chosen === 0} disabled={isRunning || chosen === 0 || invalid}
onClick={() => void submit(true)} onClick={() => void submit(true)}
icon={<Check size={14} aria-hidden="true" />} icon={<Check size={14} aria-hidden="true" />}
> >
@@ -1,4 +1,4 @@
import type { AssistantChangeLabelKey, AssistantChangeRow } from '@trek/shared'; import type { AssistantChangeLabelKey, AssistantChangeRow, AssistantPlanEdits } from '@trek/shared';
import { import {
CalendarClock, CalendarClock,
CalendarDays, CalendarDays,
@@ -13,6 +13,7 @@ import {
} from 'lucide-react'; } from 'lucide-react';
import { useTranslation } from '../../i18n'; import { useTranslation } from '../../i18n';
import { useTripStore } from '../../store/tripStore';
import { FactChange } from './cards/parts/CardFacts'; import { FactChange } from './cards/parts/CardFacts';
/** /**
@@ -45,10 +46,42 @@ function shown(row: AssistantChangeRow, value: string | null | undefined, dayWor
return value ?? ''; return value ?? '';
} }
export default function AssistantChangeFields({ rows }: { rows: AssistantChangeRow[] }) { export default function AssistantChangeFields({
rows,
visit = false,
edits,
}: {
rows: AssistantChangeRow[];
visit?: boolean;
edits?: AssistantPlanEdits;
}) {
const { t } = useTranslation(); const { t } = useTranslation();
const categoryName = useTripStore((s) =>
edits?.categoryId == null ? undefined : s.categories.find((category) => category.id === edits.categoryId)?.name
);
const dayWord = t('assistant.week.day'); const dayWord = t('assistant.week.day');
const facts = rows let editedRows = rows;
if (visit && edits) {
const fields = [
['time', edits.startTime],
['endTime', edits.endTime],
['category', edits.categoryId === null ? null : categoryName],
] as const;
for (const [labelKey, after] of fields) {
if (after === undefined) continue;
editedRows = editedRows.filter((row) => row.labelKey !== labelKey);
if (after) editedRows.push({ op: 'add', labelKey, before: null, after });
}
}
const end = visit ? editedRows.find((row) => row.labelKey === 'endTime')?.after : undefined;
const start = visit ? editedRows.find((row) => row.labelKey === 'time') : undefined;
const visible =
start?.after && end
? editedRows
.filter((row) => row.labelKey !== 'endTime')
.map((row) => (row === start ? { ...row, after: `${row.after} – ${end}` } : row))
: editedRows;
const facts = visible
.filter((row) => row.labelKey in KEY_FIELDS && row.after) .filter((row) => row.labelKey in KEY_FIELDS && row.after)
.sort((a, b) => KEY_ORDER.indexOf(a.labelKey) - KEY_ORDER.indexOf(b.labelKey)) .sort((a, b) => KEY_ORDER.indexOf(a.labelKey) - KEY_ORDER.indexOf(b.labelKey))
.slice(0, MAX_FACTS); .slice(0, MAX_FACTS);
@@ -1,18 +1,28 @@
import type { AssistantChangeEffect, AssistantMessage } from '@trek/shared'; import type { AssistantChangePreview, AssistantMessage, AssistantPlanEdits } from '@trek/shared';
import { ArrowRightLeft, Minus, Sparkles } from 'lucide-react'; import { ArrowRightLeft, FileText, MapPin, Minus, type LucideIcon } from 'lucide-react';
import { useMemo } from 'react'; import { useMemo } from 'react';
import { useShallow } from 'zustand/react/shallow'; import { useShallow } from 'zustand/react/shallow';
import { useTranslation } from '../../i18n'; import { useTranslation } from '../../i18n';
import { changeEffects } from '../../store/assistantMapModel';
import { chatOf, useAssistantStore } from '../../store/assistantStore'; import { chatOf, useAssistantStore } from '../../store/assistantStore';
import { useSettingsStore } from '../../store/settingsStore';
import { useTripStore } from '../../store/tripStore'; import { useTripStore } from '../../store/tripStore';
import type { Place } from '../../types';
import { formatTime } from '../../utils/formatters';
import { TimePill } from '../Planner/planParts';
import { getCategoryIcon } from '../shared/categoryIcons';
import { isDayNoteProposal, isVisitProposal, planField, proposalNote } from './assistantPlanFieldsModel';
/** What a waiting change does to one day, as a row of the preview. */ /** What a waiting change does to one day, as a row of the preview. */
interface PreviewRow { interface PreviewRow {
toolCallId: string; toolCallId: string;
kind: 'add' | 'in' | 'remove' | 'out'; kind: 'add' | 'in' | 'remove' | 'out' | 'note';
name: string; name: string;
categoryId: number | null;
categoryName?: string;
start?: string;
end?: string;
detail?: string;
} }
/** The changes no one has decided on yet, by their call. */ /** The changes no one has decided on yet, by their call. */
@@ -29,25 +39,77 @@ function waitingCalls(messages: readonly AssistantMessage[]): Set<string> {
} }
function rowOf( function rowOf(
toolCallId: string, preview: AssistantChangePreview,
effect: AssistantChangeEffect,
dayId: number, dayId: number,
nameOf: (id: number | null) => string | null places: readonly Place[],
) { edits: AssistantPlanEdits | undefined
const name = effect.place?.name ?? nameOf(effect.placeId); ): PreviewRow | null {
if (!name) return null; const { toolCallId, effect, subject } = preview;
if (effect.dayId === dayId) { if (preview.dayId === dayId && isDayNoteProposal(preview)) {
const kind = effect.kind === 'remove' ? 'remove' : effect.kind === 'move' ? 'in' : 'add'; return {
return { toolCallId, kind, name } satisfies PreviewRow; toolCallId,
kind: 'note',
name: edits?.noteTitle || planField(preview, 'title') || subject,
categoryId: null,
detail: proposalNote(preview, edits) ?? undefined,
};
} }
if (effect.kind === 'move' && effect.fromDayId === dayId) const kind = visitKind(preview, dayId);
return { toolCallId, kind: 'out', name } satisfies PreviewRow; if (!kind) return null;
return null; const place = places.find((p) => p.id === effect?.placeId);
return { toolCallId, kind, ...visitSubject(preview, place, edits), ...visitDetails(preview, place, edits) };
} }
const LOOK: Record<PreviewRow['kind'], { icon: typeof Sparkles; row: string; name: string; badgeKey: string }> = { function visitSubject(
preview: AssistantChangePreview,
place: Place | undefined,
edits: AssistantPlanEdits | undefined
) {
const proposed = preview.effect?.place;
const categoryId = edits?.categoryId;
return {
name: edits?.place?.name ?? proposed?.name ?? place?.name ?? preview.subject,
categoryId: categoryId === undefined ? (proposed?.categoryId ?? place?.category_id ?? null) : categoryId,
categoryName: categoryId === undefined ? planField(preview, 'category') : undefined,
};
}
function editedText(value: string | null | undefined, original: string | undefined): string | undefined {
return value === undefined ? original : (value ?? undefined);
}
function visitDetails(
preview: AssistantChangePreview,
place: Place | undefined,
edits: AssistantPlanEdits | undefined
) {
return {
start: editedText(edits?.startTime, planField(preview, 'time')),
end: editedText(edits?.endTime, planField(preview, 'endTime')),
detail:
editedText(edits?.notes, planField(preview, 'notes')) ||
editedText(edits?.place?.description, planField(preview, 'description')) ||
place?.description ||
editedText(edits?.place?.address, planField(preview, 'address')) ||
place?.address ||
undefined,
};
}
function visitKind(preview: AssistantChangePreview, dayId: number): PreviewRow['kind'] | null {
const { effect } = preview;
if (!effect) return preview.dayId === dayId && isVisitProposal(preview) ? 'add' : null;
if (effect.dayId === dayId) {
if (effect.kind === 'remove') return 'remove';
if (effect.kind === 'move') return 'in';
return 'add';
}
return effect.kind === 'move' && effect.fromDayId === dayId ? 'out' : null;
}
const LOOK: Record<PreviewRow['kind'], { icon: LucideIcon; row: string; name: string; badgeKey: string }> = {
add: { add: {
icon: Sparkles, icon: MapPin,
row: 'border-dashed border-accent bg-accent-subtle', row: 'border-dashed border-accent bg-accent-subtle',
name: 'text-content', name: 'text-content',
badgeKey: 'assistant.preview.suggested', badgeKey: 'assistant.preview.suggested',
@@ -70,6 +132,12 @@ const LOOK: Record<PreviewRow['kind'], { icon: typeof Sparkles; row: string; nam
name: 'text-content-faint line-through', name: 'text-content-faint line-through',
badgeKey: 'assistant.preview.movedAway', badgeKey: 'assistant.preview.movedAway',
}, },
note: {
icon: FileText,
row: 'border-dashed border-accent bg-accent-subtle',
name: 'text-content',
badgeKey: 'assistant.preview.suggested',
},
}; };
/** /**
@@ -80,31 +148,45 @@ const LOOK: Record<PreviewRow['kind'], { icon: typeof Sparkles; row: string; nam
* here writes; the change card stays the one place a change is applied. * here writes; the change card stays the one place a change is applied.
*/ */
export default function AssistantDayPreview({ tripId, dayId }: { tripId: number; dayId: number }) { export default function AssistantDayPreview({ tripId, dayId }: { tripId: number; dayId: number }) {
const { t } = useTranslation(); const { t, locale } = useTranslation();
const timeFormat = useSettingsStore((s) => s.settings.time_format) || '24h';
const messages = useAssistantStore((s) => chatOf(s, tripId).messages); const messages = useAssistantStore((s) => chatOf(s, tripId).messages);
const savedEdits = useAssistantStore((s) => chatOf(s, tripId).planEdits);
const liveEdit = useAssistantStore((s) => chatOf(s, tripId).planEditPreview);
const choices = useAssistantStore((s) => chatOf(s, tripId).changeChoices);
const hovered = useAssistantStore((s) => (s.mapLink?.tripId === tripId ? s.mapLink.hoveredId : null)); const hovered = useAssistantStore((s) => (s.mapLink?.tripId === tripId ? s.mapLink.hoveredId : null));
const { setMapHover, open } = useAssistantStore(useShallow((s) => ({ setMapHover: s.setMapHover, open: s.open }))); const { setMapHover, open } = useAssistantStore(useShallow((s) => ({ setMapHover: s.setMapHover, open: s.open })));
const places = useTripStore((s) => s.places); const places = useTripStore((s) => s.places);
const categories = useTripStore((s) => s.categories);
const rows = useMemo(() => { const rows = useMemo(() => {
const waiting = waitingCalls(messages); const waiting = waitingCalls(messages);
if (waiting.size === 0) return []; if (waiting.size === 0) return [];
const nameOf = (id: number | null) => (id === null ? null : (places.find((p) => p.id === id)?.name ?? null)); return messages.flatMap((message) =>
const out: PreviewRow[] = []; message.parts.flatMap((part) => {
for (const [toolCallId, effect] of changeEffects(messages)) { if (part.type !== 'data-trek-change' || !waiting.delete(part.data.toolCallId)) return [];
if (!waiting.has(toolCallId)) continue; const id = part.data.toolCallId;
const row = rowOf(toolCallId, effect, dayId, nameOf); if (choices[id] === false) return [];
if (row) out.push(row); const edits = liveEdit?.toolCallId === id ? liveEdit.edits : savedEdits[id];
} const row = rowOf(part.data, dayId, places, edits);
return out; return row ? [row] : [];
}, [messages, places, dayId]); })
);
}, [messages, places, dayId, savedEdits, liveEdit, choices]);
if (rows.length === 0) return null; if (rows.length === 0) return null;
return ( return (
<ul className="m-0 flex list-none flex-col gap-1 px-3 pb-2 pt-1" aria-label={t('assistant.preview.title')}> <ul className="m-0 flex list-none flex-col gap-1 px-3 pb-2 pt-1" aria-label={t('assistant.preview.title')}>
{rows.map((row, i) => { {rows.map((row, i) => {
const look = LOOK[row.kind]; const look = LOOK[row.kind];
const Icon = look.icon; const category = categories.find((entry) =>
row.categoryId ? entry.id === row.categoryId : entry.name === row.categoryName
);
const Icon = category ? getCategoryIcon(category.icon) : look.icon;
const time = [row.start, row.end]
.filter((value): value is string => !!value)
.map((value) => formatTime(value, locale, timeFormat))
.join(' – ');
const lit = hovered === row.toolCallId; const lit = hovered === row.toolCallId;
return ( return (
<li <li
@@ -121,11 +203,29 @@ export default function AssistantDayPreview({ tripId, dayId }: { tripId: number;
lit ? 'shadow-md ring-2 ring-accent' : 'hover:shadow-sm' lit ? 'shadow-md ring-2 ring-accent' : 'hover:shadow-sm'
}`} }`}
> >
<span className="grid h-6 w-6 flex-shrink-0 place-items-center rounded-lg bg-surface-card text-content-muted shadow-sm"> <span
<Icon size={12} aria-hidden="true" /> className="grid h-8 w-8 flex-shrink-0 place-items-center rounded-full bg-surface-card text-content-muted shadow-sm"
style={category?.color ? { backgroundColor: category.color, color: 'white' } : undefined}
>
<Icon size={14} aria-hidden="true" />
{(category?.name || row.categoryName) && (
<span className="sr-only">{category?.name ?? row.categoryName}</span>
)}
</span> </span>
<bdi className={`min-w-0 flex-1 truncate text-caption font-medium ${look.name}`}>{row.name}</bdi> <span className="min-w-0 flex-1">
<span className="flex-shrink-0 rounded-full bg-surface-card px-2 py-0.5 text-caption text-content-muted shadow-sm"> <bdi className={`block truncate text-body font-medium ${look.name}`}>{row.name}</bdi>
{time && (
<span className="mt-0.5 flex">
<TimePill quiet>{time}</TimePill>
</span>
)}
{row.detail && (
<bdi className="mt-0.5 line-clamp-2 break-words text-caption text-content-muted">{row.detail}</bdi>
)}
</span>
<span
className={row.kind === 'add' || row.kind === 'note' ? 'sr-only' : 'flex-shrink-0 text-content-muted'}
>
{t(look.badgeKey)} {t(look.badgeKey)}
</span> </span>
</button> </button>
@@ -4,10 +4,11 @@
* The error line: one sentence, at most one thing to do, and that thing * The error line: one sentence, at most one thing to do, and that thing
* does what it says. * does what it says.
*/ */
import type { AiStatusResponse, AssistantErrorCode } from '@trek/shared'; import type { AiStatusResponse, AssistantErrorCode, AssistantMessage } from '@trek/shared';
import { Route, Routes } from 'react-router'; import { Route, Routes } from 'react-router';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { HIKE } from '../../../tests/helpers/assistantTour';
import { fireEvent, render, screen } from '../../../tests/helpers/render'; import { fireEvent, render, screen } from '../../../tests/helpers/render';
import { chatOf, useAssistantStore } from '../../store/assistantStore'; import { chatOf, useAssistantStore } from '../../store/assistantStore';
import { setForcedOffline } from '../../sync/networkMode'; import { setForcedOffline } from '../../sync/networkMode';
@@ -33,13 +34,17 @@ const retry = vi.fn(async () => {});
const continueHere = vi.fn(async () => {}); const continueHere = vi.fn(async () => {});
const send = vi.fn(async () => {}); const send = vi.fn(async () => {});
function withError(error: AssistantErrorCode | null, status: AiStatusResponse = STATUS) { function withError(
error: AssistantErrorCode | null,
status: AiStatusResponse = STATUS,
messages: AssistantMessage[] = []
) {
useAssistantStore.setState({ useAssistantStore.setState({
status, status,
retry, retry,
continueHere, continueHere,
send, send,
byTrip: { [TRIP]: { ...chatOf(useAssistantStore.getState(), TRIP), error } }, byTrip: { [TRIP]: { ...chatOf(useAssistantStore.getState(), TRIP), error, messages } },
}); });
} }
@@ -119,6 +124,25 @@ describe('AssistantError', () => {
expect(screen.queryByRole('button')).toBeNull(); expect(screen.queryByRole('button')).toBeNull();
}); });
it('keeps a calculated route distinct from the rate-limited reply', () => {
const when = '2026-10-21T08:00:00.000Z';
const question: AssistantMessage = { id: 'm1', role: 'user', status: 'complete', parts: [], createdAt: when };
const answer: AssistantMessage = {
id: 'm2',
role: 'assistant',
status: 'error',
createdAt: when,
parts: [{ type: 'data-trek-card', data: { toolCallId: 'hike', card: HIKE } }],
};
withError('rate_limited', STATUS, [question, answer]);
const { unmount } = renderLine();
expect(screen.getByRole('status')).toHaveTextContent('The route preview is still available.');
unmount();
withError('rate_limited', STATUS, [question, answer, { ...question, id: 'm3' }]);
renderLine();
expect(screen.getByRole('status')).toHaveTextContent('Limit reached at Anthropic. Try again later.');
});
it('FE-AI-ERR-008: waiting changes ask for a decision before a place can be suggested', () => { it('FE-AI-ERR-008: waiting changes ask for a decision before a place can be suggested', () => {
withError('decide_first'); withError('decide_first');
renderLine(); renderLine();
@@ -4,7 +4,7 @@ import { useNavigate } from 'react-router';
import { useNetworkMode } from '../../hooks/useNetworkMode'; import { useNetworkMode } from '../../hooks/useNetworkMode';
import { useTranslation } from '../../i18n'; import { useTranslation } from '../../i18n';
import { chatOf, useAssistantStore } from '../../store/assistantStore'; import { chatOf, useAssistantStore } from '../../store/assistantStore';
import { type AssistantErrorActionKind, connectionErrorOf, errorView } from './assistantModel'; import { type AssistantErrorActionKind, connectionErrorOf, errorView, hasCurrentTourProposal } from './assistantModel';
import { AI_SETTINGS_PATH } from './assistantParts'; import { AI_SETTINGS_PATH } from './assistantParts';
import { CHATGPT_USAGE_URL, providerLabel } from './providerCatalog'; import { CHATGPT_USAGE_URL, providerLabel } from './providerCatalog';
@@ -18,6 +18,10 @@ export default function AssistantError({ tripId }: { tripId: number }) {
const navigate = useNavigate(); const navigate = useNavigate();
const { offline } = useNetworkMode(); const { offline } = useNetworkMode();
const error = useAssistantStore((s) => chatOf(s, tripId).error); const error = useAssistantStore((s) => chatOf(s, tripId).error);
const hasTourProposal = useAssistantStore((s) => {
const chat = chatOf(s, tripId);
return chat.error === 'rate_limited' && hasCurrentTourProposal(chat.messages);
});
const status = useAssistantStore((s) => s.status); const status = useAssistantStore((s) => s.status);
const retry = useAssistantStore((s) => s.retry); const retry = useAssistantStore((s) => s.retry);
const continueHere = useAssistantStore((s) => s.continueHere); const continueHere = useAssistantStore((s) => s.continueHere);
@@ -28,7 +32,7 @@ export default function AssistantError({ tripId }: { tripId: number }) {
const effective = status?.effective; const effective = status?.effective;
const provider = effective ? providerLabel(effective.kind, effective.host) : ''; const provider = effective ? providerLabel(effective.kind, effective.host) : '';
const view = errorView(code, { canConnectOwn: status?.canConnectOwn ?? false, provider }); const view = errorView(code, { canConnectOwn: status?.canConnectOwn ?? false, provider, hasTourProposal });
const run = (kind: AssistantErrorActionKind) => { const run = (kind: AssistantErrorActionKind) => {
if (kind === 'retry') void retry(tripId); if (kind === 'retry') void retry(tripId);
@@ -139,7 +139,8 @@ function Answer({ message }: { message: StoredMessage }) {
}); });
const blocks = useMemo(() => messageBlocks(message, writing), [message, writing]); const blocks = useMemo(() => messageBlocks(message, writing), [message, writing]);
const share = useAssistantShare(tripId, message, writing); const share = useAssistantShare(tripId, message, writing);
const last = blocks[blocks.length - 1]; const end = blocks[blocks.length - 1];
const last = end?.kind === 'sources' ? blocks[blocks.length - 2] : end;
const hasText = blocks.some((b) => b.kind === 'text'); const hasText = blocks.some((b) => b.kind === 'text');
const tail = tailStart(blocks); const tail = tailStart(blocks);
@@ -0,0 +1,173 @@
import type { AssistantChangePreview, AssistantPlanEdits } from '@trek/shared';
import { assistantPlanEditsSchema, parsePlaceHours, placeOpeningHoursSchema } from '@trek/shared';
import { useCallback, useEffect, useState } from 'react';
import { useIsPhone } from '../../hooks/useIsPhone';
import { useTranslation } from '../../i18n';
import { useAssistantStore } from '../../store/assistantStore';
import { useTripStore } from '../../store/tripStore';
import PlaceFormModal from '../Planner/PlaceFormModal';
import { DEFAULT_FORM, formPin, type PlaceFormData } from '../Planner/PlaceFormModal.helpers';
import { planField } from './assistantPlanFieldsModel';
import { useAssistantView } from './assistantViewContext';
type PlacePatch = NonNullable<AssistantPlanEdits['place']>;
function originalForm(preview: AssistantChangePreview, rawArgs: unknown, categoryId: number | null): PlaceFormData {
const args = rawArgs && typeof rawArgs === 'object' ? (rawArgs as Record<string, unknown>) : {};
const value = (key: string) => (typeof args[key] === 'string' ? args[key] : '');
const point = preview.effect?.place;
const coordinate = (key: 'lat' | 'lng') => String(typeof args[key] === 'number' ? args[key] : (point?.[key] ?? ''));
const text = (key: 'address' | 'description') => value(key) || planField(preview, key) || '';
const hours = placeOpeningHoursSchema.safeParse(args.opening_hours);
return {
...DEFAULT_FORM,
name: value('name') || point?.name || preview.subject,
address: text('address'),
description: text('description'),
lat: coordinate('lat'),
lng: coordinate('lng'),
category_id: String(categoryId ?? ''),
place_time: planField(preview, 'time') ?? '',
end_time: planField(preview, 'endTime') ?? '',
assignment_notes: planField(preview, 'notes') ?? '',
notes: value('place_notes'),
google_place_id: value('google_place_id'),
google_ftid: value('google_ftid'),
osm_id: value('osm_id'),
amap_poi_id: value('amap_poi_id'),
website: value('website'),
phone: value('phone'),
email: value('email'),
opening_hours: hours.success ? JSON.stringify(hours.data) : '',
image_url: value('image_url') || null,
tags: Array.isArray(args.tags) ? args.tags.filter((tag): tag is number => Number.isInteger(tag)) : [],
};
}
function restoreDraft(form: PlaceFormData, edits: AssistantPlanEdits | undefined): PlaceFormData {
const { lat, lng, place_notes, opening_hours, ...place } = edits?.place ?? {};
const restored = Object.fromEntries(Object.entries(place).map(([field, value]) => [field, value ?? '']));
return {
...form,
...restored,
...(lat === undefined ? {} : { lat: String(lat ?? '') }),
...(lng === undefined ? {} : { lng: String(lng ?? '') }),
...(place_notes === undefined ? {} : { notes: place_notes ?? '' }),
...(opening_hours === undefined ? {} : { opening_hours: opening_hours ? JSON.stringify(opening_hours) : '' }),
...visitDraft(edits ?? {}),
};
}
function visitDraft({ startTime, endTime, notes, categoryId }: AssistantPlanEdits): Partial<PlaceFormData> {
return {
...(startTime === undefined ? {} : { place_time: startTime ?? '' }),
...(endTime === undefined ? {} : { end_time: endTime ?? '' }),
...(notes === undefined ? {} : { assignment_notes: notes ?? '' }),
...(categoryId === undefined ? {} : { category_id: String(categoryId ?? '') }),
};
}
function placeValues(form: PlaceFormData): PlacePatch {
const position = formPin(form);
return {
name: form.name.trim(),
description: form.description || null,
address: form.address || null,
lat: position?.lat ?? null,
lng: position?.lng ?? null,
google_place_id: form.google_place_id || null,
google_ftid: form.google_ftid || null,
osm_id: form.osm_id || null,
amap_poi_id: form.amap_poi_id || null,
place_notes: form.notes || null,
website: form.website.trim() || null,
phone: form.phone?.trim() || null,
email: form.email?.trim() || null,
opening_hours: parsePlaceHours(form.opening_hours),
image_url: form.image_url || null,
tags: form.tags ?? [],
};
}
function changesOf(form: PlaceFormData, original: PlaceFormData, existing: boolean): AssistantPlanEdits {
const edits: AssistantPlanEdits = {};
if (form.place_time !== original.place_time) edits.startTime = form.place_time || null;
if (form.end_time !== original.end_time) edits.endTime = form.end_time || null;
if (form.assignment_notes !== original.assignment_notes) edits.notes = form.assignment_notes || null;
if (!existing) {
if (form.category_id !== original.category_id)
edits.categoryId = form.category_id ? Number(form.category_id) : null;
const previous = placeValues(original);
const changed = Object.entries(placeValues(form)).filter(
([field, value]) => JSON.stringify(previous[field as keyof PlacePatch]) !== JSON.stringify(value)
);
if (changed.length) edits.place = Object.fromEntries(changed);
}
return edits;
}
export default function AssistantPlaceProposal({
preview,
args,
edits,
disabled,
onEdit,
onClose,
}: {
preview: AssistantChangePreview;
args: unknown;
edits: AssistantPlanEdits | undefined;
disabled: boolean;
onEdit: (edits: AssistantPlanEdits) => void;
onClose: () => void;
}) {
const { t } = useTranslation();
const { tripId, variant } = useAssistantView();
const phone = useIsPhone();
const previewEdit = useAssistantStore((s) => s.previewPlanEdit);
const categories = useTripStore((s) => s.categories);
const dayAssignments = useTripStore((s) => (preview.dayId == null ? undefined : s.assignments[preview.dayId]));
const currentPlace = useTripStore((s) => s.places.find((place) => place.id === preview.effect?.placeId));
const existing = preview.verbKey === 'assignPlace';
const [original] = useState(() => {
const categoryId =
preview.effect?.place?.categoryId ??
currentPlace?.category_id ??
categories.find((category) => category.name === planField(preview, 'category'))?.id ??
null;
const form = originalForm(preview, args, categoryId);
return existing && currentPlace ? { ...form, name: currentPlace.name, address: currentPlace.address ?? '' } : form;
});
const [initialForm] = useState(() => restoreDraft(original, edits));
const { toolCallId } = preview;
const onPreview = useCallback(
(form: PlaceFormData) => {
if (!existing && (form.lat || form.lng) && !formPin(form)) return;
const parsed = assistantPlanEditsSchema.safeParse(changesOf(form, original, existing));
if (parsed.success) previewEdit(tripId, toolCallId, parsed.data);
},
[existing, original, previewEdit, toolCallId, tripId]
);
useEffect(() => () => previewEdit(tripId, toolCallId, null), [previewEdit, toolCallId, tripId]);
const onSave = (form: PlaceFormData) => {
if (!existing && (form.lat || form.lng) && !formPin(form)) throw new Error(t('places.saveError'));
const parsed = assistantPlanEditsSchema.safeParse(changesOf(form, original, existing));
if (!parsed.success) throw new Error(t('places.saveError'));
onEdit(parsed.data);
};
return (
<PlaceFormModal
isOpen
onClose={onClose}
place={null}
tripId={tripId}
categories={categories}
assignmentId={null}
dayAssignments={dayAssignments}
isMobile={phone || variant === 'fullscreen'}
proposal={{ initialForm, existing, dayId: preview.dayId, disabled, onPreview, onSave }}
/>
);
}
@@ -0,0 +1,146 @@
import type { AssistantChangePreview, AssistantPlanEdits } from '@trek/shared';
import { Check, Pencil } from 'lucide-react';
import { lazy, Suspense, useEffect, useId, useState } from 'react';
import { useTranslation } from '../../i18n';
import { useAssistantStore } from '../../store/assistantStore';
import { EditorField, PANEL, TEXTAREA } from '../shared/dialogParts';
import {
DialogButton,
DialogFooter,
DialogHeader,
DialogShell,
DialogTile,
FooterSpacer,
NEUTRAL_TINT,
} from '../shared/DialogShell';
import { Tooltip } from '../shared/Tooltip';
import { isVisitProposal, planField, proposalNote } from './assistantPlanFieldsModel';
import { useAssistantView } from './assistantViewContext';
const AssistantPlaceProposal = lazy(() => import('./AssistantPlaceProposal'));
interface ProposalEditProps {
preview: AssistantChangePreview;
args?: unknown;
edits: AssistantPlanEdits | undefined;
disabled: boolean;
onEdit: (patch: AssistantPlanEdits) => void;
}
export default function AssistantPlanFields({ preview, args, edits, disabled, onEdit }: ProposalEditProps) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
return (
<>
<Tooltip label={t('common.edit')} disabled={disabled}>
<button
type="button"
aria-label={t('common.edit')}
aria-haspopup="dialog"
disabled={disabled}
onClick={() => setOpen(true)}
className="relative grid h-8 w-8 shrink-0 place-items-center self-start rounded-lg text-content-muted transition-colors focus-visible:ring-2 focus-visible:ring-accent enabled:hover:bg-accent enabled:hover:text-accent-text disabled:opacity-50 [@media(pointer:coarse)]:before:absolute [@media(pointer:coarse)]:before:-inset-1.5"
>
<Pencil size={14} aria-hidden="true" />
</button>
</Tooltip>
{open &&
(isVisitProposal(preview) ? (
<Suspense fallback={null}>
<AssistantPlaceProposal
preview={preview}
args={args}
edits={edits}
disabled={disabled}
onEdit={onEdit}
onClose={() => setOpen(false)}
/>
</Suspense>
) : (
<DayNoteEditDialog
preview={preview}
edits={edits}
disabled={disabled}
onEdit={onEdit}
onClose={() => setOpen(false)}
/>
))}
</>
);
}
function DayNoteEditDialog({ preview, edits, disabled, onEdit, onClose }: ProposalEditProps & { onClose: () => void }) {
const { t } = useTranslation();
const { tripId } = useAssistantView();
const { toolCallId } = preview;
const previewPlanEdit = useAssistantStore((s) => s.previewPlanEdit);
const id = useId();
const [draft, setDraft] = useState<AssistantPlanEdits>(() => edits ?? {});
const change = (patch: AssistantPlanEdits) => setDraft((current) => ({ ...current, ...patch }));
const note = proposalNote(preview, draft);
const noteTitle = draft.noteTitle ?? planField(preview, 'title') ?? preview.subject;
useEffect(() => previewPlanEdit(tripId, toolCallId, draft), [draft, previewPlanEdit, toolCallId, tripId]);
useEffect(() => () => previewPlanEdit(tripId, toolCallId, null), [previewPlanEdit, toolCallId, tripId]);
const noteLabel = t('assistant.change.label.content');
const save = () => {
if (Object.keys(draft).length > 0) onEdit(draft);
onClose();
};
return (
<DialogShell
labelledBy={id}
width="narrow"
onClose={onClose}
header={
<DialogHeader
labelId={id}
tint={NEUTRAL_TINT}
tile={
<DialogTile>
<Pencil size={19} aria-hidden="true" />
</DialogTile>
}
eyebrow={t('common.edit')}
titleInput={{
label: t('assistant.change.label.title'),
value: noteTitle,
required: true,
maxLength: 500,
readOnly: disabled,
onChange: (noteTitle) => change({ noteTitle }),
}}
onClose={onClose}
/>
}
footer={
<DialogFooter>
<FooterSpacer />
<DialogButton onClick={onClose}>{t('common.cancel')}</DialogButton>
<DialogButton
variant="primary"
icon={<Check size={15} aria-hidden="true" />}
onClick={save}
disabled={disabled || !noteTitle.trim()}
>
{t('common.save')}
</DialogButton>
</DialogFooter>
}
>
<fieldset disabled={disabled} className={`${PANEL} m-0 min-w-0`}>
<EditorField label={noteLabel} htmlFor={`${id}-note`}>
<textarea
id={`${id}-note`}
className={TEXTAREA}
rows={4}
maxLength={2000}
value={note ?? ''}
onChange={(e) => change({ noteBody: e.target.value || null })}
/>
</EditorField>
</fieldset>
</DialogShell>
);
}
@@ -7,7 +7,7 @@
*/ */
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { render, screen } from '../../../tests/helpers/render'; import { fireEvent, render, screen } from '../../../tests/helpers/render';
import AssistantSources from './AssistantSources'; import AssistantSources from './AssistantSources';
import { messageBlocks } from './assistantParts'; import { messageBlocks } from './assistantParts';
@@ -31,7 +31,8 @@ describe('AssistantSources', () => {
expect(screen.getByRole('link', { name: 'example.org' })).toBeInTheDocument(); expect(screen.getByRole('link', { name: 'example.org' })).toBeInTheDocument();
}); });
it('FE-AI-SOURCES-002: an answer keeps its sources as a block of their own after its text', () => { it('FE-AI-SOURCES-002: bundles citations from multiple steps below the changes and keeps links with JSON titles', () => {
const exa = 'https://exa.ai/library/places?example=test';
const blocks = messageBlocks( const blocks = messageBlocks(
{ {
id: 'm1', id: 'm1',
@@ -40,12 +41,46 @@ describe('AssistantSources', () => {
createdAt: '2026-10-23T10:00:00.000Z', createdAt: '2026-10-23T10:00:00.000Z',
parts: [ parts: [
{ type: 'tool-call', toolCallId: 'web-1', toolName: 'web_search', args: { query: 'x' }, result: 'searched' }, { type: 'tool-call', toolCallId: 'web-1', toolName: 'web_search', args: { query: 'x' }, result: 'searched' },
{
type: 'data-trek-sources',
data: {
sources: [
{ url: 'https://a.example', title: 'https://a.example' },
{ url: exa, title: '{"places":[{"id":"truncated' },
],
},
},
{ type: 'text', text: 'Eat at the harbour.' }, { type: 'text', text: 'Eat at the harbour.' },
{ type: 'data-trek-sources', data: { sources: [{ url: 'https://a.example', title: 'A' }] } }, { type: 'tool-call', toolCallId: 'w1', toolName: 'create_todo', args: {}, approval: { id: 'w1' } },
{ type: 'data-trek-sources', data: { sources: [{ url: 'https://a.example', title: 'Harbour guide' }] } },
], ],
}, },
false false
); );
expect(blocks.map((block) => block.kind)).toEqual(['steps', 'text', 'sources']); expect(blocks.map((block) => block.kind)).toEqual(['steps', 'text', 'change', 'sources']);
const sources = blocks.find((block) => block.kind === 'sources')?.sources;
expect(sources).toEqual([
{ url: 'https://a.example', title: 'Harbour guide' },
{ url: exa, title: '' },
]);
render(<AssistantSources sources={sources ?? []} />);
expect(screen.getByRole('link', { name: 'exa.ai' })).toHaveAttribute('href', exa);
});
it('shows three links by default and lets the reader expand and collapse the list', () => {
render(
<AssistantSources
sources={['One', 'Two', 'Three', 'Four'].map((title) => ({ title, url: `https://example.org/${title}` }))}
/>
);
expect(screen.getAllByRole('link')).toHaveLength(3);
const more = screen.getByRole('button', { name: 'More sources' });
expect(more).toHaveAttribute('aria-expanded', 'false');
fireEvent.click(more);
expect(screen.getAllByRole('link')).toHaveLength(4);
const less = screen.getByRole('button', { name: 'Show less' });
expect(less).toHaveAttribute('aria-expanded', 'true');
fireEvent.click(less);
expect(screen.getAllByRole('link')).toHaveLength(3);
}); });
}); });
@@ -1,7 +1,11 @@
import type { AssistantSources as Sources } from '@trek/shared'; import type { AssistantSources as Sources } from '@trek/shared';
import { Globe } from 'lucide-react'; import { ChevronDown, Globe } from 'lucide-react';
import { useId, useState } from 'react';
import { useTranslation } from '../../i18n'; import { useTranslation } from '../../i18n';
import { Tooltip } from '../shared/Tooltip';
const INITIAL_COUNT = 3;
/** A page's host without "www.", as the chip names it; the whole address where it does not read as one. */ /** A page's host without "www.", as the chip names it; the whole address where it does not read as one. */
function hostOf(url: string): string { function hostOf(url: string): string {
@@ -19,30 +23,48 @@ function hostOf(url: string): string {
*/ */
export default function AssistantSources({ sources }: { sources: Sources['sources'] }) { export default function AssistantSources({ sources }: { sources: Sources['sources'] }) {
const { t } = useTranslation(); const { t } = useTranslation();
const id = useId();
const [expanded, setExpanded] = useState(false);
const visible = expanded ? sources : sources.slice(0, INITIAL_COUNT);
return ( return (
<nav aria-label={t('assistant.sources.title')} className="flex flex-col gap-1.5"> <nav aria-label={t('assistant.sources.title')} className="flex flex-col gap-1.5">
<span className="font-geist text-caption font-bold uppercase tracking-[.08em] text-content-faint"> <span className="font-geist text-caption font-bold uppercase tracking-[.08em] text-content-faint">
{t('assistant.sources.title')} {t('assistant.sources.title')}
</span> </span>
<ul className="m-0 flex list-none flex-wrap gap-1.5 p-0"> <ul id={id} className="m-0 flex list-none flex-wrap gap-1.5 p-0">
{sources.map((source) => ( {visible.map(({ url, title }) => {
<li key={source.url} className="min-w-0 max-w-full"> const host = hostOf(url);
<a const label = title && title !== url ? title : host;
href={source.url} return (
target="_blank" <li key={url} className="min-w-0 max-w-full">
rel="noopener noreferrer nofollow" <Tooltip label={label} placement="top">
title={source.title} <a
className="flex min-w-0 max-w-[16rem] items-center gap-1.5 rounded-full border border-edge-faint bg-surface-secondary px-2.5 py-1 text-caption text-content-secondary no-underline transition-colors hover:bg-surface-hover hover:text-content" href={url}
> target="_blank"
<Globe size={11} strokeWidth={2.2} aria-hidden="true" className="flex-none text-content-faint" /> rel="noopener noreferrer nofollow"
<span className="flex-none font-medium">{hostOf(source.url)}</span> className="flex min-w-0 max-w-[18rem] items-center gap-1.5 rounded-full border border-edge-faint bg-surface-secondary px-2.5 py-1 text-caption no-underline transition-colors hover:bg-surface-hover focus-visible:ring-2 focus-visible:ring-accent"
{source.title && source.title !== source.url && ( >
<bdi className="min-w-0 truncate text-content-muted">{source.title}</bdi> <Globe size={11} strokeWidth={2.2} aria-hidden="true" className="flex-none text-content-faint" />
)} <bdi className="min-w-0 truncate font-semibold text-content">{label}</bdi>
</a> {label !== host && <bdi className="max-w-[35%] shrink-0 truncate text-content-muted">{host}</bdi>}
</li> </a>
))} </Tooltip>
</li>
);
})}
</ul> </ul>
{sources.length > INITIAL_COUNT && (
<button
type="button"
aria-expanded={expanded}
aria-controls={id}
onClick={() => setExpanded(!expanded)}
className="inline-flex min-h-7 items-center gap-1 self-start rounded-md px-1.5 text-caption font-medium text-content-muted transition-colors hover:bg-surface-hover hover:text-content focus-visible:ring-2 focus-visible:ring-accent"
>
{t(expanded ? 'common.showLess' : 'assistant.sources.more')}
<ChevronDown size={13} aria-hidden="true" className={expanded ? 'rotate-180' : ''} />
</button>
)}
</nav> </nav>
); );
} }
@@ -2,8 +2,9 @@ import { ChevronRight } from 'lucide-react';
import { useState } from 'react'; import { useState } from 'react';
import { useTranslation } from '../../i18n'; import { useTranslation } from '../../i18n';
import { POI_CATEGORIES } from '../Map/poiCategories';
import AssistantLiveStep from './AssistantLiveStep'; import AssistantLiveStep from './AssistantLiveStep';
import { toolStepKey } from './assistantModel'; import { liveStepText } from './assistantModel';
import type { ToolStep } from './assistantParts'; import type { ToolStep } from './assistantParts';
/** /**
@@ -37,9 +38,20 @@ export default function AssistantToolSteps({ steps }: { steps: ToolStep[] }) {
</button> </button>
{open && ( {open && (
<ul className="m-0 mt-1 list-none space-y-0.5 border-s border-edge-faint ps-3"> <ul className="m-0 mt-1 list-none space-y-0.5 border-s border-edge-faint ps-3">
{steps.map((step) => ( {steps.map((step) => {
<li key={step.toolCallId}>{t(toolStepKey(step.toolName))}</li> const labels = step.categories?.flatMap((key) => {
))} const category = POI_CATEGORIES.find((entry) => entry.key === key);
return category ? [t(category.labelKey)] : [];
});
const { key, params } = labels?.length
? { key: 'assistant.step.searchingFor', params: { query: labels.join(', ') } }
: liveStepText(step.toolName, step.query ?? null);
return (
<li key={step.toolCallId} dir="auto" className="break-words">
{t(key, params)}
</li>
);
})}
</ul> </ul>
)} )}
</div> </div>
@@ -170,12 +170,18 @@ describe('AssistantWindow', () => {
it('FE-AI-WIN-014: minimized outside a trip, the round button brings the home chat back', () => { it('FE-AI-WIN-014: minimized outside a trip, the round button brings the home chat back', () => {
seed({ open: true, minimized: true }); seed({ open: true, minimized: true });
render(<AssistantWindow trip={null} />); render(<AssistantWindow trip={null} />, { initialEntries: ['/atlas'] });
expect(screen.getByText('chat 0 Your travels')).not.toBeVisible(); expect(screen.getByText('chat 0 Your travels')).not.toBeVisible();
fireEvent.click(screen.getByRole('button', { name: 'Assistant' })); fireEvent.click(screen.getByRole('button', { name: 'Assistant' }));
expect(useAssistantStore.getState().window.minimized).toBe(false); expect(useAssistantStore.getState().window.minimized).toBe(false);
}); });
it('hides the minimized launcher on the dashboard', () => {
seed({ open: true, minimized: true });
render(<AssistantWindow trip={null} />);
expect(screen.queryByRole('button', { name: 'Assistant' })).not.toBeInTheDocument();
});
it('FE-AI-WIN-005: closed while writing, the chat stays mounted and the round button breathes until it is opened', () => { it('FE-AI-WIN-005: closed while writing, the chat stays mounted and the round button breathes until it is opened', () => {
seed({ open: true, minimized: true }, true); seed({ open: true, minimized: true }, true);
render(<AssistantWindow trip={TRIP} />); render(<AssistantWindow trip={TRIP} />);
@@ -1,7 +1,7 @@
import './assistant.css'; import './assistant.css';
import { type CSSProperties, type KeyboardEvent, useCallback, useEffect, useRef, useState } from 'react'; import { type CSSProperties, type KeyboardEvent, useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router'; import { useMatch, useNavigate } from 'react-router';
import type { WindowRect } from '../../hooks/useDragResize'; import type { WindowRect } from '../../hooks/useDragResize';
import { useTranslation } from '../../i18n'; import { useTranslation } from '../../i18n';
@@ -200,6 +200,7 @@ function windowChat(
export default function AssistantWindow({ trip, onOpen, onFocusDay, onRevealMap }: AssistantWindowProps) { export default function AssistantWindow({ trip, onOpen, onFocusDay, onRevealMap }: AssistantWindowProps) {
const navigate = useNavigate(); const navigate = useNavigate();
const onDashboard = useMatch('/') !== null;
const available = useAssistantStore((s) => s.status?.available === true); const available = useAssistantStore((s) => s.status?.available === true);
const open = useAssistantStore((s) => s.window.open); const open = useAssistantStore((s) => s.window.open);
const minimized = useAssistantStore((s) => s.window.minimized); const minimized = useAssistantStore((s) => s.window.minimized);
@@ -267,8 +268,9 @@ export default function AssistantWindow({ trip, onOpen, onFocusDay, onRevealMap
onOpenTripChat={atHome ? home.openTripChat : undefined} onOpenTripChat={atHome ? home.openTripChat : undefined}
tripSwitch={tripSwitch} tripSwitch={tripSwitch}
/> />
{/* Hidden while an answer may still come in: the round button brings it back, on any page. */} {minimized && (!onDashboard || !!routeChat) && (
{minimized && <AssistantLauncher variant="floating" tripId={launcherTrip} focusOnMount />} <AssistantLauncher variant="floating" tripId={launcherTrip} focusOnMount />
)}
</> </>
); );
} }
@@ -118,6 +118,20 @@ const ERRORS: Record<AssistantErrorCode, AssistantErrorView> = {
/** The limits a provider sets; the line names the provider instead of guessing at its plan. */ /** The limits a provider sets; the line names the provider instead of guessing at its plan. */
const PROVIDER_LIMITS: ReadonlySet<AssistantErrorCode> = new Set(['rate_limited', 'usage_limit']); const PROVIDER_LIMITS: ReadonlySet<AssistantErrorCode> = new Set(['rate_limited', 'usage_limit']);
/** A route produced for the latest question can still be inspected after an interrupted answer. */
export function hasCurrentTourProposal(messages: readonly AssistantMessage[]): boolean {
for (let index = messages.length - 1; index >= 0; index--) {
const message = messages[index];
if (!message || message.role === 'user') break;
const hasRoute = message.parts.some((part) => {
const card = part.type === 'data-trek-card' ? part.data.card : null;
return card?.kind === 'tourRoute' && card.source === 'proposal' && card.routed;
});
if (hasRoute) return true;
}
return false;
}
/** /**
* The line an error shows and its one action. The daily limit only offers * The line an error shows and its one action. The daily limit only offers
* connecting an own provider where the policy allows one. A provider's limit * connecting an own provider where the policy allows one. A provider's limit
@@ -126,10 +140,13 @@ const PROVIDER_LIMITS: ReadonlySet<AssistantErrorCode> = new Set(['rate_limited'
*/ */
export function errorView( export function errorView(
code: AssistantErrorCode, code: AssistantErrorCode,
opts: { canConnectOwn: boolean; provider?: string } opts: { canConnectOwn: boolean; provider?: string; hasTourProposal?: boolean }
): AssistantErrorView { ): AssistantErrorView {
const view = ERRORS[code]; const view = ERRORS[code];
if (code === 'daily_limit' && !opts.canConnectOwn) return { ...view, action: null }; if (code === 'daily_limit' && !opts.canConnectOwn) return { ...view, action: null };
if (code === 'rate_limited' && opts.provider && opts.hasTourProposal) {
return { ...view, messageKey: 'assistant.error.providerLimitAfterRoute' };
}
if (PROVIDER_LIMITS.has(code) && opts.provider) return { ...view, messageKey: 'assistant.error.providerLimit' }; if (PROVIDER_LIMITS.has(code) && opts.provider) return { ...view, messageKey: 'assistant.error.providerLimit' };
return view; return view;
} }
@@ -98,6 +98,27 @@ describe('messageBlocks', () => {
expect(messageBlocks(message(parts), false)[0]).toMatchObject({ steps: [{ running: false }] }); expect(messageBlocks(message(parts), false)[0]).toMatchObject({ steps: [{ running: false }] });
}); });
it('keeps the query and categories of completed searches for their step labels', () => {
const searches = [
{ toolCallId: 'r1', toolName: 'search_place', args: { query: ' Hachikō\n statue ' } },
{ toolCallId: 'r2', toolName: 'search_places_via_plugins', args: { query: 'Shibuya Sky' } },
{ toolCallId: 'r3', toolName: 'search_pois', args: { category: ['restaurant', 'cafe'] } },
];
const parts = searches.map((search): AssistantMessagePart => ({
...search,
type: 'tool-call',
result: 'searched',
}));
expect(messageBlocks(message(parts), false)[0]).toMatchObject({
kind: 'steps',
steps: [
{ toolCallId: 'r1', query: 'Hachikō statue', running: false },
{ toolCallId: 'r2', query: 'Shibuya Sky', running: false },
{ toolCallId: 'r3', categories: ['restaurant', 'cafe'], running: false },
],
});
});
it('FE-AI-PARTS-003: the changes of one step share a card, each with its preview, wherever the preview sits', () => { it('FE-AI-PARTS-003: the changes of one step share a card, each with its preview, wherever the preview sits', () => {
const blocks = messageBlocks( const blocks = messageBlocks(
message([ message([
@@ -1,5 +1,6 @@
import { import {
ASSISTANT_FOLLOW_UPS_TOOL, ASSISTANT_FOLLOW_UPS_TOOL,
assistantSourceTitle,
type AssistantApplied, type AssistantApplied,
type AssistantChangeEffect, type AssistantChangeEffect,
type AssistantChangeLabelKey, type AssistantChangeLabelKey,
@@ -39,6 +40,8 @@ export interface ToolStep {
toolName: string; toolName: string;
/** Still waiting for its result while the answer is being written. */ /** Still waiting for its result while the answer is being written. */
running: boolean; running: boolean;
query?: string;
categories?: string[];
} }
/** /**
@@ -50,6 +53,7 @@ export type ChangeState = 'pending' | 'applying' | 'applied' | 'failed' | 'disca
export interface ChangeItem { export interface ChangeItem {
toolCallId: string; toolCallId: string;
args?: unknown;
/** What the card says about it; null until the preview arrived. */ /** What the card says about it; null until the preview arrived. */
preview: AssistantChangePreview | null; preview: AssistantChangePreview | null;
/** The receipt of an applied change. */ /** The receipt of an applied change. */
@@ -269,6 +273,7 @@ function changeItemOf(
const applied = receipts.get(part.toolCallId) ?? null; const applied = receipts.get(part.toolCallId) ?? null;
return { return {
toolCallId: part.toolCallId, toolCallId: part.toolCallId,
...(preview?.verbKey === 'addPlaceToDay' || preview?.verbKey === 'assignPlace' ? { args: part.args } : {}),
preview, preview,
applied, applied,
state: changeState(part, applied), state: changeState(part, applied),
@@ -295,8 +300,8 @@ function changeState(part: ToolCallPart, applied: AssistantApplied | null): Chan
* The places of all its searches join into one strip where the newest search * The places of all its searches join into one strip where the newest search
* sat, each place once, without the ones a change the model proposed in the * sat, each place once, without the ones a change the model proposed in the
* answer already holds; the weather of all steps joins * answer already holds; the weather of all steps joins
* into one row where the first look sat. A strip does not split the steps * into one row where the first look sat. The sources of all steps sit together
* around it: a step after it joins the row of steps before it. * at the end of the answer.
* *
* A reading tool's card joins the cards block of its group (by `rules`, the * A reading tool's card joins the cards block of its group (by `rules`, the
* kinds' looks unless a test hands others) when only steps lie between them; * kinds' looks unless a test hands others) when only steps lie between them;
@@ -311,6 +316,7 @@ export function messageBlocks(
const previews = new Map<string, AssistantChangePreview>(); const previews = new Map<string, AssistantChangePreview>();
const receipts = new Map<string, AssistantApplied>(); const receipts = new Map<string, AssistantApplied>();
const cards = new Map<string, TrekCard>(); const cards = new Map<string, TrekCard>();
const sources = new Map<string, AssistantSources['sources'][number]>();
const changeIds = new Set<string>(); const changeIds = new Set<string>();
const effects: AssistantChangeEffect[] = []; const effects: AssistantChangeEffect[] = [];
// A place the user suggested from the strip stays on it, marked as suggested. // A place the user suggested from the strip stays on it, marked as suggested.
@@ -324,6 +330,11 @@ export function messageBlocks(
previews.set(part.data.toolCallId, part.data); previews.set(part.data.toolCallId, part.data);
if (part.data.effect && !fromStrip.has(part.data.toolCallId)) effects.push(part.data.effect); if (part.data.effect && !fromStrip.has(part.data.toolCallId)) effects.push(part.data.effect);
changeIds.add(part.data.toolCallId); changeIds.add(part.data.toolCallId);
} else if (part.type === 'data-trek-sources') {
for (const { url, title } of part.data.sources) {
const previous = sources.get(url);
if (!previous?.title || previous.title === url) sources.set(url, { url, title: assistantSourceTitle(title) });
}
} else if (part.type === 'data-trek-applied') receipts.set(part.data.toolCallId, part.data); } else if (part.type === 'data-trek-applied') receipts.set(part.data.toolCallId, part.data);
else if (part.type === 'data-trek-places') lastPlaces = index; else if (part.type === 'data-trek-places') lastPlaces = index;
else if (part.type === 'data-trek-weather' && firstWeather < 0) firstWeather = index; else if (part.type === 'data-trek-weather' && firstWeather < 0) firstWeather = index;
@@ -335,6 +346,9 @@ export function messageBlocks(
const changeCards = message.parts.flatMap((p) => (p.type === 'data-trek-change' && p.data.card ? [p.data.card] : [])); const changeCards = message.parts.flatMap((p) => (p.type === 'data-trek-change' && p.data.card ? [p.data.card] : []));
const placesHidden = const placesHidden =
[...cards.values(), ...changeCards].some((card) => rules.hidesFoundPlaces?.(card) === true) || [...cards.values(), ...changeCards].some((card) => rules.hidesFoundPlaces?.(card) === true) ||
[...previews.values()].some(
(preview) => preview.verbKey === 'addPlaceToDay' || preview.verbKey === 'assignPlace'
) ||
message.parts.some((p) => p.type === 'tool-call' && TOUR_PLANNING_TOOLS.has(p.toolName)); message.parts.some((p) => p.type === 'tool-call' && TOUR_PLANNING_TOOLS.has(p.toolName));
const blocks: MessageBlock[] = []; const blocks: MessageBlock[] = [];
message.parts.forEach((part, index) => { message.parts.forEach((part, index) => {
@@ -347,10 +361,6 @@ export function messageBlocks(
if (strip) blocks.push(strip); if (strip) blocks.push(strip);
return; return;
} }
if (part.type === 'data-trek-sources') {
blocks.push({ kind: 'sources', key: `sources-${index}`, sources: part.data.sources });
return;
}
if (part.type === 'data-trek-weather' && index === firstWeather) { if (part.type === 'data-trek-weather' && index === firstWeather) {
blocks.push({ kind: 'weather', key: `weather-${index}`, days: weatherDays(message.parts) }); blocks.push({ kind: 'weather', key: `weather-${index}`, days: weatherDays(message.parts) });
return; return;
@@ -373,18 +383,35 @@ export function messageBlocks(
blocks.push({ kind: 'remembered', key: `remembered-${part.toolCallId}`, note }); blocks.push({ kind: 'remembered', key: `remembered-${part.toolCallId}`, note });
return; return;
} }
const step: ToolStep = { const step = toolStep(part, writing);
toolCallId: part.toolCallId,
toolName: part.toolName,
running: writing && part.result === undefined,
};
const steps = openSteps(blocks); const steps = openSteps(blocks);
if (steps) steps.steps.push(step); if (steps) steps.steps.push(step);
else blocks.push({ kind: 'steps', key: `steps-${part.toolCallId}`, steps: [step] }); else blocks.push({ kind: 'steps', key: `steps-${part.toolCallId}`, steps: [step] });
}); });
if (sources.size > 0) blocks.push({ kind: 'sources', key: 'sources', sources: [...sources.values()] });
return withoutYielded(blocks, rules); return withoutYielded(blocks, rules);
} }
function toolStep(part: ToolCallPart, writing: boolean): ToolStep {
const { toolCallId, toolName, args } = part;
const step = { toolCallId, toolName, running: writing && part.result === undefined };
if (!args || typeof args !== 'object') return step;
if (toolName === 'search_place' || toolName === 'search_places_via_plugins' || toolName === 'web_search') {
const { query } = args as { query?: unknown };
if (typeof query === 'string' && query.trim()) {
return { ...step, query: query.trim().replace(/\s+/g, ' ').slice(0, 200) };
}
}
if (toolName === 'search_pois') {
const { category } = args as { category?: unknown };
const categories = (Array.isArray(category) ? category : [category])
.filter((entry): entry is string => typeof entry === 'string')
.slice(0, 8);
if (categories.length) return { ...step, categories };
}
return step;
}
/** /**
* Whether "+ Day" was already pressed on this found place in the answer: a * Whether "+ Day" was already pressed on this found place in the answer: a
* suggestion from the strip names the trip's place by its id, a new one by * suggestion from the strip names the trip's place by its id, a new one by
@@ -477,6 +504,10 @@ export const CHANGE_LABELS: Record<AssistantChangeLabelKey, { labelKey: string }
*/ */
export function tailStart(blocks: MessageBlock[]): number { export function tailStart(blocks: MessageBlock[]): number {
let i = blocks.length; let i = blocks.length;
while (i > 0 && (blocks[i - 1].kind === 'text' || blocks[i - 1].kind === 'change')) i -= 1; while (
i > 0 &&
(blocks[i - 1].kind === 'text' || blocks[i - 1].kind === 'change' || blocks[i - 1].kind === 'sources')
)
i -= 1;
return i; return i;
} }
@@ -0,0 +1,27 @@
import type { AssistantChangeLabelKey, AssistantChangePreview, AssistantPlanEdits } from '@trek/shared';
export function isVisitProposal(preview: AssistantChangePreview | null | undefined) {
return preview?.verbKey === 'addPlaceToDay' || preview?.verbKey === 'assignPlace';
}
export function isDayNoteProposal(preview: AssistantChangePreview | null | undefined) {
return preview?.verbKey === 'addDayNote' || preview?.verbKey === 'updateDayNote';
}
export function planField(preview: AssistantChangePreview, field: AssistantChangeLabelKey) {
return preview.rows.find((row) => row.labelKey === field)?.after;
}
function dayNoteBody(preview: AssistantChangePreview) {
return planField(preview, 'content') ?? (preview.verbKey === 'addDayNote' ? planField(preview, 'time') : undefined);
}
export function proposalNote(preview: AssistantChangePreview, edits: AssistantPlanEdits | undefined) {
return isVisitProposal(preview)
? edits?.notes === undefined
? planField(preview, 'notes')
: edits.notes
: edits?.noteBody === undefined
? dayNoteBody(preview)
: edits.noteBody;
}
@@ -1,13 +1,16 @@
import type { AssistantChangePreview, TrekCardKind } from '@trek/shared'; import type { AssistantChangePreview, AssistantPlanEdits, TrekCardKind } from '@trek/shared';
import { Check, Undo2 } from 'lucide-react'; import { Check, Paperclip, Undo2 } from 'lucide-react';
import { Fragment, type ReactNode } from 'react'; import { Fragment, type ReactNode } from 'react';
import { useTranslation } from '../../../i18n'; import { useTranslation } from '../../../i18n';
import { Tooltip } from '../../shared/Tooltip'; import { Tooltip } from '../../shared/Tooltip';
import AssistantChangeFields from '../AssistantChangeFields'; import AssistantChangeFields from '../AssistantChangeFields';
import type { ChangeItem } from '../assistantParts'; import type { ChangeItem } from '../assistantParts';
import AssistantPlanFields from '../AssistantPlanFields';
import { isDayNoteProposal, isVisitProposal, planField, proposalNote } from '../assistantPlanFieldsModel';
import { useAssistantView } from '../assistantViewContext'; import { useAssistantView } from '../assistantViewContext';
import { useChangeHover } from '../useChangeHover'; import { useChangeHover } from '../useChangeHover';
import { isSingleBookingDraft } from './booking/bookingCardModel';
import { TOOL_LABELS, verbLookOf } from './cardLooks'; import { TOOL_LABELS, verbLookOf } from './cardLooks';
import type { CardView } from './cardTypes'; import type { CardView } from './cardTypes';
import { viewOf } from './cardViews'; import { viewOf } from './cardViews';
@@ -140,6 +143,11 @@ function BodySlot({ item, settled }: { item: ChangeItem; settled: boolean }) {
); );
} }
function inlineBookingCard(item: ChangeItem): boolean {
const card = item.card;
return card?.kind === 'booking' && isSingleBookingDraft(card);
}
/** A decided change that no longer stands: discarded, expired or taken back. */ /** A decided change that no longer stands: discarded, expired or taken back. */
const settledOf = (item: ChangeItem, undone: boolean) => const settledOf = (item: ChangeItem, undone: boolean) =>
item.state === 'discarded' || item.state === 'expired' || undone; item.state === 'discarded' || item.state === 'expired' || undone;
@@ -164,11 +172,21 @@ function Receipt({
const settled = settledOf(item, undone); const settled = settledOf(item, undone);
const statusLabel = t(undone ? 'assistant.change.undone' : receipt.labelKey); const statusLabel = t(undone ? 'assistant.change.undone' : receipt.labelKey);
const view = item.card ? viewOf(item.card) : null; const view = item.card ? viewOf(item.card) : null;
const inlineBooking = inlineBookingCard(item);
return ( return (
<div className="trek-assistant-enter flex items-center gap-2.5 py-1.5"> <div className="trek-assistant-enter flex items-center gap-2.5 py-1.5">
<Lead item={item} view={view} dimmed={settled} /> {!inlineBooking && <Lead item={item} view={view} dimmed={settled} />}
<div className={`min-w-0 flex-1 ${settled ? 'opacity-60' : ''}`}> <div className={`min-w-0 flex-1 ${settled ? 'opacity-60' : ''}`}>
<ChangeHead item={item} view={view} struck={settled} /> {inlineBooking ? (
<Slot
name="Body"
item={item}
view={view}
fallback={<ChangeHead item={item} view={view} struck={settled} />}
/>
) : (
<ChangeHead item={item} view={view} struck={settled} />
)}
</div> </div>
{applied && <EntityActions applied={applied} card={item.card} />} {applied && <EntityActions applied={applied} card={item.card} />}
{canUndo && ( {canUndo && (
@@ -203,67 +221,134 @@ function PendingRow({
withChoice, withChoice,
disabled, disabled,
onToggle, onToggle,
edits,
onEdit,
groupedDay,
}: { }: {
item: ChangeItem; item: ChangeItem;
excluded: boolean; excluded: boolean;
withChoice: boolean; withChoice: boolean;
disabled: boolean; disabled: boolean;
onToggle: () => void; onToggle: () => void;
edits: AssistantPlanEdits | undefined;
onEdit: (patch: AssistantPlanEdits) => void;
groupedDay: boolean;
}) { }) {
const { t } = useTranslation(); const { t } = useTranslation();
const { tripId } = useAssistantView(); const { tripId } = useAssistantView();
const { litFromMap, handlers } = useChangeHover(tripId, item.preview?.effect ? item.toolCallId : null); const { litFromMap, handlers } = useChangeHover(tripId, item.preview?.effect ? item.toolCallId : null);
const preview = item.preview; const preview = item.preview;
const view = item.card ? viewOf(item.card) : null; const view = item.card ? viewOf(item.card) : null;
const aside = <Slot item={item} view={view} name="Aside" />; const inlineBooking = inlineBookingCard(item);
const editable = preview && (isVisitProposal(preview) || isDayNoteProposal(preview));
return ( return (
<div <div
{...handlers} {...handlers}
className={`-mx-1.5 flex items-center gap-2.5 rounded-[12px] px-1.5 py-2 transition-[opacity,background-color] ${ className={`-mx-1.5 flex ${inlineBooking ? 'items-start' : 'items-center'} gap-2.5 rounded-[12px] px-1.5 py-2 transition-[opacity,background-color] ${
excluded ? 'opacity-50' : '' excluded ? 'opacity-50' : ''
} ${litFromMap ? 'bg-surface-hover' : 'hover:bg-surface-hover'}`} } ${litFromMap ? 'bg-surface-hover' : 'hover:bg-surface-hover'}`}
> >
{withChoice && ( {withChoice ? (
<button <Tooltip label={t('assistant.change.include')}>
type="button" <button
onClick={onToggle} type="button"
disabled={disabled} onClick={onToggle}
aria-pressed={!excluded} disabled={disabled}
aria-label={t('assistant.change.include')} aria-pressed={!excluded}
className={`grid h-[18px] w-[18px] flex-none place-items-center rounded-full outline-none transition-colors focus-visible:ring-2 focus-visible:ring-accent disabled:opacity-50 ${ aria-label={t('assistant.change.include')}
excluded ? 'border-[1.5px] border-edge bg-surface-card' : 'bg-accent' className="relative grid h-8 w-8 flex-none place-items-center rounded-lg outline-none ring-edge transition-shadow before:absolute before:-inset-1.5 before:rounded-xl hover:ring-1 focus-visible:ring-2 focus-visible:ring-accent disabled:cursor-default"
}`} >
> <Lead item={item} view={view} dimmed={excluded} />
{!excluded && <Check size={11} strokeWidth={3} aria-hidden="true" className="text-accent-text" />} {!excluded && (
</button> <span className="pointer-events-none absolute -bottom-0.5 -end-0.5 grid h-3.5 w-3.5 place-items-center rounded-full bg-accent text-accent-text ring-2 ring-surface-card">
)} <Check size={9} strokeWidth={3} aria-hidden="true" />
<Lead item={item} view={view} dimmed={excluded} /> </span>
<div className="min-w-0 flex-1">
{preview ? (
<>
{view?.ownsSubject ? (
aside
) : (
<SubjectLine subject={preview.subject} struck={false} aside={view?.Aside && aside} block />
)} )}
<span className="mt-1 flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-caption text-content-faint"> </button>
<span className="me-0.5 min-w-0 truncate">{verbLabel(preview, t)}</span> </Tooltip>
<DomainChip domain={preview.domain} /> ) : (
{view?.Facts ? ( !inlineBooking && <Lead item={item} view={view} dimmed={excluded} />
<Slot item={item} view={view} name="Facts" fallback={<AssistantChangeFields rows={preview.rows} />} /> )}
) : ( <div className="min-w-0 flex-1">
<AssistantChangeFields rows={preview.rows} /> {inlineBooking ? (
)} <Slot name="Body" item={item} view={view} fallback={<ChangeHead item={item} view={view} struck={false} />} />
</span> ) : preview ? (
</> <PendingDetails item={item} preview={preview} view={view} edits={edits} groupedDay={groupedDay} />
) : ( ) : (
<span className="trek-skeleton inline-block h-4 w-40" aria-hidden="true" /> <span className="trek-skeleton inline-block h-4 w-40" aria-hidden="true" />
)} )}
</div> </div>
{editable && (
<AssistantPlanFields
preview={preview}
args={item.args}
edits={edits}
disabled={disabled || excluded}
onEdit={onEdit}
/>
)}
</div> </div>
); );
} }
function PendingDetails({
item,
preview,
view,
edits,
groupedDay,
}: {
item: ChangeItem;
preview: AssistantChangePreview;
view: View | null;
edits: AssistantPlanEdits | undefined;
groupedDay: boolean;
}) {
const { t } = useTranslation();
const aside = <Slot item={item} view={view} name="Aside" />;
const visit = isVisitProposal(preview);
const dayNote = isDayNoteProposal(preview);
const note = visit || dayNote ? proposalNote(preview, edits) : null;
const receipt = preview.verbKey === 'importBooking' ? planField(preview, 'attachedTo') : undefined;
const rows = preview.rows.filter(
(row) => !(groupedDay && row.labelKey === 'day') && !(dayNote && row.labelKey === 'time')
);
return (
<>
{view?.ownsSubject ? (
aside
) : (
<SubjectLine
subject={edits?.place?.name ?? edits?.noteTitle ?? preview.subject}
struck={false}
aside={view?.Aside && aside}
block
/>
)}
<span className="mt-1 flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-caption text-content-faint">
{!visit && <span className="me-0.5 min-w-0 truncate">{verbLabel(preview, t)}</span>}
<DomainChip domain={preview.domain} />
{view?.Facts ? (
<Slot item={item} view={view} name="Facts" fallback={<AssistantChangeFields rows={preview.rows} />} />
) : (
<AssistantChangeFields rows={rows} visit={visit} edits={edits} />
)}
</span>
{receipt && (
<div
className="mt-1 flex min-w-0 items-center gap-1.5 text-caption text-content-muted"
title={t('assistant.attach.chip.keepWithBooking')}
>
<Paperclip size={13} className="flex-none" aria-hidden="true" />
<span className="sr-only">{t('assistant.attach.chip.keepWithBooking')}</span>
<bdi className="truncate">{receipt}</bdi>
</div>
)}
{note && <bdi className="mt-1 block truncate text-caption text-content-muted">{note}</bdi>}
</>
);
}
interface RowsProps { interface RowsProps {
items: readonly ChangeItem[]; items: readonly ChangeItem[];
/** The waiting rows wait behind the week grid. */ /** The waiting rows wait behind the week grid. */
@@ -274,6 +359,9 @@ interface RowsProps {
undoable: readonly string[]; undoable: readonly string[];
onToggle: (toolCallId: string) => void; onToggle: (toolCallId: string) => void;
onUndo: (toolCallId: string) => void; onUndo: (toolCallId: string) => void;
planEdits: Readonly<Record<string, AssistantPlanEdits>>;
onEdit: (toolCallId: string, patch: AssistantPlanEdits) => void;
groupedDay: boolean;
} }
/** Consecutive changes of one kind of card; a change without a card stands alone. */ /** Consecutive changes of one kind of card; a change without a card stands alone. */
@@ -299,7 +387,19 @@ function runnable(item: ChangeItem, view: View | null): boolean {
* `Group` before and after it, and two or more waiting rows its view can * `Group` before and after it, and two or more waiting rows its view can
* take together are drawn as one `Run` instead. * take together are drawn as one `Run` instead.
*/ */
export function ChangeRows({ items, folded, excluded, disabled, undone, undoable, onToggle, onUndo }: RowsProps) { export function ChangeRows({
items,
folded,
excluded,
disabled,
undone,
undoable,
onToggle,
onUndo,
planEdits,
onEdit,
groupedDay,
}: RowsProps) {
const pendingCount = items.filter((i) => i.state === 'pending').length; const pendingCount = items.filter((i) => i.state === 'pending').length;
// The body stands beside the row, in the same place whether the change waits or is decided, so a body that holds // The body stands beside the row, in the same place whether the change waits or is decided, so a body that holds
// what the user chose (the pages of a book design) keeps it, and draws on, as the change starts to apply. // what the user chose (the pages of a book design) keeps it, and draws on, as the change starts to apply.
@@ -316,6 +416,9 @@ export function ChangeRows({ items, folded, excluded, disabled, undone, undoable
withChoice={pendingCount > 1} withChoice={pendingCount > 1}
disabled={disabled} disabled={disabled}
onToggle={() => onToggle(item.toolCallId)} onToggle={() => onToggle(item.toolCallId)}
edits={planEdits[item.toolCallId]}
onEdit={(patch) => onEdit(item.toolCallId, patch)}
groupedDay={groupedDay}
/> />
) : ( ) : (
<Receipt <Receipt
@@ -325,7 +428,9 @@ export function ChangeRows({ items, folded, excluded, disabled, undone, undoable
onUndo={() => onUndo(item.toolCallId)} onUndo={() => onUndo(item.toolCallId)}
/> />
)} )}
<BodySlot item={item} settled={waiting ? excluded.has(item.toolCallId) : settledOf(item, isUndone)} /> {!inlineBookingCard(item) && (
<BodySlot item={item} settled={waiting ? excluded.has(item.toolCallId) : settledOf(item, isUndone)} />
)}
</Fragment> </Fragment>
); );
}; };
@@ -25,6 +25,7 @@ import { useAuthStore } from '../../../../store/authStore';
import { useSettingsStore } from '../../../../store/settingsStore'; import { useSettingsStore } from '../../../../store/settingsStore';
import type { ChangeItem } from '../../assistantParts'; import type { ChangeItem } from '../../assistantParts';
import { type AssistantView, AssistantViewContext } from '../../assistantViewContext'; import { type AssistantView, AssistantViewContext } from '../../assistantViewContext';
import { ChangeRows } from '../ChangeCardSlots';
import BookingBlock from './BookingBlock'; import BookingBlock from './BookingBlock';
import { BookingChangeBody, BookingChangeFacts } from './BookingChangeSlots'; import { BookingChangeBody, BookingChangeFacts } from './BookingChangeSlots';
@@ -412,4 +413,44 @@ describe('booking cards', () => {
expect(screen.queryByRole('button', { name: 'Open the booking' })).not.toBeInTheDocument(); expect(screen.queryByRole('button', { name: 'Open the booking' })).not.toBeInTheDocument();
expect(screen.getByText('Frankfurt to New York')).toBeInTheDocument(); expect(screen.getByText('Frankfurt to New York')).toBeInTheDocument();
}); });
it.each(['pending', 'failed'] as const)(
'shows a single %s booking as one card with its structured reference',
(state) => {
const card = cardOf([{ ...DINNER, reservationId: null, status: 'confirmed', hasReference: true }], 'create');
const item = changeItem(card);
item.state = state;
if (!item.preview) throw new Error('Booking preview fixture is missing');
item.preview.verbKey = 'addReservation';
item.preview.rows = [
{ op: 'add', labelKey: 'confirmation', before: null, after: 'ABC-12345' },
{ op: 'add', labelKey: 'notes', before: null, after: 'Use the side entrance. Booking code: ABC-12345.' },
];
inView(
<ChangeRows
items={[item]}
folded={false}
excluded={new Set()}
disabled={false}
undone={{}}
undoable={[]}
onToggle={vi.fn()}
onUndo={vi.fn()}
planEdits={{}}
onEdit={vi.fn()}
groupedDay={false}
/>,
{ variant: 'fullscreen', density: 'compact' }
);
const booking = within(screen.getByRole('region', { name: DINNER.title }));
expect(booking.getByText('Add booking')).toHaveClass('uppercase');
expect(screen.getAllByText('Add booking')).toHaveLength(1);
expect(booking.getByText('Start time').closest('dt')?.nextElementSibling).toHaveTextContent('19:00');
expect(booking.getByText('End time').closest('dt')?.nextElementSibling).toHaveTextContent('21:30');
expect(booking.getByText('Confirmed')).toBeInTheDocument();
expect(booking.getByText('Booking Code').closest('dt')?.nextElementSibling).toHaveTextContent('ABC-12345');
expect(booking.getByText('Use the side entrance.')).toBeInTheDocument();
expect(booking.queryByText(/Booking code: ABC-12345/)).toBeNull();
}
);
}); });
@@ -5,7 +5,16 @@ import { useTranslation } from '../../../../i18n';
import { Tooltip } from '../../../shared/Tooltip'; import { Tooltip } from '../../../shared/Tooltip';
import { useAssistantView } from '../../assistantViewContext'; import { useAssistantView } from '../../assistantViewContext';
import type { EntityTarget } from '../cardTypes'; import type { EntityTarget } from '../cardTypes';
import { BookingFooter, BookingHead, StayBody, TicketBody, VenueBody } from './bookingCardParts'; import {
BookingFooter,
BookingHead,
BookingProposalFooter,
StayBody,
StayProposalBody,
TicketBody,
VenueBody,
VenueProposalBody,
} from './bookingCardParts';
import { bookingSpotOf, bookingTarget } from './bookingLook'; import { bookingSpotOf, bookingTarget } from './bookingLook';
/** /**
@@ -88,11 +97,13 @@ export default function BookingCard({
item, item,
card, card,
actions = true, actions = true,
proposal,
}: { }: {
item: BookingItem; item: BookingItem;
card: Card; card: Card;
/** Off inside a change card, whose row has its own ways to the booking. */ /** Off inside a change card, whose row has its own ways to the booking. */
actions?: boolean; actions?: boolean;
proposal?: { label: string; notes?: string; reference?: string; receipt?: string };
}) { }) {
const { t } = useTranslation(); const { t } = useTranslation();
const body = item.body; const body = item.body;
@@ -101,17 +112,33 @@ export default function BookingCard({
aria-label={item.title} aria-label={item.title}
className={`trek-assistant-enter group overflow-hidden rounded-xl border bg-surface-card shadow-card ${FRAME[card.change]}`} className={`trek-assistant-enter group overflow-hidden rounded-xl border bg-surface-card shadow-card ${FRAME[card.change]}`}
> >
<BookingHead item={item} card={card} actions={actions ? <CardActions item={item} /> : null} /> <BookingHead
<div className="px-3 pb-2.5 pt-2"> item={item}
card={card}
actionLabel={proposal?.label}
actions={actions ? <CardActions item={item} /> : null}
/>
<div className={proposal ? 'flex flex-col gap-3 bg-surface-secondary p-3' : 'px-3 pb-2.5 pt-2'}>
{item.tripTitle && ( {item.tripTitle && (
<p className="m-0 mb-1 text-caption text-content-muted"> <p className="m-0 mb-1 text-caption text-content-muted">
{t('assistant.card.booking.inTrip', { trip: item.tripTitle })} {t('assistant.card.booking.inTrip', { trip: item.tripTitle })}
</p> </p>
)} )}
{body.shape === 'ticket' && <TicketBody item={item} body={body} card={card} />} {body.shape === 'ticket' && <TicketBody item={item} body={body} card={card} />}
{body.shape === 'stay' && <StayBody item={item} body={body} card={card} />} {body.shape === 'stay' &&
{body.shape === 'venue' && <VenueBody item={item} body={body} card={card} />} (proposal ? <StayProposalBody body={body} /> : <StayBody item={item} body={body} card={card} />)}
<BookingFooter item={item} card={card} /> {body.shape === 'venue' &&
(proposal ? <VenueProposalBody body={body} /> : <VenueBody item={item} body={body} card={card} />)}
{proposal ? (
<BookingProposalFooter
item={item}
notes={proposal.notes}
reference={proposal.reference}
receipt={proposal.receipt}
/>
) : (
<BookingFooter item={item} card={card} />
)}
</div> </div>
</section> </section>
); );
@@ -1,8 +1,12 @@
import type { TrekCardOf } from '@trek/shared'; import { withoutRepeatedBookingReference, type TrekCardOf } from '@trek/shared';
import { useTranslation } from '../../../../i18n';
import AssistantChangeFields from '../../AssistantChangeFields'; import AssistantChangeFields from '../../AssistantChangeFields';
import type { ChangeItem } from '../../assistantParts'; import type { ChangeItem } from '../../assistantParts';
import { verbLookOf } from '../cardLooks';
import { BookingList } from './BookingBlock'; import { BookingList } from './BookingBlock';
import BookingCard from './BookingCard';
import { isSingleBookingDraft } from './bookingCardModel';
/** /**
* The booking card inside a change row. The row keeps its choice, its tile * The booking card inside a change row. The row keeps its choice, its tile
@@ -17,8 +21,28 @@ interface SlotProps {
item: ChangeItem; item: ChangeItem;
} }
/** The card under the row; the row itself leads to the booking once it is saved. */ /** New single bookings carry their action in the card head. */
export function BookingChangeBody({ card }: SlotProps) { export function BookingChangeBody({ card, item }: SlotProps) {
const { t } = useTranslation();
const booking = card.items[0];
if (booking && isSingleBookingDraft(card)) {
const preview = item.preview;
const reference = preview?.rows.find((row) => row.labelKey === 'confirmation')?.after.trim() || undefined;
const notes = preview?.rows.find((row) => row.labelKey === 'notes')?.after ?? '';
return (
<BookingCard
item={booking}
card={card}
actions={false}
proposal={{
label: t(verbLookOf(preview?.verbKey ?? 'addReservation').labelKey),
notes: withoutRepeatedBookingReference(notes, reference),
reference,
receipt: preview?.rows.find((row) => row.labelKey === 'attachedTo')?.after,
}}
/>
);
}
return <BookingList items={card.items} more={card.more} card={card} actions={false} />; return <BookingList items={card.items} more={card.more} card={card} actions={false} />;
} }
@@ -13,6 +13,10 @@ import type { CardEntry } from '../cardTypes';
/** A status a booking card names in words. */ /** A status a booking card names in words. */
type BookingStatus = NonNullable<BookingItem['status']>; type BookingStatus = NonNullable<BookingItem['status']>;
export function isSingleBookingDraft(card: BookingCard): boolean {
return card.change === 'create' && card.items.length === 1 && card.more === 0;
}
/** /**
* The planner's tone of a booking (its `toneOf`): a transit hop in the info * The planner's tone of a booking (its `toneOf`): a transit hop in the info
* tone, a confirmed booking green, any other (pending, cancelled) amber; none * tone, a confirmed booking green, any other (pending, cancelled) amber; none
@@ -15,6 +15,7 @@ import {
LogOut, LogOut,
MapPin, MapPin,
Moon, Moon,
Paperclip,
Route, Route,
Ticket, Ticket,
Wallet, Wallet,
@@ -23,7 +24,16 @@ import {
import { useRef, type ReactNode } from 'react'; import { useRef, type ReactNode } from 'react';
import { useTranslation } from '../../../../i18n'; import { useTranslation } from '../../../../i18n';
import { ReviewPill, toneColor, toneTint, TypeTile } from '../../../Planner/bookings/bookingParts'; import {
Block,
BOX,
Eyebrow,
fs,
ReviewPill,
toneColor,
toneTint,
TypeTile,
} from '../../../Planner/bookings/bookingParts';
import { typeInfo } from '../../../Planner/bookings/bookingsModel'; import { typeInfo } from '../../../Planner/bookings/bookingsModel';
import { SoftPill, TimePill, type PillTone } from '../../../Planner/planParts'; import { SoftPill, TimePill, type PillTone } from '../../../Planner/planParts';
import { Tooltip } from '../../../shared/Tooltip'; import { Tooltip } from '../../../shared/Tooltip';
@@ -101,13 +111,13 @@ function StayPhoto({ item, body, size, tile }: { item: BookingItem; body: Bookin
} }
/** The lead of the head band: a stay's photo (56, 44 when compact), else the type tile. */ /** The lead of the head band: a stay's photo (56, 44 when compact), else the type tile. */
function HeadLead({ item }: { item: BookingItem }) { function HeadLead({ item, proposal }: { item: BookingItem; proposal: boolean }) {
const { density } = useAssistantView(); const { density } = useAssistantView();
const compact = density === 'compact'; const compact = density === 'compact';
if (item.body.shape === 'stay') { if (item.body.shape === 'stay') {
return <StayPhoto item={item} body={item.body} size={compact ? 44 : 56} tile={compact ? 32 : 40} />; return <StayPhoto item={item} body={item.body} size={compact ? 44 : 56} tile={compact ? 32 : 40} />;
} }
return <TypeTile type={item.type} size={compact ? 24 : 28} />; return <TypeTile type={item.type} size={proposal ? 34 : compact ? 24 : 28} />;
} }
/** /**
@@ -115,22 +125,39 @@ function HeadLead({ item }: { item: BookingItem }) {
* title), the title, the review mark, the status dot and the card's actions, * title), the title, the review mark, the status dot and the card's actions,
* on the tint of the status as on the planner's booking cards. * on the tint of the status as on the planner's booking cards.
*/ */
export function BookingHead({ item, card, actions }: { item: BookingItem; card: Card; actions?: ReactNode }) { export function BookingHead({
item,
card,
actions,
actionLabel,
}: {
item: BookingItem;
card: Card;
actions?: ReactNode;
actionLabel?: string;
}) {
const { t } = useTranslation(); const { t } = useTranslation();
const tone = toneOfItem(item); const tone = toneOfItem(item);
const removed = card.change === 'remove'; const removed = card.change === 'remove';
const address = item.body.shape === 'stay' ? item.body.address : null; const proposal = !!actionLabel;
const address =
item.body.shape === 'stay'
? item.body.address
: proposal && item.body.shape === 'venue'
? item.body.location
: null;
return ( return (
<div <div
className="flex items-center gap-2 border-b border-edge-faint px-3 py-2" className={`flex items-center gap-2.5 border-b border-edge-faint px-3 ${actionLabel ? 'py-3' : 'py-2'}`}
style={{ background: tone ? toneTint(tone) : undefined }} style={{ background: tone ? toneTint(tone) : undefined }}
> >
<HeadLead item={item} /> <HeadLead item={item} proposal={proposal} />
<span className="flex min-w-0 flex-1 flex-col gap-0.5"> <div className="flex min-w-0 flex-1 flex-col gap-0.5">
{actionLabel && <Eyebrow>{actionLabel}</Eyebrow>}
<span className="flex min-w-0 items-center gap-1.5"> <span className="flex min-w-0 items-center gap-1.5">
<bdi <bdi
title={item.title} title={item.title}
className={`line-clamp-2 text-body font-semibold leading-tight text-content ${removed ? 'line-through' : ''}`} className={`line-clamp-2 text-body leading-tight text-content ${proposal ? 'font-bold' : 'font-semibold'} ${removed ? 'line-through' : ''}`}
> >
{item.title} {item.title}
</bdi> </bdi>
@@ -138,19 +165,192 @@ export function BookingHead({ item, card, actions }: { item: BookingItem; card:
{isChanged(card, item, 'title') && <ChangedDot />} {isChanged(card, item, 'title') && <ChangedDot />}
{removed && <span className="sr-only">{t('assistant.card.common.willDelete')}</span>} {removed && <span className="sr-only">{t('assistant.card.common.willDelete')}</span>}
</span> </span>
{address && ( {address &&
<bdi title={address} className="line-clamp-2 text-caption text-content-muted"> (proposal ? (
{address} <span className="mt-0.5 flex items-start gap-1.5 text-caption text-content-muted">
</bdi> <MapPin size={12} className="mt-0.5 flex-none" aria-hidden="true" />
)} <bdi title={address} className="line-clamp-2 break-words">
</span> {address}
<StatusMark item={item} /> </bdi>
</span>
) : (
<bdi title={address} className="line-clamp-2 text-caption text-content-muted">
{address}
</bdi>
))}
</div>
{!actionLabel && <StatusMark item={item} />}
{isChanged(card, item, 'status') && <ChangedDot />} {isChanged(card, item, 'status') && <ChangedDot />}
{actions} {actions}
</div> </div>
); );
} }
/** A proposal shows the facts in the same order as the booking editor. */
const PROPOSAL_FACTS = 'm-0 grid grid-cols-[repeat(auto-fit,minmax(min(100%,8.5rem),1fr))] gap-2';
const PROPOSAL_FIELD_TEXT = fs(12.5, 'body');
function ProposalFact({ label, children }: { label: string; children: ReactNode }) {
return (
<div className="min-w-0">
<dt className="mb-[3px]">
<Eyebrow>{label}</Eyebrow>
</dt>
<dd
className={`${BOX} m-0 flex min-h-9 flex-wrap items-center gap-x-1.5 gap-y-0.5 break-words px-2.5 py-[7px] font-semibold tabular-nums text-content`}
style={PROPOSAL_FIELD_TEXT}
>
{children}
</dd>
</div>
);
}
export function VenueProposalBody({ body }: { body: BookingVenue }) {
const { t } = useTranslation();
const format = useBookingFormat();
const day = format.day(body.day);
const dayNumber = format.dayNumber(body.day);
return (
(day || body.starts || body.ends) && (
<dl className={PROPOSAL_FACTS}>
{day && (
<ProposalFact label={t(body.day?.date ? 'reservations.date' : 'reservations.timeline.day')}>
<bdi>{day}</bdi>
{dayNumber && <span className="text-caption font-normal text-content-muted">{dayNumber}</span>}
</ProposalFact>
)}
{body.starts && (
<ProposalFact label={t('reservations.startTime')}>
<bdi>{format.clock(body.starts)}</bdi>
</ProposalFact>
)}
{body.ends && (
<ProposalFact label={t('reservations.endTime')}>
<bdi>{format.clock(body.ends)}</bdi>
</ProposalFact>
)}
</dl>
)
);
}
export function StayProposalBody({ body }: { body: BookingStay }) {
const { t } = useTranslation();
const format = useBookingFormat();
const checkIn = body.checkIn;
const checkOut = body.checkOut;
return (
<>
{(checkIn || checkOut) && (
<dl className={PROPOSAL_FACTS}>
{checkIn && (
<ProposalFact label={t('assistant.change.label.checkIn')}>
<bdi>{format.day(checkIn.day)}</bdi>
{checkIn.from && (
<bdi className="text-caption">
{format.clock(checkIn.from)}
{checkIn.until ? ` – ${format.clock(checkIn.until)}` : ''}
</bdi>
)}
</ProposalFact>
)}
{checkOut && (
<ProposalFact label={t('assistant.change.label.checkOut')}>
<bdi>{format.day(checkOut.day)}</bdi>
{checkOut.by && <bdi className="text-caption">{format.clock(checkOut.by)}</bdi>}
</ProposalFact>
)}
</dl>
)}
{!!body.nights && (
<p className="m-0 flex items-center gap-1.5 text-body text-content-secondary">
<Moon size={14} aria-hidden="true" />
{t('assistant.card.booking.nights', { count: body.nights })}
</p>
)}
</>
);
}
export function BookingProposalFooter({
item,
notes,
reference,
receipt,
}: {
item: BookingItem;
notes?: string;
reference?: string;
receipt?: string;
}) {
const { t } = useTranslation();
const format = useBookingFormat();
const tone = toneOfItem(item);
return (
<>
{reference && (
<dl className="m-0">
<ProposalFact label={t('reservations.confirmationCode')}>
<bdi dir="ltr" className="min-w-0 break-all font-geist">
{reference}
</bdi>
</ProposalFact>
</dl>
)}
{notes && (
<Block label={t('assistant.change.label.notes')}>
<p
className={`${BOX} m-0 whitespace-pre-wrap break-words px-2.5 py-[7px] text-content-secondary`}
style={PROPOSAL_FIELD_TEXT}
>
<bdi>{notes}</bdi>
</p>
</Block>
)}
{receipt && (
<Block label={t('assistant.change.label.attachedTo')}>
<span
className={`${BOX} flex min-w-0 items-center gap-1.5 px-2.5 py-[7px] text-content-secondary`}
style={PROPOSAL_FIELD_TEXT}
>
<Paperclip size={14} aria-hidden="true" className="flex-none" />
<bdi className="min-w-0 break-words">{receipt}</bdi>
</span>
</Block>
)}
<div className="flex flex-wrap items-center gap-x-3 gap-y-2 border-t border-edge-faint pt-2.5 text-caption text-content-secondary">
<span className="font-semibold">{t(typeInfo(item.type).labelKey)}</span>
{item.status && tone && (
<span className="inline-flex items-center gap-1.5">
<span
className="h-2 w-2 flex-none rounded-full"
style={{ background: toneColor(tone) }}
aria-hidden="true"
/>
{t(STATUS_LABEL[item.status].labelKey)}
</span>
)}
{item.hasReference && !reference && (
<span className="inline-flex items-center gap-1.5">
<BadgeCheck size={14} aria-hidden="true" className="flex-none text-success" />
{t('reservations.confirmationCode')}
</span>
)}
{item.price && (
<bdi className="ms-auto font-semibold tabular-nums text-content">{format.money(item.price)}</bdi>
)}
{item.travelers.length > 0 && (
<span className="flex flex-none items-center gap-1">
<PeopleStack people={item.travelers} />
{item.moreTravelers > 0 && <span className="font-semibold tabular-nums">+{item.moreTravelers}</span>}
</span>
)}
</div>
</>
);
}
/** A fact as a white soft pill with its glyph, the accent dot when an update changes it. */ /** A fact as a white soft pill with its glyph, the accent dot when an update changes it. */
function Pill({ function Pill({
icon: Icon, icon: Icon,
@@ -142,6 +142,10 @@ export const STEP_LOOKS: Readonly<Partial<Record<string, StepLook>>> = {
stepKey: 'assistant.step.searching', stepKey: 'assistant.step.searching',
live: { liveKey: 'assistant.step.searchingFor', param: 'query' }, live: { liveKey: 'assistant.step.searchingFor', param: 'query' },
}, },
search_places_via_plugins: {
stepKey: 'assistant.step.searching',
live: { liveKey: 'assistant.step.searchingFor', param: 'query' },
},
search_pois: { stepKey: 'assistant.step.searching', live: { liveKey: 'assistant.step.nearbyAt', param: 'place' } }, search_pois: { stepKey: 'assistant.step.searching', live: { liveKey: 'assistant.step.nearbyAt', param: 'place' } },
get_place_details: { stepKey: 'assistant.step.details' }, get_place_details: { stepKey: 'assistant.step.details' },
search_nearby_places: { search_nearby_places: {
@@ -10,7 +10,7 @@
import type { TourRouteCard } from '@trek/shared'; import type { TourRouteCard } from '@trek/shared';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { GENTLE, HIKE, SAVED } from '../../../../../tests/helpers/assistantTour'; import { GENTLE, HIKE, SAVED, tourStop } from '../../../../../tests/helpers/assistantTour';
import { buildTrip, buildUser } from '../../../../../tests/helpers/factories'; import { buildTrip, buildUser } from '../../../../../tests/helpers/factories';
import { act, fireEvent, render, screen } from '../../../../../tests/helpers/render'; import { act, fireEvent, render, screen } from '../../../../../tests/helpers/render';
import { chatOf, useAssistantStore } from '../../../../store/assistantStore'; import { chatOf, useAssistantStore } from '../../../../store/assistantStore';
@@ -81,6 +81,34 @@ describe('TourRouteBlock', () => {
expect(document.querySelector('[data-profile-compare="call_1"]')).not.toBeNull(); expect(document.querySelector('[data-profile-compare="call_1"]')).not.toBeNull();
}); });
it('preselects the calculated way and keeps the failed way available for diagnosis', () => {
const failed: TourRouteCard = {
...HIKE,
routed: false,
distanceM: null,
problem: { why: 'point_off_the_way', position: 2, snappedM: 494 },
};
renderBlock([{ toolCallId: 'call_1', card: failed }, WAYS[1]]);
const first = screen.getByRole('radio', { name: 'Way A' });
expect(first).toHaveTextContent('not routed');
expect(first).not.toHaveTextContent('0 m');
expect(screen.getByRole('radio', { name: 'Long and gentle' })).toHaveAttribute('aria-checked', 'true');
expect(screen.getByRole('button', { name: 'Plan way B' })).toBeEnabled();
expect(screen.queryByTestId('leg-variant-delta')).not.toBeInTheDocument();
fireEvent.click(first);
expect(screen.getByText('Point 2 is too far from any path')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Plan way A' })).not.toBeInTheDocument();
});
it('warns about a long detour on an open hike while keeping the route available', () => {
const start = tourStop({ role: 'start', lat: 35.3969, lng: 138.7345 });
const end = tourStop({ role: 'end', lat: 35.3606, lng: 138.7274, atM: 35_856 });
renderBlock([{ toolCallId: 'detour', card: { ...HIKE, distanceM: 35_856, stops: [start, end] } }]);
expect(screen.getByText(/takes a long detour/)).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'On map' })).toBeInTheDocument();
});
it('FE-AI-TOUR-031: the ways stand side by side in a roomy window and stay rows on the phone', () => { it('FE-AI-TOUR-031: the ways stand side by side in a roomy window and stay rows on the phone', () => {
renderBlock(WAYS, { density: 'roomy' }); renderBlock(WAYS, { density: 'roomy' });
expect(screen.getByRole('radiogroup')).toHaveClass('grid-cols-2'); expect(screen.getByRole('radiogroup')).toHaveClass('grid-cols-2');
@@ -10,7 +10,7 @@ import TourRouteActions from './TourRouteActions';
import TourRouteDay from './TourRouteDay'; import TourRouteDay from './TourRouteDay';
import TourRouteHead, { TourRouteFields } from './TourRouteHead'; import TourRouteHead, { TourRouteFields } from './TourRouteHead';
import { profileSamples } from './tourRouteModel'; import { profileSamples } from './tourRouteModel';
import { TourRouteProblem, TourRouteWarnings } from './TourRouteNotes'; import { TourRouteDetour, TourRouteProblem, TourRouteWarnings } from './TourRouteNotes';
import TourRouteProfile from './TourRouteProfile'; import TourRouteProfile from './TourRouteProfile';
import TourRouteStops from './TourRouteStops'; import TourRouteStops from './TourRouteStops';
import { routeName } from './tourRouteWords'; import { routeName } from './tourRouteWords';
@@ -45,6 +45,7 @@ export function TourRouteBody({
return ( return (
<> <>
<TourRouteFields card={card} /> <TourRouteFields card={card} />
<TourRouteDetour card={card} />
{/* A way drawn straight has neither heights nor the line to say so under: no section at all. */} {/* A way drawn straight has neither heights nor the line to say so under: no section at all. */}
{(samples.length >= 2 || card.routed) && ( {(samples.length >= 2 || card.routed) && (
<CardSection label={t('tours.planner.inspector.elevation')}> <CardSection label={t('tours.planner.inspector.elevation')}>
@@ -5,6 +5,7 @@ import { useTranslation } from '../../../../i18n';
import { SoftPill } from '../../../Planner/planParts'; import { SoftPill } from '../../../Planner/planParts';
import { TourNotice } from '../../../Tours/tourParts'; import { TourNotice } from '../../../Tours/tourParts';
import { useCardFormat } from '../parts/useCardFormat'; import { useCardFormat } from '../parts/useCardFormat';
import { hasLongHikeDetour } from './tourRouteModel';
import { PROBLEM_LOOK, WARNING_LOOK } from './tourRouteWords'; import { PROBLEM_LOOK, WARNING_LOOK } from './tourRouteWords';
/** /**
@@ -53,3 +54,15 @@ export function TourRouteProblem({ card }: { card: TourRouteCard }) {
</div> </div>
); );
} }
export function TourRouteDetour({ card }: { card: TourRouteCard }) {
const { t } = useTranslation();
if (!hasLongHikeDetour(card)) return null;
return (
<div className="mt-2">
<TourNotice tone="warning" icon={<AlertTriangle size={12} strokeWidth={2} aria-hidden="true" />}>
{t('assistant.card.tour.longDetour')}
</TourNotice>
</div>
);
}
@@ -3,6 +3,7 @@ import { Route as RouteIcon } from 'lucide-react';
import { useMemo } from 'react'; import { useMemo } from 'react';
import { useTranslation } from '../../../../i18n'; import { useTranslation } from '../../../../i18n';
import { preferredRouteEntry } from '../../../../store/assistantRouteModel';
import { chatOf, useAssistantStore } from '../../../../store/assistantStore'; import { chatOf, useAssistantStore } from '../../../../store/assistantStore';
import { useSettingsStore } from '../../../../store/settingsStore'; import { useSettingsStore } from '../../../../store/settingsStore';
import type { DistanceUnit } from '../../../../types'; import type { DistanceUnit } from '../../../../types';
@@ -79,7 +80,7 @@ function WayOption({
entry: RouteEntry; entry: RouteEntry;
index: number; index: number;
chosen: boolean; chosen: boolean;
chosenWay: LegVariant; chosenWay: LegVariant | null;
chosenLetter: string; chosenLetter: string;
unit: DistanceUnit; unit: DistanceUnit;
onSelect: () => void; onSelect: () => void;
@@ -118,8 +119,14 @@ function WayOption({
{/* Ways of a ride or a run may differ by profile: each says its own. */} {/* Ways of a ride or a run may differ by profile: each says its own. */}
{entry.card.routingProfile && <TourGrade card={entry.card} />} {entry.card.routingProfile && <TourGrade card={entry.card} />}
</span> </span>
<WayFigures way={way} unit={unit} /> {entry.card.routed ? (
{!chosen && <WayDelta way={way} chosen={chosenWay} letter={chosenLetter} unit={unit} />} <WayFigures way={way} unit={unit} />
) : (
<span className="text-caption text-warning">{t('map.overview.notRouted')}</span>
)}
{!chosen && entry.card.routed && chosenWay && (
<WayDelta way={way} chosen={chosenWay} letter={chosenLetter} unit={unit} />
)}
</span> </span>
</button> </button>
); );
@@ -156,7 +163,7 @@ function WaysCard({
[entries, chosenIndex] [entries, chosenIndex]
); );
const chosenWay = legVariantOf(chosen.card, chosenKey); const chosenWay = chosen.card.routed ? legVariantOf(chosen.card, chosenKey) : null;
// Side by side where the window is roomy; on the phone the ways stay rows, so a finger scrubs the profile freely. // Side by side where the window is roomy; on the phone the ways stay rows, so a finger scrubs the profile freely.
let columns = ''; let columns = '';
if (density === 'roomy' && variant !== 'fullscreen') columns = entries.length >= 3 ? 'grid-cols-3' : 'grid-cols-2'; if (density === 'roomy' && variant !== 'fullscreen') columns = entries.length >= 3 ? 'grid-cols-3' : 'grid-cols-2';
@@ -216,10 +223,8 @@ function WaysCard({
export default function TourWays({ entries }: { entries: readonly RouteEntry[] }) { export default function TourWays({ entries }: { entries: readonly RouteEntry[] }) {
const { tripId } = useAssistantView(); const { tripId } = useAssistantView();
const blockKey = `tour:${entries[0]?.toolCallId ?? ''}`; const blockKey = `tour:${entries[0]?.toolCallId ?? ''}`;
const picked = useAssistantStore((s) => chatOf(s, tripId).picks[blockKey] ?? null); const picked = useAssistantStore((s) => chatOf(s, tripId).picks[blockKey]);
const index = entries.findIndex((entry) => entry.toolCallId === picked); const chosen = preferredRouteEntry(entries, picked);
const chosenIndex = index < 0 ? 0 : index;
const chosen = entries[chosenIndex];
if (!chosen) return null; if (!chosen) return null;
return <WaysCard entries={entries} chosen={chosen} chosenIndex={chosenIndex} blockKey={blockKey} />; return <WaysCard entries={entries} chosen={chosen} chosenIndex={entries.indexOf(chosen)} blockKey={blockKey} />;
} }
@@ -1,4 +1,4 @@
import { cumulativeMetres, type TourRouteCard, type TourRouteStop } from '@trek/shared'; import { cumulativeMetres, haversineMetres, type TourRouteCard, type TourRouteStop } from '@trek/shared';
import type { DistanceIndexedProfileSample } from '../../../../utils/routeGeometry'; import type { DistanceIndexedProfileSample } from '../../../../utils/routeGeometry';
import { hikePaintCss } from '../../../Tours/hike/hikePaint'; import { hikePaintCss } from '../../../Tours/hike/hikePaint';
@@ -84,6 +84,17 @@ export function profileSamples(card: TourRouteCard): DistanceIndexedProfileSampl
})); }));
} }
/** Flag a long detour on an open hike without intermediate waypoints. */
export function hasLongHikeDetour(card: TourRouteCard): boolean {
if (!card.routed || card.source !== 'proposal' || card.activity !== 'hike' || card.distanceM === null) return false;
const waypoints = card.stops.filter((stop) => stop.role !== 'along');
const [start, end] = waypoints;
if (waypoints.length !== 2 || start?.role !== 'start' || end?.role !== 'end') return false;
const directM = haversineMetres(start.lat, start.lng, end.lat, end.lng);
// Loops and short switchbacks are expected to cover much more than their direct distance.
return directM >= 1_000 && card.distanceM >= Math.max(4 * directM, directM + 10_000);
}
/** A stretch to tint behind the profile, in metres along the route. */ /** A stretch to tint behind the profile, in metres along the route. */
interface ProfileBand { interface ProfileBand {
fromM: number; fromM: number;
@@ -1,4 +1,4 @@
import { type Dispatch, type SetStateAction, useState } from 'react'; import { useMemo, useState } from 'react';
import type { ChangeItem } from '../assistantParts'; import type { ChangeItem } from '../assistantParts';
import { viewOf } from './cardViews'; import { viewOf } from './cardViews';
@@ -21,8 +21,9 @@ const arrived = (items: readonly ChangeItem[]) => items.flatMap((item) => (item.
* its preview arrives; after that only the user switches it. * its preview arrives; after that only the user switches it.
*/ */
export function useChangeExclusions( export function useChangeExclusions(
items: readonly ChangeItem[] items: readonly ChangeItem[],
): [ReadonlySet<string>, Dispatch<SetStateAction<ReadonlySet<string>>>] { choices: Readonly<Record<string, boolean>>
): ReadonlySet<string> {
const [excluded, setExcluded] = useState<ReadonlySet<string>>(() => new Set(startingOff(items, new Set()))); const [excluded, setExcluded] = useState<ReadonlySet<string>>(() => new Set(startingOff(items, new Set())));
const [seen, setSeen] = useState<ReadonlySet<string>>(() => new Set(arrived(items))); const [seen, setSeen] = useState<ReadonlySet<string>>(() => new Set(arrived(items)));
const fresh = arrived(items).filter((id) => !seen.has(id)); const fresh = arrived(items).filter((id) => !seen.has(id));
@@ -31,5 +32,11 @@ export function useChangeExclusions(
setSeen(new Set([...seen, ...fresh])); setSeen(new Set([...seen, ...fresh]));
if (off.length > 0) setExcluded((prev) => new Set([...prev, ...off])); if (off.length > 0) setExcluded((prev) => new Set([...prev, ...off]));
} }
return [excluded, setExcluded]; return useMemo(
() =>
new Set(
items.flatMap(({ toolCallId }) => ((choices[toolCallId] ?? !excluded.has(toolCallId)) ? [] : [toolCallId]))
),
[items, choices, excluded]
);
} }
@@ -17,6 +17,10 @@ const h = vi.hoisted(() => {
insets: number[] = []; insets: number[] = [];
kicks = 0; kicks = 0;
disposed = false; disposed = false;
static create(opts: GlobeEngineOptions): FakeEngine {
return new FakeEngine(opts);
}
constructor(opts: GlobeEngineOptions) { constructor(opts: GlobeEngineOptions) {
if (state.failNext !== null) { if (state.failNext !== null) {
const err = state.failNext; const err = state.failNext;
@@ -54,7 +54,7 @@ const AtlasGlobe = forwardRef<AtlasGlobeHandle, AtlasGlobeProps>(function AtlasG
if (!canvas) return; if (!canvas) return;
let engine: GlobeEngine; let engine: GlobeEngine;
try { try {
engine = new GlobeEngine({ engine = GlobeEngine.create({
canvas, canvas,
fetchJson: (p) => propsRef.current.fetchJson(p), fetchJson: (p) => propsRef.current.fetchJson(p),
theme: globeTheme(propsRef.current.dark), theme: globeTheme(propsRef.current.dark),
@@ -210,7 +210,7 @@ async function start(o: StartOptions = {}) {
onSelect: vi.fn(), onSelect: vi.fn(),
onFrame: vi.fn(), onFrame: vi.fn(),
}; };
const engine = new mod.GlobeEngine({ canvas, fetchJson, theme: o.theme ?? LIGHT, initial: o.initial, ...cb }); const engine = mod.GlobeEngine.create({ canvas, fetchJson, theme: o.theme ?? LIGHT, initial: o.initial, ...cb });
engines.push(engine); engines.push(engine);
return { return {
mod, mod,
@@ -310,7 +310,7 @@ describe('GlobeEngine boot', () => {
const otherFetch = vi.fn(async (): Promise<unknown> => null); const otherFetch = vi.fn(async (): Promise<unknown> => null);
const canvas = document.createElement('canvas'); const canvas = document.createElement('canvas');
const onReady = vi.fn(); const onReady = vi.fn();
const second = new first.mod.GlobeEngine({ canvas, fetchJson: otherFetch, theme: LIGHT, onReady }); const second = first.mod.GlobeEngine.create({ canvas, fetchJson: otherFetch, theme: LIGHT, onReady });
engines.push(second); engines.push(second);
await flush(); await flush();
expect(otherFetch).not.toHaveBeenCalled(); expect(otherFetch).not.toHaveBeenCalled();
@@ -345,7 +345,7 @@ describe('GlobeEngine boot retries', () => {
}); });
const onError = vi.fn(); const onError = vi.fn();
engines.push( engines.push(
new mod.GlobeEngine({ canvas: document.createElement('canvas'), fetchJson: fail, theme: LIGHT, onError }) mod.GlobeEngine.create({ canvas: document.createElement('canvas'), fetchJson: fail, theme: LIGHT, onError })
); );
const delays: number[] = []; const delays: number[] = [];
for (let i = 0; i < 4; i++) { for (let i = 0; i < 4; i++) {
@@ -364,7 +364,7 @@ describe('GlobeEngine boot retries', () => {
const ok = vi.fn(async (p: string): Promise<unknown> => files[p]); const ok = vi.fn(async (p: string): Promise<unknown> => files[p]);
const onReady = vi.fn(); const onReady = vi.fn();
engines.push( engines.push(
new mod.GlobeEngine({ canvas: document.createElement('canvas'), fetchJson: ok, theme: LIGHT, onReady }) mod.GlobeEngine.create({ canvas: document.createElement('canvas'), fetchJson: ok, theme: LIGHT, onReady })
); );
await flush(); await flush();
expect(ok).toHaveBeenCalledWith('manifest'); expect(ok).toHaveBeenCalledWith('manifest');
@@ -381,7 +381,9 @@ describe('GlobeEngine boot retries', () => {
return files[p]; return files[p];
}); });
const onReady = vi.fn(); const onReady = vi.fn();
engines.push(new mod.GlobeEngine({ canvas: document.createElement('canvas'), fetchJson, theme: LIGHT, onReady })); engines.push(
mod.GlobeEngine.create({ canvas: document.createElement('canvas'), fetchJson, theme: LIGHT, onReady })
);
await flush(); await flush();
expect(pending.map((t) => t.ms)).toEqual([1000]); expect(pending.map((t) => t.ms)).toEqual([1000]);
pending[0].cb(); pending[0].cb();
@@ -164,7 +164,13 @@ export class GlobeEngine {
private sun: [number, number, number] = sunVector(new Date()); private sun: [number, number, number] = sunVector(new Date());
private sunAt = 0; private sunAt = 0;
constructor(opts: GlobeEngineOptions) { static create(opts: GlobeEngineOptions): GlobeEngine {
const engine = new GlobeEngine(opts);
void engine.boot();
return engine;
}
private constructor(opts: GlobeEngineOptions) {
this.opts = opts; this.opts = opts;
this.theme = opts.theme; this.theme = opts.theme;
Object.assign(this.cam, opts.initial ?? {}); Object.assign(this.cam, opts.initial ?? {});
@@ -187,7 +193,6 @@ export class GlobeEngine {
this.resizeObs.observe(opts.canvas); this.resizeObs.observe(opts.canvas);
opts.canvas.addEventListener('webglcontextlost', this.onContextLost); opts.canvas.addEventListener('webglcontextlost', this.onContextLost);
this.resize(); this.resize();
void this.boot();
} }
// ---------------------------------------------------------------- loading // ---------------------------------------------------------------- loading
@@ -14,7 +14,7 @@ export function hexToRgb(hex: string): Rgb {
.map((c) => c + c) .map((c) => c + c)
.join('') .join('')
: h.slice(0, 6); : h.slice(0, 6);
const n = parseInt(full, 16); const n = Number.parseInt(full, 16);
if (Number.isNaN(n)) return [0.5, 0.5, 0.5]; if (Number.isNaN(n)) return [0.5, 0.5, 0.5];
return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255]; return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255];
} }
@@ -17,6 +17,7 @@ import { amountToInputString, currencyDecimals } from '../../utils/formatters'
import { localIsoDate } from '../../utils/localDate' import { localIsoDate } from '../../utils/localDate'
import type { ExpensePrefill } from './CostsPanel' import type { ExpensePrefill } from './CostsPanel'
import type { BudgetItem } from '../../types' import type { BudgetItem } from '../../types'
import type { CostsSettlement } from './costsModel'
// The split and receipt fields guard their own precision on every keystroke, so the // The split and receipt fields guard their own precision on every keystroke, so the
// guard has to follow the currency: a three-decimal one (KWD, BHD, …) seeds three // guard has to follow the currency: a three-decimal one (KWD, BHD, …) seeds three
@@ -329,3 +330,24 @@ export function expenseEditorFor(
if (receipt) return { key: 'receipt', editing: null, prefill: receipt, close: closeReceipt } if (receipt) return { key: 'receipt', editing: null, prefill: receipt, close: closeReceipt }
return null return null
} }
/** Expenses and settle-up payments grouped newest day first in the Costs ledger. */
export function groupLedgerByDay(expenses: readonly BudgetItem[], payments: readonly CostsSettlement[], locale: string, noDate: string) {
const entries = [
...expenses.map(e => ({ kind: 'expense' as const, date: e.expense_date || '', e })),
...payments.map(s => ({ kind: 'payment' as const, date: settlementDate(s), s })),
].sort((a, b) => b.date.localeCompare(a.date))
const groups = new Map<string, typeof entries>()
for (const entry of entries) {
let label = noDate
if (entry.date) {
try {
label = new Date(entry.date + 'T00:00:00Z').toLocaleDateString(locale, { weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC' })
} catch { label = entry.date }
}
const group = groups.get(label)
if (group) group.push(entry)
else groups.set(label, [entry])
}
return [...groups].map(([day, entries]) => ({ day, entries }))
}
@@ -944,13 +944,13 @@ describe('CostsPanel — overview', () => {
expect(labels).toEqual(['Food & drink', 'Transport']) expect(labels).toEqual(['Food & drink', 'Transport'])
expect(within(breakdown).getByText('90 €')).toBeInTheDocument() expect(within(breakdown).getByText('90 €')).toBeInTheDocument()
expect(within(breakdown).getByText('30 €')).toBeInTheDocument() expect(within(breakdown).getByText('30 €')).toBeInTheDocument()
}) });
it('FE-W5COSTS-006: an empty trip shows the empty ledger and the empty breakdown', async () => { it('FE-W5COSTS-006: an empty trip shows the empty ledger without a total or category breakdown', async () => {
mount([]) mount([])
expect(await screen.findByText('No expenses yet. Add your first one.')).toBeInTheDocument();
expect(await screen.findByText('No expenses yet. Add your first one.')).toBeInTheDocument() expect(screen.queryByRole('region', { name: 'Total trip spend' })).toBeNull();
expect(screen.getByText('No expenses yet.')).toBeInTheDocument() expect(screen.queryByRole('region', { name: 'By category' })).toBeNull();
expect(screen.getByText("Everyone's square")).toBeInTheDocument() expect(screen.getByText("Everyone's square")).toBeInTheDocument()
}) })
+23 -43
View File
@@ -13,7 +13,7 @@ import { CustomDatePicker } from '../shared/CustomDateTimePicker'
import { useReceiptScan } from './useReceiptScan' import { useReceiptScan } from './useReceiptScan'
import { ReceiptScanModal } from './ReceiptScanModal' import { ReceiptScanModal } from './ReceiptScanModal'
import { SPLIT_COLORS } from './BudgetPanel.constants' import { SPLIT_COLORS } from './BudgetPanel.constants'
import { finalBudgetFor, finalBudgetSources, formerParticipantRows, NOTE_MAX, paidByUser, readUserNote, settlementDate } from './CostsPanel.helpers' import { groupLedgerByDay, finalBudgetFor, finalBudgetSources, formerParticipantRows, NOTE_MAX, paidByUser, readUserNote } from './CostsPanel.helpers'
import { COST_CATEGORY_LIST, catMeta } from './costsCategories' import { COST_CATEGORY_LIST, catMeta } from './costsCategories'
import { import {
baseTotal as baseTotalOf, booked as bookedAmount, isUnfinished as isUnfinishedModel, lineOf as lineOfModel, memberShareOf, baseTotal as baseTotalOf, booked as bookedAmount, isUnfinished as isUnfinishedModel, lineOf as lineOfModel, memberShareOf,
@@ -52,12 +52,6 @@ interface CostsPanelProps {
tripMembers?: TripMember[] tripMembers?: TripMember[]
} }
// One row in the unified Costs ledger — either an expense or a settle-up payment,
// carrying the date used to group it by day.
type LedgerEntry =
| { kind: 'expense'; date: string; e: BudgetItem }
| { kind: 'payment'; date: string; s: Settlement }
const round2 = (n: number) => Math.round(n * 100) / 100 const round2 = (n: number) => Math.round(n * 100) / 100
const FIELD_H = 40 // shared height for the amount / currency / day row in the modal const FIELD_H = 40 // shared height for the amount / currency / day row in the modal
const COSTS_VIEW_KEY = 'trek:costs-view' const COSTS_VIEW_KEY = 'trek:costs-view'
@@ -66,6 +60,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
const { trip, budgetItems, deleteBudgetItem, loadBudgetItems, addBudgetItem, updateBudgetItem } = useTripStore() const { trip, budgetItems, deleteBudgetItem, loadBudgetItems, addBudgetItem, updateBudgetItem } = useTripStore()
const can = useCanDo() const can = useCanDo()
const canEdit = can('budget_edit', trip) const canEdit = can('budget_edit', trip)
const hasExpenses = budgetItems.length > 0
const receiptScan = useReceiptScan(tripId, canEdit) const receiptScan = useReceiptScan(tripId, canEdit)
const toast = useToast() const toast = useToast()
const { t, locale } = useTranslation() const { t, locale } = useTranslation()
@@ -143,27 +138,12 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
// Nobody paid, so nobody owes (#2225). // Nobody paid, so nobody owes (#2225).
const myShareOf = (e: BudgetItem) => settledShareOf(e, ctx) const myShareOf = (e: BudgetItem) => settledShareOf(e, ctx)
// ── day grouping ───────────────────────────────────────────────────────── const noDate = t('costs.noDate')
const dayGroups = useMemo(() => { const dayGroups = useMemo(() => groupLedgerByDay(filtered, filteredSettlements, locale, noDate), [filtered, filteredSettlements, locale, noDate])
const entries: LedgerEntry[] = [ const emptyLedger = !hasExpenses && dayGroups.length === 0
...filtered.map(e => ({ kind: 'expense' as const, date: e.expense_date || '', e })), const mobileEmptyLedger = emptyLedger
...filteredSettlements.map(s => ({ kind: 'payment' as const, date: settlementDate(s), s })), ? <EmptyState scene="costs" title={t('costs.emptyText')} />
] : <div className="text-content-faint" style={{ textAlign: 'center', padding: '36px 16px', fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}>{search ? t('costs.noMatch') : t('costs.emptyText')}</div>
const labelOf = (date: string) => {
if (!date) return t('costs.noDate')
try { return new Date(date + 'T00:00:00Z').toLocaleDateString(locale, { weekday: 'short', day: 'numeric', month: 'short', timeZone: 'UTC' }) } catch { return date }
}
// Newest day first; within a day, expenses before payments (insertion order).
const sorted = entries.slice().sort((a, b) => (b.date || '').localeCompare(a.date || ''))
const groups: { day: string; entries: LedgerEntry[] }[] = []
for (const en of sorted) {
const day = labelOf(en.date)
let g = groups.find(x => x.day === day)
if (!g) { g = { day, entries: [] }; groups.push(g) }
g.entries.push(en)
}
return groups
}, [filtered, filteredSettlements, locale, t])
// ── filter dropdown options (category + single day) ────────────────────── // ── filter dropdown options (category + single day) ──────────────────────
const categoryOptions = useMemo(() => [ const categoryOptions = useMemo(() => [
@@ -285,8 +265,8 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
}} /> }} />
{/* ── Summary cards; with nothing to split (#2689) the total stands alone ── */} {/* ── Summary cards; with nothing to split (#2689) the total stands alone ── */}
{!splitting ? <div style={{ marginBottom: 36 }}>{totalCard}</div> : ( {!splitting ? (hasExpenses && <div style={{ marginBottom: 36 }}>{totalCard}</div>) : (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', gap: 16, marginBottom: 36 }} className="costs-summary"> <div style={{ display: 'grid', gridTemplateColumns: hasExpenses ? 'repeat(4, minmax(0, 1fr))' : 'repeat(3, minmax(0, 1fr))', gap: 16, marginBottom: 36 }} className="costs-summary">
<SummaryCard label={t('costs.youOwe')} sub={t('costs.youOweSub')} amount={balancesKnown ? totals.owe : null} currency={base} locale={locale} <SummaryCard label={t('costs.youOwe')} sub={t('costs.youOweSub')} amount={balancesKnown ? totals.owe : null} currency={base} locale={locale}
icon={<ArrowDown size={18} />} tone="owe" failed={settlementError} icon={<ArrowDown size={18} />} tone="owe" failed={settlementError}
foot={totals.owe > 0.01 foot={totals.owe > 0.01
@@ -302,18 +282,17 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
foot={totals.outstandingCount > 0 foot={totals.outstandingCount > 0
? <span><b>{totals.outstandingCount}</b> {t('costs.outstandingItems', { count: totals.outstandingCount })}</span> ? <span><b>{totals.outstandingCount}</b> {t('costs.outstandingItems', { count: totals.outstandingCount })}</span>
: settledUp && <span className="text-content-faint">{t('costs.allSettled')}</span>} /> : settledUp && <span className="text-content-faint">{t('costs.allSettled')}</span>} />
{totalCard} {hasExpenses && totalCard}
</div>)} </div>)}
{/* ── Main grid ── */} {/* ── Main grid ── */}
{/* The same four columns as the cards above: the ledger takes three, the {/* The same four columns as the cards above: the ledger takes three, the
sidebar the last, so it lines up with the total-spend card. */} sidebar the last, so it lines up with the total-spend card. */}
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', columnGap: 16, rowGap: 32, alignItems: 'start' }} className="costs-grid"> <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', columnGap: 16, rowGap: 32, alignItems: 'start' }} className="costs-grid">
{/* expenses */} <div className="costs-main" style={{ gridColumn: emptyLedger ? '1 / -1' : 'span 3', minWidth: 0 }}>
<div className="costs-main" style={{ gridColumn: 'span 3', minWidth: 0 }}>
{dayBanner} {dayBanner}
{view === 'table' ? ( {emptyLedger ? <EmptyState scene="costs" title={t('costs.emptyText')} /> : view === 'table' && hasExpenses ? (
filtered.length === 0 && budgetItems.length > 0 ? ( filtered.length === 0 && budgetItems.length > 0 ? (
<div className="text-content-faint" style={{ textAlign: 'center', padding: '60px 20px' }}>{t('costs.noMatch')}</div> <div className="text-content-faint" style={{ textAlign: 'center', padding: '60px 20px' }}>{t('costs.noMatch')}</div>
) : ( ) : (
@@ -379,14 +358,14 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
</>} </>}
{/* by category; the table view sums up four ways instead */} {/* by category; the table view sums up four ways instead */}
{view === 'table' ? ( {hasExpenses && (view === 'table' ? (
<CostsTableSummary items={filtered} baseTotal={baseTotal} toBase={booked} fmt={v => fmt(v)} personName={personName} splitting={splitting} /> <CostsTableSummary items={filtered} baseTotal={baseTotal} toBase={booked} fmt={v => fmt(v)} personName={personName} splitting={splitting} />
) : ( ) : (
<section aria-label={t('costs.byCategory')} className={SIDE_CARD}> <section aria-label={t('costs.byCategory')} className={SIDE_CARD}>
{sideHead(t('costs.byCategory'))} {sideHead(t('costs.byCategory'))}
<div className="px-4 py-4">{categoryBars}</div> <div className="px-4 py-4">{categoryBars}</div>
</section> </section>
)} ))}
<CostsModeCard trip={trip} memberCount={people.length} canEdit={canEdit} className={SIDE_CARD} /> <CostsModeCard trip={trip} memberCount={people.length} canEdit={canEdit} className={SIDE_CARD} />
</div> </div>
</div> </div>
@@ -492,8 +471,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
function MobileBody() { function MobileBody() {
return ( return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 16, paddingTop: 8 }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 16, paddingTop: 8 }}>
{/* Total card */} {hasExpenses ? <section style={{ background: 'linear-gradient(135deg,#1f2937,#111827)', color: '#fff', borderRadius: 22, padding: '20px 20px 16px', boxShadow: '0 8px 24px -8px rgba(0,0,0,0.28)' }}>
<section style={{ background: 'linear-gradient(135deg,#1f2937,#111827)', color: '#fff', borderRadius: 22, padding: '20px 20px 16px', boxShadow: '0 8px 24px -8px rgba(0,0,0,0.28)' }}>
<div style={{ fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))', textTransform: 'uppercase', letterSpacing: '0.12em', color: 'rgba(255,255,255,0.6)', fontWeight: 600 }}>{t('costs.totalSpend')}</div> <div style={{ fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))', textTransform: 'uppercase', letterSpacing: '0.12em', color: 'rgba(255,255,255,0.6)', fontWeight: 600 }}>{t('costs.totalSpend')}</div>
<div style={{ fontSize: 'calc(44px * var(--fs-scale-title, 1))', fontWeight: 700, letterSpacing: '-0.04em', lineHeight: 1, marginTop: 8, display: 'flex', alignItems: 'baseline' }}>{bigMoney(totals.totalSpend, 24, 'rgba(255,255,255,0.6)')}</div> <div style={{ fontSize: 'calc(44px * var(--fs-scale-title, 1))', fontWeight: 700, letterSpacing: '-0.04em', lineHeight: 1, marginTop: 8, display: 'flex', alignItems: 'baseline' }}>{bigMoney(totals.totalSpend, 24, 'rgba(255,255,255,0.6)')}</div>
{splitting && <div style={{ display: 'flex', gap: 18, marginTop: 12, fontSize: 'calc(12px * var(--fs-scale-body, 1))', color: 'rgba(255,255,255,0.6)', flexWrap: 'wrap' }}> {splitting && <div style={{ display: 'flex', gap: 18, marginTop: 12, fontSize: 'calc(12px * var(--fs-scale-body, 1))', color: 'rgba(255,255,255,0.6)', flexWrap: 'wrap' }}>
@@ -512,7 +490,10 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
<ScanLine size={16} /> {t('costs.scan.button')} <ScanLine size={16} /> {t('costs.scan.button')}
</button> </button>
)} )}
</section> </section> : <div className="flex flex-wrap justify-end gap-2">
{receiptScan.offered && <DialogButton onClick={receiptScan.open}>{t('costs.scan.button')}</DialogButton>}
{canEdit && <DialogButton variant="primary" onClick={() => { setEditing(null); setModalOpen(true) }}>{t('costs.addExpense')}</DialogButton>}
</div>}
{/* Owe / Owed, outstanding and settling up: only with something to split (#2689) */} {/* Owe / Owed, outstanding and settling up: only with something to split (#2689) */}
{splitting && <> {splitting && <>
@@ -583,7 +564,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
</div> </div>
{dayBanner} {dayBanner}
{dayGroups.length === 0 {dayGroups.length === 0
? <div className="text-content-faint" style={{ textAlign: 'center', padding: '36px 16px', fontSize: 'calc(13px * var(--fs-scale-body, 1))' }}>{search ? t('costs.noMatch') : t('costs.emptyText')}</div> ? mobileEmptyLedger
: dayGroups.map(g => { : dayGroups.map(g => {
const dtot = g.entries.reduce((a, en) => en.kind === 'expense' ? a + baseTotal(en.e) : a, 0) const dtot = g.entries.reduce((a, en) => en.kind === 'expense' ? a + baseTotal(en.e) : a, 0)
return ( return (
@@ -610,11 +591,10 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
</div> </div>
</>} </>}
{/* By category */} {hasExpenses && <div className={cardCls} style={{ borderRadius: 18, padding: 16 }}>
<div className={cardCls} style={{ borderRadius: 18, padding: 16 }}>
<div className={labelCls} style={{ marginBottom: 14 }}>{t('costs.byCategory')}</div> <div className={labelCls} style={{ marginBottom: 14 }}>{t('costs.byCategory')}</div>
{categoryBars} {categoryBars}
</div> </div>}
<CostsModeCard trip={trip} memberCount={people.length} canEdit={canEdit} className={`${cardCls} rounded-[18px]`} /> <CostsModeCard trip={trip} memberCount={people.length} canEdit={canEdit} className={`${cardCls} rounded-[18px]`} />
</div> </div>
) )
+2 -1
View File
@@ -1,3 +1,4 @@
import { focusRevealedEditor } from '../shared/dialogFocus'
import { useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from 'react' import { useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from 'react'
import { ChevronDown, Lock, Pencil, Plus, Trash2 } from 'lucide-react' import { ChevronDown, Lock, Pencil, Plus, Trash2 } from 'lucide-react'
import { useTranslation } from '../../i18n' import { useTranslation } from '../../i18n'
@@ -307,7 +308,7 @@ function TextInput({ value, onSave, onCancel, label, numeric = false }: {
if (ev.key === 'Escape') { ev.preventDefault(); ev.stopPropagation(); finish(onCancel) } if (ev.key === 'Escape') { ev.preventDefault(); ev.stopPropagation(); finish(onCancel) }
} }
return ( return (
<input autoFocus type="text" value={draft} aria-label={label} inputMode={numeric ? 'decimal' : undefined} <input ref={focusRevealedEditor} type="text" value={draft} aria-label={label} inputMode={numeric ? 'decimal' : undefined}
onChange={ev => setDraft(ev.target.value)} onKeyDown={onKey} onBlur={() => finish(() => onSave(draft))} onChange={ev => setDraft(ev.target.value)} onKeyDown={onKey} onBlur={() => finish(() => onSave(draft))}
className={`${INPUT} ${numeric ? 'text-center tabular-nums' : ''}`} /> className={`${INPUT} ${numeric ? 'text-center tabular-nums' : ''}`} />
) )
@@ -197,7 +197,7 @@ function FilterMenu(f: CostsFilterProps & { splitting: boolean }) {
</button> </button>
</Tooltip> </Tooltip>
{open && ( {open && (
<div role="menu" onKeyDown={e => { if (e.key === 'Escape') close() }} className="absolute end-0 top-11 z-30" style={{ ...POPOVER, width: 310 }}> <div role="menu" tabIndex={-1} onKeyDown={e => { if (e.key === 'Escape') close() }} className="absolute end-0 top-11 z-30" style={{ ...POPOVER, width: 310 }}>
{f.splitting && <> {f.splitting && <>
<div className="mx-1.5 mb-1 mt-1.5 flex rounded-[10px] bg-surface-tertiary p-[3px]"> <div className="mx-1.5 mb-1 mt-1.5 flex rounded-[10px] bg-surface-tertiary p-[3px]">
{owners.map(([o, label]) => ( {owners.map(([o, label]) => (
+2 -1
View File
@@ -1,3 +1,4 @@
import { focusRevealedEditor } from '../shared/dialogFocus'
import { cloneElement, CSSProperties, FormEvent, ReactElement, useEffect, useId, useRef, useState } from 'react' import { cloneElement, CSSProperties, FormEvent, ReactElement, useEffect, useId, useRef, useState } from 'react'
import { createPortal } from 'react-dom' import { createPortal } from 'react-dom'
import { ExternalLink, Link2, Pencil, Pin, Plus, Trash2, X } from 'lucide-react' import { ExternalLink, Link2, Pencil, Pin, Plus, Trash2, X } from 'lucide-react'
@@ -147,7 +148,7 @@ function LinkModal({ link, onClose, onSave }: { link?: CollabLink; onClose: () =
<div style={{ padding: '14px 16px 16px', display: 'flex', flexDirection: 'column', gap: 12 }}> <div style={{ padding: '14px 16px 16px', display: 'flex', flexDirection: 'column', gap: 12 }}>
<div> <div>
<label htmlFor="collab-link-title" style={{ ...label, display: 'block' }}>{t('collab.links.titlePlaceholder')}</label> <label htmlFor="collab-link-title" style={{ ...label, display: 'block' }}>{t('collab.links.titlePlaceholder')}</label>
<input id="collab-link-title" value={title} onChange={e => setTitle(e.target.value)} placeholder={t('collab.links.titlePlaceholder')} autoFocus style={field} /> <input id="collab-link-title" value={title} onChange={e => setTitle(e.target.value)} placeholder={t('collab.links.titlePlaceholder')} ref={focusRevealedEditor} style={field} />
</div> </div>
<div> <div>
<label htmlFor="collab-link-url" style={{ ...label, display: 'block' }}>{t('collab.links.urlPlaceholder')}</label> <label htmlFor="collab-link-url" style={{ ...label, display: 'block' }}>{t('collab.links.urlPlaceholder')}</label>
+1 -1
View File
@@ -118,7 +118,7 @@ function CreatePollModal({ onClose, onCreate, t }: CreatePollModalProps) {
)} )}
> >
<EditorField label={t('collab.polls.question')} hint={t('collab.polls.markdownHint')}> <EditorField label={t('collab.polls.question')} hint={t('collab.polls.markdownHint')}>
<textarea autoFocus rows={4} value={question} onChange={e => setQuestion(e.target.value)} placeholder={t('collab.polls.questionPlaceholder')} className={`${TEXTAREA} resize-y`} /> <textarea data-initial-focus rows={4} value={question} onChange={e => setQuestion(e.target.value)} placeholder={t('collab.polls.questionPlaceholder')} className={`${TEXTAREA} resize-y`} />
</EditorField> </EditorField>
<EditorField label={t('collab.polls.options')}> <EditorField label={t('collab.polls.options')}>
@@ -102,7 +102,6 @@ export default function AddPlaceToCollectionModal({ isOpen, collectionId, collec
<div className="relative"> <div className="relative">
<Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" /> <Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" />
<input <input
autoFocus
data-initial-focus data-initial-focus
ref={searchRef} ref={searchRef}
type="text" type="text"
@@ -136,6 +136,7 @@ export default function CollectionExportMenu({ onExport, exporting, t }: Collect
ref={menuRef} ref={menuRef}
id={menuId} id={menuId}
role="menu" role="menu"
tabIndex={-1}
aria-label={t('collections.file.exportTitle')} aria-label={t('collections.file.exportTitle')}
onKeyDown={onMenuKeyDown} onKeyDown={onMenuKeyDown}
className="trek-popover-enter fixed z-[var(--z-toast)] p-1.5 rounded-xl border border-edge bg-surface-card shadow-dropdown" className="trek-popover-enter fixed z-[var(--z-toast)] p-1.5 rounded-xl border border-edge bg-surface-card shadow-dropdown"
@@ -25,6 +25,7 @@ import { placesPath } from '../../utils/placesRoutes';
import MarkdownToolbar from '../Journey/MarkdownToolbar'; import MarkdownToolbar from '../Journey/MarkdownToolbar';
import { getNavigationTargets, navigationTargetLabel, openNavigationTarget } from '../Planner/placeNavigation'; import { getNavigationTargets, navigationTargetLabel, openNavigationTarget } from '../Planner/placeNavigation';
import { getCategoryIcon } from '../shared/categoryIcons'; import { getCategoryIcon } from '../shared/categoryIcons';
import { focusRevealedEditor } from '../shared/dialogFocus';
import { DialogShell } from '../shared/DialogShell'; import { DialogShell } from '../shared/DialogShell';
import { markdownLinkComponents } from '../shared/markdownLink'; import { markdownLinkComponents } from '../shared/markdownLink';
import { NavigationMenu } from '../shared/NavigationMenu'; import { NavigationMenu } from '../shared/NavigationMenu';
@@ -202,7 +203,7 @@ function Cover({
value={form.name} value={form.name}
onChange={(e) => form.setName(e.target.value)} onChange={(e) => form.setName(e.target.value)}
className="col-detail-name-input min-w-0 flex-1" className="col-detail-name-input min-w-0 flex-1"
autoFocus ref={focusRevealedEditor}
aria-label={t('common.name')} aria-label={t('common.name')}
/> />
</div> </div>
@@ -55,7 +55,7 @@ export default function CopyToTripModal({ isOpen, onClose, placeIds, onCopy, car
<div className="relative"> <div className="relative">
<Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" /> <Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" />
<input <input
autoFocus data-initial-focus
value={search} value={search}
onChange={e => setSearch(e.target.value)} onChange={e => setSearch(e.target.value)}
placeholder={t('collections.copyToTripSearch')} placeholder={t('collections.copyToTripSearch')}
@@ -257,9 +257,14 @@ describe('ListEditorModal', () => {
fireEvent.click(screen.getByRole('button', { name: /Search Unsplash/ })) fireEvent.click(screen.getByRole('button', { name: /Search Unsplash/ }))
expect(await screen.findByRole('button', { name: 'Rin' })).toBeInTheDocument() expect(await screen.findByRole('button', { name: 'Rin' })).toBeInTheDocument()
expect(screen.getByAltText('A street')).toHaveAttribute('title', 'A street')
expect(tripsApi.searchCoverImages).toHaveBeenCalledWith('fjord') expect(tripsApi.searchCoverImages).toHaveBeenCalledWith('fjord')
// A photo without a photographer falls back to the generic label. // A photo without a photographer falls back to the generic label.
fireEvent.click(screen.getByRole('button', { name: 'Unsplash' })) const photo = screen.getByRole('button', { name: 'Unsplash' })
const thumb = photo.querySelector('img')
expect(thumb).toHaveAttribute('alt', '')
expect(thumb).not.toHaveAttribute('title')
fireEvent.click(photo)
expect(document.querySelector('img[src="https://img/full2.jpg"]')).toBeTruthy() expect(document.querySelector('img[src="https://img/full2.jpg"]')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: 'Create' })) fireEvent.click(screen.getByRole('button', { name: 'Create' }))
@@ -126,7 +126,13 @@ export default function ListEditorModal({ target, onClose, onCreated, onRequestD
aria-pressed={on} aria-pressed={on}
className={`relative h-20 overflow-hidden rounded-[10px] transition-shadow ${on ? 'ring-2 ring-accent' : 'ring-1 ring-edge-faint hover:ring-content-faint'}`} className={`relative h-20 overflow-hidden rounded-[10px] transition-shadow ${on ? 'ring-2 ring-accent' : 'ring-1 ring-edge-faint hover:ring-content-faint'}`}
> >
<img src={photo.thumb} alt={photo.description || ''} loading="lazy" className="h-full w-full object-cover" /> <img
src={photo.thumb}
alt={photo.description || ''}
title={photo.description || undefined}
loading="lazy"
className="h-full w-full object-cover"
/>
{photo.photographer && <span className={PHOTO_CREDIT} style={fs(10)}>{photo.photographer}</span>} {photo.photographer && <span className={PHOTO_CREDIT} style={fs(10)}>{photo.photographer}</span>}
</button> </button>
) )
@@ -153,4 +153,9 @@ describe('ListsRail', () => {
renderRail({ onSelectLibrary: vi.fn(), libraryCount: null }); renderRail({ onSelectLibrary: vi.fn(), libraryCount: null });
expect(screen.getByRole('button', { name: /All places/ })).toHaveTextContent(/^All places$/); expect(screen.getByRole('button', { name: /All places/ })).toHaveTextContent(/^All places$/);
}); });
it('hides All places when the library is known to be empty', () => {
renderRail({ onSelectLibrary: vi.fn(), libraryCount: 0 });
expect(screen.queryByRole('button', { name: /All places/ })).not.toBeInTheDocument();
});
}); });
@@ -75,7 +75,7 @@ export default function ListsRail(props: ListsRailProps): React.ReactElement {
</Tooltip> </Tooltip>
</div> </div>
{onSelectLibrary && ( {onSelectLibrary && libraryCount !== 0 && (
<div className="col-row"> <div className="col-row">
<button type="button" onClick={onSelectLibrary} className={`col-row-btn${libraryActive ? ' on' : ''}`} aria-current={libraryActive ? 'page' : undefined}> <button type="button" onClick={onSelectLibrary} className={`col-row-btn${libraryActive ? ' on' : ''}`} aria-current={libraryActive ? 'page' : undefined}>
<span className="ico tile"><Globe2 size={15} /></span> <span className="ico tile"><Globe2 size={15} /></span>
@@ -67,7 +67,7 @@ export default function MoveToListModal({ mode, lists, count, onPick, onClose, t
<div className="relative"> <div className="relative">
<Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" /> <Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" />
<input <input
autoFocus data-initial-focus
value={search} value={search}
onChange={e => setSearch(e.target.value)} onChange={e => setSearch(e.target.value)}
placeholder={t('collections.searchLists')} placeholder={t('collections.searchLists')}
@@ -1,11 +1,12 @@
import type { PlacesLibraryDetailResponse } from '@trek/shared'; import type { PlacesLibraryDetailResponse } from '@trek/shared';
import { Bookmark, Eye, Layers, Luggage, NotebookPen, Pencil, PenLine } from 'lucide-react'; import { Bookmark, Eye, Layers, Luggage, NotebookPen, Pencil, PenLine } from 'lucide-react';
import React, { useRef } from 'react'; import React, { useCallback, useRef } from 'react';
import Markdown from 'react-markdown'; import Markdown from 'react-markdown';
import remarkBreaks from 'remark-breaks'; import remarkBreaks from 'remark-breaks';
import remarkGfm from 'remark-gfm'; import remarkGfm from 'remark-gfm';
import type { TranslationFn } from '../../types'; import type { TranslationFn } from '../../types';
import MarkdownToolbar from '../Journey/MarkdownToolbar'; import MarkdownToolbar from '../Journey/MarkdownToolbar';
import { focusRevealedEditor } from '../shared/dialogFocus';
import { markdownLinkComponents } from '../shared/markdownLink'; import { markdownLinkComponents } from '../shared/markdownLink';
import { Tooltip } from '../shared/Tooltip'; import { Tooltip } from '../shared/Tooltip';
import PlaceCard from './PlaceCard'; import PlaceCard from './PlaceCard';
@@ -51,6 +52,10 @@ function NoteCard({ note, n, t }: { note: OriginNote; n: Notes; t: TranslationFn
*/ */
function NoteEditor({ n, t }: { n: Notes; t: TranslationFn }) { function NoteEditor({ n, t }: { n: Notes; t: TranslationFn }) {
const ref = useRef<HTMLTextAreaElement>(null); const ref = useRef<HTMLTextAreaElement>(null);
const attachEditor = useCallback((element: HTMLTextAreaElement | null) => {
ref.current = element;
focusRevealedEditor(element);
}, []);
const current = n.composeTargets.find((x) => x.key === n.editing) ?? n.notes.find((x) => x.key === n.editing); const current = n.composeTargets.find((x) => x.key === n.editing) ?? n.notes.find((x) => x.key === n.editing);
const multi = n.isNew && n.composeTargets.length > 1; const multi = n.isNew && n.composeTargets.length > 1;
return ( return (
@@ -111,8 +116,7 @@ function NoteEditor({ n, t }: { n: Notes; t: TranslationFn }) {
</div> </div>
) : ( ) : (
<textarea <textarea
ref={ref} ref={attachEditor}
autoFocus
rows={6} rows={6}
value={n.draft} value={n.draft}
onChange={(e) => n.setDraft(e.target.value)} onChange={(e) => n.setDraft(e.target.value)}
@@ -1,6 +1,7 @@
import { MapPin } from 'lucide-react'; import { MapPin } from 'lucide-react';
import React from 'react'; import React from 'react';
import type { Category, TranslationFn } from '../../types'; import type { Category, TranslationFn } from '../../types';
import { focusRevealedEditor } from '../shared/dialogFocus';
import { NumericInput } from '../shared/NumericInput'; import { NumericInput } from '../shared/NumericInput';
import CategoryTileMenu from './CategoryTileMenu'; import CategoryTileMenu from './CategoryTileMenu';
import type { PlaceEditState } from './usePlaceEdit'; import type { PlaceEditState } from './usePlaceEdit';
@@ -36,7 +37,7 @@ export default function PlaceEditForm({
/> />
)} )}
<input <input
autoFocus ref={focusRevealedEditor}
value={draft.name} value={draft.name}
onChange={(e) => edit.set('name', e.target.value)} onChange={(e) => edit.set('name', e.target.value)}
aria-label={t('common.name')} aria-label={t('common.name')}
@@ -1,6 +1,7 @@
import { Bookmark, Check, Luggage, Plus, Search, Tag, X } from 'lucide-react'; import { Bookmark, Check, Luggage, Plus, Search, Tag, X } from 'lucide-react';
import React, { useEffect, useRef } from 'react'; import React, { useEffect, useRef } from 'react';
import type { TranslationFn } from '../../types'; import type { TranslationFn } from '../../types';
import { focusRevealedEditor } from '../shared/dialogFocus';
import PlaceCard from './PlaceCard'; import PlaceCard from './PlaceCard';
import type { PlaceTagsState, TagGroup } from './usePlaceTags'; import type { PlaceTagsState, TagGroup } from './usePlaceTags';
@@ -38,7 +39,7 @@ function TagPicker({ tags, group, t }: { tags: PlaceTagsState; group: TagGroup;
> >
<Search size={14} aria-hidden="true" /> <Search size={14} aria-hidden="true" />
<input <input
autoFocus ref={focusRevealedEditor}
value={tags.query} value={tags.query}
onChange={(e) => tags.setQuery(e.target.value)} onChange={(e) => tags.setQuery(e.target.value)}
placeholder={t('placeTags.search')} placeholder={t('placeTags.search')}
@@ -55,7 +55,7 @@ export default function SaveTripPlacesToListModal({ isOpen, tripId, placeIds, on
<div className="relative"> <div className="relative">
<Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" /> <Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" />
<input <input
autoFocus data-initial-focus
value={search} value={search}
onChange={e => setSearch(e.target.value)} onChange={e => setSearch(e.target.value)}
placeholder={t('collections.searchLists')} placeholder={t('collections.searchLists')}
@@ -8,7 +8,9 @@ import { getApiErrorMessage } from '../../utils/apiError';
import { useToast } from '../shared/Toast'; import { useToast } from '../shared/Toast';
/** A pair's own name: its two keys in a fixed order, so either way round it is one pair. */ /** A pair's own name: its two keys in a fixed order, so either way round it is one pair. */
export const pairKey = (d: Pick<PlacesLibraryDuplicate, 'a' | 'b'>): string => [d.a.key, d.b.key].sort().join('|'); export function pairKey({ a, b }: Pick<PlacesLibraryDuplicate, 'a' | 'b'>): string {
return a.key <= b.key ? `${a.key}|${b.key}` : `${b.key}|${a.key}`;
}
/** /**
* Places that look like the same place (PLC-13), behind the desktop dialog and the * Places that look like the same place (PLC-13), behind the desktop dialog and the
+2 -1
View File
@@ -1,6 +1,7 @@
import { ArrowLeft, ArrowRight, Clock, ExternalLink, Images, RotateCcw } from 'lucide-react'; import { ArrowLeft, ArrowRight, Clock, ExternalLink, Images, RotateCcw } from 'lucide-react';
import { lazy, Suspense, useId } from 'react'; import { lazy, Suspense, useId } from 'react';
import { useTranslation } from '../../i18n'; import { useTranslation } from '../../i18n';
import { focusRevealedEditor } from '../shared/dialogFocus';
import { import {
DialogButton, DialogButton,
DialogFooter, DialogFooter,
@@ -116,7 +117,7 @@ function FooterLinks({ t, onCredits, focusCredits }: { t: Translate; onCredits:
<button <button
type="button" type="button"
onClick={onCredits} onClick={onCredits}
autoFocus={focusCredits} ref={focusCredits ? focusRevealedEditor : undefined}
className={FOOTER_LINK} className={FOOTER_LINK}
style={fs(12.5, 'body')} style={fs(12.5, 'body')}
> >
@@ -106,17 +106,17 @@ export default function DocSyncConnectModal({
</Field> </Field>
))} ))}
<label className="flex items-start justify-between gap-4 rounded-lg border border-edge bg-surface-secondary px-3 py-2.5"> <div className="flex items-start justify-between gap-4 rounded-lg border border-edge bg-surface-secondary px-3 py-2.5">
<span className="min-w-0"> <span className="min-w-0">
<span className="block text-body text-content">{t('docsync.allowInsecureTls')}</span> <span className="block text-body text-content">{t('docsync.allowInsecureTls')}</span>
<span className="mt-0.5 block text-caption text-content-muted"> <span id={`${labelId}-tls-hint`} className="mt-0.5 block text-caption text-content-muted">
{t('docsync.connect.insecureHint')} {t('docsync.connect.insecureHint')}
</span> </span>
</span> </span>
<span className="shrink-0 pt-0.5"> <span className="shrink-0 pt-0.5">
<ToggleSwitch on={form.insecureTls} onToggle={() => form.setInsecureTls(!form.insecureTls)} /> <ToggleSwitch on={form.insecureTls} onToggle={() => form.setInsecureTls(!form.insecureTls)} label={t('docsync.allowInsecureTls')} describedBy={`${labelId}-tls-hint`} />
</span> </span>
</label> </div>
</div> </div>
<ConfirmDialog <ConfirmDialog
@@ -206,7 +206,7 @@ export default function ContributorInviteDialog({ journeyId, existingUserIds, on
<div className="relative"> <div className="relative">
<Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" /> <Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" />
<input <input
autoFocus data-initial-focus
value={search} value={search}
onChange={e => setSearch(e.target.value)} onChange={e => setSearch(e.target.value)}
placeholder={t('journey.contributors.searchPlaceholder')} placeholder={t('journey.contributors.searchPlaceholder')}
@@ -51,7 +51,7 @@ export function AddTripDialog({ journeyId, existingTripIds, onClose, onAdded }:
<div className="relative"> <div className="relative">
<Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" /> <Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" />
<input <input
autoFocus data-initial-focus
value={search} value={search}
onChange={e => setSearch(e.target.value)} onChange={e => setSearch(e.target.value)}
placeholder={t('journey.trips.searchPlaceholder')} placeholder={t('journey.trips.searchPlaceholder')}
@@ -113,9 +113,9 @@ describe('MobileEntryView', () => {
const order: string[] = [] const order: string[] = []
const onClose = vi.fn(() => { order.push('close') }) const onClose = vi.fn(() => { order.push('close') })
const onDelete = vi.fn(() => { order.push('delete') }) const onDelete = vi.fn(() => { order.push('delete') })
const { container } = renderView(buildEntry(), { onClose, onDelete }) renderView(buildEntry(), { onClose, onDelete })
fireEvent.click(container.querySelector('svg.lucide-trash2')!.closest('button')!) fireEvent.click(screen.getByRole('button', { name: /Delete/ }))
expect(order).toEqual(['close', 'delete']) expect(order).toEqual(['close', 'delete'])
}) })
@@ -123,7 +123,7 @@ describe('MobileEntryView', () => {
it('FE-COMP-JENTRYVIEW-006: read-only journeys hide the edit and delete actions', () => { it('FE-COMP-JENTRYVIEW-006: read-only journeys hide the edit and delete actions', () => {
const { container } = renderView(buildEntry(), { readOnly: true }) const { container } = renderView(buildEntry(), { readOnly: true })
expect(screen.queryByRole('button', { name: /Edit/ })).not.toBeInTheDocument() expect(screen.queryByRole('button', { name: /Edit/ })).not.toBeInTheDocument()
expect(container.querySelector('svg.lucide-trash2')).toBeNull() expect(screen.queryByRole('button', { name: /Delete/ })).not.toBeInTheDocument()
// the close button stays // the close button stays
expect(container.querySelector('svg.lucide-x')).not.toBeNull() expect(container.querySelector('svg.lucide-x')).not.toBeNull()
}) })
@@ -104,6 +104,7 @@ export default function MobileEntryView({ entry, readOnly, publicPhotoUrl, onClo
</button> </button>
<button type="button" <button type="button"
onClick={() => { onClose(); onDelete(); }} onClick={() => { onClose(); onDelete(); }}
aria-label={t('common.delete')}
className="w-8 h-8 rounded-lg flex items-center justify-center text-zinc-400 hover:bg-red-50 hover:text-red-500 dark:hover:bg-red-900/20 dark:hover:text-red-400 transition-colors" className="w-8 h-8 rounded-lg flex items-center justify-center text-zinc-400 hover:bg-red-50 hover:text-red-500 dark:hover:bg-red-900/20 dark:hover:text-red-400 transition-colors"
> >
<Trash2 size={15} /> <Trash2 size={15} />
+2 -1
View File
@@ -1,4 +1,5 @@
import { import {
stripTrailingSlashes,
resolveValhallaProvider, resolveValhallaProvider,
VALHALLA_COSTING, VALHALLA_COSTING,
VALHALLA_RELAY_MAX_LOCATIONS, VALHALLA_RELAY_MAX_LOCATIONS,
@@ -245,7 +246,7 @@ export function valhallaBase(): string | null {
*/ */
function currentProvider(ignoreRest = false): { provider: ValhallaProvider | null; own: string } { function currentProvider(ignoreRest = false): { provider: ValhallaProvider | null; own: string } {
const settings = useSettingsStore.getState().settings const settings = useSettingsStore.getState().settings
const own = settings.valhalla_base_url?.trim().replace(/\/+$/, '') ?? '' const own = stripTrailingSlashes(settings.valhalla_base_url?.trim() ?? '')
const provider = resolveValhallaProvider({ const provider = resolveValhallaProvider({
provider: settings.routing_valhalla_provider, provider: settings.routing_valhalla_provider,
valhallaUrl: own, valhallaUrl: own,
@@ -269,7 +269,7 @@ describe('PackingListPanel', () => {
const { container } = render(<PackingListPanel tripId={1} items={items} sort="name" />); const { container } = render(<PackingListPanel tripId={1} items={items} sort="name" />);
// Only the category grip stays: the order of the categories is not the A to Z of their items. // Only the category grip stays: the order of the categories is not the A to Z of their items.
const draggable = [...container.querySelectorAll('[draggable="true"]')]; const draggable = [...container.querySelectorAll('[draggable="true"]')];
expect(draggable.map((el) => el.getAttribute('aria-label'))).toEqual(['Drag to reorder the category']); expect(draggable.map((el) => el.getAttribute('title'))).toEqual(['Drag to reorder the category']);
}); });
it('FE-COMP-PACKING-023: inline edit item name via pencil icon calls PUT', async () => { it('FE-COMP-PACKING-023: inline edit item name via pencil icon calls PUT', async () => {
@@ -1,3 +1,4 @@
import { focusRevealedEditor } from '../shared/dialogFocus'
import { useState, useRef, useCallback } from 'react' import { useState, useRef, useCallback } from 'react'
import { createPortal } from 'react-dom' import { createPortal } from 'react-dom'
import { X, Plus } from 'lucide-react' import { X, Plus } from 'lucide-react'
@@ -37,7 +38,7 @@ export function BagCard({ bag, bagItems, totalWeight, pct, tripId, tripMembers,
<div style={{ display: 'flex', alignItems: 'center', gap: sz.gap }}> <div style={{ display: 'flex', alignItems: 'center', gap: sz.gap }}>
<span style={{ width: sz.dot, height: sz.dot, borderRadius: '50%', background: bag.color, flexShrink: 0 }} /> <span style={{ width: sz.dot, height: sz.dot, borderRadius: '50%', background: bag.color, flexShrink: 0 }} />
{editingName && canEdit ? ( {editingName && canEdit ? (
<input autoFocus value={nameVal} onChange={e => setNameVal(e.target.value)} <input ref={focusRevealedEditor} value={nameVal} onChange={e => setNameVal(e.target.value)}
onBlur={saveName} onKeyDown={e => { if (e.key === 'Enter') saveName(); if (e.key === 'Escape') cancelName() }} onBlur={saveName} onKeyDown={e => { if (e.key === 'Enter') saveName(); if (e.key === 'Escape') cancelName() }}
style={{ flex: 1, fontSize: sz.name, fontWeight: 600, padding: '1px 4px', borderRadius: 4, border: '1px solid var(--border-primary)', outline: 'none', fontFamily: 'inherit', color: 'var(--text-primary)', background: 'transparent' }} /> style={{ flex: 1, fontSize: sz.name, fontWeight: 600, padding: '1px 4px', borderRadius: 4, border: '1px solid var(--border-primary)', outline: 'none', fontFamily: 'inherit', color: 'var(--text-primary)', background: 'transparent' }} />
) : ( ) : (
@@ -101,7 +102,7 @@ export function BagCard({ bag, bagItems, totalWeight, pct, tripId, tripMembers,
{editingLimit && canEdit ? ( {editingLimit && canEdit ? (
<> <>
<span>/</span> <span>/</span>
<input autoFocus value={limitVal} onChange={e => setLimitVal(e.target.value)} <input ref={focusRevealedEditor} value={limitVal} onChange={e => setLimitVal(e.target.value)}
onBlur={saveLimit} onBlur={saveLimit}
onKeyDown={e => { if (e.key === 'Enter') saveLimit(); if (e.key === 'Escape') cancelLimit() }} onKeyDown={e => { if (e.key === 'Enter') saveLimit(); if (e.key === 'Escape') cancelLimit() }}
inputMode="decimal" aria-label={t('packing.bagLimit')} placeholder={t('packing.bagLimit')} inputMode="decimal" aria-label={t('packing.bagLimit')} placeholder={t('packing.bagLimit')}
@@ -1,3 +1,4 @@
import { focusRevealedEditor } from '../shared/dialogFocus'
import { X, Plus } from 'lucide-react' import { X, Plus } from 'lucide-react'
import type { PackingState } from './usePackingListPanel' import type { PackingState } from './usePackingListPanel'
import { bagFillPct, bagLoadSummary, packedWeight, perPersonLoads } from './packingListPanel.helpers' import { bagFillPct, bagLoadSummary, packedWeight, perPersonLoads } from './packingListPanel.helpers'
@@ -72,7 +73,7 @@ export function BagModal(S: PackingState) {
{/* Add bag */} {/* Add bag */}
{canEdit && (showAddBag ? ( {canEdit && (showAddBag ? (
<div style={{ display: 'flex', gap: 6, marginTop: 14 }}> <div style={{ display: 'flex', gap: 6, marginTop: 14 }}>
<input autoFocus value={newBagName} onChange={e => setNewBagName(e.target.value)} <input ref={focusRevealedEditor} value={newBagName} onChange={e => setNewBagName(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') void handleCreateBag(); if (e.key === 'Escape') { setShowAddBag(false); setNewBagName('') } }} onKeyDown={e => { if (e.key === 'Enter') void handleCreateBag(); if (e.key === 'Escape') { setShowAddBag(false); setNewBagName('') } }}
placeholder={t('packing.bagName')} placeholder={t('packing.bagName')}
style={{ flex: 1, padding: '8px 12px', borderRadius: 10, border: '1px solid var(--border-primary)', fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontFamily: 'inherit', outline: 'none' }} /> style={{ flex: 1, padding: '8px 12px', borderRadius: 10, border: '1px solid var(--border-primary)', fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontFamily: 'inherit', outline: 'none' }} />
@@ -1,3 +1,4 @@
import { focusRevealedEditor } from '../shared/dialogFocus'
import { useCallback, useRef } from 'react' import { useCallback, useRef } from 'react'
import { Briefcase, Plus, X } from 'lucide-react' import { Briefcase, Plus, X } from 'lucide-react'
import type { PackingState } from './usePackingListPanel' import type { PackingState } from './usePackingListPanel'
@@ -47,7 +48,7 @@ export function BagSidebar(S: PackingState) {
{canEdit && showAddBag && ( {canEdit && showAddBag && (
<div ref={composerRef} style={{ ...COMPOSER, margin: '10px 10px 0', paddingBlock: 4, paddingInlineEnd: 4, paddingInlineStart: 10 }}> <div ref={composerRef} style={{ ...COMPOSER, margin: '10px 10px 0', paddingBlock: 4, paddingInlineEnd: 4, paddingInlineStart: 10 }}>
<span aria-hidden style={{ width: 10, height: 10, borderRadius: '50%', border: '1.5px dashed var(--text-faint)', flexShrink: 0 }} /> <span aria-hidden style={{ width: 10, height: 10, borderRadius: '50%', border: '1.5px dashed var(--text-faint)', flexShrink: 0 }} />
<input autoFocus value={newBagName} onChange={e => setNewBagName(e.target.value)} <input ref={focusRevealedEditor} value={newBagName} onChange={e => setNewBagName(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') void handleCreateBag(); if (e.key === 'Escape') closeComposer() }} onKeyDown={e => { if (e.key === 'Enter') void handleCreateBag(); if (e.key === 'Escape') closeComposer() }}
placeholder={t('packing.bagName')} placeholder={t('packing.bagName')}
style={{ flex: 1, minWidth: 0, padding: '5px 0', border: 'none', fontSize: 'calc(12.5px * var(--fs-scale-body, 1))', fontWeight: 500, fontFamily: 'inherit', outline: 'none', color: 'var(--text-primary)', background: 'transparent' }} /> style={{ flex: 1, minWidth: 0, padding: '5px 0', border: 'none', fontSize: 'calc(12.5px * var(--fs-scale-body, 1))', fontWeight: 500, fontFamily: 'inherit', outline: 'none', color: 'var(--text-primary)', background: 'transparent' }} />
@@ -1,3 +1,4 @@
import { focusRevealedEditor } from '../shared/dialogFocus'
import React, { useState, useRef, useEffect } from 'react' import React, { useState, useRef, useEffect } from 'react'
import { useTripStore } from '../../store/tripStore' import { useTripStore } from '../../store/tripStore'
import { useToast } from '../shared/Toast' import { useToast } from '../shared/Toast'
@@ -140,7 +141,7 @@ export function KategorieGruppe({ kategorie, items, tripId, allCategories, onRen
{editingName && canEdit ? ( {editingName && canEdit ? (
<input <input
autoFocus value={editKatName} ref={focusRevealedEditor} value={editKatName}
onChange={e => setEditKatName(e.target.value)} onChange={e => setEditKatName(e.target.value)}
onBlur={handleSaveKatName} onBlur={handleSaveKatName}
onKeyDown={e => { if (e.key === 'Enter') void handleSaveKatName(); if (e.key === 'Escape') { setEditingName(false); setEditKatName(kategorie) } }} onKeyDown={e => { if (e.key === 'Enter') void handleSaveKatName(); if (e.key === 'Escape') { setEditingName(false); setEditKatName(kategorie) } }}
@@ -319,7 +320,6 @@ export function KategorieGruppe({ kategorie, items, tripId, allCategories, onRen
<span aria-hidden style={{ width: 20, height: 20, borderRadius: 6, border: '1.5px solid var(--text-faint)', flexShrink: 0 }} /> <span aria-hidden style={{ width: 20, height: 20, borderRadius: 6, border: '1.5px solid var(--text-faint)', flexShrink: 0 }} />
<input <input
ref={addItemRef} ref={addItemRef}
autoFocus
value={newItemName} value={newItemName}
onChange={e => setNewItemName(e.target.value)} onChange={e => setNewItemName(e.target.value)}
onKeyDown={e => { onKeyDown={e => {
@@ -404,8 +404,7 @@ function CategoryGrip({ drag, kategorie, label }: { drag?: CategoryDrag; kategor
return ( return (
<span <span
draggable draggable
role="button" aria-hidden="true"
aria-label={label}
title={label} title={label}
onDragStart={e => { onDragStart={e => {
e.dataTransfer.effectAllowed = 'move' e.dataTransfer.effectAllowed = 'move'
@@ -1,3 +1,4 @@
import { replaceInlineMarkdownLinks } from '@trek/shared'
import type { PackingBag, PackingItem } from '../../types' import type { PackingBag, PackingItem } from '../../types'
import { KAT_COLORS, PACKING_PLACEHOLDER_NAME } from './packingListPanel.constants' import { KAT_COLORS, PACKING_PLACEHOLDER_NAME } from './packingListPanel.constants'
@@ -7,7 +8,7 @@ export function katColor(kat: string, allCategories?: string[]): string {
if (idx >= 0) return KAT_COLORS[idx % KAT_COLORS.length] if (idx >= 0) return KAT_COLORS[idx % KAT_COLORS.length]
// Fallback: hash-based // Fallback: hash-based
let h = 0 let h = 0
for (let i = 0; i < kat.length; i++) h = ((h << 5) - h + (kat.codePointAt(i) ?? 0)) | 0 for (let i = 0; i < kat.length; i++) h = Math.imul((h << 5) - h + (kat.codePointAt(i) ?? 0), 1)
return KAT_COLORS[Math.abs(h) % KAT_COLORS.length] return KAT_COLORS[Math.abs(h) % KAT_COLORS.length]
} }
@@ -148,7 +149,7 @@ const MD_WEIGHT = /\((\d+(?:[.,]\d+)?)\s?(g|kg)\)$/i
/** Links, emphasis and code marks as plain text: a list copied from a notes app is full of them. */ /** Links, emphasis and code marks as plain text: a list copied from a notes app is full of them. */
const plainMarkdown = (text: string): string => const plainMarkdown = (text: string): string =>
text.replace(/\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/\*\*|__|~~|`/g, '').trim() replaceInlineMarkdownLinks(text, (label) => label, true).replace(/\*\*|__|~~|`/g, '').trim()
/** /**
* Whether pasted text is a Markdown list rather than CSV rows (#875): any heading or * Whether pasted text is a Markdown list rather than CSV rows (#875): any heading or
@@ -83,11 +83,11 @@ function DayRowTourPills({ tour, stageKey }: { tour: TourListItem; stageKey?: st
} }
// Description line, one line like every stop's. // Description line, one line like every stop's.
function SublineDescription({ text, isTourPlace }: { text: string; isTourPlace: boolean }) { function SublineDescription({ text, isTourPlace, fade }: { text: string; isTourPlace: boolean; fade: boolean }) {
return ( return (
<div <div
data-testid={isTourPlace ? 'trip-plan-tour-description' : undefined} data-testid={isTourPlace ? 'trip-plan-tour-description' : undefined}
className="collab-note-md min-w-0 flex-1 text-content-faint" className={`collab-note-md min-w-0 flex-1 text-content-faint${fade ? 'trek-fade-end' : ''}`}
style={{ style={{
...fs(10.5), ...fs(10.5),
overflow: 'hidden', overflow: 'hidden',
@@ -115,13 +115,15 @@ export function DayPlanPlaceSubline({
}: DayPlanPlaceSublineProps) { }: DayPlanPlaceSublineProps) {
const { locale } = useTranslation(); const { locale } = useTranslation();
const dayRowTour = tourTimes?.tour; const dayRowTour = tourTimes?.tour;
const wrapTourFacts = !!dayRowTour || hasPlannedTimes(tourTimes);
const description = place.description || place.address || cat?.name; const description = place.description || place.address || cat?.name;
if (!(dayRowTour || place.place_time || hasPlannedTimes(tourTimes) || description)) return null; if (!(wrapTourFacts || place.place_time || description)) return null;
return ( return (
// The description stays on one line and gives way first. The pills wrap rather // At a regular stop, the time stays readable and only the description gives way.
// than run out of the row: a tour carries a time, its duration and its distance, // A tour can wrap its time, duration and distance in the narrow day column.
// and in the narrow day column the last of them used to be cut off unseen. <div
<div className="trek-fade-end mt-0.5 flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 overflow-hidden"> className={`mt-0.5 flex min-w-0 items-center gap-x-1.5 overflow-hidden ${wrapTourFacts ? 'trek-fade-end flex-wrap gap-y-1' : 'flex-nowrap'}`}
>
{place.place_time && dayRowTour && ( {place.place_time && dayRowTour && (
// TIME-02: a tour's end, typed or worked out from its start and its time. // TIME-02: a tour's end, typed or worked out from its start and its time.
<TimePill quiet> <TimePill quiet>
@@ -143,7 +145,7 @@ export function DayPlanPlaceSubline({
tourTimes && <PlannedTourPills tourTimes={tourTimes} /> tourTimes && <PlannedTourPills tourTimes={tourTimes} />
)} )}
{dayRowTour && <WalkProgressPill tour={dayRowTour} assignmentId={assignmentId} />} {dayRowTour && <WalkProgressPill tour={dayRowTour} assignmentId={assignmentId} />}
{description && <SublineDescription text={description} isTourPlace={isTourPlace} />} {description && <SublineDescription text={description} isTourPlace={isTourPlace} fade={!wrapTourFacts} />}
</div> </div>
); );
} }
@@ -1,3 +1,4 @@
import { focusRevealedEditor } from '../shared/dialogFocus'
import { useState } from 'react' import { useState } from 'react'
import { Plus, X, MapPin } from 'lucide-react' import { Plus, X, MapPin } from 'lucide-react'
import { useTranslation } from '../../i18n' import { useTranslation } from '../../i18n'
@@ -40,7 +41,7 @@ export function MobileAddPlaceButton({ dayId, places, assignments, onAssign, onA
<div style={{ borderRadius: 14, border: '1px solid var(--border-primary)', background: 'var(--bg-card)', overflow: 'hidden' }}> <div style={{ borderRadius: 14, border: '1px solid var(--border-primary)', background: 'var(--bg-card)', overflow: 'hidden' }}>
<div style={{ padding: '8px 10px', borderBottom: '1px solid var(--border-faint)', display: 'flex', gap: 6 }}> <div style={{ padding: '8px 10px', borderBottom: '1px solid var(--border-faint)', display: 'flex', gap: 6 }}>
<input <input
autoFocus ref={focusRevealedEditor}
value={search} value={search}
onChange={e => setSearch(e.target.value)} onChange={e => setSearch(e.target.value)}
placeholder={t('dayplan.mobile.searchPlaces')} placeholder={t('dayplan.mobile.searchPlaces')}
@@ -4,6 +4,7 @@ import type { Category, Place } from '../../types';
import { safeHexColor } from '../../utils/safeColor'; import { safeHexColor } from '../../utils/safeColor';
import type { StopKind } from '../Roadtrip/stopKinds'; import type { StopKind } from '../Roadtrip/stopKinds';
import { getCategoryIcon } from '../shared/categoryIcons'; import { getCategoryIcon } from '../shared/categoryIcons';
import { focusRevealedEditor } from '../shared/dialogFocus';
import { PillSelect } from '../shared/dialogParts'; import { PillSelect } from '../shared/dialogParts';
import { PILL } from '../shared/DialogShell'; import { PILL } from '../shared/DialogShell';
import { NavigationMenu } from '../shared/NavigationMenu'; import { NavigationMenu } from '../shared/NavigationMenu';
@@ -47,7 +48,7 @@ export function HeaderPills({
categories: Category[] | null; categories: Category[] | null;
categoryId: string; categoryId: string;
onCategory: (id: string) => void; onCategory: (id: string) => void;
newCategory: NewCategoryRow; newCategory?: NewCategoryRow;
pickedSource: string | null; pickedSource: string | null;
busy: boolean; busy: boolean;
/** The place as the form holds it, once it has a position: opens it in a map app (#2178). */ /** The place as the form holds it, once it has a position: opens it in a map app (#2178). */
@@ -60,14 +61,15 @@ export function HeaderPills({
// goes with it, and the focus would drop out of the dialog. It comes back to // goes with it, and the focus would drop out of the dialog. It comes back to
// the + that opened the field, as a picker's focus comes back to its pill. // the + that opened the field, as a picker's focus comes back to its pill.
const plusRef = useRef<HTMLButtonElement | null>(null); const plusRef = useRef<HTMLButtonElement | null>(null);
const wasOpen = useRef(newCategory.open); const categoryEditorOpen = newCategory?.open ?? false;
const wasOpen = useRef(categoryEditorOpen);
useEffect(() => { useEffect(() => {
const closed = wasOpen.current && !newCategory.open; const closed = wasOpen.current && !categoryEditorOpen;
wasOpen.current = newCategory.open; wasOpen.current = categoryEditorOpen;
if (!closed) return; if (!closed) return;
const active = document.activeElement; const active = document.activeElement;
if (!active || active === document.body || !active.isConnected) plusRef.current?.focus(); if (!active || active === document.body || !active.isConnected) plusRef.current?.focus();
}, [newCategory.open]); }, [categoryEditorOpen]);
const noCategory = { const noCategory = {
label: t('places.noCategory'), label: t('places.noCategory'),
@@ -95,7 +97,7 @@ export function HeaderPills({
{t(kind.labelKey)} {t(kind.labelKey)}
</span> </span>
); );
} else if (newCategory.open) { } else if (newCategory?.open) {
lead = <NewCategoryField {...newCategory} t={t} />; lead = <NewCategoryField {...newCategory} t={t} />;
} else { } else {
lead = ( lead = (
@@ -107,17 +109,19 @@ export function HeaderPills({
options={options} options={options}
fallback={noCategory} fallback={noCategory}
/> />
<Tooltip label={t('places.newCategory')}> {newCategory && (
<button <Tooltip label={t('places.newCategory')}>
ref={plusRef} <button
type="button" ref={plusRef}
onClick={() => newCategory.setOpen(true)} type="button"
aria-label={t('places.newCategory')} onClick={() => newCategory.setOpen(true)}
className={ROUND_PILL_BUTTON} aria-label={t('places.newCategory')}
> className={ROUND_PILL_BUTTON}
<Plus size={13} strokeWidth={2.4} /> >
</button> <Plus size={13} strokeWidth={2.4} />
</Tooltip> </button>
</Tooltip>
)}
</> </>
); );
} }
@@ -185,7 +189,7 @@ function NewCategoryField({ inputId, name, setName, create, setOpen, t }: NewCat
<input <input
id={inputId} id={inputId}
type="text" type="text"
autoFocus ref={focusRevealedEditor}
value={name} value={name}
onChange={(e) => setName(e.target.value)} onChange={(e) => setName(e.target.value)}
onKeyDown={(e) => { onKeyDown={(e) => {
@@ -148,7 +148,9 @@ export type PlacePrefill = {
phone?: string phone?: string
osm_id?: string osm_id?: string
/** A place Google knows, such as one the assistant found: the details column reads it by this id. */ /** A place Google knows, such as one the assistant found: the details column reads it by this id. */
google_place_id?: string google_place_id?: string;
google_ftid?: string;
amap_poi_id?: string;
} }
/** A blank form at a prefilled position, with what the POI already knew. */ /** A blank form at a prefilled position, with what the POI already knew. */
@@ -163,6 +165,8 @@ export function prefillForm(prefill: PlacePrefill, extra: Partial<PlaceFormData>
phone: prefill.phone || '', phone: prefill.phone || '',
osm_id: prefill.osm_id, osm_id: prefill.osm_id,
google_place_id: prefill.google_place_id, google_place_id: prefill.google_place_id,
google_ftid: prefill.google_ftid,
amap_poi_id: prefill.amap_poi_id,
...extra, ...extra,
} }
} }
@@ -184,7 +188,9 @@ export function openingDetailsSelection(
} }
} }
if (prefill) { if (prefill) {
return { placeId: prefill.google_place_id || prefill.osm_id || undefined, lat: prefill.lat, lng: prefill.lng, name: prefill.name || '' } return {
placeId: prefill.google_place_id || prefill.amap_poi_id || prefill.osm_id || undefined,
lat: prefill.lat, lng: prefill.lng, name: prefill.name || '' }
} }
return null return null
} }
@@ -198,11 +204,7 @@ export function openingDetailsSelection(
*/ */
export function openingAutoFilled(place: unknown, prefill: PlacePrefill | null | undefined): Set<ResultField> { export function openingAutoFilled(place: unknown, prefill: PlacePrefill | null | undefined): Set<ResultField> {
return new Set( return new Set(
!place && prefill !place && prefill ? RESULT_FIELDS.filter((field) => prefill[field] !== undefined && prefill[field] !== '') : []
? (['name', 'address', 'lat', 'lng', 'website', 'phone', 'osm_id'] as ResultField[]).filter(
(field) => !!prefill[field as keyof PlacePrefill],
)
: [],
) )
} }
File diff suppressed because it is too large Load Diff
+64 -57
View File
@@ -36,7 +36,7 @@ const tint = (color: string, percent: number) => `color-mix(in srgb, ${color} ${
* field after them adds a new tag, in a colour picked the same way and shown on * field after them adds a new tag, in a colour picked the same way and shown on
* the field as it is typed. The state is usePlaceTags'; this is its markup. * the field as it is typed. The state is usePlaceTags'; this is its markup.
*/ */
export function PlaceFormTags({ tags, t }: { tags: PlaceTagsField; t: Translate }) { export function PlaceFormTags({ tags, t, manage = true }: { tags: PlaceTagsField; t: Translate; manage?: boolean }) {
// Which palette is open: a tag's id, 'new' for the new tag's colour, or none. // Which palette is open: a tag's id, 'new' for the new tag's colour, or none.
const [palette, setPalette] = useState<number | 'new' | null>(null); const [palette, setPalette] = useState<number | 'new' | null>(null);
// The colour a tag shows while its custom colour is being dragged, before it is kept. // The colour a tag shows while its custom colour is being dragged, before it is kept.
@@ -46,6 +46,7 @@ export function PlaceFormTags({ tags, t }: { tags: PlaceTagsField; t: Translate
setPalette(null); setPalette(null);
setPreview(null); setPreview(null);
}; };
if (!manage && tags.options.length === 0) return null;
return ( return (
<div className={PANEL}> <div className={PANEL}>
@@ -59,15 +60,19 @@ export function PlaceFormTags({ tags, t }: { tags: PlaceTagsField; t: Translate
className={`${PILL} ${tag.on ? '' : PILL_OFF}`} className={`${PILL} ${tag.on ? '' : PILL_OFF}`}
style={tag.on ? { background: tint(color, 18), borderColor: tint(color, 55) } : undefined} style={tag.on ? { background: tint(color, 18), borderColor: tint(color, 55) } : undefined}
> >
<button {manage ? (
type="button" <button
aria-label={t('places.tagColor', { name: tag.name })} type="button"
aria-expanded={palette === tag.id} aria-label={t('places.tagColor', { name: tag.name })}
onClick={() => (palette === tag.id ? closePalette() : setPalette(tag.id))} aria-expanded={palette === tag.id}
className={DOT_BUTTON} onClick={() => (palette === tag.id ? closePalette() : setPalette(tag.id))}
> className={DOT_BUTTON}
<span aria-hidden="true" className={DOT} style={{ background: color }} /> >
</button> <span aria-hidden="true" className={DOT} style={{ background: color }} />
</button>
) : (
<span aria-hidden="true" className={`${DOT} ms-2`} style={{ background: color }} />
)}
<button <button
type="button" type="button"
aria-pressed={tag.on} aria-pressed={tag.on}
@@ -95,55 +100,57 @@ export function PlaceFormTags({ tags, t }: { tags: PlaceTagsField; t: Translate
</span> </span>
); );
})} })}
<span {manage && (
className={NEW_TAG} <span
style={{ className={NEW_TAG}
background: tint(tags.newColor, typing ? 14 : 6), style={{
borderColor: tint(tags.newColor, typing ? 60 : 35), background: tint(tags.newColor, typing ? 14 : 6),
borderStyle: typing ? 'solid' : 'dashed', borderColor: tint(tags.newColor, typing ? 60 : 35),
}} borderStyle: typing ? 'solid' : 'dashed',
> }}
<button
type="button"
aria-label={t('places.newTagColor')}
aria-expanded={palette === 'new'}
onClick={() => (palette === 'new' ? closePalette() : setPalette('new'))}
className={DOT_BUTTON}
> >
<span aria-hidden="true" className={DOT} style={{ background: tags.newColor }} /> <button
</button> type="button"
<input aria-label={t('places.newTagColor')}
type="text" aria-expanded={palette === 'new'}
value={tags.name} onClick={() => (palette === 'new' ? closePalette() : setPalette('new'))}
onChange={(e) => tags.setName(e.target.value)} className={DOT_BUTTON}
onKeyDown={tags.handleNameKey} >
maxLength={TRIP_TAG_NAME_MAX} <span aria-hidden="true" className={DOT} style={{ background: tags.newColor }} />
aria-label={t('places.newTag')} </button>
placeholder={t('places.newTag')} <input
className={NEW_TAG_INPUT} type="text"
style={fs(12, 'body')} value={tags.name}
/> onChange={(e) => tags.setName(e.target.value)}
<button onKeyDown={tags.handleNameKey}
type="button" maxLength={TRIP_TAG_NAME_MAX}
onClick={() => void tags.addNew()} aria-label={t('places.newTag')}
disabled={!tags.canAdd} placeholder={t('places.newTag')}
aria-label={t('places.addTag')} className={NEW_TAG_INPUT}
className={ADD_BUTTON} style={fs(12, 'body')}
style={tags.canAdd ? { background: tags.newColor, color: 'var(--bg-card)' } : undefined}
>
<Plus size={13} strokeWidth={2.8} />
</button>
{palette === 'new' && (
<TagColorPopover
label={t('places.newTagColor')}
value={tags.newColor}
onPick={tags.setNewColor}
onPreview={tags.setNewColor}
onClose={closePalette}
t={t}
/> />
)} <button
</span> type="button"
onClick={() => void tags.addNew()}
disabled={!tags.canAdd}
aria-label={t('places.addTag')}
className={ADD_BUTTON}
style={tags.canAdd ? { background: tags.newColor, color: 'var(--bg-card)' } : undefined}
>
<Plus size={13} strokeWidth={2.8} />
</button>
{palette === 'new' && (
<TagColorPopover
label={t('places.newTagColor')}
value={tags.newColor}
onPick={tags.setNewColor}
onPreview={tags.setNewColor}
onClose={closePalette}
t={t}
/>
)}
</span>
)}
</div> </div>
</DialogSection> </DialogSection>
</div> </div>
@@ -36,6 +36,7 @@ export function PlaceFormTexts({
notes, notes,
dayNotes, dayNotes,
dayNumber = null, dayNumber = null,
initialTab,
onChange, onChange,
t, t,
}: { }: {
@@ -46,10 +47,11 @@ export function PlaceFormTexts({
dayNotes: string | null; dayNotes: string | null;
/** The day that visit is on, to name the tab after it ("Only day 3"). */ /** The day that visit is on, to name the tab after it ("Only day 3"). */
dayNumber?: number | null; dayNumber?: number | null;
initialTab?: PlaceTextField;
onChange: (field: PlaceTextField, value: string) => void; onChange: (field: PlaceTextField, value: string) => void;
t: Translate; t: Translate;
}) { }) {
const { tabs, shown, setActive } = usePlaceTextTabs({ description, notes, dayNotes, dayNumber, t }); const { tabs, shown, setActive } = usePlaceTextTabs({ description, notes, dayNotes, dayNumber, t, initialTab });
const refs = { const refs = {
description: useRef<HTMLTextAreaElement | null>(null), description: useRef<HTMLTextAreaElement | null>(null),
notes: useRef<HTMLTextAreaElement | null>(null), notes: useRef<HTMLTextAreaElement | null>(null),
@@ -102,7 +104,7 @@ export function PlaceFormTexts({
value={tab.value} value={tab.value}
onChange={(e) => onChange(tab.field, e.target.value)} onChange={(e) => onChange(tab.field, e.target.value)}
rows={3} rows={3}
maxLength={tab.maxLength} maxLength={initialTab && tab.field === 'assignment_notes' ? 500 : tab.maxLength}
className={BARE_TEXTAREA} className={BARE_TEXTAREA}
/> />
{tab.markdown && ( {tab.markdown && (
@@ -81,7 +81,7 @@ export function ListImportModal(S: SidebarState) {
onChange={e => setListImportUrl(e.target.value)} onChange={e => setListImportUrl(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter' && !listImportLoading) void handleListImport() }} onKeyDown={e => { if (e.key === 'Enter' && !listImportLoading) void handleListImport() }}
placeholder={google ? 'https://maps.app.goo.gl/...' : 'https://naver.me/...'} placeholder={google ? 'https://maps.app.goo.gl/...' : 'https://naver.me/...'}
autoFocus data-initial-focus
className={INPUT} className={INPUT}
/> />
</EditorField> </EditorField>
@@ -848,7 +848,7 @@ describe('ReservationsPanel', () => {
const user = userEvent.setup(); const user = userEvent.setup();
const onEdit = vi.fn(); const onEdit = vi.fn();
render(<ReservationsPanel {...defaultProps} reservations={[transitJourney()]} onEdit={onEdit} />); render(<ReservationsPanel {...defaultProps} reservations={[transitJourney()]} onEdit={onEdit} />);
await user.click(screen.getByRole('article', { name: /Hamburg Hbf/ })); await user.click(screen.getByRole('button', { name: /Hamburg Hbf/ }));
const detail = await screen.findByRole('dialog'); const detail = await screen.findByRole('dialog');
expect(onEdit).not.toHaveBeenCalled(); expect(onEdit).not.toHaveBeenCalled();
await user.click(within(detail).getByRole('button', { name: 'Edit' })); await user.click(within(detail).getByRole('button', { name: 'Edit' }));
@@ -274,11 +274,11 @@ describe('ReservationsPanel views', () => {
it('FE-PLANNER-RESVIEW-016: a card opens the detail on click or Enter, and Close shuts it', async () => { it('FE-PLANNER-RESVIEW-016: a card opens the detail on click or Enter, and Close shuts it', async () => {
const user = userEvent.setup(); const user = userEvent.setup();
renderPanel(); renderPanel();
await user.click(screen.getByRole('article', { name: 'LH 716' })); await user.click(within(screen.getByRole('article', { name: 'LH 716' })).getByRole('button', { name: 'LH 716' }));
expect(screen.getByRole('dialog', { name: 'LH 716' })).toBeInTheDocument(); expect(screen.getByRole('dialog', { name: 'LH 716' })).toBeInTheDocument();
await user.click(within(screen.getByRole('dialog', { name: 'LH 716' })).getByRole('button', { name: 'Close' })); await user.click(within(screen.getByRole('dialog', { name: 'LH 716' })).getByRole('button', { name: 'Close' }));
expect(screen.queryByRole('dialog', { name: 'LH 716' })).toBeNull(); expect(screen.queryByRole('dialog', { name: 'LH 716' })).toBeNull();
screen.getByRole('article', { name: 'LH 716' }).focus(); within(screen.getByRole('article', { name: 'LH 716' })).getByRole('button', { name: 'LH 716' }).focus();
await user.keyboard('{Enter}'); await user.keyboard('{Enter}');
expect(screen.getByRole('dialog', { name: 'LH 716' })).toBeInTheDocument(); expect(screen.getByRole('dialog', { name: 'LH 716' })).toBeInTheDocument();
}); });
@@ -286,7 +286,7 @@ describe('ReservationsPanel views', () => {
it('FE-PLANNER-RESVIEW-017: deleting the booking the detail shows closes the detail first', async () => { it('FE-PLANNER-RESVIEW-017: deleting the booking the detail shows closes the detail first', async () => {
const user = userEvent.setup(); const user = userEvent.setup();
renderPanel(); renderPanel();
await user.click(screen.getByRole('article', { name: 'Kaiseki dinner' })); await user.click(within(screen.getByRole('article', { name: 'Kaiseki dinner' })).getByRole('button', { name: 'Kaiseki dinner' }));
expect(screen.getByRole('dialog', { name: 'Kaiseki dinner' })).toBeInTheDocument(); expect(screen.getByRole('dialog', { name: 'Kaiseki dinner' })).toBeInTheDocument();
await user.click(within(screen.getByRole('article', { name: 'Kaiseki dinner' })).getByRole('button', { name: 'Delete' })); await user.click(within(screen.getByRole('article', { name: 'Kaiseki dinner' })).getByRole('button', { name: 'Delete' }));
const deletes = screen.getAllByRole('button', { name: 'Delete' }); const deletes = screen.getAllByRole('button', { name: 'Delete' });
@@ -60,6 +60,19 @@ describe('TransitJourneyModal', () => {
expect(screen.getByText(/BVG/)).toBeInTheDocument() expect(screen.getByText(/BVG/)).toBeInTheDocument()
}) })
it('FE-PLANNER-TRANSITJOURNEY-019: keeps room for both desktop stops beside a long line name', () => {
const reservation = makeReservation()
const line = 'Melbourne Airport Express via Southern Cross'
reservation.metadata.transit.legs[1] = { ...reservation.metadata.transit.legs[1], line, line_text_color: undefined }
render(<TransitJourneyModal {...makeProps({ reservation })} />)
const label = screen.getByText(line)
expect(label.parentElement).toHaveStyle({ maxInlineSize: '40%', color: '#fff' })
expect(label).toHaveClass('[overflow-wrap:anywhere]')
expect(screen.getAllByText('Alexanderplatz').length).toBeGreaterThan(0)
expect(screen.getAllByText('Zoo').length).toBeGreaterThan(0)
})
it('FE-PLANNER-TRANSITJOURNEY-002: inline title rename + notes save as a minimal field payload', async () => { it('FE-PLANNER-TRANSITJOURNEY-002: inline title rename + notes save as a minimal field payload', async () => {
const user = userEvent.setup() const user = userEvent.setup()
const onSave = vi.fn().mockResolvedValue({}) const onSave = vi.fn().mockResolvedValue({})
@@ -263,6 +276,18 @@ describe('TransitJourneyModal (mobile viewport)', () => {
expect(screen.getByText('Kudamm')).toBeInTheDocument() expect(screen.getByText('Kudamm')).toBeInTheDocument()
}) })
it('FE-PLANNER-TRANSITJOURNEY-020: wraps a long phone badge while keeping its headsign visible', () => {
const reservation = makeMobileReservation()
const line = 'Melbourne Airport Express via Southern Cross'
reservation.metadata.transit.legs[1] = { ...reservation.metadata.transit.legs[1], line, line_text_color: undefined }
render(<TransitJourneyModal {...makeProps({ reservation })} />)
const label = screen.getByText(line)
expect(label.parentElement).toHaveStyle({ maxInlineSize: '40%', color: '#fff' })
expect(label).toHaveClass('[overflow-wrap:anywhere]')
expect(screen.getByText('Ruhleben')).toBeInTheDocument()
})
it('FE-PLANNER-TRANSITJOURNEY-016: mobile stat tiles stay iconless but keep value + caption', () => { it('FE-PLANNER-TRANSITJOURNEY-016: mobile stat tiles stay iconless but keep value + caption', () => {
render(<TransitJourneyModal {...makeProps({ reservation: makeMobileReservation() })} />) render(<TransitJourneyModal {...makeProps({ reservation: makeMobileReservation() })} />)
expect(screen.getByText('Transfers')).toBeInTheDocument() expect(screen.getByText('Transfers')).toBeInTheDocument()
@@ -15,7 +15,7 @@ import { useTranslation } from '../../i18n'
import { useSettingsStore } from '../../store/settingsStore' import { useSettingsStore } from '../../store/settingsStore'
import { useTripStore } from '../../store/tripStore' import { useTripStore } from '../../store/tripStore'
import { splitReservationDateTime, formatTime } from '../../utils/formatters' import { splitReservationDateTime, formatTime } from '../../utils/formatters'
import { TransitTitle, TransitMetaBadges, TransitWalkDivider, fmtTransitDuration } from './transitDisplay' import { TransitTitle, TransitLineBadge, TransitMetaBadges, TransitWalkDivider, fmtTransitDuration } from './transitDisplay'
import type { Reservation } from '../../types' import type { Reservation } from '../../types'
import { useIsPhone } from '../../mobile/useIsPhone' import { useIsPhone } from '../../mobile/useIsPhone'
@@ -423,9 +423,7 @@ export default function TransitJourneyModal({ reservation, onClose, onSave, onDe
</div> </div>
<div style={{ padding: '6px 0 8px', minWidth: 0 }}> <div style={{ padding: '6px 0 8px', minWidth: 0 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}> <div style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>
<span style={{ display: 'inline-flex', alignItems: 'center', background: leg.line_color || 'var(--bg-hover)', color: leg.line_color ? (leg.line_text_color || '#fff') : 'var(--text-primary)', borderRadius: 6, padding: '1px 7px', fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 700, flexShrink: 0 }}> <TransitLineBadge label={leg.line || leg.mode} besideText={Boolean(leg.headsign)} wrap style={{ background: leg.line_color || 'var(--bg-hover)', color: leg.line_color ? (leg.line_text_color || '#fff') : 'var(--text-primary)', borderRadius: 6, padding: '1px 7px', fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 700, flexShrink: 0 }} />
{leg.line || leg.mode}
</span>
{leg.headsign && ( {leg.headsign && (
<span className="text-content-faint" style={{ display: 'inline-flex', alignItems: 'center', gap: 3, fontSize: 'calc(11px * var(--fs-scale-caption, 1))', minWidth: 0 }}> <span className="text-content-faint" style={{ display: 'inline-flex', alignItems: 'center', gap: 3, fontSize: 'calc(11px * var(--fs-scale-caption, 1))', minWidth: 0 }}>
<MoveRight size={10} style={{ flexShrink: 0 }} /> <MoveRight size={10} style={{ flexShrink: 0 }} />
@@ -450,15 +448,13 @@ export default function TransitJourneyModal({ reservation, onClose, onSave, onDe
<div className="text-content-muted" style={{ width: 44, flexShrink: 0, textAlign: 'end', fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600, paddingTop: 1 }}> <div className="text-content-muted" style={{ width: 44, flexShrink: 0, textAlign: 'end', fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600, paddingTop: 1 }}>
{leg.from?.time || ''} {leg.from?.time || ''}
</div> </div>
<span style={{ display: 'inline-flex', alignItems: 'center', background: leg.line_color || 'var(--bg-hover)', color: leg.line_color ? (leg.line_text_color || '#fff') : 'var(--text-primary)', borderRadius: 6, padding: '2px 8px', fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))', fontWeight: 700, flexShrink: 0 }}> <TransitLineBadge label={leg.line || leg.mode} besideText style={{ background: leg.line_color || 'var(--bg-hover)', color: leg.line_color ? (leg.line_text_color || '#fff') : 'var(--text-primary)', borderRadius: 6, padding: '2px 8px', fontSize: 'calc(11.5px * var(--fs-scale-caption, 1))', fontWeight: 700, flexShrink: 0 }} />
{leg.line || leg.mode}
</span>
<div style={{ flex: 1, minWidth: 0 }}> <div style={{ flex: 1, minWidth: 0 }}>
<div className="text-content" style={{ fontSize: 'calc(13.5px * var(--fs-scale-body, 1))', fontWeight: 600, display: 'flex', alignItems: 'center', gap: 5, flexWrap: 'wrap' }}> <div className="text-content" style={{ fontSize: 'calc(13.5px * var(--fs-scale-body, 1))', fontWeight: 600, display: 'flex', alignItems: 'center', gap: 5, flexWrap: 'wrap' }}>
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>{leg.from?.name}</span> <span dir="auto" style={{ minWidth: 0, overflowWrap: 'anywhere' }}>{leg.from?.name}</span>
{leg.from?.track && <span className="text-content-faint" style={{ fontWeight: 500 }}>({t('transit.platform', { track: leg.from.track })})</span>} {leg.from?.track && <span className="text-content-faint" style={{ fontWeight: 500 }}>({t('transit.platform', { track: leg.from.track })})</span>}
<ArrowRight size={12} className="text-content-faint" style={{ flexShrink: 0 }} /> <ArrowRight size={12} className="text-content-faint" style={{ flexShrink: 0 }} />
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>{leg.to?.name}</span> <span dir="auto" style={{ minWidth: 0, overflowWrap: 'anywhere' }}>{leg.to?.name}</span>
</div> </div>
<div style={{ marginTop: 3 }}> <div style={{ marginTop: 3 }}>
<TransitMetaBadges items={[ <TransitMetaBadges items={[
@@ -616,7 +616,7 @@ describe('TransitSearchPanel', () => {
await pickFromAndTo(user) await pickFromAndTo(user)
await user.click(screen.getByRole('button', { name: /^Search$/ })) await user.click(screen.getByRole('button', { name: /^Search$/ }))
await screen.findByText('B1') await screen.findByText('B1')
const icon = (text: string) => screen.getAllByText(text)[0].closest('span')?.querySelector('svg')?.getAttribute('class') const icon = (text: string) => screen.getAllByText(text)[0].parentElement?.querySelector('svg')?.getAttribute('class')
expect(icon('B1')).toContain('lucide-bus') expect(icon('B1')).toContain('lucide-bus')
expect(icon('M4')).toContain('lucide-tram-front') expect(icon('M4')).toContain('lucide-tram-front')
expect(icon('F10')).toContain('lucide-sailboat') expect(icon('F10')).toContain('lucide-sailboat')
@@ -3,7 +3,7 @@ import { createPortal } from 'react-dom'
import tzlookup from 'tz-lookup' import tzlookup from 'tz-lookup'
import { ArrowLeftRight, ArrowRight, Bus, CableCar, ChevronDown, ChevronUp, Clock, Footprints, MapPin, Sailboat, Search, TramFront, TrainFront, TrainFrontTunnel } from 'lucide-react' import { ArrowLeftRight, ArrowRight, Bus, CableCar, ChevronDown, ChevronUp, Clock, Footprints, MapPin, Sailboat, Search, TramFront, TrainFront, TrainFrontTunnel } from 'lucide-react'
import CustomTimePicker from '../shared/CustomTimePicker' import CustomTimePicker from '../shared/CustomTimePicker'
import { TransitMetaBadges } from './transitDisplay' import { TransitLineBadge, TransitMetaBadges } from './transitDisplay'
import { transitApi } from '../../api/client' import { transitApi } from '../../api/client'
import { useSettingsStore } from '../../store/settingsStore' import { useSettingsStore } from '../../store/settingsStore'
import { useToast } from '../shared/Toast' import { useToast } from '../shared/Toast'
@@ -326,15 +326,17 @@ function StopPicker({ label, value, onPick, quickPicks, near, placeholder }: {
// ── itinerary card ─────────────────────────────────────────────────────────── // ── itinerary card ───────────────────────────────────────────────────────────
function LineBadge({ leg }: { leg: TransitLeg }) { function LineBadge({ leg, wrap = false }: { leg: TransitLeg; wrap?: boolean }) {
const bg = leg.lineColor || 'var(--bg-tertiary)' const bg = leg.lineColor || 'var(--bg-tertiary)'
const fg = leg.lineColor ? (leg.lineTextColor || '#fff') : 'var(--text-primary)' const fg = leg.lineColor ? (leg.lineTextColor || '#fff') : 'var(--text-primary)'
const Icon = legIcon(leg.mode) const Icon = legIcon(leg.mode)
return ( return (
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, background: bg, color: fg, borderRadius: 6, padding: '2px 7px', fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 700, whiteSpace: 'nowrap' }}> <TransitLineBadge
<Icon size={11} strokeWidth={2.2} /> label={leg.line || leg.mode}
{leg.line || leg.mode} wrap={wrap}
</span> icon={<Icon size={11} strokeWidth={2.2} className="shrink-0" />}
style={{ gap: 4, background: bg, color: fg, borderRadius: 6, padding: '2px 7px', fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 700 }}
/>
) )
} }
@@ -425,7 +427,7 @@ function ItineraryCard({ it, tzFrom, tzTo, is12h, expanded, onToggle, onAdd, add
]} /> ]} />
) : ( ) : (
<> <>
<LineBadge leg={leg} /> <LineBadge leg={leg} wrap />
<TransitMetaBadges size="sm" items={[ <TransitMetaBadges size="sm" items={[
{ icon: ArrowRight, text: leg.headsign || '' }, { icon: ArrowRight, text: leg.headsign || '' },
{ text: fmtDuration(leg.duration, t) }, { text: fmtDuration(leg.duration, t) },
@@ -49,112 +49,112 @@ export default function BookingCard(p: BookingCardProps) {
const { t, locale } = useTranslation() const { t, locale } = useTranslation()
const tone = toneOf(r) const tone = toneOf(r)
const transit = r.type === 'transit' const transit = r.type === 'transit'
const title = displayTitle(r)
return ( return (
<article <article
tabIndex={0} aria-label={title}
onClick={p.onSelect} className={`group flex cursor-pointer flex-col overflow-hidden rounded-2xl border bg-surface-secondary transition-shadow hover:shadow-md ${p.selected ? 'border-[color:var(--text-primary)]' : 'border-edge-faint'}`}
onKeyDown={e => { if (e.target === e.currentTarget && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); p.onSelect() } }}
aria-label={displayTitle(r)}
className={`group flex cursor-pointer flex-col overflow-hidden rounded-2xl border bg-surface-secondary transition-shadow hover:shadow-md focus-visible:outline focus-visible:outline-2 focus-visible:outline-[color:var(--text-primary)] ${p.selected ? 'border-[color:var(--text-primary)]' : 'border-edge-faint'}`}
> >
<div className="flex items-center gap-2 border-b border-edge-faint px-3 py-2.5" style={{ background: toneTint(tone) }}> <div role="presentation" onClick={p.onSelect} className="flex flex-1 flex-col">
<StatusDot r={r} canToggle={p.canEdit} onToggle={p.onToggleStatus} /> <div className="flex items-center gap-2 border-b border-edge-faint px-3 py-2.5" style={{ background: toneTint(tone) }}>
<TypeChip type={r.type} /> <StatusDot r={r} canToggle={p.canEdit} onToggle={p.onToggleStatus} />
<span className="flex min-w-0 flex-1 items-center gap-1.5"> <TypeChip type={r.type} />
<span className="min-w-0 truncate font-bold text-content" style={fs(13.5, 'body')}>{displayTitle(r)}</span> <button type="button" aria-label={title} className="flex min-w-0 flex-1 items-center gap-1.5 rounded text-start focus-visible:outline focus-visible:outline-2 focus-visible:outline-[color:var(--text-primary)]">
{!!r.needs_review && <ReviewPill />} <span className="min-w-0 truncate font-bold text-content" style={fs(13.5, 'body')}>{title}</span>
</span> {!!r.needs_review && <ReviewPill />}
<AirTrailPill r={r} /> </button>
{p.canEdit && <RoundAction label={t('common.edit')} onClick={p.onEdit}><Pencil size={12} strokeWidth={2} /></RoundAction>} <AirTrailPill r={r} />
{p.canEdit && <RoundAction label={t('common.delete')} onClick={p.onDelete} danger><Trash2 size={12} strokeWidth={2} /></RoundAction>} {p.canEdit && <RoundAction label={t('common.edit')} onClick={p.onEdit}><Pencil size={12} strokeWidth={2} /></RoundAction>}
</div> {p.canEdit && <RoundAction label={t('common.delete')} onClick={p.onDelete} danger><Trash2 size={12} strokeWidth={2} /></RoundAction>}
</div>
<div className="flex flex-1 flex-col gap-2 px-3 pb-3 pt-2.5"> <div className="flex flex-1 flex-col gap-2 px-3 pb-3 pt-2.5">
<WhenFields facts={facts} /> <WhenFields facts={facts} />
<FlightLiveStrip tripId={p.tripId} reservationId={r.id} type={r.type} /> <FlightLiveStrip tripId={p.tripId} reservationId={r.id} type={r.type} />
{transit ? <TransitBody r={r} /> : ( {transit ? <TransitBody r={r} /> : (
<> <>
{r.confirmation_number && ( {r.confirmation_number && (
<Field label={t('reservations.confirmationCode')} tabular> <Field label={t('reservations.confirmationCode')} tabular>
<BlurredCode className="font-geist">{r.confirmation_number}</BlurredCode> <BlurredCode className="font-geist">{r.confirmation_number}</BlurredCode>
</Field> </Field>
)} )}
<RouteBox type={r.type} facts={facts} /> <RouteBox type={r.type} facts={facts} />
{facts.legCodes.length > 0 && ( {facts.legCodes.length > 0 && (
<Block label={t('reservations.segmentCodes')}> <Block label={t('reservations.segmentCodes')}>
<div className={`${BOX} flex flex-col gap-1 px-[10px] py-2`}> <div className={`${BOX} flex flex-col gap-1 px-[10px] py-2`}>
{facts.legCodes.map((l, i) => ( {facts.legCodes.map((l, i) => (
<div key={i} className="flex items-center gap-2" style={fs(12, 'body')}> <div key={i} className="flex items-center gap-2" style={fs(12, 'body')}>
<span className="min-w-0 flex-1 truncate font-medium text-content-secondary">{l.route || t('reservations.confirmationCode')}</span> <span className="min-w-0 flex-1 truncate font-medium text-content-secondary">{l.route || t('reservations.confirmationCode')}</span>
<BlurredCode className="font-geist tabular-nums text-content-muted">{l.code}</BlurredCode> <BlurredCode className="font-geist tabular-nums text-content-muted">{l.code}</BlurredCode>
</div> </div>
))} ))}
</div>
</Block>
)}
{facts.cells.length > 0 && (
<div className="grid grid-cols-3 gap-2">
{facts.cells.map((c, i) => <Field key={i} label={c.label}>{c.value}</Field>)}
</div> </div>
</Block> )}
)} </>
{facts.cells.length > 0 && ( )}
<div className="grid grid-cols-3 gap-2">
{facts.cells.map((c, i) => <Field key={i} label={c.label}>{c.value}</Field>)} {facts.place && <Field label={t('reservations.locationAddress')}>{facts.place}</Field>}
{facts.accommodation && <Field label={t('reservations.meta.linkAccommodation')}>{facts.accommodation}</Field>}
{facts.linked && <Field label={t('reservations.linkedTo')}>{facts.linked}</Field>}
{facts.url && (
<Field label={t('reservations.urlLabel')}>
{facts.url.href
? <a href={facts.url.href} target="_blank" rel="noopener noreferrer" onClick={e => e.stopPropagation()} className="text-content hover:underline">{facts.url.href}</a>
: facts.url.text}
</Field>
)}
{r.notes && (
<Block label={t('reservations.notes')}>
<div className={`${BOX} collab-note-md line-clamp-4 px-[10px] py-2 text-content-muted`} style={fs(12, 'body')}>
<Markdown remarkPlugins={[remarkGfm, remarkBreaks]} components={markdownLinkComponents}>{r.notes}</Markdown>
</div> </div>
)} </Block>
</> )}
)}
{facts.place && <Field label={t('reservations.locationAddress')}>{facts.place}</Field>} {(r.travelers || []).length > 0 && (
{facts.accommodation && <Field label={t('reservations.meta.linkAccommodation')}>{facts.accommodation}</Field>} <Block label={t('reservations.travelers.label')}>
{facts.linked && <Field label={t('reservations.linkedTo')}>{facts.linked}</Field>} <TravelerChips travelers={r.travelers || []} />
{facts.url && ( </Block>
<Field label={t('reservations.urlLabel')}> )}
{facts.url.href
? <a href={facts.url.href} target="_blank" rel="noopener noreferrer" onClick={e => e.stopPropagation()} className="text-content hover:underline">{facts.url.href}</a>
: facts.url.text}
</Field>
)}
{r.notes && ( {p.files.length > 0 && (
<Block label={t('reservations.notes')}> <Block label={t('files.title')}>
<div className={`${BOX} collab-note-md line-clamp-4 px-[10px] py-2 text-content-muted`} style={fs(12, 'body')}> <FileRows files={p.files} />
<Markdown remarkPlugins={[remarkGfm, remarkBreaks]} components={markdownLinkComponents}>{r.notes}</Markdown> </Block>
)}
{p.costs.length > 0 && (
<div className="mt-auto flex flex-wrap justify-end gap-1.5 pt-0.5">
{p.costs.map(c => (
<span key={c.currency} className="inline-flex items-center gap-1 rounded-full bg-surface-tertiary px-2.5 py-[3px] font-geist font-semibold tabular-nums text-content-secondary" style={fs(11.5)}>
<Wallet size={11} strokeWidth={2} className="text-content-faint" />
{formatMoney(c.amount, c.currency, locale)}
</span>
))}
</div> </div>
</Block> )}
)} </div>
{(r.travelers || []).length > 0 && ( <PluginCardFooter items={p.contributions} tripId={p.tripId} />
<Block label={t('reservations.travelers.label')}> {p.showFrames && p.detailPlugins.length > 0 && (
<TravelerChips travelers={r.travelers || []} /> <div role="presentation" onClick={e => e.stopPropagation()} className="flex flex-col gap-2 px-3 pb-3">
</Block> {p.detailPlugins.map(pl => (
)} <div key={pl.id} className={`${BOX} overflow-hidden`}>
<PluginFrame pluginId={pl.id} tripId={String(p.tripId)} reservationId={String(r.id)} title={pl.name} surface="detail-slot" />
{p.files.length > 0 && ( </div>
<Block label={t('files.title')}>
<FileRows files={p.files} />
</Block>
)}
{p.costs.length > 0 && (
<div className="mt-auto flex flex-wrap justify-end gap-1.5 pt-0.5">
{p.costs.map(c => (
<span key={c.currency} className="inline-flex items-center gap-1 rounded-full bg-surface-tertiary px-2.5 py-[3px] font-geist font-semibold tabular-nums text-content-secondary" style={fs(11.5)}>
<Wallet size={11} strokeWidth={2} className="text-content-faint" />
{formatMoney(c.amount, c.currency, locale)}
</span>
))} ))}
</div> </div>
)} )}
</div> </div>
<PluginCardFooter items={p.contributions} tripId={p.tripId} />
{p.showFrames && p.detailPlugins.length > 0 && (
<div role="presentation" onClick={e => e.stopPropagation()} className="flex flex-col gap-2 px-3 pb-3">
{p.detailPlugins.map(pl => (
<div key={pl.id} className={`${BOX} overflow-hidden`}>
<PluginFrame pluginId={pl.id} tripId={String(p.tripId)} reservationId={String(r.id)} title={pl.name} surface="detail-slot" />
</div>
))}
</div>
)}
</article> </article>
) )
} }
@@ -163,7 +163,7 @@ function usePopover() {
function Menu({ children, onClose, width = 260 }: { children: ReactNode; onClose: () => void; width?: number }) { function Menu({ children, onClose, width = 260 }: { children: ReactNode; onClose: () => void; width?: number }) {
return ( return (
<div role="menu" onKeyDown={e => { if (e.key === 'Escape') onClose() }} className="absolute end-0 top-11 z-30" style={{ ...POPOVER, width }}> <div role="menu" tabIndex={-1} onKeyDown={e => { if (e.key === 'Escape') onClose() }} className="absolute end-0 top-11 z-30" style={{ ...POPOVER, width }}>
{children} {children}
</div> </div>
) )
@@ -35,7 +35,7 @@ export default function BookingsList(p: BookingsListProps) {
const rootRef = useRef<HTMLDivElement>(null) const rootRef = useRef<HTMLDivElement>(null)
const flat = p.groups.flatMap(g => (p.collapsed(g.id) ? [] : g.items)) const flat = p.groups.flatMap(g => (p.collapsed(g.id) ? [] : g.items))
const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => { const onNavigate = (e: KeyboardEvent<HTMLElement>) => {
if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return
e.preventDefault() e.preventDefault()
const focused = document.activeElement instanceof HTMLElement ? Number(document.activeElement.dataset.row) : Number.NaN const focused = document.activeElement instanceof HTMLElement ? Number(document.activeElement.dataset.row) : Number.NaN
@@ -45,13 +45,13 @@ export default function BookingsList(p: BookingsListProps) {
} }
return ( return (
<div ref={rootRef} onKeyDown={onKeyDown} className="flex flex-col gap-6"> <div ref={rootRef} className="flex flex-col gap-6">
{p.groups.map(g => { {p.groups.map(g => {
const open = !p.collapsed(g.id) const open = !p.collapsed(g.id)
return ( return (
<section key={g.id} className="overflow-hidden rounded-2xl border border-edge-faint bg-surface-card"> <section key={g.id} className="overflow-hidden rounded-2xl border border-edge-faint bg-surface-card">
{g.label && ( {g.label && (
<button type="button" onClick={() => p.onToggleGroup(g.id)} aria-expanded={open} <button type="button" onClick={() => p.onToggleGroup(g.id)} onKeyDown={onNavigate} aria-expanded={open}
className="flex w-full items-center gap-2 bg-surface-secondary px-3.5 py-2.5 text-start"> className="flex w-full items-center gap-2 bg-surface-secondary px-3.5 py-2.5 text-start">
<span className={EYEBROW} style={fs(10.5)}>{g.label}</span> <span className={EYEBROW} style={fs(10.5)}>{g.label}</span>
{g.sub && <span className="truncate font-geist font-medium text-content-muted" style={fs(11.5)}>{g.sub}</span>} {g.sub && <span className="truncate font-geist font-medium text-content-muted" style={fs(11.5)}>{g.sub}</span>}
@@ -59,7 +59,7 @@ export default function BookingsList(p: BookingsListProps) {
</button> </button>
)} )}
{open && g.items.map(r => ( {open && g.items.map(r => (
<Row key={r.id} r={r} p={p} facts={p.factsOf(r)} files={p.filesCount(r)} costs={p.costsOf(r)} t={t} locale={locale} /> <Row key={r.id} r={r} p={p} facts={p.factsOf(r)} files={p.filesCount(r)} costs={p.costsOf(r)} t={t} locale={locale} onNavigate={onNavigate} />
))} ))}
</section> </section>
) )
@@ -68,7 +68,7 @@ export default function BookingsList(p: BookingsListProps) {
) )
} }
function Row({ r, p, facts, files, costs, t, locale }: { function Row({ r, p, facts, files, costs, t, locale, onNavigate }: {
r: Reservation r: Reservation
p: BookingsListProps p: BookingsListProps
facts: BookingFacts facts: BookingFacts
@@ -76,6 +76,7 @@ function Row({ r, p, facts, files, costs, t, locale }: {
costs: CostTotal[] costs: CostTotal[]
t: (k: string, v?: Record<string, string | number>) => string t: (k: string, v?: Record<string, string | number>) => string
locale: string locale: string
onNavigate: (e: KeyboardEvent<HTMLElement>) => void
}) { }) {
const selected = p.selectedId === r.id const selected = p.selectedId === r.id
const transit = r.type === 'transit' const transit = r.type === 'transit'
@@ -93,7 +94,10 @@ function Row({ r, p, facts, files, costs, t, locale }: {
aria-pressed={selected} aria-pressed={selected}
aria-label={displayTitle(r)} aria-label={displayTitle(r)}
onClick={() => p.onSelect(r)} onClick={() => p.onSelect(r)}
onKeyDown={e => { if (e.target === e.currentTarget && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); p.onSelect(r) } }} onKeyDown={e => {
if (e.target === e.currentTarget && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); p.onSelect(r) }
else onNavigate(e)
}}
className={`group relative grid cursor-pointer grid-cols-[22px_32px_minmax(0,1fr)_minmax(118px,auto)_auto] items-center gap-3 border-t border-edge-faint px-3.5 py-2.5 first:border-t-0 hover:bg-surface-hover focus-visible:outline-none focus-visible:bg-surface-hover ${selected ? 'bg-surface-hover shadow-[inset_3px_0_0_0_var(--text-primary)]' : ''}`} className={`group relative grid cursor-pointer grid-cols-[22px_32px_minmax(0,1fr)_minmax(118px,auto)_auto] items-center gap-3 border-t border-edge-faint px-3.5 py-2.5 first:border-t-0 hover:bg-surface-hover focus-visible:outline-none focus-visible:bg-surface-hover ${selected ? 'bg-surface-hover shadow-[inset_3px_0_0_0_var(--text-primary)]' : ''}`}
> >
<StatusDot r={r} canToggle={p.canEdit} onToggle={() => p.onToggleStatus(r)} /> <StatusDot r={r} canToggle={p.canEdit} onToggle={() => p.onToggleStatus(r)} />

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