mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 01:28:55 +00:00
Compare commits
41 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c8d09fc132 | |||
| f5a510c78e | |||
| 86e98fde65 | |||
| 62a3e63f3f | |||
| 01ad13623c | |||
| 59e5c5a3c9 | |||
| a2cf911ce1 | |||
| 7a66a54e66 | |||
| 748434fc47 | |||
| 618f070675 | |||
| dacf19b4d5 | |||
| 103631d5fc | |||
| 10fecf4e80 | |||
| 12483f618f | |||
| 17c4d69e40 | |||
| d6184559e9 | |||
| 3089aee593 | |||
| 24ddc3e4b0 | |||
| a4cb6c69d8 | |||
| 6e224cb7a4 | |||
| 56b4568a16 | |||
| 756ef14b97 | |||
| e539860530 | |||
| 0d6a432967 | |||
| 89035059ec | |||
| 4ad926aafc | |||
| 60a30afb81 | |||
| b77c246df4 | |||
| 7f4ece2e6f | |||
| a14b6a61e6 | |||
| 871135edeb | |||
| c22c464e68 | |||
| 3c2dc51439 | |||
| 28eea68559 | |||
| 1ff8a814ae | |||
| 0d521f0930 | |||
| 7fc011408a | |||
| 8f20f9f7ea | |||
| 67b65a7647 | |||
| 82b2a530f3 | |||
| 76a3983972 |
@@ -438,10 +438,10 @@ jobs:
|
||||
- name: Lint
|
||||
# Errors fail, and the warnings per rule may not pass
|
||||
# scripts/eslint-baseline.json (src, tests and eslint-disable'd
|
||||
# messages counted apart). Type-aware rules build the src + tests
|
||||
# program, which outgrows Node's default ~4 GB heap on the runner.
|
||||
# messages counted apart). The typed src and test programs can exhaust
|
||||
# an 8 GiB heap. Leave headroom within the runner's 16 GB of RAM.
|
||||
env:
|
||||
NODE_OPTIONS: --max-old-space-size=8192
|
||||
NODE_OPTIONS: --max-old-space-size=10240
|
||||
TREK_LINT_BASE: refs/remotes/lint-base
|
||||
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
|
||||
# whose warning count rises above scripts/eslint-baseline.json.
|
||||
# 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:
|
||||
NODE_OPTIONS: --max-old-space-size=8192
|
||||
TREK_LINT_BASE: refs/remotes/lint-base
|
||||
|
||||
+15
-14
@@ -55,13 +55,13 @@
|
||||
"dependencies": {
|
||||
"@assistant-ui/react": "0.15.38",
|
||||
"@capacitor/action-sheet": "^8.1.1",
|
||||
"@capacitor/android": "^8.6.2",
|
||||
"@capacitor/android": "^8.6.3",
|
||||
"@capacitor/app": "^8.1.1",
|
||||
"@capacitor/core": "^8.6.2",
|
||||
"@capacitor/core": "^8.6.3",
|
||||
"@capacitor/dialog": "^8.0.1",
|
||||
"@capacitor/filesystem": "^8.1.3",
|
||||
"@capacitor/filesystem": "^8.1.6",
|
||||
"@capacitor/haptics": "^8.0.2",
|
||||
"@capacitor/ios": "^8.6.2",
|
||||
"@capacitor/ios": "^8.6.3",
|
||||
"@capacitor/keyboard": "^8.0.5",
|
||||
"@capacitor/share": "^8.0.1",
|
||||
"@capacitor/splash-screen": "^8.0.2",
|
||||
@@ -101,6 +101,7 @@
|
||||
"@fontsource/satisfy": "^5.3.0",
|
||||
"@fontsource/shrikhand": "^5.3.0",
|
||||
"@fontsource/yellowtail": "^5.3.0",
|
||||
"@lucide/icons": "1.82.0",
|
||||
"@maplibre/maplibre-gl-leaflet": "0.1.4",
|
||||
"@noble/hashes": "^2.4.0",
|
||||
"@simplewebauthn/browser": "^14.0.0",
|
||||
@@ -112,9 +113,9 @@
|
||||
"heic-to": "^1.6.7",
|
||||
"iso-3166-2": "^1.0.0",
|
||||
"leaflet": "^1.9.4",
|
||||
"lucide-react": "^0.577.0",
|
||||
"lucide-react": "^1.82.0",
|
||||
"mapbox-gl": "3.32.0",
|
||||
"maplibre-gl": "6.19.0",
|
||||
"maplibre-gl": "6.20.0",
|
||||
"modern-screenshot": "4.7.0",
|
||||
"plyr": "^3.8.5",
|
||||
"react": "^19.3.1",
|
||||
@@ -123,7 +124,7 @@
|
||||
"react-leaflet": "^5.0.0",
|
||||
"react-leaflet-cluster": "^4.1.3",
|
||||
"react-markdown": "^10.1.0",
|
||||
"react-router": "^7.18.4",
|
||||
"react-router": "^8.5.3",
|
||||
"rehype-sanitize": "^6.0.0",
|
||||
"remark-breaks": "^4.0.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
@@ -133,12 +134,12 @@
|
||||
"zustand": "^5.0.15"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@capacitor/cli": "^8.6.2",
|
||||
"@capacitor/cli": "^8.6.3",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@jscpd/core": "^4.2.5",
|
||||
"@jscpd/tokenizer": "^4.2.6",
|
||||
"@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/react": "^16.3.3",
|
||||
"@testing-library/user-event": "^14.6.13",
|
||||
@@ -146,22 +147,22 @@
|
||||
"@types/geojson": "^7946.0.16",
|
||||
"@types/leaflet": "^1.9.23",
|
||||
"@types/node": "^26.6.11",
|
||||
"@types/react": "^19.3.2",
|
||||
"@types/react": "^19.3.3",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@types/topojson-client": "^3.1.5",
|
||||
"@types/topojson-specification": "^1.0.5",
|
||||
"@vitejs/plugin-react": "^6.2.1",
|
||||
"@vitest/coverage-v8": "^5.1.2",
|
||||
"autoprefixer": "^10.7.0",
|
||||
"autoprefixer": "^10.7.1",
|
||||
"eslint": "^10.11.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-refresh": "^0.5.8",
|
||||
"fake-indexeddb": "^6.2.7",
|
||||
"jsdom": "^29.1.1",
|
||||
"msw": "^3.0.8",
|
||||
"postcss": "^8.5.33",
|
||||
"postcss": "^8.5.34",
|
||||
"prettier": "^3.10.1",
|
||||
"prettier-plugin-organize-imports": "^4.3.0",
|
||||
"prettier-plugin-tailwindcss": "^0.8.1",
|
||||
@@ -170,7 +171,7 @@
|
||||
"tailwindcss": "^3.4.19",
|
||||
"typescript": "^6.0.3",
|
||||
"typescript-eslint": "^8.74.0",
|
||||
"vite": "8.3.8",
|
||||
"vite": "8.4.0",
|
||||
"vite-plugin-pwa": "^2.0.0",
|
||||
"vitest": "^5.1.2"
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
"trek/no-swallowed-catch": 124,
|
||||
"max-params": 31,
|
||||
"trek/store-without-selector": 65,
|
||||
"react-hooks/refs": 385,
|
||||
"react-hooks/refs": 384,
|
||||
"react-hooks/set-state-in-effect": 188,
|
||||
"@typescript-eslint/no-floating-promises": 162,
|
||||
"react-hooks/exhaustive-deps": 112,
|
||||
@@ -35,7 +35,7 @@
|
||||
},
|
||||
"tests": {
|
||||
"@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-unused-vars": 48,
|
||||
"@typescript-eslint/no-floating-promises": 33,
|
||||
|
||||
@@ -776,7 +776,7 @@
|
||||
{
|
||||
"feature": "Place add/edit form and maps search: usePlaceForm",
|
||||
"hooks": ["src/components/Planner/usePlaceForm.ts"],
|
||||
"desktop": ["src/components/Planner/PlaceFormModal.tsx"],
|
||||
"desktop": ["src/components/Planner/usePlaceFormModal.ts"],
|
||||
"mobile": [
|
||||
"src/mobile/screens/trip/sheets/MPlaceEditSheet.tsx",
|
||||
"src/mobile/screens/trip/sheets/PlCategoryPicker.tsx"
|
||||
@@ -785,13 +785,13 @@
|
||||
{
|
||||
"feature": "Place add/edit form and maps search: usePlaceSearch",
|
||||
"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"]
|
||||
},
|
||||
{
|
||||
"feature": "Place add/edit form: tags",
|
||||
"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"]
|
||||
},
|
||||
{
|
||||
|
||||
@@ -640,7 +640,6 @@
|
||||
"src/components/Planner/PlaceFormModal.helpers.test.ts",
|
||||
"src/components/Planner/PlaceFormModal.helpers.ts",
|
||||
"src/components/Planner/PlaceFormModal.test.tsx",
|
||||
"src/components/Planner/PlaceFormModal.tsx",
|
||||
"src/components/Planner/PlaceInspector.test.tsx",
|
||||
"src/components/Planner/PlaceInspector.tsx",
|
||||
"src/components/Planner/PlacesBulkCategoryModal.test.tsx",
|
||||
@@ -1426,7 +1425,6 @@
|
||||
"src/mobile/screens/vacay/MVacayShareSheet.tsx",
|
||||
"src/mobile/screens/vacay/useMVacay.ts",
|
||||
"src/mobile/screens/vacay/vacayDayModel.ts",
|
||||
"src/mobile/useIsPhone.ts",
|
||||
"src/pages/AdminPage.test.tsx",
|
||||
"src/pages/AdminPage.tsx",
|
||||
"src/pages/AtlasPage.tsx",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"src/components/Admin/AdminPluginsPanel.test.tsx": 2704,
|
||||
"src/components/Admin/AdminPluginsPanel.tsx": 1265,
|
||||
"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/MapViewGL.test.tsx": 2919,
|
||||
"src/components/Map/MapViewGL.tsx": 2083,
|
||||
|
||||
@@ -48,7 +48,6 @@
|
||||
"src/components/Planner/DayPlanSidebar.tsx": 52,
|
||||
"src/components/Planner/DayPlanSidebarNoteModal.test.tsx": 1,
|
||||
"src/components/Planner/PlaceFormModal.test.tsx": 3,
|
||||
"src/components/Planner/PlaceFormModal.tsx": 1,
|
||||
"src/components/Planner/PlaceInspector.tsx": 16,
|
||||
"src/components/Planner/PlacesBulkCategoryModal.test.tsx": 1,
|
||||
"src/components/Planner/PlacesSidebar.tsx": 1,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import {
|
||||
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,
|
||||
Globe, History, Puzzle, Bot, Loader2,
|
||||
} from 'lucide-react'
|
||||
@@ -789,7 +789,7 @@ function PluginDetailModal({ item, installed, busy, onInstall, onClose, t, local
|
||||
footer={(
|
||||
<DialogFooter>
|
||||
<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 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>
|
||||
|
||||
@@ -210,11 +210,8 @@ describe('BackupPanel', () => {
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('backup-2025-01-15.zip')).toBeInTheDocument()
|
||||
})
|
||||
const trashBtn = Array.from(document.querySelectorAll('button')).find(
|
||||
b => b.querySelector('svg.lucide-trash2'),
|
||||
) as HTMLElement
|
||||
expect(trashBtn).toBeTruthy()
|
||||
await user.click(trashBtn!)
|
||||
const trashBtn = screen.getByRole('button', { name: 'Delete' })
|
||||
await user.click(trashBtn)
|
||||
// The question is the shared confirm dialog now, not window.confirm
|
||||
expect(await screen.findByText('Delete backup "backup-2025-01-15.zip"?')).toBeInTheDocument()
|
||||
const deleteButtons = screen.getAllByRole('button', { name: 'Delete' })
|
||||
@@ -428,9 +425,7 @@ describe('BackupPanel', () => {
|
||||
render(<><ToastContainer /><BackupPanel /></>)
|
||||
await screen.findByText('backup-2025-01-15.zip')
|
||||
|
||||
const trashBtn = Array.from(document.querySelectorAll('button')).find(
|
||||
b => b.querySelector('svg.lucide-trash2'),
|
||||
) as HTMLElement
|
||||
const trashBtn = screen.getByRole('button', { name: 'Delete' })
|
||||
await user.click(trashBtn)
|
||||
await user.click(await screen.findByRole('button', { name: 'Cancel' }))
|
||||
expect(deleteCalls).toBe(0)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { Plus, Trash2, Pencil, Package, X, Check, ChevronRight, FolderPlus, Loader2 } from 'lucide-react'
|
||||
import { fs } from '../shared/DialogShell'
|
||||
@@ -57,7 +58,7 @@ export default function PackingTemplateManager() {
|
||||
{showCreate && (
|
||||
<div className={COMPOSER_ROW} style={{ boxShadow: COMPOSER.boxShadow }}>
|
||||
<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) }}
|
||||
placeholder={t('admin.packingTemplates.namePlaceholder')} className={COMPOSER_INPUT} style={fs(13, 'body')} />
|
||||
<Tooltip label={t('common.save')}>
|
||||
@@ -101,7 +102,7 @@ export default function PackingTemplateManager() {
|
||||
<Package size={15} strokeWidth={1.9} />
|
||||
</span>
|
||||
{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)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') void handleRenameTemplate(tmpl.id); if (e.key === 'Escape') setEditingTemplate(null) }}
|
||||
aria-label={t('common.rename')}
|
||||
@@ -132,7 +133,7 @@ export default function PackingTemplateManager() {
|
||||
{/* 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">
|
||||
{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)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') void handleRenameCategory(cat.id); if (e.key === 'Escape') setEditingCatId(null) }}
|
||||
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">
|
||||
{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) }}
|
||||
aria-label={t('common.rename')}
|
||||
className={`${ROW_INPUT} flex-1`} style={fs(12.5, 'body')} />
|
||||
@@ -219,7 +220,7 @@ export default function PackingTemplateManager() {
|
||||
{/* Add category */}
|
||||
{addingCategory ? (
|
||||
<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('') } }}
|
||||
placeholder={t('admin.packingTemplates.categoryName')}
|
||||
className={COMPOSER_INPUT} style={fs(13, 'body')} />
|
||||
|
||||
@@ -67,7 +67,7 @@ function Catalog() {
|
||||
}}>
|
||||
<div className={GRID_2}>
|
||||
<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 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" />
|
||||
|
||||
@@ -62,7 +62,7 @@ export default function SchoolHolidayRegionEditor({ region, busy, offline = fals
|
||||
<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' : ''}`}>
|
||||
<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>
|
||||
<SettingsHint>{t('schoolCatalog.periodHint')}</SettingsHint>
|
||||
{holidays.map((holiday, index) => {
|
||||
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
ArrowUpCircle,
|
||||
Bug,
|
||||
CircleDot,
|
||||
Github,
|
||||
Globe,
|
||||
History,
|
||||
Info,
|
||||
@@ -23,6 +22,7 @@ import { createPortal } from 'react-dom';
|
||||
import { POPOVER } from '../../Packing/packingPopoverStyles';
|
||||
import ToggleSwitch from '../../Settings/ToggleSwitch';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import { Github } from '../../shared/legacyLucideIcons';
|
||||
import PluginIcon from '../../shared/PluginIcon';
|
||||
import { Tooltip } from '../../shared/Tooltip';
|
||||
import { deriveCaps } from '../pluginCaps';
|
||||
|
||||
@@ -11,12 +11,13 @@
|
||||
import type { AssistantApplied, AssistantChangeEffect, AssistantChangePreview } from '@trek/shared';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { buildAssignment, buildDay, buildPlace, buildTrip } from '../../../tests/helpers/factories';
|
||||
import { act, fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import { buildAssignment, buildCategory, buildDay, buildPlace, buildTrip } from '../../../tests/helpers/factories';
|
||||
import { act, fireEvent, render, screen, within } from '../../../tests/helpers/render';
|
||||
import { chatOf, useAssistantStore } from '../../store/assistantStore';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import AssistantChangeCard from './AssistantChangeCard';
|
||||
import AssistantCompareSwitch from './AssistantCompareSwitch';
|
||||
import AssistantDayPreview from './AssistantDayPreview';
|
||||
import type { ChangeItem } from './assistantParts';
|
||||
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: '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', () => {
|
||||
|
||||
@@ -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 { 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. */
|
||||
function CardHead({ open, count, actions }: { open: boolean; count: number; actions?: ReactNode }) {
|
||||
const { t } = useTranslation();
|
||||
const Icon = open ? ListChecks : CheckCheck;
|
||||
return (
|
||||
<CardHeader
|
||||
icon={open ? ListChecks : CheckCheck}
|
||||
icon={Icon}
|
||||
tone={open ? 'info' : 'success'}
|
||||
tint={open ? NEUTRAL_TINT : DONE_TINT}
|
||||
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}
|
||||
/>
|
||||
);
|
||||
@@ -186,11 +194,23 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
|
||||
const undone = useAssistantStore((s) => chatOf(s, tripId).undone);
|
||||
const decide = useAssistantStore((s) => s.decide);
|
||||
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 pending = items.filter((i) => i.state === 'pending');
|
||||
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 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.
|
||||
const folded = week.length > 0 && !showAll;
|
||||
|
||||
const toggleDay = (ids: readonly string[], include: boolean) =>
|
||||
setExcluded((prev) => {
|
||||
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 toggleDay = (ids: readonly string[], include: boolean) => choosePlanChanges(tripId, ids, include);
|
||||
const toggle = (toolCallId: string) => toggleDay([toolCallId], excluded.has(toolCallId));
|
||||
|
||||
const submit = (applyChosen: boolean) =>
|
||||
decide(
|
||||
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.
|
||||
@@ -230,6 +240,21 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
|
||||
};
|
||||
|
||||
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 (
|
||||
<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
|
||||
@@ -249,16 +274,31 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
|
||||
{t('assistant.week.showAll', { count: pending.length })}
|
||||
</button>
|
||||
)}
|
||||
<ChangeRows
|
||||
items={items}
|
||||
folded={folded}
|
||||
excluded={excluded}
|
||||
disabled={isRunning}
|
||||
undone={undone}
|
||||
undoable={undoable}
|
||||
onToggle={toggle}
|
||||
onUndo={(toolCallId) => void runUndo(toolCallId)}
|
||||
/>
|
||||
{!folded && groupedDay && planDay ? (
|
||||
<details open className="group/day mt-1">
|
||||
<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">
|
||||
<span
|
||||
aria-hidden="true"
|
||||
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"
|
||||
>
|
||||
{planDay.day_number}
|
||||
</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 && (
|
||||
<>
|
||||
<p className="sr-only" role="status">
|
||||
@@ -270,7 +310,7 @@ export default function AssistantChangeCard({ items }: { items: ChangeItem[] })
|
||||
</DialogButton>
|
||||
<DialogButton
|
||||
variant="primary"
|
||||
disabled={isRunning || chosen === 0}
|
||||
disabled={isRunning || chosen === 0 || invalid}
|
||||
onClick={() => void submit(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 {
|
||||
CalendarClock,
|
||||
CalendarDays,
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
} from 'lucide-react';
|
||||
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useTripStore } from '../../store/tripStore';
|
||||
import { FactChange } from './cards/parts/CardFacts';
|
||||
|
||||
/**
|
||||
@@ -45,10 +46,42 @@ function shown(row: AssistantChangeRow, value: string | null | undefined, dayWor
|
||||
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 categoryName = useTripStore((s) =>
|
||||
edits?.categoryId == null ? undefined : s.categories.find((category) => category.id === edits.categoryId)?.name
|
||||
);
|
||||
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)
|
||||
.sort((a, b) => KEY_ORDER.indexOf(a.labelKey) - KEY_ORDER.indexOf(b.labelKey))
|
||||
.slice(0, MAX_FACTS);
|
||||
|
||||
@@ -1,18 +1,28 @@
|
||||
import type { AssistantChangeEffect, AssistantMessage } from '@trek/shared';
|
||||
import { ArrowRightLeft, Minus, Sparkles } from 'lucide-react';
|
||||
import type { AssistantChangePreview, AssistantMessage, AssistantPlanEdits } from '@trek/shared';
|
||||
import { ArrowRightLeft, FileText, MapPin, Minus, type LucideIcon } from 'lucide-react';
|
||||
import { useMemo } from 'react';
|
||||
import { useShallow } from 'zustand/react/shallow';
|
||||
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { changeEffects } from '../../store/assistantMapModel';
|
||||
import { chatOf, useAssistantStore } from '../../store/assistantStore';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
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. */
|
||||
interface PreviewRow {
|
||||
toolCallId: string;
|
||||
kind: 'add' | 'in' | 'remove' | 'out';
|
||||
kind: 'add' | 'in' | 'remove' | 'out' | 'note';
|
||||
name: string;
|
||||
categoryId: number | null;
|
||||
categoryName?: string;
|
||||
start?: string;
|
||||
end?: string;
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
/** The changes no one has decided on yet, by their call. */
|
||||
@@ -29,25 +39,77 @@ function waitingCalls(messages: readonly AssistantMessage[]): Set<string> {
|
||||
}
|
||||
|
||||
function rowOf(
|
||||
toolCallId: string,
|
||||
effect: AssistantChangeEffect,
|
||||
preview: AssistantChangePreview,
|
||||
dayId: number,
|
||||
nameOf: (id: number | null) => string | null
|
||||
) {
|
||||
const name = effect.place?.name ?? nameOf(effect.placeId);
|
||||
if (!name) return null;
|
||||
if (effect.dayId === dayId) {
|
||||
const kind = effect.kind === 'remove' ? 'remove' : effect.kind === 'move' ? 'in' : 'add';
|
||||
return { toolCallId, kind, name } satisfies PreviewRow;
|
||||
places: readonly Place[],
|
||||
edits: AssistantPlanEdits | undefined
|
||||
): PreviewRow | null {
|
||||
const { toolCallId, effect, subject } = preview;
|
||||
if (preview.dayId === dayId && isDayNoteProposal(preview)) {
|
||||
return {
|
||||
toolCallId,
|
||||
kind: 'note',
|
||||
name: edits?.noteTitle || planField(preview, 'title') || subject,
|
||||
categoryId: null,
|
||||
detail: proposalNote(preview, edits) ?? undefined,
|
||||
};
|
||||
}
|
||||
if (effect.kind === 'move' && effect.fromDayId === dayId)
|
||||
return { toolCallId, kind: 'out', name } satisfies PreviewRow;
|
||||
return null;
|
||||
const kind = visitKind(preview, dayId);
|
||||
if (!kind) 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: {
|
||||
icon: Sparkles,
|
||||
icon: MapPin,
|
||||
row: 'border-dashed border-accent bg-accent-subtle',
|
||||
name: 'text-content',
|
||||
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',
|
||||
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.
|
||||
*/
|
||||
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 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 { setMapHover, open } = useAssistantStore(useShallow((s) => ({ setMapHover: s.setMapHover, open: s.open })));
|
||||
const places = useTripStore((s) => s.places);
|
||||
const categories = useTripStore((s) => s.categories);
|
||||
|
||||
const rows = useMemo(() => {
|
||||
const waiting = waitingCalls(messages);
|
||||
if (waiting.size === 0) return [];
|
||||
const nameOf = (id: number | null) => (id === null ? null : (places.find((p) => p.id === id)?.name ?? null));
|
||||
const out: PreviewRow[] = [];
|
||||
for (const [toolCallId, effect] of changeEffects(messages)) {
|
||||
if (!waiting.has(toolCallId)) continue;
|
||||
const row = rowOf(toolCallId, effect, dayId, nameOf);
|
||||
if (row) out.push(row);
|
||||
}
|
||||
return out;
|
||||
}, [messages, places, dayId]);
|
||||
return messages.flatMap((message) =>
|
||||
message.parts.flatMap((part) => {
|
||||
if (part.type !== 'data-trek-change' || !waiting.delete(part.data.toolCallId)) return [];
|
||||
const id = part.data.toolCallId;
|
||||
if (choices[id] === false) return [];
|
||||
const edits = liveEdit?.toolCallId === id ? liveEdit.edits : savedEdits[id];
|
||||
const row = rowOf(part.data, dayId, places, edits);
|
||||
return row ? [row] : [];
|
||||
})
|
||||
);
|
||||
}, [messages, places, dayId, savedEdits, liveEdit, choices]);
|
||||
|
||||
if (rows.length === 0) return null;
|
||||
return (
|
||||
<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) => {
|
||||
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;
|
||||
return (
|
||||
<li
|
||||
@@ -121,11 +203,29 @@ export default function AssistantDayPreview({ tripId, dayId }: { tripId: number;
|
||||
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">
|
||||
<Icon size={12} aria-hidden="true" />
|
||||
<span
|
||||
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>
|
||||
<bdi className={`min-w-0 flex-1 truncate text-caption font-medium ${look.name}`}>{row.name}</bdi>
|
||||
<span className="flex-shrink-0 rounded-full bg-surface-card px-2 py-0.5 text-caption text-content-muted shadow-sm">
|
||||
<span className="min-w-0 flex-1">
|
||||
<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)}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
@@ -4,10 +4,11 @@
|
||||
* The error line: one sentence, at most one thing to do, and that thing
|
||||
* 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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { HIKE } from '../../../tests/helpers/assistantTour';
|
||||
import { fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import { chatOf, useAssistantStore } from '../../store/assistantStore';
|
||||
import { setForcedOffline } from '../../sync/networkMode';
|
||||
@@ -33,13 +34,17 @@ const retry = vi.fn(async () => {});
|
||||
const continueHere = 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({
|
||||
status,
|
||||
retry,
|
||||
continueHere,
|
||||
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();
|
||||
});
|
||||
|
||||
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', () => {
|
||||
withError('decide_first');
|
||||
renderLine();
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useNavigate } from 'react-router';
|
||||
import { useNetworkMode } from '../../hooks/useNetworkMode';
|
||||
import { useTranslation } from '../../i18n';
|
||||
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 { CHATGPT_USAGE_URL, providerLabel } from './providerCatalog';
|
||||
|
||||
@@ -18,6 +18,10 @@ export default function AssistantError({ tripId }: { tripId: number }) {
|
||||
const navigate = useNavigate();
|
||||
const { offline } = useNetworkMode();
|
||||
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 retry = useAssistantStore((s) => s.retry);
|
||||
const continueHere = useAssistantStore((s) => s.continueHere);
|
||||
@@ -28,7 +32,7 @@ export default function AssistantError({ tripId }: { tripId: number }) {
|
||||
|
||||
const effective = status?.effective;
|
||||
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) => {
|
||||
if (kind === 'retry') void retry(tripId);
|
||||
|
||||
@@ -139,7 +139,8 @@ function Answer({ message }: { message: StoredMessage }) {
|
||||
});
|
||||
const blocks = useMemo(() => messageBlocks(message, writing), [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 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 { render, screen } from '../../../tests/helpers/render';
|
||||
import { fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import AssistantSources from './AssistantSources';
|
||||
import { messageBlocks } from './assistantParts';
|
||||
|
||||
@@ -31,7 +31,8 @@ describe('AssistantSources', () => {
|
||||
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(
|
||||
{
|
||||
id: 'm1',
|
||||
@@ -40,12 +41,46 @@ describe('AssistantSources', () => {
|
||||
createdAt: '2026-10-23T10:00:00.000Z',
|
||||
parts: [
|
||||
{ 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: '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
|
||||
);
|
||||
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 { Globe } from 'lucide-react';
|
||||
import { ChevronDown, Globe } from 'lucide-react';
|
||||
import { useId, useState } from 'react';
|
||||
|
||||
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. */
|
||||
function hostOf(url: string): string {
|
||||
@@ -19,30 +23,48 @@ function hostOf(url: string): string {
|
||||
*/
|
||||
export default function AssistantSources({ sources }: { sources: Sources['sources'] }) {
|
||||
const { t } = useTranslation();
|
||||
const id = useId();
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const visible = expanded ? sources : sources.slice(0, INITIAL_COUNT);
|
||||
return (
|
||||
<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">
|
||||
{t('assistant.sources.title')}
|
||||
</span>
|
||||
<ul className="m-0 flex list-none flex-wrap gap-1.5 p-0">
|
||||
{sources.map((source) => (
|
||||
<li key={source.url} className="min-w-0 max-w-full">
|
||||
<a
|
||||
href={source.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer nofollow"
|
||||
title={source.title}
|
||||
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"
|
||||
>
|
||||
<Globe size={11} strokeWidth={2.2} aria-hidden="true" className="flex-none text-content-faint" />
|
||||
<span className="flex-none font-medium">{hostOf(source.url)}</span>
|
||||
{source.title && source.title !== source.url && (
|
||||
<bdi className="min-w-0 truncate text-content-muted">{source.title}</bdi>
|
||||
)}
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
<ul id={id} className="m-0 flex list-none flex-wrap gap-1.5 p-0">
|
||||
{visible.map(({ url, title }) => {
|
||||
const host = hostOf(url);
|
||||
const label = title && title !== url ? title : host;
|
||||
return (
|
||||
<li key={url} className="min-w-0 max-w-full">
|
||||
<Tooltip label={label} placement="top">
|
||||
<a
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer nofollow"
|
||||
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"
|
||||
>
|
||||
<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>
|
||||
{label !== host && <bdi className="max-w-[35%] shrink-0 truncate text-content-muted">{host}</bdi>}
|
||||
</a>
|
||||
</Tooltip>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,8 +2,9 @@ import { ChevronRight } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { POI_CATEGORIES } from '../Map/poiCategories';
|
||||
import AssistantLiveStep from './AssistantLiveStep';
|
||||
import { toolStepKey } from './assistantModel';
|
||||
import { liveStepText } from './assistantModel';
|
||||
import type { ToolStep } from './assistantParts';
|
||||
|
||||
/**
|
||||
@@ -37,9 +38,20 @@ export default function AssistantToolSteps({ steps }: { steps: ToolStep[] }) {
|
||||
</button>
|
||||
{open && (
|
||||
<ul className="m-0 mt-1 list-none space-y-0.5 border-s border-edge-faint ps-3">
|
||||
{steps.map((step) => (
|
||||
<li key={step.toolCallId}>{t(toolStepKey(step.toolName))}</li>
|
||||
))}
|
||||
{steps.map((step) => {
|
||||
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>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -170,12 +170,18 @@ describe('AssistantWindow', () => {
|
||||
|
||||
it('FE-AI-WIN-014: minimized outside a trip, the round button brings the home chat back', () => {
|
||||
seed({ open: true, minimized: true });
|
||||
render(<AssistantWindow trip={null} />);
|
||||
render(<AssistantWindow trip={null} />, { initialEntries: ['/atlas'] });
|
||||
expect(screen.getByText('chat 0 Your travels')).not.toBeVisible();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Assistant' }));
|
||||
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', () => {
|
||||
seed({ open: true, minimized: true }, true);
|
||||
render(<AssistantWindow trip={TRIP} />);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import './assistant.css';
|
||||
|
||||
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 { useTranslation } from '../../i18n';
|
||||
@@ -200,6 +200,7 @@ function windowChat(
|
||||
|
||||
export default function AssistantWindow({ trip, onOpen, onFocusDay, onRevealMap }: AssistantWindowProps) {
|
||||
const navigate = useNavigate();
|
||||
const onDashboard = useMatch('/') !== null;
|
||||
const available = useAssistantStore((s) => s.status?.available === true);
|
||||
const open = useAssistantStore((s) => s.window.open);
|
||||
const minimized = useAssistantStore((s) => s.window.minimized);
|
||||
@@ -267,8 +268,9 @@ export default function AssistantWindow({ trip, onOpen, onFocusDay, onRevealMap
|
||||
onOpenTripChat={atHome ? home.openTripChat : undefined}
|
||||
tripSwitch={tripSwitch}
|
||||
/>
|
||||
{/* Hidden while an answer may still come in: the round button brings it back, on any page. */}
|
||||
{minimized && <AssistantLauncher variant="floating" tripId={launcherTrip} focusOnMount />}
|
||||
{minimized && (!onDashboard || !!routeChat) && (
|
||||
<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. */
|
||||
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
|
||||
* 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(
|
||||
code: AssistantErrorCode,
|
||||
opts: { canConnectOwn: boolean; provider?: string }
|
||||
opts: { canConnectOwn: boolean; provider?: string; hasTourProposal?: boolean }
|
||||
): AssistantErrorView {
|
||||
const view = ERRORS[code];
|
||||
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' };
|
||||
return view;
|
||||
}
|
||||
|
||||
@@ -98,6 +98,27 @@ describe('messageBlocks', () => {
|
||||
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', () => {
|
||||
const blocks = messageBlocks(
|
||||
message([
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
ASSISTANT_FOLLOW_UPS_TOOL,
|
||||
assistantSourceTitle,
|
||||
type AssistantApplied,
|
||||
type AssistantChangeEffect,
|
||||
type AssistantChangeLabelKey,
|
||||
@@ -39,6 +40,8 @@ export interface ToolStep {
|
||||
toolName: string;
|
||||
/** Still waiting for its result while the answer is being written. */
|
||||
running: boolean;
|
||||
query?: string;
|
||||
categories?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -50,6 +53,7 @@ export type ChangeState = 'pending' | 'applying' | 'applied' | 'failed' | 'disca
|
||||
|
||||
export interface ChangeItem {
|
||||
toolCallId: string;
|
||||
args?: unknown;
|
||||
/** What the card says about it; null until the preview arrived. */
|
||||
preview: AssistantChangePreview | null;
|
||||
/** The receipt of an applied change. */
|
||||
@@ -269,6 +273,7 @@ function changeItemOf(
|
||||
const applied = receipts.get(part.toolCallId) ?? null;
|
||||
return {
|
||||
toolCallId: part.toolCallId,
|
||||
...(preview?.verbKey === 'addPlaceToDay' || preview?.verbKey === 'assignPlace' ? { args: part.args } : {}),
|
||||
preview,
|
||||
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
|
||||
* sat, each place once, without the ones a change the model proposed in the
|
||||
* answer already holds; the weather of all steps joins
|
||||
* into one row where the first look sat. A strip does not split the steps
|
||||
* around it: a step after it joins the row of steps before it.
|
||||
* into one row where the first look sat. The sources of all steps sit together
|
||||
* at the end of the answer.
|
||||
*
|
||||
* 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;
|
||||
@@ -311,6 +316,7 @@ export function messageBlocks(
|
||||
const previews = new Map<string, AssistantChangePreview>();
|
||||
const receipts = new Map<string, AssistantApplied>();
|
||||
const cards = new Map<string, TrekCard>();
|
||||
const sources = new Map<string, AssistantSources['sources'][number]>();
|
||||
const changeIds = new Set<string>();
|
||||
const effects: AssistantChangeEffect[] = [];
|
||||
// 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);
|
||||
if (part.data.effect && !fromStrip.has(part.data.toolCallId)) effects.push(part.data.effect);
|
||||
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-places') lastPlaces = 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 placesHidden =
|
||||
[...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));
|
||||
const blocks: MessageBlock[] = [];
|
||||
message.parts.forEach((part, index) => {
|
||||
@@ -347,10 +361,6 @@ export function messageBlocks(
|
||||
if (strip) blocks.push(strip);
|
||||
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) {
|
||||
blocks.push({ kind: 'weather', key: `weather-${index}`, days: weatherDays(message.parts) });
|
||||
return;
|
||||
@@ -373,18 +383,35 @@ export function messageBlocks(
|
||||
blocks.push({ kind: 'remembered', key: `remembered-${part.toolCallId}`, note });
|
||||
return;
|
||||
}
|
||||
const step: ToolStep = {
|
||||
toolCallId: part.toolCallId,
|
||||
toolName: part.toolName,
|
||||
running: writing && part.result === undefined,
|
||||
};
|
||||
const step = toolStep(part, writing);
|
||||
const steps = openSteps(blocks);
|
||||
if (steps) steps.steps.push(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);
|
||||
}
|
||||
|
||||
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
|
||||
* 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 {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -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 { Check, Undo2 } from 'lucide-react';
|
||||
import type { AssistantChangePreview, AssistantPlanEdits, TrekCardKind } from '@trek/shared';
|
||||
import { Check, Paperclip, Undo2 } from 'lucide-react';
|
||||
import { Fragment, type ReactNode } from 'react';
|
||||
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { Tooltip } from '../../shared/Tooltip';
|
||||
import AssistantChangeFields from '../AssistantChangeFields';
|
||||
import type { ChangeItem } from '../assistantParts';
|
||||
import AssistantPlanFields from '../AssistantPlanFields';
|
||||
import { isDayNoteProposal, isVisitProposal, planField, proposalNote } from '../assistantPlanFieldsModel';
|
||||
import { useAssistantView } from '../assistantViewContext';
|
||||
import { useChangeHover } from '../useChangeHover';
|
||||
import { isSingleBookingDraft } from './booking/bookingCardModel';
|
||||
import { TOOL_LABELS, verbLookOf } from './cardLooks';
|
||||
import type { CardView } from './cardTypes';
|
||||
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. */
|
||||
const settledOf = (item: ChangeItem, undone: boolean) =>
|
||||
item.state === 'discarded' || item.state === 'expired' || undone;
|
||||
@@ -164,11 +172,21 @@ function Receipt({
|
||||
const settled = settledOf(item, undone);
|
||||
const statusLabel = t(undone ? 'assistant.change.undone' : receipt.labelKey);
|
||||
const view = item.card ? viewOf(item.card) : null;
|
||||
const inlineBooking = inlineBookingCard(item);
|
||||
return (
|
||||
<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' : ''}`}>
|
||||
<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>
|
||||
{applied && <EntityActions applied={applied} card={item.card} />}
|
||||
{canUndo && (
|
||||
@@ -203,67 +221,134 @@ function PendingRow({
|
||||
withChoice,
|
||||
disabled,
|
||||
onToggle,
|
||||
edits,
|
||||
onEdit,
|
||||
groupedDay,
|
||||
}: {
|
||||
item: ChangeItem;
|
||||
excluded: boolean;
|
||||
withChoice: boolean;
|
||||
disabled: boolean;
|
||||
onToggle: () => void;
|
||||
edits: AssistantPlanEdits | undefined;
|
||||
onEdit: (patch: AssistantPlanEdits) => void;
|
||||
groupedDay: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { tripId } = useAssistantView();
|
||||
const { litFromMap, handlers } = useChangeHover(tripId, item.preview?.effect ? item.toolCallId : null);
|
||||
const preview = item.preview;
|
||||
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 (
|
||||
<div
|
||||
{...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' : ''
|
||||
} ${litFromMap ? 'bg-surface-hover' : 'hover:bg-surface-hover'}`}
|
||||
>
|
||||
{withChoice && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggle}
|
||||
disabled={disabled}
|
||||
aria-pressed={!excluded}
|
||||
aria-label={t('assistant.change.include')}
|
||||
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 ${
|
||||
excluded ? 'border-[1.5px] border-edge bg-surface-card' : 'bg-accent'
|
||||
}`}
|
||||
>
|
||||
{!excluded && <Check size={11} strokeWidth={3} aria-hidden="true" className="text-accent-text" />}
|
||||
</button>
|
||||
)}
|
||||
<Lead item={item} view={view} dimmed={excluded} />
|
||||
<div className="min-w-0 flex-1">
|
||||
{preview ? (
|
||||
<>
|
||||
{view?.ownsSubject ? (
|
||||
aside
|
||||
) : (
|
||||
<SubjectLine subject={preview.subject} struck={false} aside={view?.Aside && aside} block />
|
||||
{withChoice ? (
|
||||
<Tooltip label={t('assistant.change.include')}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggle}
|
||||
disabled={disabled}
|
||||
aria-pressed={!excluded}
|
||||
aria-label={t('assistant.change.include')}
|
||||
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 && (
|
||||
<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" />
|
||||
</span>
|
||||
)}
|
||||
<span className="mt-1 flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-1 text-caption text-content-faint">
|
||||
<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={preview.rows} />
|
||||
)}
|
||||
</span>
|
||||
</>
|
||||
</button>
|
||||
</Tooltip>
|
||||
) : (
|
||||
!inlineBooking && <Lead item={item} view={view} dimmed={excluded} />
|
||||
)}
|
||||
<div className="min-w-0 flex-1">
|
||||
{inlineBooking ? (
|
||||
<Slot name="Body" item={item} view={view} fallback={<ChangeHead item={item} view={view} struck={false} />} />
|
||||
) : 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" />
|
||||
)}
|
||||
</div>
|
||||
{editable && (
|
||||
<AssistantPlanFields
|
||||
preview={preview}
|
||||
args={item.args}
|
||||
edits={edits}
|
||||
disabled={disabled || excluded}
|
||||
onEdit={onEdit}
|
||||
/>
|
||||
)}
|
||||
</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 {
|
||||
items: readonly ChangeItem[];
|
||||
/** The waiting rows wait behind the week grid. */
|
||||
@@ -274,6 +359,9 @@ interface RowsProps {
|
||||
undoable: readonly string[];
|
||||
onToggle: (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. */
|
||||
@@ -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
|
||||
* 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;
|
||||
// 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.
|
||||
@@ -316,6 +416,9 @@ export function ChangeRows({ items, folded, excluded, disabled, undone, undoable
|
||||
withChoice={pendingCount > 1}
|
||||
disabled={disabled}
|
||||
onToggle={() => onToggle(item.toolCallId)}
|
||||
edits={planEdits[item.toolCallId]}
|
||||
onEdit={(patch) => onEdit(item.toolCallId, patch)}
|
||||
groupedDay={groupedDay}
|
||||
/>
|
||||
) : (
|
||||
<Receipt
|
||||
@@ -325,7 +428,9 @@ export function ChangeRows({ items, folded, excluded, disabled, undone, undoable
|
||||
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>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -25,6 +25,7 @@ import { useAuthStore } from '../../../../store/authStore';
|
||||
import { useSettingsStore } from '../../../../store/settingsStore';
|
||||
import type { ChangeItem } from '../../assistantParts';
|
||||
import { type AssistantView, AssistantViewContext } from '../../assistantViewContext';
|
||||
import { ChangeRows } from '../ChangeCardSlots';
|
||||
import BookingBlock from './BookingBlock';
|
||||
import { BookingChangeBody, BookingChangeFacts } from './BookingChangeSlots';
|
||||
|
||||
@@ -412,4 +413,44 @@ describe('booking cards', () => {
|
||||
expect(screen.queryByRole('button', { name: 'Open the booking' })).not.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 { useAssistantView } from '../../assistantViewContext';
|
||||
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';
|
||||
|
||||
/**
|
||||
@@ -88,11 +97,13 @@ export default function BookingCard({
|
||||
item,
|
||||
card,
|
||||
actions = true,
|
||||
proposal,
|
||||
}: {
|
||||
item: BookingItem;
|
||||
card: Card;
|
||||
/** Off inside a change card, whose row has its own ways to the booking. */
|
||||
actions?: boolean;
|
||||
proposal?: { label: string; notes?: string; reference?: string; receipt?: string };
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const body = item.body;
|
||||
@@ -101,17 +112,33 @@ export default function BookingCard({
|
||||
aria-label={item.title}
|
||||
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} />
|
||||
<div className="px-3 pb-2.5 pt-2">
|
||||
<BookingHead
|
||||
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 && (
|
||||
<p className="m-0 mb-1 text-caption text-content-muted">
|
||||
{t('assistant.card.booking.inTrip', { trip: item.tripTitle })}
|
||||
</p>
|
||||
)}
|
||||
{body.shape === 'ticket' && <TicketBody item={item} body={body} card={card} />}
|
||||
{body.shape === 'stay' && <StayBody item={item} body={body} card={card} />}
|
||||
{body.shape === 'venue' && <VenueBody item={item} body={body} card={card} />}
|
||||
<BookingFooter item={item} card={card} />
|
||||
{body.shape === 'stay' &&
|
||||
(proposal ? <StayProposalBody body={body} /> : <StayBody item={item} body={body} 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>
|
||||
</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 type { ChangeItem } from '../../assistantParts';
|
||||
import { verbLookOf } from '../cardLooks';
|
||||
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
|
||||
@@ -17,8 +21,28 @@ interface SlotProps {
|
||||
item: ChangeItem;
|
||||
}
|
||||
|
||||
/** The card under the row; the row itself leads to the booking once it is saved. */
|
||||
export function BookingChangeBody({ card }: SlotProps) {
|
||||
/** New single bookings carry their action in the card head. */
|
||||
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} />;
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,10 @@ import type { CardEntry } from '../cardTypes';
|
||||
/** A status a booking card names in words. */
|
||||
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
|
||||
* tone, a confirmed booking green, any other (pending, cancelled) amber; none
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
LogOut,
|
||||
MapPin,
|
||||
Moon,
|
||||
Paperclip,
|
||||
Route,
|
||||
Ticket,
|
||||
Wallet,
|
||||
@@ -23,7 +24,16 @@ import {
|
||||
import { useRef, type ReactNode } from 'react';
|
||||
|
||||
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 { SoftPill, TimePill, type PillTone } from '../../../Planner/planParts';
|
||||
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. */
|
||||
function HeadLead({ item }: { item: BookingItem }) {
|
||||
function HeadLead({ item, proposal }: { item: BookingItem; proposal: boolean }) {
|
||||
const { density } = useAssistantView();
|
||||
const compact = density === 'compact';
|
||||
if (item.body.shape === 'stay') {
|
||||
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,
|
||||
* 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 tone = toneOfItem(item);
|
||||
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 (
|
||||
<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 }}
|
||||
>
|
||||
<HeadLead item={item} />
|
||||
<span className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<HeadLead item={item} proposal={proposal} />
|
||||
<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">
|
||||
<bdi
|
||||
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}
|
||||
</bdi>
|
||||
@@ -138,19 +165,192 @@ export function BookingHead({ item, card, actions }: { item: BookingItem; card:
|
||||
{isChanged(card, item, 'title') && <ChangedDot />}
|
||||
{removed && <span className="sr-only">{t('assistant.card.common.willDelete')}</span>}
|
||||
</span>
|
||||
{address && (
|
||||
<bdi title={address} className="line-clamp-2 text-caption text-content-muted">
|
||||
{address}
|
||||
</bdi>
|
||||
)}
|
||||
</span>
|
||||
<StatusMark item={item} />
|
||||
{address &&
|
||||
(proposal ? (
|
||||
<span className="mt-0.5 flex items-start gap-1.5 text-caption text-content-muted">
|
||||
<MapPin size={12} className="mt-0.5 flex-none" aria-hidden="true" />
|
||||
<bdi title={address} className="line-clamp-2 break-words">
|
||||
{address}
|
||||
</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 />}
|
||||
{actions}
|
||||
</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. */
|
||||
function Pill({
|
||||
icon: Icon,
|
||||
|
||||
@@ -142,6 +142,10 @@ export const STEP_LOOKS: Readonly<Partial<Record<string, StepLook>>> = {
|
||||
stepKey: 'assistant.step.searching',
|
||||
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' } },
|
||||
get_place_details: { stepKey: 'assistant.step.details' },
|
||||
search_nearby_places: {
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
import type { TourRouteCard } from '@trek/shared';
|
||||
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 { act, fireEvent, render, screen } from '../../../../../tests/helpers/render';
|
||||
import { chatOf, useAssistantStore } from '../../../../store/assistantStore';
|
||||
@@ -81,6 +81,34 @@ describe('TourRouteBlock', () => {
|
||||
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', () => {
|
||||
renderBlock(WAYS, { density: 'roomy' });
|
||||
expect(screen.getByRole('radiogroup')).toHaveClass('grid-cols-2');
|
||||
|
||||
@@ -10,7 +10,7 @@ import TourRouteActions from './TourRouteActions';
|
||||
import TourRouteDay from './TourRouteDay';
|
||||
import TourRouteHead, { TourRouteFields } from './TourRouteHead';
|
||||
import { profileSamples } from './tourRouteModel';
|
||||
import { TourRouteProblem, TourRouteWarnings } from './TourRouteNotes';
|
||||
import { TourRouteDetour, TourRouteProblem, TourRouteWarnings } from './TourRouteNotes';
|
||||
import TourRouteProfile from './TourRouteProfile';
|
||||
import TourRouteStops from './TourRouteStops';
|
||||
import { routeName } from './tourRouteWords';
|
||||
@@ -45,6 +45,7 @@ export function TourRouteBody({
|
||||
return (
|
||||
<>
|
||||
<TourRouteFields card={card} />
|
||||
<TourRouteDetour card={card} />
|
||||
{/* A way drawn straight has neither heights nor the line to say so under: no section at all. */}
|
||||
{(samples.length >= 2 || card.routed) && (
|
||||
<CardSection label={t('tours.planner.inspector.elevation')}>
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useTranslation } from '../../../../i18n';
|
||||
import { SoftPill } from '../../../Planner/planParts';
|
||||
import { TourNotice } from '../../../Tours/tourParts';
|
||||
import { useCardFormat } from '../parts/useCardFormat';
|
||||
import { hasLongHikeDetour } from './tourRouteModel';
|
||||
import { PROBLEM_LOOK, WARNING_LOOK } from './tourRouteWords';
|
||||
|
||||
/**
|
||||
@@ -53,3 +54,15 @@ export function TourRouteProblem({ card }: { card: TourRouteCard }) {
|
||||
</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 { useTranslation } from '../../../../i18n';
|
||||
import { preferredRouteEntry } from '../../../../store/assistantRouteModel';
|
||||
import { chatOf, useAssistantStore } from '../../../../store/assistantStore';
|
||||
import { useSettingsStore } from '../../../../store/settingsStore';
|
||||
import type { DistanceUnit } from '../../../../types';
|
||||
@@ -79,7 +80,7 @@ function WayOption({
|
||||
entry: RouteEntry;
|
||||
index: number;
|
||||
chosen: boolean;
|
||||
chosenWay: LegVariant;
|
||||
chosenWay: LegVariant | null;
|
||||
chosenLetter: string;
|
||||
unit: DistanceUnit;
|
||||
onSelect: () => void;
|
||||
@@ -118,8 +119,14 @@ function WayOption({
|
||||
{/* Ways of a ride or a run may differ by profile: each says its own. */}
|
||||
{entry.card.routingProfile && <TourGrade card={entry.card} />}
|
||||
</span>
|
||||
<WayFigures way={way} unit={unit} />
|
||||
{!chosen && <WayDelta way={way} chosen={chosenWay} letter={chosenLetter} unit={unit} />}
|
||||
{entry.card.routed ? (
|
||||
<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>
|
||||
</button>
|
||||
);
|
||||
@@ -156,7 +163,7 @@ function WaysCard({
|
||||
[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.
|
||||
let columns = '';
|
||||
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[] }) {
|
||||
const { tripId } = useAssistantView();
|
||||
const blockKey = `tour:${entries[0]?.toolCallId ?? ''}`;
|
||||
const picked = useAssistantStore((s) => chatOf(s, tripId).picks[blockKey] ?? null);
|
||||
const index = entries.findIndex((entry) => entry.toolCallId === picked);
|
||||
const chosenIndex = index < 0 ? 0 : index;
|
||||
const chosen = entries[chosenIndex];
|
||||
const picked = useAssistantStore((s) => chatOf(s, tripId).picks[blockKey]);
|
||||
const chosen = preferredRouteEntry(entries, picked);
|
||||
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 { 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. */
|
||||
interface ProfileBand {
|
||||
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 { 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.
|
||||
*/
|
||||
export function useChangeExclusions(
|
||||
items: readonly ChangeItem[]
|
||||
): [ReadonlySet<string>, Dispatch<SetStateAction<ReadonlySet<string>>>] {
|
||||
items: readonly ChangeItem[],
|
||||
choices: Readonly<Record<string, boolean>>
|
||||
): ReadonlySet<string> {
|
||||
const [excluded, setExcluded] = useState<ReadonlySet<string>>(() => new Set(startingOff(items, new Set())));
|
||||
const [seen, setSeen] = useState<ReadonlySet<string>>(() => new Set(arrived(items)));
|
||||
const fresh = arrived(items).filter((id) => !seen.has(id));
|
||||
@@ -31,5 +32,11 @@ export function useChangeExclusions(
|
||||
setSeen(new Set([...seen, ...fresh]));
|
||||
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[] = [];
|
||||
kicks = 0;
|
||||
disposed = false;
|
||||
static create(opts: GlobeEngineOptions): FakeEngine {
|
||||
return new FakeEngine(opts);
|
||||
}
|
||||
|
||||
constructor(opts: GlobeEngineOptions) {
|
||||
if (state.failNext !== null) {
|
||||
const err = state.failNext;
|
||||
|
||||
@@ -54,7 +54,7 @@ const AtlasGlobe = forwardRef<AtlasGlobeHandle, AtlasGlobeProps>(function AtlasG
|
||||
if (!canvas) return;
|
||||
let engine: GlobeEngine;
|
||||
try {
|
||||
engine = new GlobeEngine({
|
||||
engine = GlobeEngine.create({
|
||||
canvas,
|
||||
fetchJson: (p) => propsRef.current.fetchJson(p),
|
||||
theme: globeTheme(propsRef.current.dark),
|
||||
|
||||
@@ -210,7 +210,7 @@ async function start(o: StartOptions = {}) {
|
||||
onSelect: 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);
|
||||
return {
|
||||
mod,
|
||||
@@ -310,7 +310,7 @@ describe('GlobeEngine boot', () => {
|
||||
const otherFetch = vi.fn(async (): Promise<unknown> => null);
|
||||
const canvas = document.createElement('canvas');
|
||||
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);
|
||||
await flush();
|
||||
expect(otherFetch).not.toHaveBeenCalled();
|
||||
@@ -345,7 +345,7 @@ describe('GlobeEngine boot retries', () => {
|
||||
});
|
||||
const onError = vi.fn();
|
||||
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[] = [];
|
||||
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 onReady = vi.fn();
|
||||
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();
|
||||
expect(ok).toHaveBeenCalledWith('manifest');
|
||||
@@ -381,7 +381,9 @@ describe('GlobeEngine boot retries', () => {
|
||||
return files[p];
|
||||
});
|
||||
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();
|
||||
expect(pending.map((t) => t.ms)).toEqual([1000]);
|
||||
pending[0].cb();
|
||||
|
||||
@@ -164,7 +164,13 @@ export class GlobeEngine {
|
||||
private sun: [number, number, number] = sunVector(new Date());
|
||||
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.theme = opts.theme;
|
||||
Object.assign(this.cam, opts.initial ?? {});
|
||||
@@ -187,7 +193,6 @@ export class GlobeEngine {
|
||||
this.resizeObs.observe(opts.canvas);
|
||||
opts.canvas.addEventListener('webglcontextlost', this.onContextLost);
|
||||
this.resize();
|
||||
void this.boot();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- loading
|
||||
|
||||
@@ -14,7 +14,7 @@ export function hexToRgb(hex: string): Rgb {
|
||||
.map((c) => c + c)
|
||||
.join('')
|
||||
: 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];
|
||||
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 type { ExpensePrefill } from './CostsPanel'
|
||||
import type { BudgetItem } from '../../types'
|
||||
import type { CostsSettlement } from './costsModel'
|
||||
|
||||
// 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
|
||||
@@ -329,3 +330,24 @@ export function expenseEditorFor(
|
||||
if (receipt) return { key: 'receipt', editing: null, prefill: receipt, close: closeReceipt }
|
||||
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(within(breakdown).getByText('90 €')).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([])
|
||||
|
||||
expect(await screen.findByText('No expenses yet. Add your first one.')).toBeInTheDocument()
|
||||
expect(screen.getByText('No expenses yet.')).toBeInTheDocument()
|
||||
expect(await screen.findByText('No expenses yet. Add your first one.')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('region', { name: 'Total trip spend' })).toBeNull();
|
||||
expect(screen.queryByRole('region', { name: 'By category' })).toBeNull();
|
||||
expect(screen.getByText("Everyone's square")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ import { CustomDatePicker } from '../shared/CustomDateTimePicker'
|
||||
import { useReceiptScan } from './useReceiptScan'
|
||||
import { ReceiptScanModal } from './ReceiptScanModal'
|
||||
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 {
|
||||
baseTotal as baseTotalOf, booked as bookedAmount, isUnfinished as isUnfinishedModel, lineOf as lineOfModel, memberShareOf,
|
||||
@@ -52,12 +52,6 @@ interface CostsPanelProps {
|
||||
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 FIELD_H = 40 // shared height for the amount / currency / day row in the modal
|
||||
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 can = useCanDo()
|
||||
const canEdit = can('budget_edit', trip)
|
||||
const hasExpenses = budgetItems.length > 0
|
||||
const receiptScan = useReceiptScan(tripId, canEdit)
|
||||
const toast = useToast()
|
||||
const { t, locale } = useTranslation()
|
||||
@@ -143,27 +138,12 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
// Nobody paid, so nobody owes (#2225).
|
||||
const myShareOf = (e: BudgetItem) => settledShareOf(e, ctx)
|
||||
|
||||
// ── day grouping ─────────────────────────────────────────────────────────
|
||||
const dayGroups = useMemo(() => {
|
||||
const entries: LedgerEntry[] = [
|
||||
...filtered.map(e => ({ kind: 'expense' as const, date: e.expense_date || '', e })),
|
||||
...filteredSettlements.map(s => ({ kind: 'payment' as const, date: settlementDate(s), s })),
|
||||
]
|
||||
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])
|
||||
const noDate = t('costs.noDate')
|
||||
const dayGroups = useMemo(() => groupLedgerByDay(filtered, filteredSettlements, locale, noDate), [filtered, filteredSettlements, locale, noDate])
|
||||
const emptyLedger = !hasExpenses && dayGroups.length === 0
|
||||
const mobileEmptyLedger = emptyLedger
|
||||
? <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>
|
||||
|
||||
// ── filter dropdown options (category + single day) ──────────────────────
|
||||
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 ── */}
|
||||
{!splitting ? <div style={{ marginBottom: 36 }}>{totalCard}</div> : (
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', gap: 16, marginBottom: 36 }} className="costs-summary">
|
||||
{!splitting ? (hasExpenses && <div style={{ marginBottom: 36 }}>{totalCard}</div>) : (
|
||||
<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}
|
||||
icon={<ArrowDown size={18} />} tone="owe" failed={settlementError}
|
||||
foot={totals.owe > 0.01
|
||||
@@ -302,18 +282,17 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
foot={totals.outstandingCount > 0
|
||||
? <span><b>{totals.outstandingCount}</b> {t('costs.outstandingItems', { count: totals.outstandingCount })}</span>
|
||||
: settledUp && <span className="text-content-faint">{t('costs.allSettled')}</span>} />
|
||||
{totalCard}
|
||||
{hasExpenses && totalCard}
|
||||
</div>)}
|
||||
|
||||
{/* ── Main grid ── */}
|
||||
{/* 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. */}
|
||||
<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: 'span 3', minWidth: 0 }}>
|
||||
<div className="costs-main" style={{ gridColumn: emptyLedger ? '1 / -1' : 'span 3', minWidth: 0 }}>
|
||||
|
||||
{dayBanner}
|
||||
{view === 'table' ? (
|
||||
{emptyLedger ? <EmptyState scene="costs" title={t('costs.emptyText')} /> : view === 'table' && hasExpenses ? (
|
||||
filtered.length === 0 && budgetItems.length > 0 ? (
|
||||
<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 */}
|
||||
{view === 'table' ? (
|
||||
{hasExpenses && (view === 'table' ? (
|
||||
<CostsTableSummary items={filtered} baseTotal={baseTotal} toBase={booked} fmt={v => fmt(v)} personName={personName} splitting={splitting} />
|
||||
) : (
|
||||
<section aria-label={t('costs.byCategory')} className={SIDE_CARD}>
|
||||
{sideHead(t('costs.byCategory'))}
|
||||
<div className="px-4 py-4">{categoryBars}</div>
|
||||
</section>
|
||||
)}
|
||||
))}
|
||||
<CostsModeCard trip={trip} memberCount={people.length} canEdit={canEdit} className={SIDE_CARD} />
|
||||
</div>
|
||||
</div>
|
||||
@@ -492,8 +471,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
function MobileBody() {
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 16, paddingTop: 8 }}>
|
||||
{/* Total card */}
|
||||
<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)' }}>
|
||||
{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)' }}>
|
||||
<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>
|
||||
{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')}
|
||||
</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) */}
|
||||
{splitting && <>
|
||||
@@ -583,7 +564,7 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
</div>
|
||||
{dayBanner}
|
||||
{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 => {
|
||||
const dtot = g.entries.reduce((a, en) => en.kind === 'expense' ? a + baseTotal(en.e) : a, 0)
|
||||
return (
|
||||
@@ -610,11 +591,10 @@ export default function CostsPanel({ tripId, tripMembers = [] }: CostsPanelProps
|
||||
</div>
|
||||
</>}
|
||||
|
||||
{/* By category */}
|
||||
<div className={cardCls} style={{ borderRadius: 18, padding: 16 }}>
|
||||
{hasExpenses && <div className={cardCls} style={{ borderRadius: 18, padding: 16 }}>
|
||||
<div className={labelCls} style={{ marginBottom: 14 }}>{t('costs.byCategory')}</div>
|
||||
{categoryBars}
|
||||
</div>
|
||||
</div>}
|
||||
<CostsModeCard trip={trip} memberCount={people.length} canEdit={canEdit} className={`${cardCls} rounded-[18px]`} />
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus'
|
||||
import { useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from 'react'
|
||||
import { ChevronDown, Lock, Pencil, Plus, Trash2 } from 'lucide-react'
|
||||
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) }
|
||||
}
|
||||
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))}
|
||||
className={`${INPUT} ${numeric ? 'text-center tabular-nums' : ''}`} />
|
||||
)
|
||||
|
||||
@@ -197,7 +197,7 @@ function FilterMenu(f: CostsFilterProps & { splitting: boolean }) {
|
||||
</button>
|
||||
</Tooltip>
|
||||
{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 && <>
|
||||
<div className="mx-1.5 mb-1 mt-1.5 flex rounded-[10px] bg-surface-tertiary p-[3px]">
|
||||
{owners.map(([o, label]) => (
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus'
|
||||
import { cloneElement, CSSProperties, FormEvent, ReactElement, useEffect, useId, useRef, useState } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
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>
|
||||
<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>
|
||||
<label htmlFor="collab-link-url" style={{ ...label, display: 'block' }}>{t('collab.links.urlPlaceholder')}</label>
|
||||
|
||||
@@ -118,7 +118,7 @@ function CreatePollModal({ onClose, onCreate, t }: CreatePollModalProps) {
|
||||
)}
|
||||
>
|
||||
<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 label={t('collab.polls.options')}>
|
||||
|
||||
@@ -102,7 +102,6 @@ export default function AddPlaceToCollectionModal({ isOpen, collectionId, collec
|
||||
<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" />
|
||||
<input
|
||||
autoFocus
|
||||
data-initial-focus
|
||||
ref={searchRef}
|
||||
type="text"
|
||||
|
||||
@@ -136,6 +136,7 @@ export default function CollectionExportMenu({ onExport, exporting, t }: Collect
|
||||
ref={menuRef}
|
||||
id={menuId}
|
||||
role="menu"
|
||||
tabIndex={-1}
|
||||
aria-label={t('collections.file.exportTitle')}
|
||||
onKeyDown={onMenuKeyDown}
|
||||
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 { getNavigationTargets, navigationTargetLabel, openNavigationTarget } from '../Planner/placeNavigation';
|
||||
import { getCategoryIcon } from '../shared/categoryIcons';
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus';
|
||||
import { DialogShell } from '../shared/DialogShell';
|
||||
import { markdownLinkComponents } from '../shared/markdownLink';
|
||||
import { NavigationMenu } from '../shared/NavigationMenu';
|
||||
@@ -202,7 +203,7 @@ function Cover({
|
||||
value={form.name}
|
||||
onChange={(e) => form.setName(e.target.value)}
|
||||
className="col-detail-name-input min-w-0 flex-1"
|
||||
autoFocus
|
||||
ref={focusRevealedEditor}
|
||||
aria-label={t('common.name')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -55,7 +55,7 @@ export default function CopyToTripModal({ isOpen, onClose, placeIds, onCopy, car
|
||||
<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" />
|
||||
<input
|
||||
autoFocus
|
||||
data-initial-focus
|
||||
value={search}
|
||||
onChange={e => setSearch(e.target.value)}
|
||||
placeholder={t('collections.copyToTripSearch')}
|
||||
|
||||
@@ -257,9 +257,14 @@ describe('ListEditorModal', () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: /Search Unsplash/ }))
|
||||
|
||||
expect(await screen.findByRole('button', { name: 'Rin' })).toBeInTheDocument()
|
||||
expect(screen.getByAltText('A street')).toHaveAttribute('title', 'A street')
|
||||
expect(tripsApi.searchCoverImages).toHaveBeenCalledWith('fjord')
|
||||
// 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()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Create' }))
|
||||
|
||||
@@ -126,7 +126,13 @@ export default function ListEditorModal({ target, onClose, onCreated, onRequestD
|
||||
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'}`}
|
||||
>
|
||||
<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>}
|
||||
</button>
|
||||
)
|
||||
|
||||
@@ -153,4 +153,9 @@ describe('ListsRail', () => {
|
||||
renderRail({ onSelectLibrary: vi.fn(), libraryCount: null });
|
||||
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>
|
||||
</div>
|
||||
|
||||
{onSelectLibrary && (
|
||||
{onSelectLibrary && libraryCount !== 0 && (
|
||||
<div className="col-row">
|
||||
<button type="button" onClick={onSelectLibrary} className={`col-row-btn${libraryActive ? ' on' : ''}`} aria-current={libraryActive ? 'page' : undefined}>
|
||||
<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">
|
||||
<Search size={14} className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint" aria-hidden="true" />
|
||||
<input
|
||||
autoFocus
|
||||
data-initial-focus
|
||||
value={search}
|
||||
onChange={e => setSearch(e.target.value)}
|
||||
placeholder={t('collections.searchLists')}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import type { PlacesLibraryDetailResponse } from '@trek/shared';
|
||||
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 remarkBreaks from 'remark-breaks';
|
||||
import remarkGfm from 'remark-gfm';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import MarkdownToolbar from '../Journey/MarkdownToolbar';
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus';
|
||||
import { markdownLinkComponents } from '../shared/markdownLink';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
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 }) {
|
||||
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 multi = n.isNew && n.composeTargets.length > 1;
|
||||
return (
|
||||
@@ -111,8 +116,7 @@ function NoteEditor({ n, t }: { n: Notes; t: TranslationFn }) {
|
||||
</div>
|
||||
) : (
|
||||
<textarea
|
||||
ref={ref}
|
||||
autoFocus
|
||||
ref={attachEditor}
|
||||
rows={6}
|
||||
value={n.draft}
|
||||
onChange={(e) => n.setDraft(e.target.value)}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { MapPin } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import type { Category, TranslationFn } from '../../types';
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus';
|
||||
import { NumericInput } from '../shared/NumericInput';
|
||||
import CategoryTileMenu from './CategoryTileMenu';
|
||||
import type { PlaceEditState } from './usePlaceEdit';
|
||||
@@ -36,7 +37,7 @@ export default function PlaceEditForm({
|
||||
/>
|
||||
)}
|
||||
<input
|
||||
autoFocus
|
||||
ref={focusRevealedEditor}
|
||||
value={draft.name}
|
||||
onChange={(e) => edit.set('name', e.target.value)}
|
||||
aria-label={t('common.name')}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Bookmark, Check, Luggage, Plus, Search, Tag, X } from 'lucide-react';
|
||||
import React, { useEffect, useRef } from 'react';
|
||||
import type { TranslationFn } from '../../types';
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus';
|
||||
import PlaceCard from './PlaceCard';
|
||||
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" />
|
||||
<input
|
||||
autoFocus
|
||||
ref={focusRevealedEditor}
|
||||
value={tags.query}
|
||||
onChange={(e) => tags.setQuery(e.target.value)}
|
||||
placeholder={t('placeTags.search')}
|
||||
|
||||
@@ -55,7 +55,7 @@ export default function SaveTripPlacesToListModal({ isOpen, tripId, placeIds, on
|
||||
<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" />
|
||||
<input
|
||||
autoFocus
|
||||
data-initial-focus
|
||||
value={search}
|
||||
onChange={e => setSearch(e.target.value)}
|
||||
placeholder={t('collections.searchLists')}
|
||||
|
||||
@@ -8,7 +8,9 @@ import { getApiErrorMessage } from '../../utils/apiError';
|
||||
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. */
|
||||
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
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { ArrowLeft, ArrowRight, Clock, ExternalLink, Images, RotateCcw } from 'lucide-react';
|
||||
import { lazy, Suspense, useId } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus';
|
||||
import {
|
||||
DialogButton,
|
||||
DialogFooter,
|
||||
@@ -116,7 +117,7 @@ function FooterLinks({ t, onCredits, focusCredits }: { t: Translate; onCredits:
|
||||
<button
|
||||
type="button"
|
||||
onClick={onCredits}
|
||||
autoFocus={focusCredits}
|
||||
ref={focusCredits ? focusRevealedEditor : undefined}
|
||||
className={FOOTER_LINK}
|
||||
style={fs(12.5, 'body')}
|
||||
>
|
||||
|
||||
@@ -106,17 +106,17 @@ export default function DocSyncConnectModal({
|
||||
</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="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')}
|
||||
</span>
|
||||
</span>
|
||||
<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>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ConfirmDialog
|
||||
|
||||
@@ -206,7 +206,7 @@ export default function ContributorInviteDialog({ journeyId, existingUserIds, on
|
||||
<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" />
|
||||
<input
|
||||
autoFocus
|
||||
data-initial-focus
|
||||
value={search}
|
||||
onChange={e => setSearch(e.target.value)}
|
||||
placeholder={t('journey.contributors.searchPlaceholder')}
|
||||
|
||||
@@ -51,7 +51,7 @@ export function AddTripDialog({ journeyId, existingTripIds, onClose, onAdded }:
|
||||
<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" />
|
||||
<input
|
||||
autoFocus
|
||||
data-initial-focus
|
||||
value={search}
|
||||
onChange={e => setSearch(e.target.value)}
|
||||
placeholder={t('journey.trips.searchPlaceholder')}
|
||||
|
||||
@@ -113,9 +113,9 @@ describe('MobileEntryView', () => {
|
||||
const order: string[] = []
|
||||
const onClose = vi.fn(() => { order.push('close') })
|
||||
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'])
|
||||
})
|
||||
@@ -123,7 +123,7 @@ describe('MobileEntryView', () => {
|
||||
it('FE-COMP-JENTRYVIEW-006: read-only journeys hide the edit and delete actions', () => {
|
||||
const { container } = renderView(buildEntry(), { readOnly: true })
|
||||
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
|
||||
expect(container.querySelector('svg.lucide-x')).not.toBeNull()
|
||||
})
|
||||
|
||||
@@ -104,6 +104,7 @@ export default function MobileEntryView({ entry, readOnly, publicPhotoUrl, onClo
|
||||
</button>
|
||||
<button type="button"
|
||||
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"
|
||||
>
|
||||
<Trash2 size={15} />
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
stripTrailingSlashes,
|
||||
resolveValhallaProvider,
|
||||
VALHALLA_COSTING,
|
||||
VALHALLA_RELAY_MAX_LOCATIONS,
|
||||
@@ -245,7 +246,7 @@ export function valhallaBase(): string | null {
|
||||
*/
|
||||
function currentProvider(ignoreRest = false): { provider: ValhallaProvider | null; own: string } {
|
||||
const settings = useSettingsStore.getState().settings
|
||||
const own = settings.valhalla_base_url?.trim().replace(/\/+$/, '') ?? ''
|
||||
const own = stripTrailingSlashes(settings.valhalla_base_url?.trim() ?? '')
|
||||
const provider = resolveValhallaProvider({
|
||||
provider: settings.routing_valhalla_provider,
|
||||
valhallaUrl: own,
|
||||
|
||||
@@ -269,7 +269,7 @@ describe('PackingListPanel', () => {
|
||||
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.
|
||||
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 () => {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus'
|
||||
import { useState, useRef, useCallback } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
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 }}>
|
||||
<span style={{ width: sz.dot, height: sz.dot, borderRadius: '50%', background: bag.color, flexShrink: 0 }} />
|
||||
{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() }}
|
||||
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 ? (
|
||||
<>
|
||||
<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}
|
||||
onKeyDown={e => { if (e.key === 'Enter') saveLimit(); if (e.key === 'Escape') cancelLimit() }}
|
||||
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 type { PackingState } from './usePackingListPanel'
|
||||
import { bagFillPct, bagLoadSummary, packedWeight, perPersonLoads } from './packingListPanel.helpers'
|
||||
@@ -72,7 +73,7 @@ export function BagModal(S: PackingState) {
|
||||
{/* Add bag */}
|
||||
{canEdit && (showAddBag ? (
|
||||
<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('') } }}
|
||||
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' }} />
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus'
|
||||
import { useCallback, useRef } from 'react'
|
||||
import { Briefcase, Plus, X } from 'lucide-react'
|
||||
import type { PackingState } from './usePackingListPanel'
|
||||
@@ -47,7 +48,7 @@ export function BagSidebar(S: PackingState) {
|
||||
{canEdit && showAddBag && (
|
||||
<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 }} />
|
||||
<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() }}
|
||||
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' }} />
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus'
|
||||
import React, { useState, useRef, useEffect } from 'react'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { useToast } from '../shared/Toast'
|
||||
@@ -140,7 +141,7 @@ export function KategorieGruppe({ kategorie, items, tripId, allCategories, onRen
|
||||
|
||||
{editingName && canEdit ? (
|
||||
<input
|
||||
autoFocus value={editKatName}
|
||||
ref={focusRevealedEditor} value={editKatName}
|
||||
onChange={e => setEditKatName(e.target.value)}
|
||||
onBlur={handleSaveKatName}
|
||||
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 }} />
|
||||
<input
|
||||
ref={addItemRef}
|
||||
autoFocus
|
||||
value={newItemName}
|
||||
onChange={e => setNewItemName(e.target.value)}
|
||||
onKeyDown={e => {
|
||||
@@ -404,8 +404,7 @@ function CategoryGrip({ drag, kategorie, label }: { drag?: CategoryDrag; kategor
|
||||
return (
|
||||
<span
|
||||
draggable
|
||||
role="button"
|
||||
aria-label={label}
|
||||
aria-hidden="true"
|
||||
title={label}
|
||||
onDragStart={e => {
|
||||
e.dataTransfer.effectAllowed = 'move'
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { replaceInlineMarkdownLinks } from '@trek/shared'
|
||||
import type { PackingBag, PackingItem } from '../../types'
|
||||
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]
|
||||
// Fallback: hash-based
|
||||
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]
|
||||
}
|
||||
|
||||
@@ -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. */
|
||||
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
|
||||
|
||||
@@ -83,11 +83,11 @@ function DayRowTourPills({ tour, stageKey }: { tour: TourListItem; stageKey?: st
|
||||
}
|
||||
|
||||
// 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 (
|
||||
<div
|
||||
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={{
|
||||
...fs(10.5),
|
||||
overflow: 'hidden',
|
||||
@@ -115,13 +115,15 @@ export function DayPlanPlaceSubline({
|
||||
}: DayPlanPlaceSublineProps) {
|
||||
const { locale } = useTranslation();
|
||||
const dayRowTour = tourTimes?.tour;
|
||||
const wrapTourFacts = !!dayRowTour || hasPlannedTimes(tourTimes);
|
||||
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 (
|
||||
// The description stays on one line and gives way first. The pills wrap rather
|
||||
// than run out of the row: a tour carries a time, its duration and its distance,
|
||||
// and in the narrow day column the last of them used to be cut off unseen.
|
||||
<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">
|
||||
// At a regular stop, the time stays readable and only the description gives way.
|
||||
// A tour can wrap its time, duration and distance in the narrow day column.
|
||||
<div
|
||||
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 && (
|
||||
// TIME-02: a tour's end, typed or worked out from its start and its time.
|
||||
<TimePill quiet>
|
||||
@@ -143,7 +145,7 @@ export function DayPlanPlaceSubline({
|
||||
tourTimes && <PlannedTourPills tourTimes={tourTimes} />
|
||||
)}
|
||||
{dayRowTour && <WalkProgressPill tour={dayRowTour} assignmentId={assignmentId} />}
|
||||
{description && <SublineDescription text={description} isTourPlace={isTourPlace} />}
|
||||
{description && <SublineDescription text={description} isTourPlace={isTourPlace} fade={!wrapTourFacts} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus'
|
||||
import { useState } from 'react'
|
||||
import { Plus, X, MapPin } from 'lucide-react'
|
||||
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={{ padding: '8px 10px', borderBottom: '1px solid var(--border-faint)', display: 'flex', gap: 6 }}>
|
||||
<input
|
||||
autoFocus
|
||||
ref={focusRevealedEditor}
|
||||
value={search}
|
||||
onChange={e => setSearch(e.target.value)}
|
||||
placeholder={t('dayplan.mobile.searchPlaces')}
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { Category, Place } from '../../types';
|
||||
import { safeHexColor } from '../../utils/safeColor';
|
||||
import type { StopKind } from '../Roadtrip/stopKinds';
|
||||
import { getCategoryIcon } from '../shared/categoryIcons';
|
||||
import { focusRevealedEditor } from '../shared/dialogFocus';
|
||||
import { PillSelect } from '../shared/dialogParts';
|
||||
import { PILL } from '../shared/DialogShell';
|
||||
import { NavigationMenu } from '../shared/NavigationMenu';
|
||||
@@ -47,7 +48,7 @@ export function HeaderPills({
|
||||
categories: Category[] | null;
|
||||
categoryId: string;
|
||||
onCategory: (id: string) => void;
|
||||
newCategory: NewCategoryRow;
|
||||
newCategory?: NewCategoryRow;
|
||||
pickedSource: string | null;
|
||||
busy: boolean;
|
||||
/** 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
|
||||
// the + that opened the field, as a picker's focus comes back to its pill.
|
||||
const plusRef = useRef<HTMLButtonElement | null>(null);
|
||||
const wasOpen = useRef(newCategory.open);
|
||||
const categoryEditorOpen = newCategory?.open ?? false;
|
||||
const wasOpen = useRef(categoryEditorOpen);
|
||||
useEffect(() => {
|
||||
const closed = wasOpen.current && !newCategory.open;
|
||||
wasOpen.current = newCategory.open;
|
||||
const closed = wasOpen.current && !categoryEditorOpen;
|
||||
wasOpen.current = categoryEditorOpen;
|
||||
if (!closed) return;
|
||||
const active = document.activeElement;
|
||||
if (!active || active === document.body || !active.isConnected) plusRef.current?.focus();
|
||||
}, [newCategory.open]);
|
||||
}, [categoryEditorOpen]);
|
||||
|
||||
const noCategory = {
|
||||
label: t('places.noCategory'),
|
||||
@@ -95,7 +97,7 @@ export function HeaderPills({
|
||||
{t(kind.labelKey)}
|
||||
</span>
|
||||
);
|
||||
} else if (newCategory.open) {
|
||||
} else if (newCategory?.open) {
|
||||
lead = <NewCategoryField {...newCategory} t={t} />;
|
||||
} else {
|
||||
lead = (
|
||||
@@ -107,17 +109,19 @@ export function HeaderPills({
|
||||
options={options}
|
||||
fallback={noCategory}
|
||||
/>
|
||||
<Tooltip label={t('places.newCategory')}>
|
||||
<button
|
||||
ref={plusRef}
|
||||
type="button"
|
||||
onClick={() => newCategory.setOpen(true)}
|
||||
aria-label={t('places.newCategory')}
|
||||
className={ROUND_PILL_BUTTON}
|
||||
>
|
||||
<Plus size={13} strokeWidth={2.4} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
{newCategory && (
|
||||
<Tooltip label={t('places.newCategory')}>
|
||||
<button
|
||||
ref={plusRef}
|
||||
type="button"
|
||||
onClick={() => newCategory.setOpen(true)}
|
||||
aria-label={t('places.newCategory')}
|
||||
className={ROUND_PILL_BUTTON}
|
||||
>
|
||||
<Plus size={13} strokeWidth={2.4} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -185,7 +189,7 @@ function NewCategoryField({ inputId, name, setName, create, setOpen, t }: NewCat
|
||||
<input
|
||||
id={inputId}
|
||||
type="text"
|
||||
autoFocus
|
||||
ref={focusRevealedEditor}
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
|
||||
@@ -148,7 +148,9 @@ export type PlacePrefill = {
|
||||
phone?: string
|
||||
osm_id?: string
|
||||
/** 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. */
|
||||
@@ -163,6 +165,8 @@ export function prefillForm(prefill: PlacePrefill, extra: Partial<PlaceFormData>
|
||||
phone: prefill.phone || '',
|
||||
osm_id: prefill.osm_id,
|
||||
google_place_id: prefill.google_place_id,
|
||||
google_ftid: prefill.google_ftid,
|
||||
amap_poi_id: prefill.amap_poi_id,
|
||||
...extra,
|
||||
}
|
||||
}
|
||||
@@ -184,7 +188,9 @@ export function openingDetailsSelection(
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -198,11 +204,7 @@ export function openingDetailsSelection(
|
||||
*/
|
||||
export function openingAutoFilled(place: unknown, prefill: PlacePrefill | null | undefined): Set<ResultField> {
|
||||
return new Set(
|
||||
!place && prefill
|
||||
? (['name', 'address', 'lat', 'lng', 'website', 'phone', 'osm_id'] as ResultField[]).filter(
|
||||
(field) => !!prefill[field as keyof PlacePrefill],
|
||||
)
|
||||
: [],
|
||||
!place && prefill ? RESULT_FIELDS.filter((field) => prefill[field] !== undefined && prefill[field] !== '') : []
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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
|
||||
* 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.
|
||||
const [palette, setPalette] = useState<number | 'new' | null>(null);
|
||||
// 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);
|
||||
setPreview(null);
|
||||
};
|
||||
if (!manage && tags.options.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className={PANEL}>
|
||||
@@ -59,15 +60,19 @@ export function PlaceFormTags({ tags, t }: { tags: PlaceTagsField; t: Translate
|
||||
className={`${PILL} ${tag.on ? '' : PILL_OFF}`}
|
||||
style={tag.on ? { background: tint(color, 18), borderColor: tint(color, 55) } : undefined}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('places.tagColor', { name: tag.name })}
|
||||
aria-expanded={palette === tag.id}
|
||||
onClick={() => (palette === tag.id ? closePalette() : setPalette(tag.id))}
|
||||
className={DOT_BUTTON}
|
||||
>
|
||||
<span aria-hidden="true" className={DOT} style={{ background: color }} />
|
||||
</button>
|
||||
{manage ? (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t('places.tagColor', { name: tag.name })}
|
||||
aria-expanded={palette === tag.id}
|
||||
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} ms-2`} style={{ background: color }} />
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={tag.on}
|
||||
@@ -95,55 +100,57 @@ export function PlaceFormTags({ tags, t }: { tags: PlaceTagsField; t: Translate
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
<span
|
||||
className={NEW_TAG}
|
||||
style={{
|
||||
background: tint(tags.newColor, typing ? 14 : 6),
|
||||
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}
|
||||
{manage && (
|
||||
<span
|
||||
className={NEW_TAG}
|
||||
style={{
|
||||
background: tint(tags.newColor, typing ? 14 : 6),
|
||||
borderColor: tint(tags.newColor, typing ? 60 : 35),
|
||||
borderStyle: typing ? 'solid' : 'dashed',
|
||||
}}
|
||||
>
|
||||
<span aria-hidden="true" className={DOT} style={{ background: tags.newColor }} />
|
||||
</button>
|
||||
<input
|
||||
type="text"
|
||||
value={tags.name}
|
||||
onChange={(e) => tags.setName(e.target.value)}
|
||||
onKeyDown={tags.handleNameKey}
|
||||
maxLength={TRIP_TAG_NAME_MAX}
|
||||
aria-label={t('places.newTag')}
|
||||
placeholder={t('places.newTag')}
|
||||
className={NEW_TAG_INPUT}
|
||||
style={fs(12, 'body')}
|
||||
/>
|
||||
<button
|
||||
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}
|
||||
<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>
|
||||
<input
|
||||
type="text"
|
||||
value={tags.name}
|
||||
onChange={(e) => tags.setName(e.target.value)}
|
||||
onKeyDown={tags.handleNameKey}
|
||||
maxLength={TRIP_TAG_NAME_MAX}
|
||||
aria-label={t('places.newTag')}
|
||||
placeholder={t('places.newTag')}
|
||||
className={NEW_TAG_INPUT}
|
||||
style={fs(12, 'body')}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
<button
|
||||
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>
|
||||
</DialogSection>
|
||||
</div>
|
||||
|
||||
@@ -36,6 +36,7 @@ export function PlaceFormTexts({
|
||||
notes,
|
||||
dayNotes,
|
||||
dayNumber = null,
|
||||
initialTab,
|
||||
onChange,
|
||||
t,
|
||||
}: {
|
||||
@@ -46,10 +47,11 @@ export function PlaceFormTexts({
|
||||
dayNotes: string | null;
|
||||
/** The day that visit is on, to name the tab after it ("Only day 3"). */
|
||||
dayNumber?: number | null;
|
||||
initialTab?: PlaceTextField;
|
||||
onChange: (field: PlaceTextField, value: string) => void;
|
||||
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 = {
|
||||
description: useRef<HTMLTextAreaElement | null>(null),
|
||||
notes: useRef<HTMLTextAreaElement | null>(null),
|
||||
@@ -102,7 +104,7 @@ export function PlaceFormTexts({
|
||||
value={tab.value}
|
||||
onChange={(e) => onChange(tab.field, e.target.value)}
|
||||
rows={3}
|
||||
maxLength={tab.maxLength}
|
||||
maxLength={initialTab && tab.field === 'assignment_notes' ? 500 : tab.maxLength}
|
||||
className={BARE_TEXTAREA}
|
||||
/>
|
||||
{tab.markdown && (
|
||||
|
||||
@@ -81,7 +81,7 @@ export function ListImportModal(S: SidebarState) {
|
||||
onChange={e => setListImportUrl(e.target.value)}
|
||||
onKeyDown={e => { if (e.key === 'Enter' && !listImportLoading) void handleListImport() }}
|
||||
placeholder={google ? 'https://maps.app.goo.gl/...' : 'https://naver.me/...'}
|
||||
autoFocus
|
||||
data-initial-focus
|
||||
className={INPUT}
|
||||
/>
|
||||
</EditorField>
|
||||
|
||||
@@ -848,7 +848,7 @@ describe('ReservationsPanel', () => {
|
||||
const user = userEvent.setup();
|
||||
const onEdit = vi.fn();
|
||||
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');
|
||||
expect(onEdit).not.toHaveBeenCalled();
|
||||
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 () => {
|
||||
const user = userEvent.setup();
|
||||
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();
|
||||
await user.click(within(screen.getByRole('dialog', { name: 'LH 716' })).getByRole('button', { name: 'Close' }));
|
||||
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}');
|
||||
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 () => {
|
||||
const user = userEvent.setup();
|
||||
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();
|
||||
await user.click(within(screen.getByRole('article', { name: 'Kaiseki dinner' })).getByRole('button', { name: 'Delete' }));
|
||||
const deletes = screen.getAllByRole('button', { name: 'Delete' });
|
||||
|
||||
@@ -60,6 +60,19 @@ describe('TransitJourneyModal', () => {
|
||||
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 () => {
|
||||
const user = userEvent.setup()
|
||||
const onSave = vi.fn().mockResolvedValue({})
|
||||
@@ -263,6 +276,18 @@ describe('TransitJourneyModal (mobile viewport)', () => {
|
||||
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', () => {
|
||||
render(<TransitJourneyModal {...makeProps({ reservation: makeMobileReservation() })} />)
|
||||
expect(screen.getByText('Transfers')).toBeInTheDocument()
|
||||
|
||||
@@ -15,7 +15,7 @@ import { useTranslation } from '../../i18n'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
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 { useIsPhone } from '../../mobile/useIsPhone'
|
||||
|
||||
@@ -423,9 +423,7 @@ export default function TransitJourneyModal({ reservation, onClose, onSave, onDe
|
||||
</div>
|
||||
<div style={{ padding: '6px 0 8px', 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 }}>
|
||||
{leg.line || leg.mode}
|
||||
</span>
|
||||
<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.headsign && (
|
||||
<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 }} />
|
||||
@@ -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 }}>
|
||||
{leg.from?.time || ''}
|
||||
</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 }}>
|
||||
{leg.line || leg.mode}
|
||||
</span>
|
||||
<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 }} />
|
||||
<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' }}>
|
||||
<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>}
|
||||
<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 style={{ marginTop: 3 }}>
|
||||
<TransitMetaBadges items={[
|
||||
|
||||
@@ -616,7 +616,7 @@ describe('TransitSearchPanel', () => {
|
||||
await pickFromAndTo(user)
|
||||
await user.click(screen.getByRole('button', { name: /^Search$/ }))
|
||||
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('M4')).toContain('lucide-tram-front')
|
||||
expect(icon('F10')).toContain('lucide-sailboat')
|
||||
|
||||
@@ -3,7 +3,7 @@ import { createPortal } from 'react-dom'
|
||||
import tzlookup from 'tz-lookup'
|
||||
import { ArrowLeftRight, ArrowRight, Bus, CableCar, ChevronDown, ChevronUp, Clock, Footprints, MapPin, Sailboat, Search, TramFront, TrainFront, TrainFrontTunnel } from 'lucide-react'
|
||||
import CustomTimePicker from '../shared/CustomTimePicker'
|
||||
import { TransitMetaBadges } from './transitDisplay'
|
||||
import { TransitLineBadge, TransitMetaBadges } from './transitDisplay'
|
||||
import { transitApi } from '../../api/client'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { useToast } from '../shared/Toast'
|
||||
@@ -326,15 +326,17 @@ function StopPicker({ label, value, onPick, quickPicks, near, placeholder }: {
|
||||
|
||||
// ── itinerary card ───────────────────────────────────────────────────────────
|
||||
|
||||
function LineBadge({ leg }: { leg: TransitLeg }) {
|
||||
function LineBadge({ leg, wrap = false }: { leg: TransitLeg; wrap?: boolean }) {
|
||||
const bg = leg.lineColor || 'var(--bg-tertiary)'
|
||||
const fg = leg.lineColor ? (leg.lineTextColor || '#fff') : 'var(--text-primary)'
|
||||
const Icon = legIcon(leg.mode)
|
||||
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' }}>
|
||||
<Icon size={11} strokeWidth={2.2} />
|
||||
{leg.line || leg.mode}
|
||||
</span>
|
||||
<TransitLineBadge
|
||||
label={leg.line || leg.mode}
|
||||
wrap={wrap}
|
||||
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={[
|
||||
{ icon: ArrowRight, text: leg.headsign || '' },
|
||||
{ text: fmtDuration(leg.duration, t) },
|
||||
|
||||
@@ -49,112 +49,112 @@ export default function BookingCard(p: BookingCardProps) {
|
||||
const { t, locale } = useTranslation()
|
||||
const tone = toneOf(r)
|
||||
const transit = r.type === 'transit'
|
||||
const title = displayTitle(r)
|
||||
|
||||
return (
|
||||
<article
|
||||
tabIndex={0}
|
||||
onClick={p.onSelect}
|
||||
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'}`}
|
||||
aria-label={title}
|
||||
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'}`}
|
||||
>
|
||||
<div className="flex items-center gap-2 border-b border-edge-faint px-3 py-2.5" style={{ background: toneTint(tone) }}>
|
||||
<StatusDot r={r} canToggle={p.canEdit} onToggle={p.onToggleStatus} />
|
||||
<TypeChip type={r.type} />
|
||||
<span className="flex min-w-0 flex-1 items-center gap-1.5">
|
||||
<span className="min-w-0 truncate font-bold text-content" style={fs(13.5, 'body')}>{displayTitle(r)}</span>
|
||||
{!!r.needs_review && <ReviewPill />}
|
||||
</span>
|
||||
<AirTrailPill r={r} />
|
||||
{p.canEdit && <RoundAction label={t('common.edit')} onClick={p.onEdit}><Pencil size={12} strokeWidth={2} /></RoundAction>}
|
||||
{p.canEdit && <RoundAction label={t('common.delete')} onClick={p.onDelete} danger><Trash2 size={12} strokeWidth={2} /></RoundAction>}
|
||||
</div>
|
||||
<div role="presentation" onClick={p.onSelect} className="flex flex-1 flex-col">
|
||||
<div className="flex items-center gap-2 border-b border-edge-faint px-3 py-2.5" style={{ background: toneTint(tone) }}>
|
||||
<StatusDot r={r} canToggle={p.canEdit} onToggle={p.onToggleStatus} />
|
||||
<TypeChip type={r.type} />
|
||||
<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)]">
|
||||
<span className="min-w-0 truncate font-bold text-content" style={fs(13.5, 'body')}>{title}</span>
|
||||
{!!r.needs_review && <ReviewPill />}
|
||||
</button>
|
||||
<AirTrailPill r={r} />
|
||||
{p.canEdit && <RoundAction label={t('common.edit')} onClick={p.onEdit}><Pencil size={12} strokeWidth={2} /></RoundAction>}
|
||||
{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">
|
||||
<WhenFields facts={facts} />
|
||||
<FlightLiveStrip tripId={p.tripId} reservationId={r.id} type={r.type} />
|
||||
<div className="flex flex-1 flex-col gap-2 px-3 pb-3 pt-2.5">
|
||||
<WhenFields facts={facts} />
|
||||
<FlightLiveStrip tripId={p.tripId} reservationId={r.id} type={r.type} />
|
||||
|
||||
{transit ? <TransitBody r={r} /> : (
|
||||
<>
|
||||
{r.confirmation_number && (
|
||||
<Field label={t('reservations.confirmationCode')} tabular>
|
||||
<BlurredCode className="font-geist">{r.confirmation_number}</BlurredCode>
|
||||
</Field>
|
||||
)}
|
||||
<RouteBox type={r.type} facts={facts} />
|
||||
{facts.legCodes.length > 0 && (
|
||||
<Block label={t('reservations.segmentCodes')}>
|
||||
<div className={`${BOX} flex flex-col gap-1 px-[10px] py-2`}>
|
||||
{facts.legCodes.map((l, i) => (
|
||||
<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>
|
||||
<BlurredCode className="font-geist tabular-nums text-content-muted">{l.code}</BlurredCode>
|
||||
</div>
|
||||
))}
|
||||
{transit ? <TransitBody r={r} /> : (
|
||||
<>
|
||||
{r.confirmation_number && (
|
||||
<Field label={t('reservations.confirmationCode')} tabular>
|
||||
<BlurredCode className="font-geist">{r.confirmation_number}</BlurredCode>
|
||||
</Field>
|
||||
)}
|
||||
<RouteBox type={r.type} facts={facts} />
|
||||
{facts.legCodes.length > 0 && (
|
||||
<Block label={t('reservations.segmentCodes')}>
|
||||
<div className={`${BOX} flex flex-col gap-1 px-[10px] py-2`}>
|
||||
{facts.legCodes.map((l, i) => (
|
||||
<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>
|
||||
<BlurredCode className="font-geist tabular-nums text-content-muted">{l.code}</BlurredCode>
|
||||
</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>
|
||||
</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>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Block>
|
||||
)}
|
||||
|
||||
{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.travelers || []).length > 0 && (
|
||||
<Block label={t('reservations.travelers.label')}>
|
||||
<TravelerChips travelers={r.travelers || []} />
|
||||
</Block>
|
||||
)}
|
||||
|
||||
{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>
|
||||
{p.files.length > 0 && (
|
||||
<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>
|
||||
</Block>
|
||||
)}
|
||||
)}
|
||||
</div>
|
||||
|
||||
{(r.travelers || []).length > 0 && (
|
||||
<Block label={t('reservations.travelers.label')}>
|
||||
<TravelerChips travelers={r.travelers || []} />
|
||||
</Block>
|
||||
)}
|
||||
|
||||
{p.files.length > 0 && (
|
||||
<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>
|
||||
<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>
|
||||
)}
|
||||
</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>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -163,7 +163,7 @@ function usePopover() {
|
||||
|
||||
function Menu({ children, onClose, width = 260 }: { children: ReactNode; onClose: () => void; width?: number }) {
|
||||
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}
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -35,7 +35,7 @@ export default function BookingsList(p: BookingsListProps) {
|
||||
const rootRef = useRef<HTMLDivElement>(null)
|
||||
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
|
||||
e.preventDefault()
|
||||
const focused = document.activeElement instanceof HTMLElement ? Number(document.activeElement.dataset.row) : Number.NaN
|
||||
@@ -45,13 +45,13 @@ export default function BookingsList(p: BookingsListProps) {
|
||||
}
|
||||
|
||||
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 => {
|
||||
const open = !p.collapsed(g.id)
|
||||
return (
|
||||
<section key={g.id} className="overflow-hidden rounded-2xl border border-edge-faint bg-surface-card">
|
||||
{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">
|
||||
<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>}
|
||||
@@ -59,7 +59,7 @@ export default function BookingsList(p: BookingsListProps) {
|
||||
</button>
|
||||
)}
|
||||
{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>
|
||||
)
|
||||
@@ -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
|
||||
p: BookingsListProps
|
||||
facts: BookingFacts
|
||||
@@ -76,6 +76,7 @@ function Row({ r, p, facts, files, costs, t, locale }: {
|
||||
costs: CostTotal[]
|
||||
t: (k: string, v?: Record<string, string | number>) => string
|
||||
locale: string
|
||||
onNavigate: (e: KeyboardEvent<HTMLElement>) => void
|
||||
}) {
|
||||
const selected = p.selectedId === r.id
|
||||
const transit = r.type === 'transit'
|
||||
@@ -93,7 +94,10 @@ function Row({ r, p, facts, files, costs, t, locale }: {
|
||||
aria-pressed={selected}
|
||||
aria-label={displayTitle(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)]' : ''}`}
|
||||
>
|
||||
<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
Reference in New Issue
Block a user