mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-02 09:22:15 +00:00
feat(tours): add non-motorized day tour planning
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
import React from 'react'
|
||||
import { MapPin, Mountain } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n/TranslationContext'
|
||||
import { NEUTRAL_TINT } from '../shared/DialogShell'
|
||||
|
||||
interface PlacesToursModeSwitchProps {
|
||||
active: boolean
|
||||
onChange: (tours: boolean) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Switches the right add-panel between the ordinary Places sidebar and the
|
||||
* Tours selection list. Top level of the panel, mirroring RoadtripModeSwitch
|
||||
* (Days <-> Roadtrip), using the same placement and addon gating convention.
|
||||
* Only rendered while the tours addon is on.
|
||||
*/
|
||||
export default function PlacesToursModeSwitch({ active, onChange }: PlacesToursModeSwitchProps): React.ReactElement {
|
||||
const { t } = useTranslation()
|
||||
const options: [boolean, string, typeof MapPin][] = [
|
||||
[false, t('tours.mode.places'), MapPin],
|
||||
[true, t('tours.mode.tours'), Mountain],
|
||||
]
|
||||
return (
|
||||
<div className="flex-none px-3 pb-1 pt-3" style={{ background: NEUTRAL_TINT }}>
|
||||
<div role="tablist" aria-label={t('tours.mode.label')} className="flex gap-1 rounded-xl border border-edge-faint bg-surface-tertiary p-1">
|
||||
{options.map(([value, label, Icon]) => {
|
||||
const selected = active === value
|
||||
return (
|
||||
<button
|
||||
key={label}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={selected}
|
||||
onClick={() => onChange(value)}
|
||||
style={{ fontSize: 'calc(11.5px * var(--fs-scale-body, 1))' }}
|
||||
className={`flex h-[30px] flex-1 items-center justify-center gap-1.5 rounded-lg px-2 transition-colors ${
|
||||
selected
|
||||
? 'bg-surface-card font-semibold text-content shadow-card'
|
||||
: 'font-medium text-content-muted hover:bg-surface-hover hover:text-content'
|
||||
}`}
|
||||
>
|
||||
<Icon size={13} strokeWidth={1.8} aria-hidden />
|
||||
<span className="truncate">{label}</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import React, { useState } from 'react'
|
||||
import { fireEvent, render, screen, waitFor } from '../../../tests/helpers/render'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { TourListItem } from '@trek/shared'
|
||||
import { buildPlace } from '../../../tests/helpers/factories'
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import TourDetailDialog from './TourDetailDialog'
|
||||
|
||||
vi.mock('../../../../server/src/config', () => { throw new Error('Config initialization is forbidden in client tests') })
|
||||
vi.mock('../../../../server/src/db/database', () => { throw new Error('Legacy database imports are forbidden in client tests') })
|
||||
vi.mock('../../../../server/src/nest/database/database.service', () => { throw new Error('Database service imports are forbidden in client tests') })
|
||||
vi.mock('better-sqlite3', () => { throw new Error('SQLite imports are forbidden in client tests') })
|
||||
|
||||
const place = buildPlace({
|
||||
id: 42,
|
||||
name: 'Ridge walk',
|
||||
lat: 48,
|
||||
lng: 11,
|
||||
notes: 'Bring water',
|
||||
route_geometry: JSON.stringify([
|
||||
[48, 11, 500],
|
||||
[48, 11.01, 550],
|
||||
[48, 11.03, 520],
|
||||
]),
|
||||
})
|
||||
|
||||
const tour: TourListItem = {
|
||||
place_id: 42,
|
||||
name: 'Ridge walk',
|
||||
tour_type: 'hike',
|
||||
distance: 999,
|
||||
elevation_gain: 999,
|
||||
elevation_loss: 999,
|
||||
duration: null,
|
||||
difficulty: null,
|
||||
wanderer_ref: null,
|
||||
match_confidence: null,
|
||||
tour_group_id: null,
|
||||
max_hiking_difficulty: 2,
|
||||
planned: false,
|
||||
caution: false,
|
||||
}
|
||||
|
||||
const defaultProps = {
|
||||
canEdit: true,
|
||||
canAssign: true,
|
||||
tour,
|
||||
place,
|
||||
onClose: vi.fn(),
|
||||
onUpdatePlace: vi.fn().mockResolvedValue(undefined),
|
||||
onAssignToDay: vi.fn(),
|
||||
onRemoveAssignment: vi.fn(),
|
||||
onDelete: vi.fn(),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores()
|
||||
vi.clearAllMocks()
|
||||
seedStore(useSettingsStore, { settings: { distance_unit: 'metric' } })
|
||||
})
|
||||
|
||||
describe('TourDetailDialog', () => {
|
||||
it('keeps desktop detail non-modal and returns focus to its Tour row on Escape', async () => {
|
||||
const opener = document.createElement('button')
|
||||
opener.textContent = 'Open Tour'
|
||||
document.body.appendChild(opener)
|
||||
const onClose = vi.fn()
|
||||
function DesktopDetail() {
|
||||
const [open, setOpen] = useState(true)
|
||||
return open ? <TourDetailDialog {...defaultProps} desktopNonModal desktopFocusReturnTarget={opener}
|
||||
onClose={() => { onClose(); setOpen(false) }} /> : null
|
||||
}
|
||||
|
||||
const view = render(<DesktopDetail />)
|
||||
const close = screen.getByRole('button', { name: 'Close' })
|
||||
expect(close).toHaveClass('focus-visible:outline')
|
||||
expect(document.querySelector('[aria-modal="true"]')).toBeNull()
|
||||
expect(document.querySelector('.trek-modal-backdrop')).toBeNull()
|
||||
expect(document.body.style.overflow).toBe('')
|
||||
const tab = new KeyboardEvent('keydown', { key: 'Tab', bubbles: true, cancelable: true })
|
||||
close.dispatchEvent(tab)
|
||||
expect(tab.defaultPrevented).toBe(false)
|
||||
|
||||
fireEvent.keyDown(document, { key: 'Escape' })
|
||||
await waitFor(() => expect(screen.queryByText('Ridge walk')).not.toBeInTheDocument())
|
||||
expect(onClose).toHaveBeenCalledTimes(1)
|
||||
expect(document.activeElement).toBe(opener)
|
||||
view.unmount()
|
||||
document.body.removeChild(opener)
|
||||
})
|
||||
|
||||
it('shows only curated tour content and uses live geometry instead of cached tour metrics', () => {
|
||||
render(<TourDetailDialog {...defaultProps} />)
|
||||
|
||||
expect(screen.getByText('Ridge walk')).toBeInTheDocument()
|
||||
expect(screen.getByText('Minimum altitude')).toBeInTheDocument()
|
||||
expect(screen.getByText('Maximum altitude')).toBeInTheDocument()
|
||||
expect(screen.getByText('Ascent')).toBeInTheDocument()
|
||||
expect(screen.getByText('Descent')).toBeInTheDocument()
|
||||
expect(screen.getByText('50 m')).toBeInTheDocument()
|
||||
expect(screen.getByText('30 m')).toBeInTheDocument()
|
||||
expect(screen.queryByText('999 m')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('Bring water')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Opening Hours')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Participants')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('uses existing assignment callbacks for add and remove actions', () => {
|
||||
const { rerender } = render(<TourDetailDialog {...defaultProps} days={[{ id: 7 } as never]} selectedDayId={7} />)
|
||||
fireEvent.click(screen.getByRole('button', { name: /Add to Day/i }))
|
||||
expect(defaultProps.onAssignToDay).toHaveBeenCalledWith(42)
|
||||
|
||||
rerender(<TourDetailDialog {...defaultProps} days={[{ id: 7 } as never]} selectedDayId={7} assignments={{ '7': [{ id: 9, place }] as never }} />)
|
||||
fireEvent.click(screen.getByRole('button', { name: /Remove from Day/i }))
|
||||
expect(defaultProps.onRemoveAssignment).toHaveBeenCalledWith(7, 9)
|
||||
})
|
||||
|
||||
it('requires place-edit permission for deletion while retaining day-edit assignment removal', () => {
|
||||
render(<TourDetailDialog
|
||||
{...defaultProps}
|
||||
canEdit={false}
|
||||
canAssign={true}
|
||||
days={[{ id: 7 } as never]}
|
||||
selectedDayId={7}
|
||||
assignments={{ '7': [{ id: 9, place }] as never }}
|
||||
/>)
|
||||
|
||||
expect(screen.queryByRole('button', { name: 'Delete' })).not.toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: /Remove from Day/i }))
|
||||
expect(defaultProps.onRemoveAssignment).toHaveBeenCalledWith(7, 9)
|
||||
expect(defaultProps.onDelete).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('renames through the supplied place update path', async () => {
|
||||
render(<TourDetailDialog {...defaultProps} />)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Edit' }))
|
||||
const input = screen.getByDisplayValue('Ridge walk')
|
||||
fireEvent.change(input, { target: { value: 'New route name' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Save' }))
|
||||
expect(defaultProps.onUpdatePlace).toHaveBeenCalledWith(42, { name: 'New route name' })
|
||||
})
|
||||
|
||||
it('labels GPX imports as view-only planner content', () => {
|
||||
render(<TourDetailDialog {...defaultProps} tour={{ ...tour, has_waypoints: false }} />)
|
||||
|
||||
expect(screen.getByText('GPX import')).toBeInTheDocument()
|
||||
expect(screen.getByText('GPX tours are view-only and cannot be edited in the planner yet.')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,288 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { AlertTriangle, ArrowDown, ArrowUp, Check, Clock, File, FileImage, FileText, MapPin, Mountain, Navigation, Pencil, Plus, Minus, Ruler, Trash2, Upload } from 'lucide-react'
|
||||
import Markdown from 'react-markdown'
|
||||
import remarkBreaks from 'remark-breaks'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
import type { TourListItem } from '@trek/shared'
|
||||
import type { Assignment, AssignmentsMap, Day, Place, TripFile } from '../../types'
|
||||
import { useTranslation, translateApiError } from '../../i18n'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { formatDistance, formatElevation } from '../../utils/units'
|
||||
import { resolveTrackColor, inheritedTrackColor } from '../Map/trackColors'
|
||||
import TrackColorPicker from '../shared/TrackColorPicker'
|
||||
import DetailShell from '../shared/DetailShell'
|
||||
import ElevationProfile from '../shared/ElevationProfile'
|
||||
import { NavigationMenu } from '../shared/NavigationMenu'
|
||||
import { markdownLinkComponents } from '../shared/markdownLink'
|
||||
import { analyzeRouteGeometry } from '../../utils/routeGeometry'
|
||||
import { filesForPlace } from '../../utils/placeFiles'
|
||||
import { openFile } from '../../utils/fileDownload'
|
||||
import { getNavigationTargets, openNavigationTarget } from '../Planner/placeNavigation'
|
||||
import { hikeSourceBadgeLabel, tourSource } from './tourPresentation'
|
||||
import { useTourPermissions, type TourPermissionProps } from './useTourPermissions'
|
||||
|
||||
interface TourDetailDialogProps extends TourPermissionProps {
|
||||
tour: TourListItem
|
||||
place: Place
|
||||
days?: Day[]
|
||||
selectedDayId?: number | null
|
||||
selectedAssignmentId?: number | null
|
||||
assignments?: AssignmentsMap
|
||||
files?: TripFile[]
|
||||
onClose: () => void
|
||||
onUpdatePlace?: (placeId: number, data: Partial<Place>) => Promise<void> | void
|
||||
onFileUpload?: (formData: FormData) => Promise<unknown>
|
||||
onAssignToDay?: (placeId: number, dayId?: number) => void
|
||||
onRemoveAssignment?: (dayId: number, assignmentId: number) => void
|
||||
onDelete?: () => void
|
||||
leftWidth?: number
|
||||
rightWidth?: number
|
||||
desktopNonModal?: boolean
|
||||
readOnly?: boolean
|
||||
/** Desktop-only opener; the map detail stays non-modal and returns focus when closed. */
|
||||
desktopFocusReturnTarget?: HTMLElement | null
|
||||
}
|
||||
|
||||
function formatFileSize(bytes: number | null | undefined): string {
|
||||
if (!bytes) return ''
|
||||
if (bytes < 1024) return `${bytes} B`
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
|
||||
return `${(bytes / 1024 / 1024).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
function assignmentForSelectedDay(
|
||||
assignments: AssignmentsMap,
|
||||
selectedDayId: number | null,
|
||||
selectedAssignmentId: number | null,
|
||||
placeId: number,
|
||||
): Assignment | null {
|
||||
if (selectedDayId == null) return null
|
||||
const dayAssignments = assignments[String(selectedDayId)] || []
|
||||
return (selectedAssignmentId ? dayAssignments.find(assignment => assignment.id === selectedAssignmentId) : null)
|
||||
?? dayAssignments.find(assignment => assignment.place?.id === placeId)
|
||||
?? null
|
||||
}
|
||||
|
||||
export default function TourDetailDialog({
|
||||
tour,
|
||||
place,
|
||||
selectedDayId = null,
|
||||
selectedAssignmentId = null,
|
||||
assignments = {},
|
||||
files = [],
|
||||
onClose,
|
||||
onUpdatePlace,
|
||||
onFileUpload,
|
||||
onAssignToDay,
|
||||
onRemoveAssignment,
|
||||
onDelete,
|
||||
leftWidth = 0,
|
||||
rightWidth = 0,
|
||||
desktopNonModal = false,
|
||||
readOnly = false,
|
||||
desktopFocusReturnTarget = null,
|
||||
canEdit: editPermission,
|
||||
canAssign: assignPermission,
|
||||
}: TourDetailDialogProps) {
|
||||
const { canEdit: hasEditPermission, canAssign } = useTourPermissions({ tripId: place.trip_id, canEdit: editPermission, canAssign: assignPermission })
|
||||
const canEdit = hasEditPermission && !readOnly
|
||||
const { t } = useTranslation()
|
||||
const toast = useToast()
|
||||
const distanceUnit = useSettingsStore(state => state.settings.distance_unit)
|
||||
const [editingName, setEditingName] = useState(false)
|
||||
const [nameDraft, setNameDraft] = useState(place.name)
|
||||
const [savingName, setSavingName] = useState(false)
|
||||
const [filesExpanded, setFilesExpanded] = useState(false)
|
||||
const [uploading, setUploading] = useState(false)
|
||||
const [navigationOpen, setNavigationOpen] = useState(false)
|
||||
const navigationButtonRef = useRef<HTMLButtonElement>(null)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const closeRef = useRef(onClose)
|
||||
closeRef.current = onClose
|
||||
const focusReturnRef = useRef(desktopFocusReturnTarget)
|
||||
focusReturnRef.current = desktopFocusReturnTarget
|
||||
|
||||
useEffect(() => {
|
||||
if (!desktopNonModal) return
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key !== 'Escape' || event.defaultPrevented) return
|
||||
event.preventDefault()
|
||||
closeRef.current()
|
||||
}
|
||||
document.addEventListener('keydown', handleKeyDown)
|
||||
return () => {
|
||||
document.removeEventListener('keydown', handleKeyDown)
|
||||
const opener = focusReturnRef.current
|
||||
if (opener?.isConnected) opener.focus()
|
||||
}
|
||||
}, [desktopNonModal])
|
||||
|
||||
const analysis = useMemo(() => analyzeRouteGeometry(place.route_geometry), [place.route_geometry])
|
||||
const trackColor = resolveTrackColor(place)
|
||||
const inheritedColor = inheritedTrackColor(place)
|
||||
const assignment = assignmentForSelectedDay(assignments, selectedDayId, selectedAssignmentId, place.id)
|
||||
const placeFiles = filesForPlace(files, place.id, [], assignment ? [assignment.id] : [])
|
||||
const navigationTargets = getNavigationTargets(place)
|
||||
const source = tourSource(tour)
|
||||
|
||||
const saveName = async () => {
|
||||
if (!canEdit) return
|
||||
const name = nameDraft.trim()
|
||||
if (!name || name === place.name || !onUpdatePlace) { setEditingName(false); return }
|
||||
setSavingName(true)
|
||||
try {
|
||||
await onUpdatePlace(place.id, { name })
|
||||
setEditingName(false)
|
||||
} catch (error: unknown) {
|
||||
toast.error(translateApiError(t, error, 'common.error'))
|
||||
} finally {
|
||||
setSavingName(false)
|
||||
}
|
||||
}
|
||||
|
||||
const uploadFiles = async (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const selectedFiles = Array.from(event.target.files || [])
|
||||
event.target.value = ''
|
||||
if (!canEdit || !onFileUpload || selectedFiles.length === 0) return
|
||||
setUploading(true)
|
||||
try {
|
||||
for (const file of selectedFiles) {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
formData.append('place_id', String(place.id))
|
||||
await onFileUpload(formData)
|
||||
}
|
||||
setFilesExpanded(true)
|
||||
} catch (error: unknown) {
|
||||
toast.error(translateApiError(t, error, 'files.uploadError'))
|
||||
} finally {
|
||||
setUploading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const header = canEdit && editingName ? (
|
||||
<div style={{ display: 'flex', gap: 6, flex: 1, minWidth: 0 }}>
|
||||
<input
|
||||
autoFocus
|
||||
value={nameDraft}
|
||||
onChange={event => setNameDraft(event.target.value)}
|
||||
onKeyDown={event => {
|
||||
if (event.key === 'Enter') void saveName()
|
||||
if (event.key === 'Escape') { setNameDraft(place.name); setEditingName(false) }
|
||||
}}
|
||||
className="border border-edge bg-surface-secondary text-content"
|
||||
style={{ flex: 1, minWidth: 0, borderRadius: 8, padding: '6px 10px', fontSize: 'calc(16px * var(--fs-scale-subtitle, 1))', fontWeight: 600 }}
|
||||
/>
|
||||
<button type="button" onClick={() => void saveName()} disabled={savingName} className="text-accent" style={{ padding: 6 }} aria-label={t('common.save')}>
|
||||
<Check size={18} strokeWidth={2} />
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<h2 className="text-content" style={{ minWidth: 0, fontSize: 'calc(18px * var(--fs-scale-title, 1))', fontWeight: 700, margin: 0 }}>{place.name}</h2>
|
||||
{canEdit && onUpdatePlace && (
|
||||
<button type="button" onClick={() => { setNameDraft(place.name); setEditingName(true) }} className="text-content-faint shrink-0" style={{ padding: 2, background: 'none', border: 'none', cursor: 'pointer' }} aria-label={t('common.edit')}>
|
||||
<Pencil size={14} strokeWidth={2} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-1 flex flex-wrap items-center gap-2 text-xs text-content-muted">
|
||||
<span className="rounded-md border border-edge bg-surface-tertiary px-1.5 py-0.5">{t(`tourTypes.${tour.tour_type}`)}</span>
|
||||
{tour.difficulty && <span>{t('tours.detail.difficulty')}: {tour.difficulty}</span>}
|
||||
{tour.duration != null && <span className="inline-flex items-center gap-1"><Clock size={11} />{t('tours.durationMinutes', { count: tour.duration })}</span>}
|
||||
{tour.caution && <span className="inline-flex items-center gap-1 text-warning"><AlertTriangle size={11} />{t('tours.caution.badge')}</span>}
|
||||
<span className="rounded-md border border-edge bg-surface-tertiary px-1.5 py-0.5">{hikeSourceBadgeLabel(tour, t)}</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
const footer = <>
|
||||
{canAssign && selectedDayId != null && (assignment ? onRemoveAssignment && (
|
||||
<TourActionButton onClick={() => { if (canAssign) onRemoveAssignment(selectedDayId, assignment.id) }} icon={<Minus size={13} />} label={t('inspector.removeFromDay')} />
|
||||
) : (
|
||||
onAssignToDay && <TourActionButton onClick={() => { if (canAssign) onAssignToDay(place.id) }} icon={<Plus size={13} />} label={t('inspector.addToDay')} primary />
|
||||
))}
|
||||
{navigationTargets.length > 0 && (
|
||||
<>
|
||||
<TourActionButton
|
||||
buttonRef={navigationButtonRef}
|
||||
onClick={() => {
|
||||
if (navigationTargets.length === 1) openNavigationTarget(navigationTargets[0])
|
||||
else setNavigationOpen(open => !open)
|
||||
}}
|
||||
icon={<Navigation size={13} />}
|
||||
label={navigationTargets.length === 1 ? navigationTargets[0].label : t('inspector.navigation')}
|
||||
/>
|
||||
{navigationOpen && <NavigationMenu targets={navigationTargets} anchor={navigationButtonRef.current} onClose={() => setNavigationOpen(false)} />}
|
||||
</>
|
||||
)}
|
||||
<div style={{ flex: 1 }} />
|
||||
{canEdit && onDelete && <TourActionButton onClick={() => { if (canEdit) onDelete() }} icon={<Trash2 size={13} />} label={t('common.delete')} danger />}
|
||||
</>
|
||||
|
||||
return (
|
||||
<DetailShell header={header} footer={footer} onClose={onClose} closeLabel={t('common.close')} leftWidth={leftWidth} rightWidth={rightWidth}
|
||||
closeButtonClassName="focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-2">
|
||||
{source === 'gpx' && (
|
||||
<div className="rounded-lg border border-edge bg-surface-hover px-3 py-2 text-xs text-content-secondary">
|
||||
{t('tours.detail.gpxReadOnly')}
|
||||
{/* TODO(tours-roadmap): add the planned left-rail “Convert to TREK Tour” action here. */}
|
||||
</div>
|
||||
)}
|
||||
<div className="bg-surface-hover" style={{ borderRadius: 10, padding: '10px 12px', display: 'flex', flexDirection: 'column', gap: 10 }}>
|
||||
<div className="text-content-secondary" style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600 }}>{t('inspector.trackStats')}</div>
|
||||
{analysis && (
|
||||
<>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 12 }}>
|
||||
<TourMetric label={t('tours.detail.distance')} value={formatDistance(analysis.distanceKm, distanceUnit)} icon={<Ruler size={13} />} />
|
||||
{analysis.minEle != null && <TourMetric label={t('tours.detail.minAltitude')} value={formatElevation(analysis.minEle, distanceUnit)} icon={<Mountain size={13} />} />}
|
||||
{analysis.maxEle != null && <TourMetric label={t('tours.detail.maxAltitude')} value={formatElevation(analysis.maxEle, distanceUnit)} icon={<Mountain size={13} />} />}
|
||||
{analysis.gain != null && <TourMetric label={t('tours.detail.ascent')} value={formatElevation(analysis.gain, distanceUnit)} icon={<ArrowUp size={13} />} />}
|
||||
{analysis.loss != null && <TourMetric label={t('tours.detail.descent')} value={formatElevation(analysis.loss, distanceUnit)} icon={<ArrowDown size={13} />} />}
|
||||
</div>
|
||||
<ElevationProfile samples={analysis.distanceIndexedProfileSamples} color={trackColor} gradientId={`tour-elevation-${place.id}`} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="bg-surface-hover" style={{ borderRadius: 10, padding: '10px 12px' }}>
|
||||
<p className="text-content-faint" style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 600, margin: '0 0 6px' }}>{t('tours.detail.trackColor')}</p>
|
||||
{canEdit && onUpdatePlace ? <TrackColorPicker value={place.route_color ?? null} inheritedColor={inheritedColor} onChange={color => { if (canEdit) void onUpdatePlace(place.id, { route_color: color }) }} /> : <span aria-label={t('tours.detail.trackColor')} style={{ display: 'block', width: 20, height: 20, borderRadius: 4, background: trackColor }} />}
|
||||
</div>
|
||||
|
||||
{(place.description || place.notes || assignment?.notes) && (
|
||||
<div className="bg-surface-hover" style={{ borderRadius: 10, padding: '10px 12px', display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||
{place.description && <div className="collab-note-md text-content-muted" style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', lineHeight: 1.5 }}><Markdown remarkPlugins={[remarkGfm, remarkBreaks]} components={markdownLinkComponents}>{place.description}</Markdown></div>}
|
||||
{place.notes && <div className="collab-note-md text-content-muted" style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', lineHeight: 1.5 }}><Markdown remarkPlugins={[remarkGfm, remarkBreaks]} components={markdownLinkComponents}>{place.notes}</Markdown></div>}
|
||||
{assignment?.notes && <div><div className="text-content-faint" style={{ fontSize: 'calc(9px * var(--fs-scale-caption, 1))', fontWeight: 600, textTransform: 'uppercase' }}>{t('places.assignmentNotes')}</div><div className="collab-note-md text-content-muted" style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))' }}><Markdown remarkPlugins={[remarkGfm, remarkBreaks]} components={markdownLinkComponents}>{assignment.notes}</Markdown></div></div>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(placeFiles.length > 0 || (canEdit && onFileUpload)) && (
|
||||
<div className="bg-surface-hover" style={{ borderRadius: 10, overflow: 'hidden' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', padding: '8px 12px', gap: 6 }}>
|
||||
<button type="button" onClick={() => setFilesExpanded(expanded => !expanded)} style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 6, background: 'none', border: 'none', cursor: 'pointer', padding: 0, fontFamily: 'inherit', textAlign: 'left' }}>
|
||||
<FileText size={13} color="var(--text-faint)" />
|
||||
<span className="text-content-secondary" style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 500 }}>{placeFiles.length ? t('inspector.filesCount', { count: placeFiles.length }) : t('inspector.files')}</span>
|
||||
</button>
|
||||
{canEdit && onFileUpload && <label className="text-content-muted bg-surface-tertiary" style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 4, fontSize: 'calc(11px * var(--fs-scale-caption, 1))', padding: '2px 6px', borderRadius: 6 }}><input ref={fileInputRef} type="file" multiple style={{ display: 'none' }} onChange={uploadFiles} />{uploading ? '…' : <><Upload size={11} /> {t('common.upload')}</>}</label>}
|
||||
</div>
|
||||
{filesExpanded && placeFiles.length > 0 && <div style={{ padding: '0 12px 10px', display: 'flex', flexDirection: 'column', gap: 4 }}>{placeFiles.map(file => <button type="button" key={file.id} onClick={() => void openFile(file.url)} style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', background: 'none', border: 'none', width: '100%', textAlign: 'left' }}>{(file.mime_type || '').startsWith('image/') ? <FileImage size={12} /> : <File size={12} />}<span className="text-content-secondary" style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{file.original_name}</span><span className="text-content-faint">{formatFileSize(file.file_size)}</span></button>)}</div>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{navigationTargets.length > 0 && <div className="text-content-faint" style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 'calc(11px * var(--fs-scale-caption, 1))' }}><MapPin size={12} />{t('tours.detail.navigationHint')}</div>}
|
||||
</DetailShell>
|
||||
)
|
||||
}
|
||||
|
||||
function TourMetric({ label, value, icon }: { label: string; value: string; icon: React.ReactNode }) {
|
||||
return <div><div className="text-content-faint" style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 'calc(10px * var(--fs-scale-caption, 1))' }}>{icon}{label}</div><div className="text-content" style={{ marginTop: 2, fontSize: 'calc(13px * var(--fs-scale-body, 1))', fontWeight: 600 }}>{value}</div></div>
|
||||
}
|
||||
|
||||
function TourActionButton({ buttonRef, onClick, icon, label, primary = false, danger = false }: { buttonRef?: React.Ref<HTMLButtonElement>; onClick: () => void; icon: React.ReactNode; label: string; primary?: boolean; danger?: boolean }) {
|
||||
const className = primary ? 'bg-accent text-accent-text' : danger ? 'text-danger hover:bg-danger-subtle' : 'text-content-secondary hover:bg-surface-hover'
|
||||
return <button ref={buttonRef} type="button" onClick={onClick} className={className} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, padding: '6px 10px', borderRadius: 8, border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 'calc(12px * var(--fs-scale-body, 1))', fontWeight: 500, background: primary ? undefined : 'transparent' }}>{icon}<span className="hidden sm:inline">{label}</span></button>
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import type { TourListItem } from '@trek/shared'
|
||||
import { AlertTriangle, ArrowDown, ArrowUp } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { formatDistance, formatElevation } from '../../utils/units'
|
||||
import { hikeSourceBadgeLabel } from './tourPresentation'
|
||||
|
||||
interface TourListRowProps {
|
||||
tour: TourListItem
|
||||
selected?: boolean
|
||||
disabled?: boolean
|
||||
onSelect: (tour: TourListItem, opener: HTMLElement) => void
|
||||
action?: ReactNode
|
||||
children?: ReactNode
|
||||
}
|
||||
|
||||
/** Shared Tours list row used by both the ADD flow and the planner workspace. */
|
||||
export default function TourListRow({ tour, selected = false, disabled = false, onSelect, action, children }: TourListRowProps) {
|
||||
const { t } = useTranslation()
|
||||
const distanceUnit = useSettingsStore(state => state.settings.distance_unit)
|
||||
|
||||
return (
|
||||
<li
|
||||
role="option"
|
||||
tabIndex={disabled ? -1 : 0}
|
||||
aria-selected={selected}
|
||||
aria-disabled={disabled || undefined}
|
||||
className={`rounded-xl border border-edge p-3 ${disabled ? 'cursor-default opacity-60' : 'cursor-pointer'}`}
|
||||
style={{ background: selected ? 'var(--border-faint)' : 'transparent', transition: 'background 0.1s' }}
|
||||
onClick={event => { if (!disabled) onSelect(tour, event.currentTarget) }}
|
||||
onKeyDown={event => {
|
||||
if (disabled) return
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault()
|
||||
onSelect(tour, event.currentTarget)
|
||||
}
|
||||
}}
|
||||
onMouseEnter={event => { if (!selected) event.currentTarget.style.background = 'var(--bg-hover)' }}
|
||||
onMouseLeave={event => { if (!selected) event.currentTarget.style.background = 'transparent' }}
|
||||
>
|
||||
<div className="min-w-0">
|
||||
<span className="block min-w-0 line-clamp-2 break-words font-medium text-content" title={tour.name}>{tour.name}</span>
|
||||
<div className="mt-1 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-xs text-content-secondary">
|
||||
<span className="shrink-0 rounded-md border border-edge bg-surface-tertiary px-1.5 py-0.5 text-[10px] font-medium text-content-faint">
|
||||
{hikeSourceBadgeLabel(tour, t)}
|
||||
</span>
|
||||
<span
|
||||
title={t(`tours.planner.difficulty.t${tour.max_hiking_difficulty}`)}
|
||||
aria-label={t(`tours.planner.difficulty.t${tour.max_hiking_difficulty}`)}
|
||||
className="shrink-0 rounded-md border border-edge bg-surface-tertiary px-1.5 py-0.5 text-[10px] font-semibold text-content-secondary"
|
||||
>T{tour.max_hiking_difficulty}</span>
|
||||
{tour.caution && (
|
||||
<span title={t('tours.caution.tooltip')} aria-label={t('tours.caution.badge')} className="shrink-0 inline-flex items-center gap-0.5 rounded-md border border-amber-300/60 bg-amber-100/60 px-1.5 py-0.5 text-[10px] font-medium text-amber-700 dark:bg-amber-900/30 dark:text-amber-400">
|
||||
<AlertTriangle className="h-2.5 w-2.5" strokeWidth={2} /> {t('tours.caution.badge')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div data-testid="tour-metrics" className="mt-1 flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 text-xs text-content-secondary">
|
||||
<span className="whitespace-nowrap" aria-label={`${t('tours.detail.distance')}: ${formatDistance(tour.distance ?? 0, distanceUnit)}`}>
|
||||
{formatDistance(tour.distance ?? 0, distanceUnit)}
|
||||
</span>
|
||||
{tour.elevation_gain != null && (
|
||||
<span className="inline-flex items-center gap-0.5 whitespace-nowrap" aria-label={`${t('tours.detail.ascent')}: ${formatElevation(tour.elevation_gain, distanceUnit)}`}>
|
||||
<ArrowUp className="h-3 w-3" strokeWidth={2} aria-hidden="true" />
|
||||
{formatElevation(tour.elevation_gain, distanceUnit)}
|
||||
</span>
|
||||
)}
|
||||
{tour.elevation_loss != null && (
|
||||
<span className="inline-flex items-center gap-0.5 whitespace-nowrap" aria-label={`${t('tours.detail.descent')}: ${formatElevation(tour.elevation_loss, distanceUnit)}`}>
|
||||
<ArrowDown className="h-3 w-3" strokeWidth={2} aria-hidden="true" />
|
||||
{formatElevation(tour.elevation_loss, distanceUnit)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{action && <div data-testid="tour-action-row" className="mt-2 w-full [&>button]:w-full [&>button]:justify-center">{action}</div>}
|
||||
</div>
|
||||
{children}
|
||||
</li>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
import { act, fireEvent, render, screen, waitFor, within } from '../../../tests/helpers/render'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { TourListItem } from '@trek/shared'
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { toursApi } from '../../api/client'
|
||||
import ToursSidebar from './ToursSidebar'
|
||||
|
||||
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }))
|
||||
|
||||
vi.mock('../shared/Toast', () => ({ useToast: () => toast }))
|
||||
|
||||
vi.mock('../../../../server/src/config', () => { throw new Error('Config initialization is forbidden in client tests') })
|
||||
vi.mock('../../../../server/src/db/database', () => { throw new Error('Legacy database imports are forbidden in client tests') })
|
||||
vi.mock('../../../../server/src/nest/database/database.service', () => { throw new Error('Database service imports are forbidden in client tests') })
|
||||
vi.mock('better-sqlite3', () => { throw new Error('SQLite imports are forbidden in client tests') })
|
||||
|
||||
const tour: TourListItem = {
|
||||
place_id: 42,
|
||||
name: 'Selected ridge walk',
|
||||
tour_type: 'hike',
|
||||
distance: 4,
|
||||
elevation_gain: 100,
|
||||
elevation_loss: 80,
|
||||
duration: null,
|
||||
difficulty: null,
|
||||
wanderer_ref: null,
|
||||
match_confidence: null,
|
||||
tour_group_id: null,
|
||||
max_hiking_difficulty: 2,
|
||||
planned: false,
|
||||
caution: false,
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores()
|
||||
seedStore(useSettingsStore, { settings: { distance_unit: 'metric' } })
|
||||
})
|
||||
|
||||
describe('ToursSidebar', () => {
|
||||
it('uses the compact counted dropdown for All, Unplanned and Planned', () => {
|
||||
render(<ToursSidebar tripId={1} days={[]} tours={[tour, { ...tour, place_id: 43, name: 'Planned walk', planned: true }]} onAssignToDay={vi.fn()} onSelectTour={vi.fn()} />)
|
||||
const trigger = screen.getByRole('button', { name: 'Show' })
|
||||
expect(trigger).toHaveTextContent('All')
|
||||
expect(trigger).toHaveTextContent('2')
|
||||
fireEvent.click(trigger)
|
||||
const choices = screen.getByRole('group', { name: 'Show' })
|
||||
expect(within(choices).getByRole('button', { name: /All\s*2/ })).toHaveAttribute('aria-pressed', 'true')
|
||||
expect(within(choices).getByRole('button', { name: /Unplanned\s*1/ })).toBeInTheDocument()
|
||||
expect(within(choices).getByRole('button', { name: /Planned\s*1/ })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('uses the place selection id for the same selected background as a place row', () => {
|
||||
render(<ToursSidebar tripId={1} days={[]} tours={[tour]} selectedPlaceId={42} onAssignToDay={vi.fn()} onSelectTour={vi.fn()} />)
|
||||
const row = screen.getByRole('option', { name: /Selected ridge walk/i })
|
||||
expect(row).toHaveAttribute('aria-selected', 'true')
|
||||
expect(row).toHaveStyle({ background: 'var(--border-faint)' })
|
||||
})
|
||||
|
||||
it('selects the tour from keyboard activation', () => {
|
||||
const onSelectTour = vi.fn()
|
||||
render(<ToursSidebar tripId={1} days={[]} tours={[tour]} selectedPlaceId={null} onAssignToDay={vi.fn()} onSelectTour={onSelectTour} />)
|
||||
const row = screen.getByRole('option', { name: /Selected ridge walk/i })
|
||||
fireEvent.keyDown(row, { key: 'Enter' })
|
||||
expect(onSelectTour).toHaveBeenCalledWith(tour, row)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['en', 'A deliberately long English hiking tour name that should wrap without pushing its metrics aside'],
|
||||
['de', 'Eine außergewöhnlich lange deutsche Wanderung mit ausführlicher Bezeichnung für schmale Seitenleisten'],
|
||||
])('keeps %s title, badges, atomic metrics and full-width action in separate rows', (language, name) => {
|
||||
seedStore(useSettingsStore, { settings: { language, distance_unit: 'metric' } })
|
||||
const onAssignToDay = vi.fn()
|
||||
const { container } = render(<ToursSidebar
|
||||
canEdit={true}
|
||||
canAssign={true}
|
||||
tripId={1}
|
||||
days={[{ id: 7, trip_id: 1, day_number: 1, title: 'Day one', date: null } as never]}
|
||||
tours={[{ ...tour, name, distance: 1.9, elevation_gain: 13, elevation_loss: 11, has_waypoints: true }]}
|
||||
selectedPlaceId={42}
|
||||
onAssignToDay={onAssignToDay}
|
||||
onSelectTour={vi.fn()}
|
||||
/>)
|
||||
|
||||
const row = screen.getByRole('option', { name: new RegExp(name) })
|
||||
expect(row).toHaveAttribute('aria-selected', 'true')
|
||||
expect(row.querySelector('span[title]')).toHaveAttribute('title', name)
|
||||
const metrics = row.querySelector('[data-testid="tour-metrics"]')!
|
||||
expect(metrics).toHaveTextContent('1.9 km')
|
||||
expect(metrics).toHaveTextContent('13 m')
|
||||
expect(metrics).toHaveTextContent('11 m')
|
||||
for (const metric of metrics.children) expect(metric).toHaveClass('whitespace-nowrap')
|
||||
expect(metrics.children[0].getAttribute('aria-label')).toContain('1.9 km')
|
||||
expect(metrics.children[1].getAttribute('aria-label')).toContain('13 m')
|
||||
expect(metrics.children[2].getAttribute('aria-label')).toContain('11 m')
|
||||
expect(screen.getByText('TREK')).toBeInTheDocument()
|
||||
expect(screen.getByLabelText(/Maximum trail difficulty|Maximale Wanderschwierigkeit|T2/)).toBeInTheDocument()
|
||||
const actionRow = row.querySelector('[data-testid="tour-action-row"]')!
|
||||
expect(actionRow).toHaveClass('w-full')
|
||||
expect(actionRow.querySelector('button')).toHaveClass('w-full')
|
||||
expect(container.querySelector('[data-testid="tour-metrics"]')).toBeTruthy()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Add to day|Zum Tag hinzufügen/ }))
|
||||
expect(screen.getByRole('button', { name: /Day one/ })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('leaves the post-write refresh to the shared assignment handler', async () => {
|
||||
let resolveAssignment!: () => void
|
||||
const assignment = new Promise<void>(resolve => { resolveAssignment = resolve })
|
||||
const onAssignToDay = vi.fn(() => assignment)
|
||||
const onToursChanged = vi.fn()
|
||||
render(<ToursSidebar
|
||||
canEdit={true}
|
||||
canAssign={true}
|
||||
tripId={1}
|
||||
days={[{ id: 7, trip_id: 1, day_number: 1, title: 'Day one', date: null } as never]}
|
||||
tours={[tour]}
|
||||
onAssignToDay={onAssignToDay}
|
||||
onToursChanged={onToursChanged}
|
||||
onSelectTour={vi.fn()}
|
||||
/>)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Add to day|Zum Tag hinzufügen/ }))
|
||||
fireEvent.click(screen.getByRole('button', { name: /Day one/ }))
|
||||
expect(onAssignToDay).toHaveBeenCalledWith(42, 7)
|
||||
expect(onToursChanged).not.toHaveBeenCalled()
|
||||
|
||||
await act(async () => { resolveAssignment(); await assignment })
|
||||
expect(onToursChanged).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps the day picker open and does not refresh when assignment fails', async () => {
|
||||
const onToursChanged = vi.fn()
|
||||
render(<ToursSidebar
|
||||
canAssign={true}
|
||||
tripId={1}
|
||||
days={[{ id: 7, trip_id: 1, day_number: 1, title: 'Day one', date: null } as never]}
|
||||
tours={[tour]}
|
||||
onAssignToDay={vi.fn().mockResolvedValue(false)}
|
||||
onToursChanged={onToursChanged}
|
||||
onSelectTour={vi.fn()}
|
||||
/>)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Add to day|Zum Tag hinzufügen/ }))
|
||||
fireEvent.click(screen.getByRole('button', { name: /Day one/ }))
|
||||
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: /Day one/ })).toBeInTheDocument())
|
||||
expect(onToursChanged).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('quarantines returned Tour ids before loading the imported Places', async () => {
|
||||
const importCall = vi.spyOn(toursApi, 'importGpx').mockResolvedValue({
|
||||
tours: [tour], caution: false, skipped: 0,
|
||||
})
|
||||
const onToursChanged = vi.fn()
|
||||
const loadTrip = vi.spyOn(useTripStore.getState(), 'loadTrip').mockResolvedValue(undefined)
|
||||
const { container } = render(<ToursSidebar
|
||||
tripId={1}
|
||||
days={[]}
|
||||
tours={[]}
|
||||
canEdit={true}
|
||||
onAssignToDay={vi.fn()}
|
||||
onToursChanged={onToursChanged}
|
||||
onSelectTour={vi.fn()}
|
||||
/>)
|
||||
|
||||
const input = container.querySelector('input[type="file"]')!
|
||||
const file = new File(['<gpx/>'], 'ridge.gpx', { type: 'application/gpx+xml' })
|
||||
fireEvent.change(input, { target: { files: [file] } })
|
||||
|
||||
await waitFor(() => expect(loadTrip).toHaveBeenCalledWith(1))
|
||||
expect(onToursChanged).toHaveBeenCalledWith([42])
|
||||
expect(onToursChanged.mock.invocationCallOrder[0]).toBeLessThan(loadTrip.mock.invocationCallOrder[0])
|
||||
expect(importCall).toHaveBeenCalledOnce()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('reports duplicate-only GPX success without refetching or invalidating unchanged data', async () => {
|
||||
vi.spyOn(toursApi, 'importGpx').mockResolvedValue({ tours: [], caution: false, skipped: 3 })
|
||||
const onToursChanged = vi.fn()
|
||||
const loadTrip = vi.spyOn(useTripStore.getState(), 'loadTrip').mockResolvedValue(undefined)
|
||||
const { container } = render(<ToursSidebar
|
||||
tripId={1}
|
||||
days={[]}
|
||||
tours={[]}
|
||||
canEdit={true}
|
||||
onAssignToDay={vi.fn()}
|
||||
onToursChanged={onToursChanged}
|
||||
onSelectTour={vi.fn()}
|
||||
/>)
|
||||
|
||||
fireEvent.change(container.querySelector('input[type=file]')!, {
|
||||
target: { files: [new File(['<gpx/>'], 'already-imported.gpx', { type: 'application/gpx+xml' })] },
|
||||
})
|
||||
|
||||
await waitFor(() => expect(toast.warning).toHaveBeenCalledWith('All places were already in the trip.'))
|
||||
expect(onToursChanged).not.toHaveBeenCalled()
|
||||
expect(loadTrip).not.toHaveBeenCalled()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,225 @@
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { Check, ChevronDown, FileDown, Mountain } from 'lucide-react'
|
||||
import type { TourListItem } from '@trek/shared'
|
||||
import type { Day } from '../../types'
|
||||
import { toursApi } from '../../api/client'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { useToast } from '../shared/Toast'
|
||||
import TourListRow from './TourListRow'
|
||||
import { useTourPermissions, type TourPermissionProps } from './useTourPermissions'
|
||||
import { NEUTRAL_TINT, fs } from '../shared/DialogShell'
|
||||
import { Tooltip } from '../shared/Tooltip'
|
||||
|
||||
const MAX_FILE_BYTES = 10 * 1024 * 1024
|
||||
|
||||
interface ToursSidebarProps extends TourPermissionProps {
|
||||
tripId: number
|
||||
days: Day[]
|
||||
tours: TourListItem[]
|
||||
loading?: boolean
|
||||
selectedPlaceId?: number | null
|
||||
onAssignToDay: (placeId: number, dayId: number) => void | boolean | Promise<void | boolean>
|
||||
pushUndo?: (label: string, undo: () => void | Promise<void>) => void
|
||||
/** Imported place ids are excluded immediately; no ids means refresh derived Tour metadata. */
|
||||
onToursChanged?: (placeIds?: number[]) => void | Promise<void>
|
||||
/** Tour row was clicked — caller will render the detail modal. */
|
||||
onSelectTour?: (tour: TourListItem | null, opener?: HTMLElement) => void
|
||||
}
|
||||
|
||||
function dayLabel(day: Day, index: number, t: (key: string, params?: Record<string, unknown>) => string): string {
|
||||
if (day.title) return day.title
|
||||
return t('dayplan.dayN', { n: index + 1 })
|
||||
}
|
||||
|
||||
/**
|
||||
* Tours mode of the right add-panel: a selection list of existing tours
|
||||
* with GPX import and day assignment.
|
||||
*
|
||||
* Reuses the existing day-assignment mechanism as-is: `onAssignToDay` is the
|
||||
* same `handleAssignToDay` PlacesSidebar calls, so a tour lands on a day
|
||||
* exactly like a place does, and its route line renders on the day map
|
||||
* without any Tours-specific rendering code.
|
||||
*/
|
||||
export default function ToursSidebar({ tripId, days, tours, loading = false, selectedPlaceId = null, onAssignToDay, onToursChanged, onSelectTour, canEdit: editPermission, canAssign: assignPermission }: ToursSidebarProps): React.ReactElement {
|
||||
const { t } = useTranslation()
|
||||
const { canEdit, canAssign } = useTourPermissions({ tripId, canEdit: editPermission, canAssign: assignPermission })
|
||||
const toast = useToast()
|
||||
const loadTrip = useTripStore(s => s.loadTrip)
|
||||
const [filter, setFilter] = useState<'all' | 'unplanned' | 'planned'>('all')
|
||||
const [importing, setImporting] = useState(false)
|
||||
const [pickerOpenFor, setPickerOpenFor] = useState<number | null>(null)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const filterRef = useRef<HTMLDivElement>(null)
|
||||
const filterButtonRef = useRef<HTMLButtonElement>(null)
|
||||
const [filterOpen, setFilterOpen] = useState(false)
|
||||
|
||||
const handleImportClick = () => { if (canEdit) fileInputRef.current?.click() }
|
||||
|
||||
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0]
|
||||
e.target.value = ''
|
||||
if (!canEdit || !file) return
|
||||
const ext = file.name.toLowerCase().split('.').pop()
|
||||
if (ext !== 'gpx') { toast.error(t('places.importFileUnsupported')); return }
|
||||
if (file.size > MAX_FILE_BYTES) { toast.error(t('places.importFileTooLarge', { maxMb: 10 })); return }
|
||||
|
||||
setImporting(true)
|
||||
try {
|
||||
const result = await toursApi.importGpx(tripId, file)
|
||||
if (result.tours.length > 0) {
|
||||
// The server publishes place:created with sender echo suppression.
|
||||
// Reload the importing client's trip so new places and route geometry
|
||||
// enter the shared store used by the day map.
|
||||
await onToursChanged?.(result.tours.map(tour => tour.place_id))
|
||||
await loadTrip(tripId)
|
||||
toast.success(t(result.tours.length === 1 ? 'tours.import.successOne' : 'tours.import.success', { count: result.tours.length }))
|
||||
if (result.caution) toast.info(t('tours.import.caution'))
|
||||
} else {
|
||||
toast.warning(t('places.importAllSkipped'))
|
||||
}
|
||||
} catch (err: any) {
|
||||
const message = err?.response?.data?.error
|
||||
toast.error(message === 'No track or route found in GPX file' ? t('tours.import.noTrack') : t('tours.import.error'))
|
||||
} finally {
|
||||
setImporting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleAssign = async (tour: TourListItem, day: Day, index: number) => {
|
||||
if (!canAssign) return
|
||||
const assigned = await onAssignToDay(tour.place_id, day.id)
|
||||
if (assigned === false) return
|
||||
setPickerOpenFor(null)
|
||||
toast.success(t('tours.addedToDay', { n: index + 1 }))
|
||||
}
|
||||
|
||||
const counts = {
|
||||
all: tours.length,
|
||||
unplanned: tours.filter(tr => !tr.planned).length,
|
||||
planned: tours.filter(tr => tr.planned).length,
|
||||
}
|
||||
const filtered = tours.filter(tr => {
|
||||
if (filter === 'unplanned') return !tr.planned
|
||||
if (filter === 'planned') return tr.planned
|
||||
return true
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (!filterOpen) return
|
||||
const onDown = (event: MouseEvent) => {
|
||||
if (!filterRef.current?.contains(event.target as Node)) setFilterOpen(false)
|
||||
}
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.key !== 'Escape') return
|
||||
event.stopPropagation()
|
||||
setFilterOpen(false)
|
||||
filterButtonRef.current?.focus()
|
||||
}
|
||||
document.addEventListener('mousedown', onDown)
|
||||
document.addEventListener('keydown', onKey, true)
|
||||
return () => {
|
||||
document.removeEventListener('mousedown', onDown)
|
||||
document.removeEventListener('keydown', onKey, true)
|
||||
}
|
||||
}, [filterOpen])
|
||||
|
||||
const filterLabel = filter === 'all' ? t('places.all') : filter === 'unplanned' ? t('places.unplanned') : t('places.planned')
|
||||
const filterCount = counts[filter]
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', height: '100%', fontFamily: 'var(--font-system)' }}>
|
||||
<div className="flex flex-none flex-col gap-2 border-b border-edge-faint px-3 py-2.5" style={{ background: NEUTRAL_TINT }}>
|
||||
{/* GPX import stays — the tour-appropriate import path. List Import
|
||||
(place/route-of-driving oriented) is deliberately absent here. */}
|
||||
<div>
|
||||
<Tooltip label={t('places.importFile')}>
|
||||
<button type="button" onClick={handleImportClick} disabled={!canEdit || importing}
|
||||
className="flex h-8 w-full min-w-0 items-center justify-center gap-1.5 overflow-hidden rounded-[10px] bg-accent px-3 font-semibold text-accent-text shadow-sm transition-opacity hover:opacity-90 disabled:cursor-default disabled:opacity-40"
|
||||
style={fs(12.5, 'body')}>
|
||||
<FileDown size={14} strokeWidth={2.2} className="flex-none" />
|
||||
<span className="truncate">{t('places.importFile')}</span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
<input ref={fileInputRef} type="file" accept=".gpx" onChange={handleFileChange} style={{ display: 'none' }} />
|
||||
</div>
|
||||
<div ref={filterRef} className="relative min-w-0">
|
||||
<button ref={filterButtonRef} type="button" onClick={() => setFilterOpen(value => !value)}
|
||||
aria-expanded={filterOpen} aria-haspopup="listbox" aria-label={t('places.filterShow')}
|
||||
className="flex h-8 w-full min-w-0 items-center gap-1.5 rounded-[10px] bg-surface-card px-2.5 font-semibold text-content-secondary shadow-sm transition-colors hover:text-content"
|
||||
style={fs(12, 'body')}>
|
||||
<span className="min-w-0 truncate text-left">{filterLabel}</span>
|
||||
<span className="font-geist tabular-nums text-content-faint" style={fs(10.5)}>{filterCount}</span>
|
||||
<ChevronDown size={13} strokeWidth={2.2} className={`ml-auto flex-none text-content-faint transition-transform ${filterOpen ? 'rotate-180' : ''}`} />
|
||||
</button>
|
||||
{filterOpen && (
|
||||
<div role="group" aria-label={t('places.filterShow')} className="trek-popover-enter absolute left-0 top-full z-50 mt-1.5 flex w-full min-w-[180px] flex-col gap-px rounded-[12px] border border-edge-secondary bg-surface-card p-1.5 shadow-popover">
|
||||
{(['all', 'unplanned', 'planned'] as const).map(id => {
|
||||
const label = id === 'all' ? t('places.all') : id === 'unplanned' ? t('places.unplanned') : t('places.planned')
|
||||
const active = filter === id
|
||||
return <button key={id} type="button" onClick={() => { setFilter(id); setFilterOpen(false) }} aria-pressed={active}
|
||||
className={`flex w-full items-center gap-2 rounded-[9px] px-2 py-1.5 text-left transition-colors ${active ? 'bg-surface-tertiary' : 'hover:bg-surface-hover'}`}
|
||||
style={fs(12.5, 'body')}>
|
||||
<span className="min-w-0 flex-1 truncate text-content">{label}</span>
|
||||
<span className="font-geist tabular-nums text-content-faint" style={fs(11)}>{counts[id]}</span>
|
||||
<span className="grid w-3.5 flex-none place-items-center">{active && <Check size={13} strokeWidth={2.4} className="text-content-muted" />}</span>
|
||||
</button>
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ flex: 1, overflowY: 'auto', padding: '10px 16px 16px' }}>
|
||||
{!loading && filtered.length === 0 ? (
|
||||
<div className="rounded-xl border border-edge bg-surface-secondary p-6 text-center">
|
||||
<Mountain className="mx-auto mb-2 h-6 w-6 text-content-faint" strokeWidth={1.6} />
|
||||
<p className="font-medium text-content">{t('tours.empty.title')}</p>
|
||||
<p className="mt-1 text-sm text-content-secondary">{t('tours.empty.body')}</p>
|
||||
</div>
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
{filtered.map((tour) => {
|
||||
const isSelected = tour.place_id === selectedPlaceId
|
||||
return (
|
||||
<TourListRow
|
||||
key={tour.place_id}
|
||||
tour={tour}
|
||||
selected={isSelected}
|
||||
onSelect={(selectedTour, opener) => onSelectTour?.(selectedTour, opener)}
|
||||
action={(
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => { e.stopPropagation(); if (canAssign) setPickerOpenFor(v => v === tour.place_id ? null : tour.place_id) }}
|
||||
disabled={!canAssign || days.length === 0}
|
||||
className="inline-flex min-h-9 w-full items-center justify-center gap-1 rounded-lg border border-edge px-3 py-1.5 text-sm font-medium text-content disabled:opacity-50"
|
||||
>
|
||||
{t('tours.addToDay')}
|
||||
<ChevronDown className="h-3 w-3" strokeWidth={2} style={{ transform: pickerOpenFor === tour.place_id ? 'rotate(180deg)' : 'none', transition: 'transform 0.15s' }} />
|
||||
</button>
|
||||
)}
|
||||
>
|
||||
{canAssign && pickerOpenFor === tour.place_id && (
|
||||
<div className="mt-2 border-t border-edge-faint pt-2 flex flex-col gap-1" onClick={e => e.stopPropagation()}>
|
||||
{days.map((day, i) => (
|
||||
<button
|
||||
type="button"
|
||||
key={day.id}
|
||||
onClick={() => { void handleAssign(tour, day, i) }}
|
||||
className="flex items-center gap-2 rounded-lg px-2 py-1.5 text-left text-sm text-content hover:bg-surface-tertiary"
|
||||
>
|
||||
<span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-surface-tertiary text-[11px] font-semibold">{i + 1}</span>
|
||||
{dayLabel(day, i, t)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</TourListRow>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,571 @@
|
||||
import { act, useState } from 'react'
|
||||
import { fireEvent, render, screen, waitFor } from '../../../../tests/helpers/render'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { TourListItem } from '@trek/shared'
|
||||
import { resetAllStores, seedStore } from '../../../../tests/helpers/store'
|
||||
import { useSettingsStore } from '../../../store/settingsStore'
|
||||
import { analyzeRouteGeometry } from '../../../utils/routeGeometry'
|
||||
import type { TourPlannerController } from './useTourPlanner'
|
||||
import type { Day } from '../../../types'
|
||||
import { TourPlannerRail, TourPlannerToursRail } from './TourPlannerPanels'
|
||||
|
||||
vi.mock('../../../../../server/src/config', () => { throw new Error('Config initialization is forbidden in client tests') })
|
||||
vi.mock('../../../../../server/src/db/database', () => { throw new Error('Legacy database imports are forbidden in client tests') })
|
||||
vi.mock('../../../../../server/src/nest/database/database.service', () => { throw new Error('Database service imports are forbidden in client tests') })
|
||||
vi.mock('better-sqlite3', () => { throw new Error('SQLite imports are forbidden in client tests') })
|
||||
|
||||
const tour: TourListItem = {
|
||||
place_id: 42,
|
||||
name: 'Saved ridge walk',
|
||||
tour_type: 'hike',
|
||||
distance: 4,
|
||||
elevation_gain: 100,
|
||||
elevation_loss: 80,
|
||||
duration: 60,
|
||||
difficulty: null,
|
||||
wanderer_ref: null,
|
||||
match_confidence: 1,
|
||||
tour_group_id: null,
|
||||
max_hiking_difficulty: 2,
|
||||
planned: false,
|
||||
caution: false,
|
||||
}
|
||||
|
||||
const days = [{ id: 7, title: 'Summit day', date: '2026-05-15' } as Day]
|
||||
const railProps = {
|
||||
days,
|
||||
loading: false,
|
||||
onAssignToDay: vi.fn(),
|
||||
onViewGpxTour: vi.fn(),
|
||||
}
|
||||
|
||||
const routeAnalysis = analyzeRouteGeometry(JSON.stringify([[48, 11, 500], [48.036, 11, 550]]))
|
||||
|
||||
function planner(overrides: Partial<TourPlannerController> = {}): TourPlannerController {
|
||||
const state = {
|
||||
canEdit: true,
|
||||
canAssign: true,
|
||||
isSaving: false,
|
||||
maxHikingDifficulty: 2,
|
||||
setMaxHikingDifficulty: vi.fn(),
|
||||
name: '',
|
||||
startNewTour: vi.fn(),
|
||||
newTourConfirmationOpen: false,
|
||||
cancelNewTour: vi.fn(),
|
||||
elevationProfileExpanded: true,
|
||||
toggleElevationProfile: vi.fn(),
|
||||
routeProfileFocus: null,
|
||||
setRouteProfileFocus: vi.fn(),
|
||||
draftRestored: false,
|
||||
returnToNeutral: vi.fn(),
|
||||
waypoints: [],
|
||||
route: [[48, 11], [48.01, 11.02]],
|
||||
routeAnalysis,
|
||||
distanceMeters: 4000,
|
||||
durationSeconds: 3600,
|
||||
editingPlaceId: null,
|
||||
openingTourId: null,
|
||||
openTour: vi.fn().mockResolvedValue(true),
|
||||
saveOutcome: null,
|
||||
hasUnsavedChanges: false,
|
||||
discard: vi.fn(),
|
||||
readOnlyGpxTour: null,
|
||||
readOnlyGpxAnalysis: null,
|
||||
closeGpxTour: vi.fn(),
|
||||
...overrides,
|
||||
}
|
||||
const mode = overrides.mode ?? (state.readOnlyGpxTour
|
||||
? { type: 'view-gpx' as const, placeId: state.readOnlyGpxTour.tour.place_id, tour: state.readOnlyGpxTour.tour }
|
||||
: state.editingPlaceId != null
|
||||
? { type: 'edit-saved' as const, placeId: state.editingPlaceId }
|
||||
: state.hasUnsavedChanges || state.waypoints.length > 0 || state.name !== '' || state.status !== undefined && state.status !== 'empty'
|
||||
? { type: 'new-draft' as const }
|
||||
: { type: 'neutral' as const })
|
||||
return {
|
||||
...state,
|
||||
mode,
|
||||
} as unknown as TourPlannerController
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores()
|
||||
seedStore(useSettingsStore, { settings: { distance_unit: 'metric' } })
|
||||
})
|
||||
|
||||
describe('TourPlannerToursRail', () => {
|
||||
it('disables saved-tour switching and Plan another while a Save is pending', () => {
|
||||
const controller = planner({
|
||||
isSaving: true,
|
||||
saveOutcome: tour,
|
||||
hasUnsavedChanges: true,
|
||||
mode: { type: 'edit-saved', placeId: tour.place_id },
|
||||
editingPlaceId: tour.place_id,
|
||||
})
|
||||
render(<TourPlannerToursRail planner={controller} tours={[tour]} {...railProps} />)
|
||||
|
||||
const row = screen.getByRole('option', { name: /Saved ridge walk/i })
|
||||
expect(row).toHaveAttribute('aria-disabled', 'true')
|
||||
expect(row).toHaveAttribute('tabindex', '-1')
|
||||
fireEvent.click(row)
|
||||
expect(controller.openTour).not.toHaveBeenCalled()
|
||||
expect(screen.getByRole('button', { name: 'Plan another' })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-RAIL-001: shows saved Tours rows and route stats without hiding the safety note in navigation', () => {
|
||||
render(<TourPlannerToursRail planner={planner({ mode: { type: 'new-draft' } })} tours={[tour]} {...railProps} />)
|
||||
|
||||
expect(screen.getByRole('complementary', { name: 'Tours of this trip' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('option', { name: /Saved ridge walk/i })).toHaveTextContent('TREK')
|
||||
expect(screen.getByRole('option', { name: /Saved ridge walk/i })).toHaveTextContent('4 km')
|
||||
expect(screen.getByText('Ascent')).toBeInTheDocument()
|
||||
expect(screen.getByText('50 m')).toBeInTheDocument()
|
||||
expect(document.querySelector('svg[viewBox="0 0 440 100"]')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Routing is planning assistance, not a safety guarantee.')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-RAIL-002: guards a saved-tour open while the current draft is unsaved', () => {
|
||||
const controller = planner({ hasUnsavedChanges: true })
|
||||
render(<TourPlannerToursRail planner={controller} tours={[tour]} {...railProps} />)
|
||||
|
||||
fireEvent.click(screen.getByRole('option', { name: /Saved ridge walk/i }))
|
||||
expect(controller.openTour).not.toHaveBeenCalled()
|
||||
expect(screen.getByRole('heading', { name: 'Discard unsaved tour changes?' })).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Discard changes' }))
|
||||
expect(controller.openTour).toHaveBeenCalledWith(tour)
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-RAIL-003: assigns the saved tour immediately when a day is picked', async () => {
|
||||
const controller = planner({ saveOutcome: tour, editingPlaceId: tour.place_id })
|
||||
const onAssignToDay = vi.fn().mockResolvedValue(undefined)
|
||||
render(<TourPlannerToursRail planner={controller} tours={[tour]} {...railProps} onAssignToDay={onAssignToDay} />)
|
||||
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Tour saved')
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Plan another' }))
|
||||
expect(controller.startNewTour).toHaveBeenCalledOnce()
|
||||
expect(controller.discard).not.toHaveBeenCalled()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Assign to a day' }))
|
||||
const dayOption = screen.getByLabelText('Pick a day').querySelector('option[value="7"]')
|
||||
expect(dayOption).toHaveTextContent(/Day 1/i)
|
||||
expect(dayOption).toHaveTextContent(/May 15/i)
|
||||
expect(dayOption).toHaveTextContent(/Fri/i)
|
||||
fireEvent.change(screen.getByLabelText('Pick a day'), { target: { value: '7' } })
|
||||
await waitFor(() => expect(onAssignToDay).toHaveBeenCalledWith(42, 7))
|
||||
})
|
||||
|
||||
it('keeps the saved Tour day picker open when assignment fails', async () => {
|
||||
const controller = planner({ saveOutcome: tour, editingPlaceId: tour.place_id })
|
||||
const onAssignToDay = vi.fn().mockResolvedValue(false)
|
||||
render(<TourPlannerToursRail planner={controller} tours={[tour]} {...railProps} onAssignToDay={onAssignToDay} />)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Assign to a day' }))
|
||||
fireEvent.change(screen.getByLabelText('Pick a day'), { target: { value: '7' } })
|
||||
|
||||
await waitFor(() => expect(onAssignToDay).toHaveBeenCalledWith(42, 7))
|
||||
expect(screen.getByLabelText('Pick a day')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-RAIL-004: protects a dirty draft before selecting a GPX Tour', () => {
|
||||
const gpxTour = { ...tour, has_waypoints: false }
|
||||
const controller = planner({ hasUnsavedChanges: true, mode: { type: 'new-draft' } })
|
||||
const onViewGpxTour = vi.fn()
|
||||
render(<TourPlannerToursRail planner={controller} tours={[gpxTour]} {...railProps} onViewGpxTour={onViewGpxTour} />)
|
||||
|
||||
expect(screen.getByRole('option', { name: /Saved ridge walk/i })).toHaveTextContent('GPX import')
|
||||
fireEvent.click(screen.getByRole('option', { name: /Saved ridge walk/i }))
|
||||
expect(onViewGpxTour).not.toHaveBeenCalled()
|
||||
expect(controller.openTour).not.toHaveBeenCalled()
|
||||
expect(screen.getByRole('heading', { name: 'Discard unsaved tour changes?' })).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
|
||||
expect(onViewGpxTour).not.toHaveBeenCalled()
|
||||
expect(screen.getByRole('option', { name: /Saved ridge walk/i })).not.toHaveAttribute('aria-selected', 'true')
|
||||
|
||||
fireEvent.click(screen.getByRole('option', { name: /Saved ridge walk/i }))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Discard changes' }))
|
||||
expect(onViewGpxTour).toHaveBeenCalledWith(gpxTour)
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-RAIL-020: cancelling a dirty saved-tour switch preserves the selected row', () => {
|
||||
const otherTour = { ...tour, place_id: 43, name: 'Other ridge walk' }
|
||||
const controller = planner({
|
||||
mode: { type: 'edit-saved', placeId: tour.place_id },
|
||||
editingPlaceId: tour.place_id,
|
||||
hasUnsavedChanges: true,
|
||||
})
|
||||
render(<TourPlannerToursRail planner={controller} tours={[tour, otherTour]} {...railProps} />)
|
||||
|
||||
fireEvent.click(screen.getByRole('option', { name: /Other ridge walk/i }))
|
||||
expect(screen.getByRole('heading', { name: 'Discard unsaved tour changes?' })).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
|
||||
|
||||
expect(screen.getByRole('option', { name: /Saved ridge walk/i })).toHaveAttribute('aria-selected', 'true')
|
||||
expect(screen.getByRole('option', { name: /Other ridge walk/i })).not.toHaveAttribute('aria-selected', 'true')
|
||||
expect(controller.openTour).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-RAIL-005: shows analyzed GPX metrics and profile without editable controls', () => {
|
||||
const geometry = JSON.stringify([[48, 11, 500], [48, 11.01, 550], [48, 11.02, 520]])
|
||||
const controller = planner({
|
||||
readOnlyGpxTour: { tour: { ...tour, has_waypoints: false }, routeGeometry: geometry },
|
||||
readOnlyGpxAnalysis: analyzeRouteGeometry(geometry),
|
||||
})
|
||||
const { container } = render(<TourPlannerRail planner={controller} />)
|
||||
|
||||
expect(screen.getByRole('heading', { name: 'GPX tour' })).toBeInTheDocument()
|
||||
expect(screen.getByText('Saved ridge walk')).toBeInTheDocument()
|
||||
expect(screen.getByText('Walking time')).toBeInTheDocument()
|
||||
expect(screen.getByText('60 min')).toBeInTheDocument()
|
||||
expect(screen.getByText('Minimum altitude')).toBeInTheDocument()
|
||||
expect(screen.getByText('Ascent')).toBeInTheDocument()
|
||||
expect(screen.getByText('50 m')).toBeInTheDocument()
|
||||
expect(container.querySelector('svg[viewBox="0 0 440 100"]')).toBeInTheDocument()
|
||||
expect(screen.queryByLabelText('Tour name')).not.toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Back to Tours' }))
|
||||
expect(controller.returnToNeutral).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it.each(['editable', 'GPX'] as const)('uses the same interactive profile focus contract for %s Tours', kind => {
|
||||
let scheduledFrame: FrameRequestCallback | null = null
|
||||
vi.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => {
|
||||
scheduledFrame = callback
|
||||
return 1
|
||||
})
|
||||
const geometry = JSON.stringify([[48, 11, 500], [48.01, 11.02, 550]])
|
||||
const focus = { distanceMeters: 500, elevationMeters: 525, lat: 48.005, lng: 11.01, sampleIndex: 1 }
|
||||
const setRouteProfileFocus = vi.fn()
|
||||
const controller = kind === 'GPX'
|
||||
? planner({ routeProfileFocus: focus, setRouteProfileFocus, readOnlyGpxTour: { tour: { ...tour, has_waypoints: false }, routeGeometry: geometry }, readOnlyGpxAnalysis: analyzeRouteGeometry(geometry) })
|
||||
: planner({ mode: { type: 'new-draft' }, routeProfileFocus: focus, setRouteProfileFocus })
|
||||
expect(controller.routeAnalysis?.distanceIndexedProfileSamples[0]).toMatchObject({ lat: 48, lng: 11 })
|
||||
const { container } = kind === 'GPX'
|
||||
? render(<TourPlannerRail planner={controller} />)
|
||||
: render(<TourPlannerToursRail planner={controller} tours={[tour]} {...railProps} />)
|
||||
const profile = container.querySelector('svg[viewBox="0 0 440 100"]') as SVGSVGElement | null
|
||||
expect(profile).not.toBeNull()
|
||||
expect(profile).toHaveAttribute('tabindex', '0')
|
||||
expect(profile).toHaveAttribute('aria-label', 'Elevation profile')
|
||||
const line = container.querySelector('[data-profile-focus-line]')
|
||||
expect(line).toBeInTheDocument()
|
||||
expect(container.querySelector('[data-profile-focus-readout]')?.textContent).toContain('At ')
|
||||
|
||||
vi.spyOn(profile!, 'getBoundingClientRect').mockReturnValue({
|
||||
x: 0, y: 0, left: 0, top: 0, right: 440, bottom: 100, width: 440, height: 100,
|
||||
toJSON: () => ({}),
|
||||
} as DOMRect)
|
||||
fireEvent.pointerMove(profile!, { clientX: 220, pointerType: 'mouse' })
|
||||
expect(scheduledFrame).not.toBeNull()
|
||||
act(() => scheduledFrame?.(16))
|
||||
const focused = setRouteProfileFocus.mock.calls[0][0]!
|
||||
expect(focused.lat).toBeCloseTo(kind === 'GPX' ? 48.005 : 48.018, 6)
|
||||
expect(focused.lng).toBe(kind === 'GPX' ? 11.01 : 11)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['en', 'metric', 'At 500 m: 525 m'],
|
||||
['de', 'imperial', 'Bei 0.3 mi: 1722 ft'],
|
||||
] as const)('formats focused profile distance/elevation for %s %s units', async (language, distance_unit, expected) => {
|
||||
seedStore(useSettingsStore, { settings: { language, distance_unit } })
|
||||
const controller = planner({
|
||||
mode: { type: 'new-draft' },
|
||||
routeProfileFocus: { distanceMeters: 500, elevationMeters: 525, lat: 48.005, lng: 11, sampleIndex: 1 },
|
||||
setRouteProfileFocus: vi.fn(),
|
||||
})
|
||||
const { container } = render(<TourPlannerToursRail planner={controller} tours={[tour]} {...railProps} />)
|
||||
await waitFor(() => expect(container.querySelector('[data-profile-focus-readout]')?.textContent).toBe(expected))
|
||||
})
|
||||
})
|
||||
|
||||
describe('TourPlannerRail', () => {
|
||||
it('disables draft mutation and replacement controls while saving', () => {
|
||||
const controller = planner({
|
||||
mode: { type: 'new-draft' },
|
||||
status: 'saving',
|
||||
isSaving: true,
|
||||
hasUnsavedChanges: true,
|
||||
canSave: true,
|
||||
canUndo: true,
|
||||
canRedo: true,
|
||||
waypoints: [
|
||||
{ id: 'a', lat: 48, lng: 11, role: 'start' },
|
||||
{ id: 'b', lat: 48.1, lng: 11.1, role: 'end' },
|
||||
],
|
||||
name: 'Ridge walk',
|
||||
selectedWaypointId: 'a',
|
||||
setSelectedWaypointId: vi.fn(),
|
||||
moveWaypoint: vi.fn(),
|
||||
removeWaypoint: vi.fn(),
|
||||
undo: vi.fn(),
|
||||
redo: vi.fn(),
|
||||
save: vi.fn(),
|
||||
setName: vi.fn(),
|
||||
})
|
||||
render(<TourPlannerRail planner={controller} />)
|
||||
|
||||
expect(screen.getByLabelText('Tour name')).toBeDisabled()
|
||||
expect(screen.getByRole('button', { name: 'Maximum trail difficulty' })).toBeDisabled()
|
||||
expect(screen.getByRole('button', { name: 'Save tour' })).toBeDisabled()
|
||||
expect(screen.getByRole('button', { name: 'Back to Tours' })).toBeDisabled()
|
||||
expect(screen.getAllByLabelText('Move waypoint up')).toHaveLength(2)
|
||||
expect(screen.getAllByLabelText('Move waypoint up').every(element => element.getAttribute('aria-disabled') === 'true')).toBe(true)
|
||||
expect(screen.getAllByLabelText('Move waypoint down').every(element => element.getAttribute('aria-disabled') === 'true')).toBe(true)
|
||||
expect(screen.getAllByLabelText('Remove waypoint').every(element => element.getAttribute('aria-disabled') === 'true')).toBe(true)
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Saving…')
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-RAIL-006: places the safety note beside Save and numbers rows like map pins', () => {
|
||||
const controller = planner({
|
||||
status: 'ready',
|
||||
waypoints: [
|
||||
{ id: 'a', lat: 48, lng: 11, role: 'start' },
|
||||
{ id: 'b', lat: 48.1, lng: 11.1, role: 'end' },
|
||||
],
|
||||
selectedWaypointId: 'a',
|
||||
canSave: true,
|
||||
canUndo: false,
|
||||
canRedo: false,
|
||||
setSelectedWaypointId: vi.fn(),
|
||||
moveWaypoint: vi.fn(),
|
||||
removeWaypoint: vi.fn(),
|
||||
undo: vi.fn(),
|
||||
redo: vi.fn(),
|
||||
save: vi.fn(),
|
||||
setName: vi.fn(),
|
||||
name: 'Ridge walk',
|
||||
})
|
||||
render(<TourPlannerRail planner={controller} />)
|
||||
|
||||
const save = screen.getByRole('button', { name: 'Save tour' })
|
||||
expect(save.parentElement?.parentElement).toHaveTextContent('Routing is planning assistance, not a safety guarantee.')
|
||||
expect(save).toHaveClass('bg-accent', 'text-accent-text')
|
||||
expect(save).toHaveClass('hover:opacity-90')
|
||||
const firstNumber = screen.getByLabelText('Waypoint 1')
|
||||
const secondNumber = screen.getByLabelText('Waypoint 2')
|
||||
expect(firstNumber).toHaveTextContent('1')
|
||||
expect(secondNumber).toHaveTextContent('2')
|
||||
expect(firstNumber).toHaveAttribute('data-waypoint-number', '1')
|
||||
expect(secondNumber).toHaveAttribute('data-waypoint-number', '2')
|
||||
expect(firstNumber).toHaveClass('bg-surface-tertiary', 'text-content-secondary', 'font-geist', 'tabular-nums')
|
||||
expect(firstNumber).not.toHaveClass('text-white')
|
||||
expect(firstNumber).toHaveStyle({ display: 'flex', width: '28px', minWidth: '28px', height: '28px', lineHeight: '1' })
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-RAIL-007: acknowledges alpine routing once per planner session', () => {
|
||||
const setDifficulty = vi.fn()
|
||||
const controller = planner({ mode: { type: 'new-draft' }, setMaxHikingDifficulty: setDifficulty })
|
||||
render(<TourPlannerRail planner={controller} />)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Maximum trail difficulty' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: /T4 — Alpine hiking/ }))
|
||||
expect(screen.getByRole('heading', { name: 'Enable alpine routing?' })).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Enable alpine routing' }))
|
||||
expect(setDifficulty).toHaveBeenCalledWith(4)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Maximum trail difficulty' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: /T5 — Demanding alpine hiking/ }))
|
||||
expect(screen.queryByRole('heading', { name: 'Enable alpine routing?' })).not.toBeInTheDocument()
|
||||
expect(setDifficulty).toHaveBeenLastCalledWith(5)
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-RAIL-008: cancelling alpine acknowledgement leaves the setting unchanged', () => {
|
||||
const setDifficulty = vi.fn()
|
||||
render(<TourPlannerRail planner={planner({ mode: { type: 'new-draft' }, setMaxHikingDifficulty: setDifficulty })} />)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Maximum trail difficulty' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: /T4 — Alpine hiking/ }))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
|
||||
expect(setDifficulty).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-RAIL-014: exposes every T1-T6 choice and the T3 warning', () => {
|
||||
const setDifficulty = vi.fn()
|
||||
function StatefulDifficultyRail() {
|
||||
const [difficulty, setDifficultyState] = useState<1 | 2 | 3 | 4 | 5 | 6>(2)
|
||||
return <TourPlannerRail planner={planner({
|
||||
mode: { type: 'new-draft' },
|
||||
maxHikingDifficulty: difficulty,
|
||||
setMaxHikingDifficulty: value => { setDifficulty(value); setDifficultyState(value as 1 | 2 | 3 | 4 | 5 | 6) },
|
||||
})} />
|
||||
}
|
||||
render(<StatefulDifficultyRail />)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Maximum trail difficulty' }))
|
||||
|
||||
for (const label of [
|
||||
'T1 — Hiking',
|
||||
'T2 — Mountain hiking',
|
||||
'T3 — Demanding mountain hiking',
|
||||
'T4 — Alpine hiking',
|
||||
'T5 — Demanding alpine hiking',
|
||||
'T6 — Difficult alpine hiking',
|
||||
]) expect(screen.getByRole('button', { name: label })).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'T3 — Demanding mountain hiking' }))
|
||||
expect(setDifficulty).toHaveBeenCalledWith(3)
|
||||
expect(screen.getByRole('status')).toHaveTextContent(/T3 routes may include exposed/)
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-RAIL-009: neutral shows only the Plan new entry and new-draft guidance hides after the first waypoint', () => {
|
||||
const controller = planner({ mode: { type: 'neutral' } })
|
||||
const { rerender } = render(<TourPlannerRail planner={controller} />)
|
||||
|
||||
expect(screen.getByText('Plan a tour')).toBeInTheDocument()
|
||||
expect(screen.getByText('Create a route with waypoints and save it to this trip.')).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Plan new tour' }))
|
||||
expect(controller.startNewTour).toHaveBeenCalledOnce()
|
||||
expect(screen.queryByLabelText('Tour name')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Maximum trail difficulty')).not.toBeInTheDocument()
|
||||
|
||||
rerender(<TourPlannerRail planner={planner({ mode: { type: 'new-draft' } })} />)
|
||||
expect(screen.queryByRole('button', { name: 'Plan new tour' })).not.toBeInTheDocument()
|
||||
expect(screen.getByTestId('tour-planner-empty-state')).toHaveTextContent('Click the map to add your starting point.')
|
||||
expect(screen.getByTestId('tour-planner-empty-state')).toHaveTextContent('Add another point to calculate a route.')
|
||||
rerender(<TourPlannerRail planner={planner({ mode: { type: 'new-draft' }, waypoints: [{ id: 'first', lat: 48, lng: 11, role: 'start' }] })} />)
|
||||
expect(screen.queryByTestId('tour-planner-empty-state')).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Plan new tour' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-RAIL-010: elevation disclosure is focusable and toggles with Enter and Space', async () => {
|
||||
function StatefulToursRail() {
|
||||
const [expanded, setExpanded] = useState(true)
|
||||
return (
|
||||
<TourPlannerToursRail
|
||||
planner={planner({
|
||||
mode: { type: 'new-draft' },
|
||||
elevationProfileExpanded: expanded,
|
||||
toggleElevationProfile: () => setExpanded(value => !value),
|
||||
})}
|
||||
tours={[tour]}
|
||||
{...railProps}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const user = userEvent.setup()
|
||||
const { container } = render(<StatefulToursRail />)
|
||||
const toggle = screen.getByRole('button', { name: 'Collapse elevation profile' })
|
||||
toggle.focus()
|
||||
expect(document.activeElement).toBe(toggle)
|
||||
expect(toggle).toHaveAttribute('aria-expanded', 'true')
|
||||
expect(document.getElementById(toggle.getAttribute('aria-controls')!)).not.toBeNull()
|
||||
|
||||
await user.keyboard('{Enter}')
|
||||
const expand = screen.getByRole('button', { name: 'Expand elevation profile' })
|
||||
expect(expand).toHaveAttribute('aria-expanded', 'false')
|
||||
expect(container.querySelector('svg[viewBox="0 0 440 100"]')).not.toBeInTheDocument()
|
||||
|
||||
expand.focus()
|
||||
await user.keyboard(' ')
|
||||
expect(screen.getByRole('button', { name: 'Collapse elevation profile' })).toHaveAttribute('aria-expanded', 'true')
|
||||
expect(container.querySelector('svg[viewBox="0 0 440 100"]')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-RAIL-011: routes Plan new confirmation cancel and confirm through the hook action', () => {
|
||||
const controller = planner({ newTourConfirmationOpen: true, mode: { type: 'new-draft' } })
|
||||
const { rerender } = render(<TourPlannerRail planner={controller} />)
|
||||
|
||||
expect(screen.getByRole('heading', { name: 'Start a new tour?' })).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
|
||||
expect(controller.cancelNewTour).toHaveBeenCalledOnce()
|
||||
|
||||
rerender(<TourPlannerRail planner={controller} />)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Discard changes and start new tour' }))
|
||||
expect(controller.startNewTour).toHaveBeenCalledWith(true)
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-RAIL-012: exposes the same Plan new action while editing a saved Tour', () => {
|
||||
const controller = planner({
|
||||
editingPlaceId: tour.place_id,
|
||||
name: tour.name,
|
||||
waypoints: [{ id: 'saved-start', lat: 48, lng: 11, role: 'start' }],
|
||||
})
|
||||
render(<TourPlannerRail planner={controller} />)
|
||||
|
||||
expect(screen.getByRole('heading', { name: 'Edit tour' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Plan new tour' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-RAIL-013: does not compete with the GPX read-only presentation', () => {
|
||||
const geometry = JSON.stringify([[48, 11, 500], [48, 11.01, 550]])
|
||||
const controller = planner({
|
||||
readOnlyGpxTour: { tour: { ...tour, has_waypoints: false }, routeGeometry: geometry },
|
||||
readOnlyGpxAnalysis: analyzeRouteGeometry(geometry),
|
||||
})
|
||||
render(<TourPlannerRail planner={controller} />)
|
||||
|
||||
expect(screen.getByRole('heading', { name: 'GPX tour' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Plan new tour' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-RAIL-015: returns from GPX view to the blank editable Planner', () => {
|
||||
const controller = planner({
|
||||
readOnlyGpxTour: { tour: { ...tour, has_waypoints: false }, routeGeometry: null },
|
||||
readOnlyGpxAnalysis: null,
|
||||
})
|
||||
const { rerender } = render(<TourPlannerRail planner={controller} />)
|
||||
expect(screen.getByText('GPX tours are view-only and cannot be edited in the planner yet.')).toBeInTheDocument()
|
||||
|
||||
rerender(<TourPlannerRail planner={planner({ mode: { type: 'neutral' } })} />)
|
||||
expect(screen.getByText('Plan a tour')).toBeInTheDocument()
|
||||
expect(screen.queryByText('GPX tours are view-only and cannot be edited in the planner yet.')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-RAIL-016: the master list reflects neutral, saved-edit, and GPX selection modes', () => {
|
||||
const gpxTour = { ...tour, place_id: 43, name: 'Imported GPX walk', has_waypoints: false }
|
||||
const geometry = JSON.stringify([[48, 11], [48.01, 11.02]])
|
||||
const { rerender } = render(<TourPlannerToursRail planner={planner({ mode: { type: 'neutral' } })} tours={[tour, gpxTour]} {...railProps} />)
|
||||
expect(screen.getAllByRole('option').every(row => row.getAttribute('aria-selected') !== 'true')).toBe(true)
|
||||
|
||||
rerender(<TourPlannerToursRail planner={planner({ editingPlaceId: tour.place_id })} tours={[tour, gpxTour]} {...railProps} />)
|
||||
expect(screen.getByRole('option', { name: /Saved ridge walk/i })).toHaveAttribute('aria-selected', 'true')
|
||||
|
||||
rerender(<TourPlannerToursRail planner={planner({
|
||||
readOnlyGpxTour: { tour: gpxTour, routeGeometry: geometry },
|
||||
readOnlyGpxAnalysis: analyzeRouteGeometry(geometry),
|
||||
})} tours={[tour, gpxTour]} {...railProps} />)
|
||||
expect(screen.getByRole('option', { name: /Imported GPX walk/i })).toHaveAttribute('aria-selected', 'true')
|
||||
expect(screen.getByRole('option', { name: /Saved ridge walk/i })).not.toHaveAttribute('aria-selected', 'true')
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-RAIL-018: clean saved editor closes directly; dirty editor close is cancellable', () => {
|
||||
const clean = planner({ mode: { type: 'edit-saved', placeId: tour.place_id }, editingPlaceId: tour.place_id, hasUnsavedChanges: false })
|
||||
const { rerender } = render(<TourPlannerRail planner={clean} />)
|
||||
const back = screen.getByRole('button', { name: 'Back to Tours' })
|
||||
expect(back).toHaveAttribute('aria-label', 'Back to Tours')
|
||||
expect(back).toHaveClass('focus-visible:outline')
|
||||
fireEvent.click(back)
|
||||
expect(clean.returnToNeutral).toHaveBeenCalledOnce()
|
||||
expect(screen.queryByRole('heading', { name: 'Discard unsaved tour changes?' })).not.toBeInTheDocument()
|
||||
|
||||
const dirty = planner({ mode: { type: 'edit-saved', placeId: tour.place_id }, editingPlaceId: tour.place_id, hasUnsavedChanges: true })
|
||||
rerender(<TourPlannerRail planner={dirty} />)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Back to Tours' }))
|
||||
expect(screen.getByRole('heading', { name: 'Discard unsaved tour changes?' })).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
|
||||
expect(dirty.returnToNeutral).not.toHaveBeenCalled()
|
||||
expect(screen.getByRole('heading', { name: 'Edit tour' })).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Back to Tours' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Discard unsaved changes' }))
|
||||
expect(dirty.returnToNeutral).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-RAIL-021: dirty new-draft close requires confirmation', () => {
|
||||
const controller = planner({ mode: { type: 'new-draft' }, hasUnsavedChanges: true })
|
||||
render(<TourPlannerRail planner={controller} />)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Back to Tours' }))
|
||||
expect(screen.getByRole('heading', { name: 'Discard unsaved tour changes?' })).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
|
||||
expect(controller.returnToNeutral).not.toHaveBeenCalled()
|
||||
expect(screen.getByRole('heading', { name: 'New tour' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-RAIL-019: restored new and saved drafts show a non-blocking notice', () => {
|
||||
const { rerender } = render(<TourPlannerRail planner={planner({ draftRestored: true, hasUnsavedChanges: true, mode: { type: 'new-draft' } })} />)
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Unsaved draft restored')
|
||||
expect(screen.getByRole('heading', { name: 'New tour' })).toBeInTheDocument()
|
||||
|
||||
rerender(<TourPlannerRail planner={planner({ draftRestored: true, hasUnsavedChanges: true, editingPlaceId: tour.place_id, mode: { type: 'edit-saved', placeId: tour.place_id } })} />)
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Unsaved draft restored')
|
||||
expect(screen.getByRole('heading', { name: 'Edit tour' })).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,533 @@
|
||||
import { useRef, useState } from 'react'
|
||||
import type { TourListItem } from '@trek/shared'
|
||||
import { ArrowDown, ArrowLeft, ArrowUp, CheckCircle2, ChevronDown, Clock3, Mountain, Plus, Redo2, RotateCcw, Save, ShieldAlert, Trash2, Undo2 } from 'lucide-react'
|
||||
import type { Day } from '../../../types'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import { useSettingsStore } from '../../../store/settingsStore'
|
||||
import { formatDate } from '../../../utils/formatters'
|
||||
import { formatDistance, formatElevation } from '../../../utils/units'
|
||||
import ConfirmDialog from '../../shared/ConfirmDialog'
|
||||
import CustomSelect from '../../shared/CustomSelect'
|
||||
import { DialogButton } from '../../shared/DialogShell'
|
||||
import EmptyState from '../../shared/EmptyState'
|
||||
import { useToast } from '../../shared/Toast'
|
||||
import { BarButton } from '../../Planner/planParts'
|
||||
import TourListRow from '../TourListRow'
|
||||
import ElevationProfile from '../../shared/ElevationProfile'
|
||||
import { hikeSourceBadgeLabel, tourSource } from '../tourPresentation'
|
||||
import type { RouteProfileFocus } from '../../../utils/routeGeometry'
|
||||
import type { TourPlannerController, TourPlannerStatus } from './useTourPlanner'
|
||||
import { useTourPermissions, type TourPermissionProps } from '../useTourPermissions'
|
||||
|
||||
const STATUS_KEY: Partial<Record<TourPlannerStatus, string>> = {
|
||||
dirty: 'tours.planner.status.dirty',
|
||||
routing: 'tours.planner.status.routing',
|
||||
'routing-failed': 'tours.planner.status.routingFailed',
|
||||
'enriching-elevation': 'tours.planner.status.elevation',
|
||||
'elevation-failed': 'tours.planner.status.elevationFailed',
|
||||
ready: 'tours.planner.status.ready',
|
||||
saving: 'tours.planner.status.saving',
|
||||
saved: 'tours.planner.saved',
|
||||
}
|
||||
|
||||
function roleLabel(role: 'start' | 'via' | 'end', t: (key: string) => string) {
|
||||
return t(`tours.planner.${role}`)
|
||||
}
|
||||
|
||||
function profileFocusLabel(focus: RouteProfileFocus, t: (key: string, params?: Record<string, string | number | null>) => string, unit: 'metric' | 'imperial'): string {
|
||||
return t('tours.planner.inspector.profileFocus', {
|
||||
distance: formatDistance(focus.distanceMeters / 1000, unit),
|
||||
elevation: focus.elevationMeters == null ? '—' : formatElevation(focus.elevationMeters, unit),
|
||||
})
|
||||
}
|
||||
|
||||
export function TourPlannerRail({ planner, canEdit: editPermission, canAssign: assignPermission }: { planner: TourPlannerController } & TourPermissionProps) {
|
||||
const { canEdit } = useTourPermissions({ canEdit: editPermission ?? planner.canEdit, canAssign: assignPermission ?? planner.canAssign })
|
||||
const { t } = useTranslation()
|
||||
const distanceUnit = useSettingsStore(state => state.settings.distance_unit)
|
||||
const [confirmDiscard, setConfirmDiscard] = useState(false)
|
||||
const [pendingDifficulty, setPendingDifficulty] = useState<1 | 2 | 3 | 4 | 5 | 6 | null>(null)
|
||||
const alpineAcknowledged = useRef(false)
|
||||
const isSaving = planner.isSaving
|
||||
const statusKey = isSaving ? STATUS_KEY.saving : STATUS_KEY[planner.status]
|
||||
const canRetry = planner.status === 'routing-failed' || planner.status === 'elevation-failed'
|
||||
const requestClose = () => {
|
||||
if (isSaving) return
|
||||
if (planner.hasUnsavedChanges) setConfirmDiscard(true)
|
||||
else planner.returnToNeutral()
|
||||
}
|
||||
|
||||
if (planner.mode.type === 'neutral') {
|
||||
return (
|
||||
<section className="flex h-full min-h-0 flex-col bg-transparent" aria-label={t('tours.planner.title')}>
|
||||
<EmptyState
|
||||
scene="idle"
|
||||
title={t('tours.planner.neutralTitle')}
|
||||
size={48}
|
||||
compact
|
||||
className="min-h-0 flex-1 gap-2 px-4 py-4"
|
||||
action={(
|
||||
<div className="max-w-full">
|
||||
<p className="text-xs leading-5 text-content-secondary">{t('tours.planner.neutralBody')}</p>
|
||||
<div className="mt-3 [&>button]:w-full [&>button]:justify-center">
|
||||
<DialogButton variant="primary" icon={<Plus size={14} />} disabled={!canEdit} onClick={() => { if (canEdit) planner.startNewTour() }}>
|
||||
{t('tours.planner.newTour')}
|
||||
</DialogButton>
|
||||
</div>
|
||||
<p className="mt-2 text-[11px] leading-4 text-content-tertiary">{t('tours.planner.neutralHint')}</p>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
if (planner.mode.type === 'view-gpx') {
|
||||
const { tour } = planner.readOnlyGpxTour
|
||||
const analysis = planner.readOnlyGpxAnalysis
|
||||
return (
|
||||
<>
|
||||
<section className="flex h-full min-h-0 flex-col bg-transparent" aria-label={tour.name}>
|
||||
<div className="flex items-start gap-2 border-b border-edge px-4 py-3">
|
||||
<BarButton label={t('tours.planner.backToTours')} onClick={() => planner.returnToNeutral()} className="mt-0.5 focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent">
|
||||
<ArrowLeft size={16} />
|
||||
</BarButton>
|
||||
<div className="min-w-0 flex-1">
|
||||
<h2 className="text-sm font-semibold text-content">{t('tours.planner.gpxTitle')}</h2>
|
||||
<p className="mt-0.5 truncate text-xs text-content">{tour.name}</p>
|
||||
<p className="mt-0.5 text-[11px] text-content-secondary">{hikeSourceBadgeLabel(tour, t)}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-4 py-4">
|
||||
<p className="text-xs leading-5 text-content-secondary">{t('tours.detail.gpxReadOnly')}</p>
|
||||
{analysis ? (
|
||||
<section className="mt-5" aria-label={t('tours.planner.inspector.title')}>
|
||||
<h3 className="text-xs font-semibold text-content-secondary">{t('tours.planner.inspector.title')}</h3>
|
||||
<dl className="mt-3 grid grid-cols-2 gap-x-3 gap-y-4">
|
||||
<TourPlannerMetric label={t('tours.detail.distance')} value={formatDistance(analysis.distanceKm, distanceUnit)} />
|
||||
{tour.duration != null && <TourPlannerMetric label={t('tours.planner.inspector.duration')} value={t('tours.durationMinutes', { count: Math.max(1, Math.round(tour.duration)) })} />}
|
||||
{analysis.minEle != null && <TourPlannerMetric label={t('tours.detail.minAltitude')} value={formatElevation(analysis.minEle, distanceUnit)} />}
|
||||
{analysis.maxEle != null && <TourPlannerMetric label={t('tours.detail.maxAltitude')} value={formatElevation(analysis.maxEle, distanceUnit)} />}
|
||||
{analysis.gain != null && <TourPlannerMetric label={t('tours.detail.ascent')} value={formatElevation(analysis.gain, distanceUnit)} />}
|
||||
{analysis.loss != null && <TourPlannerMetric label={t('tours.detail.descent')} value={formatElevation(analysis.loss, distanceUnit)} />}
|
||||
</dl>
|
||||
{analysis.distanceIndexedProfileSamples.length >= 2 ? (
|
||||
<div className="mt-5">
|
||||
<div className="mb-2 flex items-center justify-between gap-2">
|
||||
<h3 className="text-xs font-semibold text-content-secondary">{t('tours.planner.inspector.elevation')}</h3>
|
||||
<ElevationProfileToggle
|
||||
id="tour-planner-gpx-elevation-profile"
|
||||
expanded={planner.elevationProfileExpanded}
|
||||
onToggle={planner.toggleElevationProfile}
|
||||
t={t}
|
||||
/>
|
||||
</div>
|
||||
<div id="tour-planner-gpx-elevation-profile" hidden={!planner.elevationProfileExpanded}>
|
||||
{planner.elevationProfileExpanded && <ElevationProfile
|
||||
samples={analysis.distanceIndexedProfileSamples}
|
||||
color="var(--text-secondary)"
|
||||
gradientId={`planner-gpx-elevation-${tour.place_id}`}
|
||||
ariaLabel={t('tours.planner.inspector.elevation')}
|
||||
focus={planner.routeProfileFocus}
|
||||
onFocusChange={planner.setRouteProfileFocus}
|
||||
formatFocus={focus => profileFocusLabel(focus, t, distanceUnit)}
|
||||
/>}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<p className="mt-4 text-xs text-content-secondary">{t('tours.planner.inspector.elevationPlaceholder')}</p>
|
||||
)}
|
||||
</section>
|
||||
) : (
|
||||
<p className="mt-5 text-xs text-content-secondary">{t('tours.planner.gpxNoGeometry')}</p>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
<NewTourConfirmDialog planner={planner} canEdit={canEdit} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const isSavedEdit = planner.mode.type === 'edit-saved'
|
||||
|
||||
return (
|
||||
<>
|
||||
<section className="flex h-full min-h-0 flex-col bg-transparent" aria-label={t('tours.planner.title')}>
|
||||
<div className="border-b border-edge px-4 py-3">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<BarButton label={t('tours.planner.backToTours')} onClick={() => requestClose()} disabled={isSaving} className="shrink-0 focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent">
|
||||
<ArrowLeft size={16} />
|
||||
</BarButton>
|
||||
<div className="min-w-0">
|
||||
<h2 className="text-sm font-semibold text-content">{t(isSavedEdit ? 'tours.planner.editTitle' : 'tours.planner.newTitle')}</h2>
|
||||
<p className="mt-0.5 text-xs text-content-secondary">{t('tours.planner.mapHint')}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 gap-1">
|
||||
<BarButton label={t('tours.planner.undo')} onClick={() => { if (canEdit && !isSaving) planner.undo() }} disabled={!canEdit || isSaving || !planner.canUndo}>
|
||||
<Undo2 size={16} />
|
||||
</BarButton>
|
||||
<BarButton label={t('tours.planner.redo')} onClick={() => { if (canEdit && !isSaving) planner.redo() }} disabled={!canEdit || isSaving || !planner.canRedo}>
|
||||
<Redo2 size={16} />
|
||||
</BarButton>
|
||||
</div>
|
||||
</div>
|
||||
{planner.draftRestored && planner.hasUnsavedChanges && <p className="mt-2 rounded-md bg-surface-hover px-2 py-1 text-[11px] text-content-secondary" role="status">{t('tours.planner.restored')}</p>}
|
||||
<label className="mt-3 block text-xs font-medium text-content-secondary" htmlFor="tour-planner-name">
|
||||
{t('tours.planner.name')}
|
||||
</label>
|
||||
<input
|
||||
id="tour-planner-name"
|
||||
disabled={!canEdit || isSaving}
|
||||
value={planner.name}
|
||||
onChange={event => { if (canEdit && !isSaving) planner.setName(event.target.value) }}
|
||||
maxLength={255}
|
||||
placeholder={t('tours.planner.namePlaceholder')}
|
||||
className="mt-1 w-full rounded-lg border border-edge bg-surface px-3 py-2 text-sm text-content outline-none focus:border-accent"
|
||||
/>
|
||||
<label className="mt-3 block text-xs font-medium text-content-secondary" htmlFor="tour-planner-difficulty">
|
||||
{t('tours.planner.maxDifficulty')}
|
||||
</label>
|
||||
<CustomSelect
|
||||
id="tour-planner-difficulty"
|
||||
disabled={!canEdit || isSaving}
|
||||
ariaLabel={t('tours.planner.maxDifficulty')}
|
||||
value={planner.maxHikingDifficulty}
|
||||
onChange={nextValue => {
|
||||
if (!canEdit || isSaving) return
|
||||
const value = Number(nextValue) as 1 | 2 | 3 | 4 | 5 | 6
|
||||
if (value >= 4 && !alpineAcknowledged.current) setPendingDifficulty(value)
|
||||
else planner.setMaxHikingDifficulty(value)
|
||||
}}
|
||||
options={[1, 2, 3, 4, 5, 6].map(value => ({ value, label: t(`tours.planner.difficulty.t${value}`) }))}
|
||||
size="sm"
|
||||
style={{ marginTop: 4 }}
|
||||
/>
|
||||
{planner.maxHikingDifficulty === 3 && <p className="mt-2 rounded-lg border border-warning bg-warning-soft px-3 py-2 text-xs leading-4 text-warning" role="status">{t('tours.planner.difficulty.t3Warning')}</p>}
|
||||
</div>
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto px-3 py-3">
|
||||
<h3 className="px-1 text-xs font-semibold uppercase tracking-wide text-content-secondary">{t('tours.planner.waypoints')}</h3>
|
||||
{planner.waypoints.length === 0 ? (
|
||||
<div data-testid="tour-planner-empty-state" className="mt-3 rounded-lg border border-dashed border-edge bg-surface-hover px-3 py-4 text-center">
|
||||
<EmptyState scene="idle" title={t('tours.planner.startingPoint')} size={30} layout="row" compact className="gap-2 px-1 py-1" />
|
||||
<p className="mt-1 text-[11px] leading-4 text-content-secondary">{t('tours.planner.firstUseDetails')}</p>
|
||||
</div>
|
||||
) : (
|
||||
<ol className="mt-2 space-y-1.5">
|
||||
{planner.waypoints.map((point, index) => {
|
||||
const selected = planner.selectedWaypointId === point.id
|
||||
return (
|
||||
<li key={point.id}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => planner.setSelectedWaypointId(point.id)}
|
||||
className={`flex w-full items-center gap-2 rounded-xl border px-2 py-2 text-left ${selected ? 'border-accent bg-accent-subtle' : 'border-edge bg-transparent hover:bg-surface-hover'}`}
|
||||
aria-current={selected ? 'true' : undefined}
|
||||
>
|
||||
<span
|
||||
aria-label={t('tours.planner.waypointLabel', { n: index + 1 })}
|
||||
data-waypoint-number={index + 1}
|
||||
className="shrink-0 rounded-full bg-surface-tertiary font-geist text-xs font-semibold tabular-nums text-content-secondary"
|
||||
style={{ width: 28, minWidth: 28, height: 28, display: 'flex', alignItems: 'center', justifyContent: 'center', lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}
|
||||
>
|
||||
{index + 1}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block text-xs font-semibold text-content">{roleLabel(point.role, t)}</span>
|
||||
<span className="block truncate font-mono text-[10px] text-content-tertiary">{point.lat.toFixed(5)}, {point.lng.toFixed(5)}</span>
|
||||
</span>
|
||||
{canEdit && <span className="flex items-center">
|
||||
<span role="button" tabIndex={isSaving || index === 0 ? -1 : 0} aria-label={t('tours.planner.moveUp')} aria-disabled={isSaving || index === 0} onClick={event => { event.stopPropagation(); if (!isSaving) planner.moveWaypoint(point.id, -1) }} onKeyDown={event => { if (!isSaving && event.key === 'Enter' && index > 0) planner.moveWaypoint(point.id, -1) }} className={`rounded p-1 ${isSaving || index === 0 ? 'pointer-events-none opacity-25' : 'hover:bg-surface-card'}`}><ArrowUp size={13} /></span>
|
||||
<span role="button" tabIndex={isSaving || index === planner.waypoints.length - 1 ? -1 : 0} aria-label={t('tours.planner.moveDown')} aria-disabled={isSaving || index === planner.waypoints.length - 1} onClick={event => { event.stopPropagation(); if (!isSaving) planner.moveWaypoint(point.id, 1) }} onKeyDown={event => { if (!isSaving && event.key === 'Enter' && index < planner.waypoints.length - 1) planner.moveWaypoint(point.id, 1) }} className={`rounded p-1 ${isSaving || index === planner.waypoints.length - 1 ? 'pointer-events-none opacity-25' : 'hover:bg-surface-card'}`}><ArrowDown size={13} /></span>
|
||||
<span role="button" tabIndex={isSaving ? -1 : 0} aria-label={t('tours.planner.remove')} aria-disabled={isSaving} onClick={event => { event.stopPropagation(); if (!isSaving) planner.removeWaypoint(point.id) }} onKeyDown={event => { if (!isSaving && event.key === 'Enter') planner.removeWaypoint(point.id) }} className={`rounded p-1 text-red-500 hover:bg-red-50 ${isSaving ? 'pointer-events-none opacity-25' : ''}`}><Trash2 size={13} /></span>
|
||||
</span>}
|
||||
</button>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ol>
|
||||
)}
|
||||
|
||||
{(statusKey || planner.error) && (
|
||||
<div className={`mt-3 rounded-lg px-3 py-2 text-xs ${planner.error ? 'border border-warning bg-warning-soft text-warning' : 'bg-surface-hover text-content-secondary'}`} role="status">
|
||||
{planner.error === 'save' ? t('tours.planner.status.saveFailed') : statusKey ? t(statusKey) : null}
|
||||
{canRetry && <button type="button" onClick={planner.retry} className="ml-2 font-semibold underline">{t('tours.planner.retry')}</button>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="border-t border-edge p-3">
|
||||
<p className="mb-2 flex items-start gap-1.5 text-[11px] leading-4 text-content-secondary">
|
||||
<ShieldAlert className="mt-0.5 h-3.5 w-3.5 shrink-0" />
|
||||
<span>{t('tours.planner.safetyNote')} {t('tours.planner.safetyNoteDetails')}</span>
|
||||
</p>
|
||||
<div className="grid grid-cols-[auto_1fr] gap-2">
|
||||
<DialogButton icon={<RotateCcw size={14} />} onClick={requestClose} disabled={isSaving || (!planner.hasUnsavedChanges && !isSavedEdit)}>
|
||||
{t(isSavedEdit ? 'tours.planner.discardChanges' : 'tours.planner.discard')}
|
||||
</DialogButton>
|
||||
<DialogButton variant="primary" icon={<Save size={14} />} onClick={() => { if (canEdit && !isSaving) void planner.save() }} disabled={!canEdit || isSaving || !planner.canSave}>
|
||||
{t(isSavedEdit ? 'tours.planner.saveChanges' : 'tours.planner.save')}
|
||||
</DialogButton>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ConfirmDialog
|
||||
isOpen={confirmDiscard && !isSaving}
|
||||
onClose={() => setConfirmDiscard(false)}
|
||||
onConfirm={planner.returnToNeutral}
|
||||
title={t('tours.planner.discardTitle')}
|
||||
message={t('tours.planner.discardBody')}
|
||||
confirmLabel={t('tours.planner.discardUnsaved')}
|
||||
/>
|
||||
<NewTourConfirmDialog planner={planner} canEdit={canEdit} />
|
||||
<ConfirmDialog
|
||||
isOpen={pendingDifficulty !== null && !isSaving}
|
||||
onClose={() => setPendingDifficulty(null)}
|
||||
onConfirm={() => {
|
||||
if (canEdit && !isSaving && pendingDifficulty !== null) {
|
||||
alpineAcknowledged.current = true
|
||||
planner.setMaxHikingDifficulty(pendingDifficulty)
|
||||
}
|
||||
setPendingDifficulty(null)
|
||||
}}
|
||||
title={t('tours.planner.difficulty.alpineTitle')}
|
||||
message={t('tours.planner.difficulty.alpineBody')}
|
||||
confirmLabel={t('tours.planner.difficulty.enable')}
|
||||
/>
|
||||
</section>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function TourPlannerMetric({ label, value }: { label: string; value: string }) {
|
||||
return <div><dt className="text-[11px] text-content-secondary">{label}</dt><dd className="mt-1 text-sm font-semibold text-content">{value}</dd></div>
|
||||
}
|
||||
|
||||
function ElevationProfileToggle({ id, expanded, onToggle, t }: { id: string; expanded: boolean; onToggle: () => void; t: (key: string) => string }) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onToggle}
|
||||
aria-expanded={expanded}
|
||||
aria-controls={id}
|
||||
aria-label={t(expanded ? 'tours.planner.collapseElevation' : 'tours.planner.expandElevation')}
|
||||
className="rounded p-1 text-content-secondary hover:bg-surface-hover focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent"
|
||||
>
|
||||
<ChevronDown size={15} className={expanded ? '' : '-rotate-90'} />
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
function NewTourConfirmDialog({ planner, canEdit }: { planner: TourPlannerController; canEdit: boolean }) {
|
||||
const { t } = useTranslation()
|
||||
return (
|
||||
<ConfirmDialog
|
||||
isOpen={canEdit && planner.newTourConfirmationOpen}
|
||||
onClose={planner.cancelNewTour}
|
||||
onConfirm={() => { if (canEdit) planner.startNewTour(true) }}
|
||||
title={t('tours.planner.newTourConfirmTitle')}
|
||||
message={t('tours.planner.newTourConfirmBody')}
|
||||
confirmLabel={t('tours.planner.newTourConfirm')}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
interface TourPlannerToursRailProps extends TourPermissionProps {
|
||||
planner: TourPlannerController
|
||||
tours: TourListItem[]
|
||||
days: Day[]
|
||||
loading: boolean
|
||||
onAssignToDay: (placeId: number, dayId: number) => void | boolean | Promise<void | boolean>
|
||||
onViewGpxTour: (tour: TourListItem) => void
|
||||
}
|
||||
|
||||
function plannerDayLabel(day: Day, index: number, locale: string, t: (key: string, params?: Record<string, unknown>) => string): string {
|
||||
const dayNumber = t('dayplan.dayN', { n: index + 1 })
|
||||
const date = formatDate(day.date, locale)
|
||||
return [dayNumber, date, day.title].filter(Boolean).join(' · ')
|
||||
}
|
||||
|
||||
export function TourPlannerToursRail({ planner, tours, days, loading, onAssignToDay, onViewGpxTour, canEdit: editPermission, canAssign: assignPermission }: TourPlannerToursRailProps) {
|
||||
const { canEdit, canAssign } = useTourPermissions({ canEdit: editPermission ?? planner.canEdit, canAssign: assignPermission ?? planner.canAssign })
|
||||
const { t, locale } = useTranslation()
|
||||
const toast = useToast()
|
||||
const distanceUnit = useSettingsStore(state => state.settings.distance_unit)
|
||||
const [pendingTour, setPendingTour] = useState<TourListItem | null>(null)
|
||||
const [dayPickerOpen, setDayPickerOpen] = useState(false)
|
||||
const [assigning, setAssigning] = useState(false)
|
||||
const isSaving = planner.isSaving
|
||||
const hasRoute = (planner.mode.type === 'new-draft' || planner.mode.type === 'edit-saved') && planner.route !== null
|
||||
const routeAnalysis = planner.routeAnalysis
|
||||
|
||||
const openTour = async (tour: TourListItem) => {
|
||||
const opened = await planner.openTour(tour)
|
||||
if (!opened) toast.error(t('tours.planner.openFailed'))
|
||||
}
|
||||
|
||||
const selectTour = (tour: TourListItem) => {
|
||||
if (tourSource(tour) === 'gpx') onViewGpxTour(tour)
|
||||
else void openTour(tour)
|
||||
}
|
||||
|
||||
const requestOpenTour = (tour: TourListItem) => {
|
||||
if (isSaving) return
|
||||
if (planner.hasUnsavedChanges) {
|
||||
setPendingTour(tour)
|
||||
return
|
||||
}
|
||||
selectTour(tour)
|
||||
}
|
||||
|
||||
const assignSavedTour = async (dayId: number) => {
|
||||
const savedTour = planner.saveOutcome
|
||||
if (!canAssign || !savedTour) return
|
||||
setAssigning(true)
|
||||
try {
|
||||
const assigned = await onAssignToDay(savedTour.place_id, dayId)
|
||||
if (assigned === false) return
|
||||
setDayPickerOpen(false)
|
||||
} finally {
|
||||
setAssigning(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<aside className="flex h-full min-h-0 flex-col bg-transparent" aria-label={t('tours.planner.tripTours')}>
|
||||
<div className="shrink-0 border-b border-edge px-4 py-3">
|
||||
<h2 className="text-sm font-semibold text-content">{t('tours.planner.tripTours')}</h2>
|
||||
<p className="mt-0.5 text-xs text-content-secondary">{t('tours.subtitle')}</p>
|
||||
{hasRoute && (
|
||||
<dl className="mt-4 grid grid-cols-2 gap-2">
|
||||
<div className="rounded-xl border border-edge bg-surface p-3">
|
||||
<dt className="text-[11px] text-content-secondary">{t('tours.planner.inspector.distance')}</dt>
|
||||
<dd className="mt-1 text-sm font-semibold text-content">{routeAnalysis ? formatDistance(routeAnalysis.distanceKm, distanceUnit) : '—'}</dd>
|
||||
</div>
|
||||
<div className="rounded-xl border border-edge bg-surface p-3">
|
||||
<dt className="flex items-center gap-1 text-[11px] text-content-secondary"><Clock3 size={12} />{t('tours.planner.inspector.duration')}</dt>
|
||||
<dd className="mt-1 text-sm font-semibold text-content">{t('tours.durationMinutes', { count: Math.max(1, Math.round((planner.durationSeconds ?? 0) / 60)) })}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
)}
|
||||
{hasRoute && routeAnalysis && (
|
||||
<>
|
||||
<dl className="mt-3 grid grid-cols-2 gap-2">
|
||||
{routeAnalysis.minEle != null && <TourPlannerMetric label={t('tours.detail.minAltitude')} value={formatElevation(routeAnalysis.minEle, distanceUnit)} />}
|
||||
{routeAnalysis.maxEle != null && <TourPlannerMetric label={t('tours.detail.maxAltitude')} value={formatElevation(routeAnalysis.maxEle, distanceUnit)} />}
|
||||
{routeAnalysis.gain != null && <TourPlannerMetric label={t('tours.detail.ascent')} value={formatElevation(routeAnalysis.gain, distanceUnit)} />}
|
||||
{routeAnalysis.loss != null && <TourPlannerMetric label={t('tours.detail.descent')} value={formatElevation(routeAnalysis.loss, distanceUnit)} />}
|
||||
</dl>
|
||||
{routeAnalysis.distanceIndexedProfileSamples.length >= 2 && (
|
||||
<div className="mt-3">
|
||||
<div className="mb-2 flex items-center justify-between gap-2">
|
||||
<h3 className="text-xs font-semibold text-content-secondary">{t('tours.planner.inspector.elevation')}</h3>
|
||||
<ElevationProfileToggle
|
||||
id="tour-planner-editable-elevation-profile"
|
||||
expanded={planner.elevationProfileExpanded}
|
||||
onToggle={planner.toggleElevationProfile}
|
||||
t={t}
|
||||
/>
|
||||
</div>
|
||||
<div id="tour-planner-editable-elevation-profile" hidden={!planner.elevationProfileExpanded}>
|
||||
{planner.elevationProfileExpanded && <ElevationProfile
|
||||
samples={routeAnalysis.distanceIndexedProfileSamples}
|
||||
color="var(--text-secondary)"
|
||||
gradientId={`planner-editable-elevation-${planner.editingPlaceId ?? 'draft'}`}
|
||||
ariaLabel={t('tours.planner.inspector.elevation')}
|
||||
focus={planner.routeProfileFocus}
|
||||
onFocusChange={planner.setRouteProfileFocus}
|
||||
formatFocus={focus => profileFocusLabel(focus, t, distanceUnit)}
|
||||
/>}
|
||||
</div>
|
||||
</div>
|
||||
) || <p className="mt-2 text-xs text-content-secondary">{t('tours.planner.inspector.elevationPlaceholder')}</p>}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{planner.saveOutcome && (
|
||||
<div className="m-3 mb-0 rounded-xl border border-edge bg-surface p-3" role="status">
|
||||
<div className="flex items-center gap-2 text-sm font-semibold text-content">
|
||||
<CheckCircle2 className="h-4 w-4 text-success" />
|
||||
{t('tours.planner.saved')}
|
||||
</div>
|
||||
<div className="mt-3 grid grid-cols-2 gap-2">
|
||||
<DialogButton onClick={() => { if (canEdit && !isSaving) planner.startNewTour() }} disabled={!canEdit || isSaving}>
|
||||
{t('tours.planner.planAnother')}
|
||||
</DialogButton>
|
||||
<DialogButton variant="primary" icon={<ChevronDown size={13} />} onClick={() => { if (canAssign) setDayPickerOpen(open => !open) }} aria-expanded={dayPickerOpen} disabled={!canAssign || days.length === 0}>
|
||||
{t('tours.planner.assignToDay')}
|
||||
</DialogButton>
|
||||
</div>
|
||||
{canAssign && dayPickerOpen && (
|
||||
<label className="mt-2 block text-xs font-medium text-content-secondary" htmlFor="tour-planner-assign-day">
|
||||
{t('tours.addToDay.pickDay')}
|
||||
<select
|
||||
id="tour-planner-assign-day"
|
||||
defaultValue=""
|
||||
disabled={assigning}
|
||||
onChange={event => { if (event.target.value) void assignSavedTour(Number(event.target.value)) }}
|
||||
className="mt-1 w-full rounded-lg border border-edge bg-surface px-2 py-1.5 text-xs text-content"
|
||||
>
|
||||
<option value="" disabled>{t('tours.addToDay.pickDay')}</option>
|
||||
{days.map((day, index) => <option key={day.id} value={day.id}>{plannerDayLabel(day, index, locale, t)}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="min-h-0 flex-1 overflow-y-auto p-3">
|
||||
{loading && tours.length === 0 ? (
|
||||
<p className="py-6 text-center text-xs text-content-secondary">{t('common.loading')}</p>
|
||||
) : tours.length === 0 ? (
|
||||
<div className="rounded-xl border border-edge bg-surface-secondary p-6 text-center">
|
||||
<Mountain className="mx-auto mb-2 h-6 w-6 text-content-faint" strokeWidth={1.6} />
|
||||
<p className="font-medium text-content">{t('tours.empty.title')}</p>
|
||||
<p className="mt-1 text-sm text-content-secondary">{t('tours.empty.body')}</p>
|
||||
</div>
|
||||
) : (
|
||||
<ul className="space-y-2">
|
||||
{tours.map(tour => (
|
||||
<TourListRow
|
||||
key={tour.place_id}
|
||||
tour={tour}
|
||||
disabled={isSaving}
|
||||
selected={(planner.mode.type === 'edit-saved' || planner.mode.type === 'view-gpx') && planner.mode.placeId === tour.place_id}
|
||||
onSelect={requestOpenTour}
|
||||
action={canAssign && days.length > 0 ? (
|
||||
<select
|
||||
aria-label={`${t('tours.addToDay')}: ${tour.name}`}
|
||||
value=""
|
||||
onChange={event => {
|
||||
const dayId = Number(event.target.value)
|
||||
if (canAssign && dayId) void onAssignToDay(tour.place_id, dayId)
|
||||
}}
|
||||
className="w-full rounded-lg border border-edge bg-surface px-2 py-1.5 text-xs text-content"
|
||||
>
|
||||
<option value="" disabled>{t('tours.addToDay.pickDay')}</option>
|
||||
{days.map((day, index) => <option key={day.id} value={day.id}>{plannerDayLabel(day, index, locale, t)}</option>)}
|
||||
</select>
|
||||
) : undefined}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<ConfirmDialog
|
||||
isOpen={pendingTour !== null}
|
||||
onClose={() => setPendingTour(null)}
|
||||
onConfirm={() => {
|
||||
const tour = pendingTour
|
||||
setPendingTour(null)
|
||||
if (tour) selectTour(tour)
|
||||
}}
|
||||
title={t('tours.planner.discardTitle')}
|
||||
message={t('tours.planner.discardBody')}
|
||||
confirmLabel={t('tours.planner.discardChanges')}
|
||||
/>
|
||||
</aside>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { valhallaBase, valhallaRun } = vi.hoisted(() => ({
|
||||
valhallaBase: vi.fn(),
|
||||
valhallaRun: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../Map/valhallaRoute', () => ({
|
||||
valhallaBase,
|
||||
valhallaRun,
|
||||
}))
|
||||
|
||||
import { enrichTourElevations, parseValhallaElevation, routeWalkingTour } from './tourRouting'
|
||||
|
||||
const waypoints = [
|
||||
{ lat: 47.3822621, lng: 10.9888935 },
|
||||
{ lat: 47.3896073, lng: 11.0089761 },
|
||||
]
|
||||
|
||||
describe('routeWalkingTour', () => {
|
||||
beforeEach(() => {
|
||||
valhallaRun.mockReset().mockResolvedValue(null)
|
||||
valhallaBase.mockReset().mockReturnValue('https://valhalla.test')
|
||||
})
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
it('TOUR-ROUTING-001: explicitly admits T2 mountain_hiking trails for Tours only', async () => {
|
||||
await routeWalkingTour(waypoints)
|
||||
|
||||
expect(valhallaRun).toHaveBeenCalledWith(waypoints, 'walking', [], undefined, {
|
||||
max_hiking_difficulty: 2,
|
||||
})
|
||||
})
|
||||
|
||||
it.each([1, 2, 3, 4, 5, 6] as const)('TOUR-ROUTING-002: forwards T%i unchanged to Valhalla', async difficulty => {
|
||||
await routeWalkingTour(waypoints, undefined, difficulty)
|
||||
|
||||
expect(valhallaRun).toHaveBeenCalledWith(waypoints, 'walking', [], undefined, {
|
||||
max_hiking_difficulty: difficulty,
|
||||
})
|
||||
})
|
||||
|
||||
it.each([
|
||||
[0, 0],
|
||||
[123.5, 123.5],
|
||||
[-42.25, -42.25],
|
||||
])('accepts finite numeric Valhalla elevation %s', (input, expected) => {
|
||||
expect(parseValhallaElevation(input)).toBe(expected)
|
||||
})
|
||||
|
||||
it.each([null, undefined, '', ' ', '\t', '123', true, false, Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, '12m', {}, []])(
|
||||
'preserves invalid Valhalla elevation as missing for %s', value => {
|
||||
expect(parseValhallaElevation(value)).toBeNull()
|
||||
},
|
||||
)
|
||||
|
||||
it('keeps valid route coordinates and explicit missing samples when height data is partial', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ range_height: [[0, 0], [1, null], [2, ' ']] }),
|
||||
}))
|
||||
const coordinates: [number, number][] = [[48, 11], [48.01, 11.01], [48.02, 11.02]]
|
||||
|
||||
await expect(enrichTourElevations(coordinates)).resolves.toEqual([
|
||||
[48, 11, 0], [48.01, 11.01], [48.02, 11.02],
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps the full route as 2D geometry when height enrichment is unavailable', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, json: async () => ({}) }))
|
||||
const coordinates: [number, number][] = [[48, 11], [48.01, 11.01]]
|
||||
|
||||
await expect(enrichTourElevations(coordinates)).resolves.toEqual(coordinates)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,98 @@
|
||||
import type { Waypoint } from '../../../types'
|
||||
import { valhallaBase, valhallaRun } from '../../Map/valhallaRoute'
|
||||
|
||||
export interface TourRouteResult {
|
||||
coordinates: [number, number][]
|
||||
distanceMeters: number
|
||||
durationSeconds: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Defensive fallback only. Normal planner calls pass the persisted/draft value.
|
||||
* TREK exposes 1..6 and never exposes Valhalla's internal 0.
|
||||
*/
|
||||
const TOURS_MAX_HIKING_DIFFICULTY = 2
|
||||
|
||||
/** Tours deliberately bypasses the OSRM-first RouteCalculator. */
|
||||
export async function routeWalkingTour(
|
||||
waypoints: Pick<Waypoint, 'lat' | 'lng'>[],
|
||||
signal?: AbortSignal,
|
||||
maxHikingDifficulty = TOURS_MAX_HIKING_DIFFICULTY,
|
||||
): Promise<TourRouteResult | null> {
|
||||
const run = await valhallaRun(waypoints, 'walking', [], signal, {
|
||||
max_hiking_difficulty: maxHikingDifficulty,
|
||||
})
|
||||
if (!run) return null
|
||||
return {
|
||||
coordinates: run.total.coordinates,
|
||||
distanceMeters: run.total.distance,
|
||||
durationSeconds: run.total.duration,
|
||||
}
|
||||
}
|
||||
|
||||
const HEIGHT_CHUNK_SIZE = 500
|
||||
|
||||
export type TourElevationPoint = [number, number] | [number, number, number]
|
||||
|
||||
type HeightResponse = {
|
||||
range_height?: unknown
|
||||
}
|
||||
|
||||
export function parseValhallaElevation(value: unknown): number | null {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? value : null
|
||||
}
|
||||
|
||||
function parseElevations(data: HeightResponse, expected: number): (number | null)[] | null {
|
||||
if (!Array.isArray(data.range_height) || data.range_height.length !== expected) return null
|
||||
return data.range_height.map(entry => {
|
||||
if (!Array.isArray(entry) || entry.length < 2) return null
|
||||
return parseValhallaElevation(entry[1])
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask Valhalla's independent /height stage for every routed vertex. Chunks
|
||||
* overlap by one point so full route resolution is retained without inventing
|
||||
* elevations when a host rejects a large request.
|
||||
*/
|
||||
export async function enrichTourElevations(
|
||||
coordinates: [number, number][],
|
||||
signal?: AbortSignal,
|
||||
): Promise<TourElevationPoint[] | null> {
|
||||
const base = valhallaBase()
|
||||
if (!base || coordinates.length < 2) return null
|
||||
|
||||
const elevations: (number | null)[] = Array(coordinates.length).fill(null)
|
||||
for (let offset = 0; offset < coordinates.length; offset += HEIGHT_CHUNK_SIZE - 1) {
|
||||
if (signal?.aborted) return null
|
||||
const chunk = coordinates.slice(offset, offset + HEIGHT_CHUNK_SIZE)
|
||||
if (chunk.length === 1 && offset > 0) break
|
||||
try {
|
||||
const response = await fetch(`${base}/height`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'X-Client-Id': 'trek' },
|
||||
body: JSON.stringify({
|
||||
shape: chunk.map(([lat, lng]) => ({ lat, lon: lng })),
|
||||
range: true,
|
||||
}),
|
||||
signal,
|
||||
})
|
||||
if (!response.ok) break
|
||||
const chunkElevations = parseElevations(await response.json() as HeightResponse, chunk.length)
|
||||
if (!chunkElevations) break
|
||||
chunkElevations.forEach((elevation, index) => {
|
||||
const routeIndex = offset + index
|
||||
if (offset > 0 && index === 0 && elevations[routeIndex] !== null) return
|
||||
elevations[routeIndex] = elevation
|
||||
})
|
||||
} catch {
|
||||
if (signal?.aborted) return null
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return coordinates.map(([lat, lng], index) => {
|
||||
const elevation = elevations[index]
|
||||
return elevation === null ? [lat, lng] : [lat, lng, elevation]
|
||||
})
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,622 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { TourCreateResponse, TourListItem, TourWaypointRole, TourMaxHikingDifficulty } from '@trek/shared'
|
||||
import { toursApi } from '../../../api/client'
|
||||
import { randomId } from '../../../utils/randomId'
|
||||
import type { TourBaseLayer } from '../../Map/MapLayerSwitcher'
|
||||
import { analyzeRouteGeometry, type RouteProfileFocus } from '../../../utils/routeGeometry'
|
||||
import { enrichTourElevations, routeWalkingTour, type TourElevationPoint } from './tourRouting'
|
||||
import { useTourPermissions, type TourPermissionProps } from '../useTourPermissions'
|
||||
|
||||
export interface TourPlannerWaypoint {
|
||||
id: string
|
||||
lat: number
|
||||
lng: number
|
||||
role: TourWaypointRole
|
||||
}
|
||||
|
||||
export type TourPlannerStatus =
|
||||
| 'empty'
|
||||
| 'dirty'
|
||||
| 'routing'
|
||||
| 'routing-failed'
|
||||
| 'enriching-elevation'
|
||||
| 'elevation-failed'
|
||||
| 'ready'
|
||||
| 'saving'
|
||||
| 'saved'
|
||||
|
||||
interface DraftPayload {
|
||||
version: 1 | 2
|
||||
name: string
|
||||
waypoints: TourPlannerWaypoint[]
|
||||
maxHikingDifficulty?: TourMaxHikingDifficulty
|
||||
editingPlaceId?: number | null
|
||||
}
|
||||
|
||||
interface HistoryState {
|
||||
past: Array<{ waypoints: TourPlannerWaypoint[]; difficulty: TourMaxHikingDifficulty }>
|
||||
future: Array<{ waypoints: TourPlannerWaypoint[]; difficulty: TourMaxHikingDifficulty }>
|
||||
}
|
||||
|
||||
const ROUTE_DEBOUNCE_MS = 450
|
||||
const HISTORY_LIMIT = 30
|
||||
|
||||
function hasCompleteElevation(points: TourElevationPoint[] | null): points is [number, number, number][] {
|
||||
return !!points && points.every(point => point.length === 3 && Number.isFinite(point[2]))
|
||||
}
|
||||
|
||||
export function normalizePlannerWaypoints(points: TourPlannerWaypoint[]): TourPlannerWaypoint[] {
|
||||
return points.map((point, index) => ({
|
||||
...point,
|
||||
role: index === 0 ? 'start' : index === points.length - 1 ? 'end' : 'via',
|
||||
}))
|
||||
}
|
||||
|
||||
export function tourWaypointKey(points: TourPlannerWaypoint[]): string {
|
||||
return points.map(point => `${point.id}:${point.lat.toFixed(7)}:${point.lng.toFixed(7)}`).join('|')
|
||||
}
|
||||
|
||||
function sameWaypointSnapshot(a: TourPlannerWaypoint[], b: TourPlannerWaypoint[]): boolean {
|
||||
return tourWaypointKey(a) === tourWaypointKey(b)
|
||||
}
|
||||
|
||||
function validDraft(value: unknown): value is DraftPayload {
|
||||
if (!value || typeof value !== 'object') return false
|
||||
const draft = value as Partial<DraftPayload>
|
||||
return (draft.version === 1 || draft.version === 2) && typeof draft.name === 'string'
|
||||
&& (draft.editingPlaceId == null || (Number.isInteger(draft.editingPlaceId) && draft.editingPlaceId > 0))
|
||||
&& (draft.maxHikingDifficulty == null || (Number.isInteger(draft.maxHikingDifficulty) && draft.maxHikingDifficulty >= 1 && draft.maxHikingDifficulty <= 6))
|
||||
&& Array.isArray(draft.waypoints)
|
||||
&& draft.waypoints.every(point => point && typeof point.id === 'string'
|
||||
&& Number.isFinite(point.lat) && Math.abs(point.lat) <= 90
|
||||
&& Number.isFinite(point.lng) && Math.abs(point.lng) <= 180)
|
||||
}
|
||||
|
||||
export interface UseTourPlannerOptions extends TourPermissionProps {
|
||||
tripId: number | string
|
||||
active?: boolean
|
||||
onSaved?: (result: TourCreateResponse) => void | Promise<void>
|
||||
}
|
||||
|
||||
export type TourPlannerMode =
|
||||
| { type: 'neutral' }
|
||||
| { type: 'new-draft' }
|
||||
| { type: 'edit-saved'; placeId: number }
|
||||
| { type: 'view-gpx'; placeId: number; tour: TourListItem }
|
||||
|
||||
export function selectTourPlannerMode(state: {
|
||||
readOnlyGpxTour: { tour: TourListItem } | null
|
||||
editingPlaceId: number | null
|
||||
hasUnsavedChanges: boolean
|
||||
}): TourPlannerMode {
|
||||
if (state.readOnlyGpxTour) {
|
||||
return { type: 'view-gpx', placeId: state.readOnlyGpxTour.tour.place_id, tour: state.readOnlyGpxTour.tour }
|
||||
}
|
||||
if (state.editingPlaceId !== null) return { type: 'edit-saved', placeId: state.editingPlaceId }
|
||||
if (state.hasUnsavedChanges) return { type: 'new-draft' }
|
||||
return { type: 'neutral' }
|
||||
}
|
||||
|
||||
export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPermission, canAssign: assignPermission }: UseTourPlannerOptions) {
|
||||
const { canEdit, canAssign } = useTourPermissions({ tripId, canEdit: editPermission, canAssign: assignPermission })
|
||||
const editPermissionRef = useRef(canEdit)
|
||||
editPermissionRef.current = canEdit
|
||||
const storageKey = `tour-draft-${tripId}`
|
||||
const restored = useMemo(() => {
|
||||
try {
|
||||
const parsed = JSON.parse(localStorage.getItem(storageKey) || 'null') as unknown
|
||||
return validDraft(parsed) ? { ...parsed, waypoints: normalizePlannerWaypoints(parsed.waypoints) } : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}, [storageKey])
|
||||
|
||||
const [name, setNameState] = useState(restored?.name ?? '')
|
||||
const [waypoints, setWaypoints] = useState<TourPlannerWaypoint[]>(restored?.waypoints ?? [])
|
||||
const [maxHikingDifficulty, setMaxHikingDifficultyState] = useState<TourMaxHikingDifficulty>(restored?.maxHikingDifficulty ?? 2)
|
||||
const [selectedWaypointId, setSelectedWaypointId] = useState<string | null>(restored?.waypoints[0]?.id ?? null)
|
||||
const [history, setHistory] = useState<HistoryState>({ past: [], future: [] })
|
||||
const [status, setStatus] = useState<TourPlannerStatus>(restored?.waypoints.length ? 'dirty' : 'empty')
|
||||
const [route, setRoute] = useState<[number, number][] | null>(null)
|
||||
const [enrichedGeometry, setEnrichedGeometry] = useState<TourElevationPoint[] | null>(null)
|
||||
const [routeForKey, setRouteForKey] = useState<string | null>(null)
|
||||
const [distanceMeters, setDistanceMeters] = useState<number | null>(null)
|
||||
const [durationSeconds, setDurationSeconds] = useState<number | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(Boolean(restored))
|
||||
const [isSaving, setIsSaving] = useState(false)
|
||||
const [draftRestored, setDraftRestored] = useState(Boolean(restored))
|
||||
const [editingPlaceId, setEditingPlaceId] = useState<number | null>(restored?.editingPlaceId ?? null)
|
||||
const [openingTourId, setOpeningTourId] = useState<number | null>(null)
|
||||
const [saveOutcome, setSaveOutcome] = useState<TourListItem | null>(null)
|
||||
const [retryToken, setRetryToken] = useState(0)
|
||||
const [mapBaseLayer, setMapBaseLayer] = useState<TourBaseLayer>('default')
|
||||
const [readOnlyGpxTour, setReadOnlyGpxTour] = useState<{ tour: TourListItem; routeGeometry: string | null } | null>(null)
|
||||
const [newTourConfirmationOpen, setNewTourConfirmationOpen] = useState(false)
|
||||
const [elevationProfileExpanded, setElevationProfileExpanded] = useState(true)
|
||||
const [routeProfileFocus, setRouteProfileFocus] = useState<RouteProfileFocus | null>(null)
|
||||
const [newDraftGeneration, setNewDraftGeneration] = useState(0)
|
||||
const abortRef = useRef<AbortController | null>(null)
|
||||
const generationRef = useRef(0)
|
||||
const draftRevisionRef = useRef(0)
|
||||
const saveRequestIdRef = useRef(0)
|
||||
const saveInFlightRef = useRef(false)
|
||||
const mountedRef = useRef(false)
|
||||
const contextGenerationRef = useRef(0)
|
||||
const detailRequestIdRef = useRef(0)
|
||||
const detailAbortRef = useRef<AbortController | null>(null)
|
||||
const detailPlaceIdRef = useRef<number | null>(null)
|
||||
const activeRef = useRef(active)
|
||||
const readOnlyGpxTourRef = useRef(readOnlyGpxTour)
|
||||
const tripIdRef = useRef(tripId)
|
||||
const editingPlaceIdRef = useRef(editingPlaceId)
|
||||
activeRef.current = active
|
||||
readOnlyGpxTourRef.current = readOnlyGpxTour
|
||||
tripIdRef.current = tripId
|
||||
editingPlaceIdRef.current = editingPlaceId
|
||||
const waypointsRef = useRef(waypoints)
|
||||
const difficultyRef = useRef(maxHikingDifficulty)
|
||||
waypointsRef.current = waypoints
|
||||
difficultyRef.current = maxHikingDifficulty
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true
|
||||
return () => {
|
||||
mountedRef.current = false
|
||||
saveRequestIdRef.current += 1
|
||||
saveInFlightRef.current = false
|
||||
detailRequestIdRef.current += 1
|
||||
detailPlaceIdRef.current = null
|
||||
detailAbortRef.current?.abort()
|
||||
detailAbortRef.current = null
|
||||
}
|
||||
}, [])
|
||||
|
||||
const invalidateDetailRequest = useCallback(() => {
|
||||
detailRequestIdRef.current += 1
|
||||
detailPlaceIdRef.current = null
|
||||
detailAbortRef.current?.abort()
|
||||
detailAbortRef.current = null
|
||||
if (mountedRef.current) setOpeningTourId(null)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!active) invalidateDetailRequest()
|
||||
}, [active, invalidateDetailRequest])
|
||||
|
||||
useEffect(() => {
|
||||
invalidateDetailRequest()
|
||||
}, [tripId, invalidateDetailRequest])
|
||||
|
||||
const interruptRouting = useCallback(() => {
|
||||
generationRef.current += 1
|
||||
abortRef.current?.abort()
|
||||
abortRef.current = null
|
||||
}, [])
|
||||
|
||||
const commitWaypoints = useCallback((nextValue: TourPlannerWaypoint[] | ((current: TourPlannerWaypoint[]) => TourPlannerWaypoint[])) => {
|
||||
if (!editPermissionRef.current) return
|
||||
const current = waypointsRef.current
|
||||
const next = normalizePlannerWaypoints(typeof nextValue === 'function' ? nextValue(current) : nextValue)
|
||||
if (sameWaypointSnapshot(current, next)) return
|
||||
invalidateDetailRequest()
|
||||
interruptRouting()
|
||||
draftRevisionRef.current += 1
|
||||
setHistory(previous => ({ past: [...previous.past, { waypoints: current, difficulty: difficultyRef.current }].slice(-HISTORY_LIMIT), future: [] }))
|
||||
waypointsRef.current = next
|
||||
setWaypoints(next)
|
||||
setHasUnsavedChanges(true)
|
||||
setSaveOutcome(null)
|
||||
setStatus('dirty')
|
||||
setError(null)
|
||||
}, [invalidateDetailRequest, interruptRouting])
|
||||
|
||||
const setMaxHikingDifficulty = useCallback((value: TourMaxHikingDifficulty) => {
|
||||
if (!editPermissionRef.current) return
|
||||
if (value === difficultyRef.current) return
|
||||
invalidateDetailRequest()
|
||||
interruptRouting()
|
||||
draftRevisionRef.current += 1
|
||||
setHistory(current => ({
|
||||
past: [...current.past, { waypoints: waypointsRef.current, difficulty: difficultyRef.current }].slice(-HISTORY_LIMIT),
|
||||
future: [],
|
||||
}))
|
||||
difficultyRef.current = value
|
||||
setMaxHikingDifficultyState(value)
|
||||
setHasUnsavedChanges(true)
|
||||
setSaveOutcome(null)
|
||||
setStatus('dirty')
|
||||
setError(null)
|
||||
}, [invalidateDetailRequest, interruptRouting])
|
||||
|
||||
const addWaypoint = useCallback((lat: number, lng: number) => {
|
||||
if (!editPermissionRef.current) return
|
||||
const id = randomId()
|
||||
commitWaypoints(current => [...current, { id, lat, lng, role: 'end' }])
|
||||
setSelectedWaypointId(id)
|
||||
}, [commitWaypoints])
|
||||
|
||||
const removeWaypoint = useCallback((id: string) => {
|
||||
if (!editPermissionRef.current) return
|
||||
commitWaypoints(current => current.filter(point => point.id !== id))
|
||||
setSelectedWaypointId(current => current === id ? null : current)
|
||||
}, [commitWaypoints])
|
||||
|
||||
const moveWaypoint = useCallback((id: string, direction: -1 | 1) => {
|
||||
commitWaypoints(current => {
|
||||
const index = current.findIndex(point => point.id === id)
|
||||
const target = index + direction
|
||||
if (index < 0 || target < 0 || target >= current.length) return current
|
||||
const next = [...current]
|
||||
;[next[index], next[target]] = [next[target], next[index]]
|
||||
return next
|
||||
})
|
||||
}, [commitWaypoints])
|
||||
|
||||
const undo = useCallback(() => {
|
||||
if (!editPermissionRef.current) return
|
||||
const previous = history.past[history.past.length - 1]
|
||||
if (!previous) return
|
||||
invalidateDetailRequest()
|
||||
interruptRouting()
|
||||
draftRevisionRef.current += 1
|
||||
const present = { waypoints: waypointsRef.current, difficulty: difficultyRef.current }
|
||||
waypointsRef.current = previous.waypoints
|
||||
difficultyRef.current = previous.difficulty
|
||||
setWaypoints(previous.waypoints)
|
||||
setMaxHikingDifficultyState(previous.difficulty)
|
||||
setSelectedWaypointId(id => previous.waypoints.some(point => point.id === id) ? id : previous.waypoints[0]?.id ?? null)
|
||||
setHistory({ past: history.past.slice(0, -1), future: [present, ...history.future].slice(0, HISTORY_LIMIT) })
|
||||
setHasUnsavedChanges(true)
|
||||
setStatus('dirty')
|
||||
setError(null)
|
||||
}, [history, invalidateDetailRequest, interruptRouting])
|
||||
|
||||
const redo = useCallback(() => {
|
||||
if (!editPermissionRef.current) return
|
||||
const next = history.future[0]
|
||||
if (!next) return
|
||||
invalidateDetailRequest()
|
||||
interruptRouting()
|
||||
draftRevisionRef.current += 1
|
||||
const present = { waypoints: waypointsRef.current, difficulty: difficultyRef.current }
|
||||
waypointsRef.current = next.waypoints
|
||||
difficultyRef.current = next.difficulty
|
||||
setWaypoints(next.waypoints)
|
||||
setMaxHikingDifficultyState(next.difficulty)
|
||||
setSelectedWaypointId(id => next.waypoints.some(point => point.id === id) ? id : next.waypoints[0]?.id ?? null)
|
||||
setHistory({ past: [...history.past, present].slice(-HISTORY_LIMIT), future: history.future.slice(1) })
|
||||
setHasUnsavedChanges(true)
|
||||
setStatus('dirty')
|
||||
setError(null)
|
||||
}, [history, invalidateDetailRequest, interruptRouting])
|
||||
|
||||
const setName = useCallback((value: string) => {
|
||||
if (!editPermissionRef.current) return
|
||||
if (value === name) return
|
||||
invalidateDetailRequest()
|
||||
draftRevisionRef.current += 1
|
||||
setNameState(value)
|
||||
setHasUnsavedChanges(true)
|
||||
setSaveOutcome(null)
|
||||
if (status === 'saved' || status === 'saving') setStatus(waypointsRef.current.length < 2 ? 'dirty' : 'ready')
|
||||
}, [invalidateDetailRequest, name, status])
|
||||
|
||||
const returnToNeutral = useCallback(() => {
|
||||
if (saveInFlightRef.current) return
|
||||
invalidateDetailRequest()
|
||||
interruptRouting()
|
||||
contextGenerationRef.current += 1
|
||||
draftRevisionRef.current += 1
|
||||
setRouteProfileFocus(null)
|
||||
localStorage.removeItem(storageKey)
|
||||
setNameState('')
|
||||
setWaypoints([])
|
||||
setMaxHikingDifficultyState(2)
|
||||
waypointsRef.current = []
|
||||
difficultyRef.current = 2
|
||||
setSelectedWaypointId(null)
|
||||
setHistory({ past: [], future: [] })
|
||||
setStatus('empty')
|
||||
setRoute(null)
|
||||
setEnrichedGeometry(null)
|
||||
setRouteForKey(null)
|
||||
setDistanceMeters(null)
|
||||
setDurationSeconds(null)
|
||||
setError(null)
|
||||
setHasUnsavedChanges(false)
|
||||
setDraftRestored(false)
|
||||
setEditingPlaceId(null)
|
||||
editingPlaceIdRef.current = null
|
||||
setOpeningTourId(null)
|
||||
setSaveOutcome(null)
|
||||
setReadOnlyGpxTour(null)
|
||||
setNewTourConfirmationOpen(false)
|
||||
setElevationProfileExpanded(true)
|
||||
setNewDraftGeneration(generation => generation + 1)
|
||||
}, [invalidateDetailRequest, interruptRouting, storageKey])
|
||||
|
||||
const startNewTour = useCallback((confirmed = false) => {
|
||||
if (!editPermissionRef.current || saveInFlightRef.current) return
|
||||
const currentDraftIsEmpty = editingPlaceId === null && waypoints.length === 0 && name.trim().length === 0
|
||||
if (!confirmed && hasUnsavedChanges && !currentDraftIsEmpty) {
|
||||
setNewTourConfirmationOpen(true)
|
||||
return
|
||||
}
|
||||
returnToNeutral()
|
||||
setHasUnsavedChanges(true)
|
||||
}, [editingPlaceId, hasUnsavedChanges, name, returnToNeutral, waypoints.length])
|
||||
|
||||
const cancelNewTour = useCallback(() => setNewTourConfirmationOpen(false), [])
|
||||
const toggleElevationProfile = useCallback(() => {
|
||||
if (elevationProfileExpanded) setRouteProfileFocus(null)
|
||||
setElevationProfileExpanded(expanded => !expanded)
|
||||
}, [elevationProfileExpanded])
|
||||
const discard = useCallback(() => returnToNeutral(), [returnToNeutral])
|
||||
|
||||
const viewGpxTour = useCallback((tour: TourListItem, routeGeometry: string | null) => {
|
||||
if (saveInFlightRef.current) return
|
||||
invalidateDetailRequest()
|
||||
contextGenerationRef.current += 1
|
||||
returnToNeutral()
|
||||
setReadOnlyGpxTour({ tour, routeGeometry })
|
||||
}, [invalidateDetailRequest, returnToNeutral])
|
||||
|
||||
const closeGpxTour = useCallback(() => {
|
||||
invalidateDetailRequest()
|
||||
contextGenerationRef.current += 1
|
||||
setRouteProfileFocus(null)
|
||||
setReadOnlyGpxTour(null)
|
||||
}, [invalidateDetailRequest])
|
||||
|
||||
const openTour = useCallback(async (tour: TourListItem) => {
|
||||
if (!mountedRef.current || !activeRef.current || saveInFlightRef.current) return false
|
||||
detailAbortRef.current?.abort()
|
||||
const controller = new AbortController()
|
||||
detailAbortRef.current = controller
|
||||
const requestId = ++detailRequestIdRef.current
|
||||
const submittedTripId = String(tripId)
|
||||
const submittedPlaceId = tour.place_id
|
||||
const submittedContextGeneration = contextGenerationRef.current
|
||||
const submittedRevision = draftRevisionRef.current
|
||||
const submittedEditingPlaceId = editingPlaceIdRef.current
|
||||
const submittedGpxPlaceId = readOnlyGpxTourRef.current?.tour.place_id ?? null
|
||||
detailPlaceIdRef.current = submittedPlaceId
|
||||
const requestIsCurrent = () => mountedRef.current
|
||||
&& activeRef.current
|
||||
&& requestId === detailRequestIdRef.current
|
||||
&& detailPlaceIdRef.current === submittedPlaceId
|
||||
&& String(tripIdRef.current) === submittedTripId
|
||||
&& contextGenerationRef.current === submittedContextGeneration
|
||||
&& draftRevisionRef.current === submittedRevision
|
||||
&& editingPlaceIdRef.current === submittedEditingPlaceId
|
||||
&& (readOnlyGpxTourRef.current?.tour.place_id ?? null) === submittedGpxPlaceId
|
||||
setRouteProfileFocus(null)
|
||||
setOpeningTourId(tour.place_id)
|
||||
setError(null)
|
||||
try {
|
||||
const result = await toursApi.detail(tripId, tour.place_id, controller.signal)
|
||||
if (!requestIsCurrent() || saveInFlightRef.current) return false
|
||||
if (result.waypoints.length < 2) {
|
||||
setError('open')
|
||||
return false
|
||||
}
|
||||
|
||||
interruptRouting()
|
||||
const nextWaypoints = normalizePlannerWaypoints(result.waypoints.map(point => ({
|
||||
id: randomId(),
|
||||
lat: point.lat,
|
||||
lng: point.lng,
|
||||
role: point.role,
|
||||
})))
|
||||
localStorage.removeItem(storageKey)
|
||||
contextGenerationRef.current += 1
|
||||
draftRevisionRef.current += 1
|
||||
setNameState(result.tour.name)
|
||||
setWaypoints(nextWaypoints)
|
||||
setMaxHikingDifficultyState(result.tour.max_hiking_difficulty ?? 2)
|
||||
waypointsRef.current = nextWaypoints
|
||||
difficultyRef.current = result.tour.max_hiking_difficulty ?? 2
|
||||
setSelectedWaypointId(nextWaypoints[0]?.id ?? null)
|
||||
setHistory({ past: [], future: [] })
|
||||
setStatus('dirty')
|
||||
setRoute(null)
|
||||
setEnrichedGeometry(null)
|
||||
setRouteForKey(null)
|
||||
setDistanceMeters(null)
|
||||
setDurationSeconds(null)
|
||||
setHasUnsavedChanges(false)
|
||||
setDraftRestored(false)
|
||||
setEditingPlaceId(result.tour.place_id)
|
||||
editingPlaceIdRef.current = result.tour.place_id
|
||||
setSaveOutcome(null)
|
||||
setReadOnlyGpxTour(null)
|
||||
return true
|
||||
} catch {
|
||||
if (requestIsCurrent() && !saveInFlightRef.current) setError('open')
|
||||
return false
|
||||
} finally {
|
||||
if (mountedRef.current && requestId === detailRequestIdRef.current) {
|
||||
detailPlaceIdRef.current = null
|
||||
if (detailAbortRef.current === controller) detailAbortRef.current = null
|
||||
setOpeningTourId(null)
|
||||
}
|
||||
}
|
||||
}, [interruptRouting, storageKey, tripId])
|
||||
|
||||
const retry = useCallback(() => {
|
||||
if (waypointsRef.current.length < 2) return
|
||||
interruptRouting()
|
||||
setError(null)
|
||||
setStatus('dirty')
|
||||
setRetryToken(value => value + 1)
|
||||
}, [interruptRouting])
|
||||
|
||||
const waypointKey = useMemo(() => tourWaypointKey(waypoints), [waypoints])
|
||||
const routeAnalysis = useMemo(
|
||||
() => analyzeRouteGeometry(JSON.stringify(enrichedGeometry ?? route)),
|
||||
[enrichedGeometry, route],
|
||||
)
|
||||
const readOnlyGpxAnalysis = useMemo(
|
||||
() => analyzeRouteGeometry(readOnlyGpxTour?.routeGeometry),
|
||||
[readOnlyGpxTour?.routeGeometry],
|
||||
)
|
||||
const mode = useMemo(() => selectTourPlannerMode({ readOnlyGpxTour, editingPlaceId, hasUnsavedChanges }), [editingPlaceId, hasUnsavedChanges, readOnlyGpxTour])
|
||||
const focusOwner = mode.type === 'view-gpx' || mode.type === 'edit-saved' ? `${mode.type}:${mode.placeId}` : mode.type
|
||||
useEffect(() => { setRouteProfileFocus(null) }, [focusOwner, routeAnalysis, readOnlyGpxAnalysis, readOnlyGpxTour])
|
||||
|
||||
useEffect(() => {
|
||||
if (waypoints.length < 2) {
|
||||
interruptRouting()
|
||||
setStatus(waypoints.length === 0 ? 'empty' : 'dirty')
|
||||
setRoute(null)
|
||||
setRouteForKey(null)
|
||||
setEnrichedGeometry(null)
|
||||
setDistanceMeters(null)
|
||||
setDurationSeconds(null)
|
||||
setRouteProfileFocus(null)
|
||||
setError(null)
|
||||
return
|
||||
}
|
||||
|
||||
const generation = ++generationRef.current
|
||||
const controller = new AbortController()
|
||||
abortRef.current?.abort()
|
||||
abortRef.current = controller
|
||||
const timer = window.setTimeout(async () => {
|
||||
setStatus('routing')
|
||||
const routed = await routeWalkingTour(waypoints, controller.signal, maxHikingDifficulty)
|
||||
if (controller.signal.aborted || generation !== generationRef.current) return
|
||||
if (!routed) {
|
||||
setStatus('routing-failed')
|
||||
setError('routing')
|
||||
return
|
||||
}
|
||||
|
||||
setRoute(routed.coordinates)
|
||||
setDistanceMeters(routed.distanceMeters)
|
||||
setDurationSeconds(routed.durationSeconds)
|
||||
setRouteForKey(waypointKey)
|
||||
setEnrichedGeometry(null)
|
||||
setStatus('enriching-elevation')
|
||||
|
||||
const enriched = await enrichTourElevations(routed.coordinates, controller.signal)
|
||||
if (controller.signal.aborted || generation !== generationRef.current) return
|
||||
if (!enriched) {
|
||||
setStatus('elevation-failed')
|
||||
setError('elevation')
|
||||
return
|
||||
}
|
||||
setEnrichedGeometry(enriched)
|
||||
if (!hasCompleteElevation(enriched)) {
|
||||
setStatus('elevation-failed')
|
||||
setError('elevation')
|
||||
return
|
||||
}
|
||||
setStatus('ready')
|
||||
setError(null)
|
||||
}, ROUTE_DEBOUNCE_MS)
|
||||
|
||||
return () => {
|
||||
window.clearTimeout(timer)
|
||||
controller.abort()
|
||||
}
|
||||
}, [interruptRouting, maxHikingDifficulty, retryToken, waypointKey, waypoints])
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasUnsavedChanges) return
|
||||
const draft: DraftPayload = { version: 2, name, waypoints, maxHikingDifficulty, editingPlaceId }
|
||||
localStorage.setItem(storageKey, JSON.stringify(draft))
|
||||
}, [editingPlaceId, hasUnsavedChanges, maxHikingDifficulty, name, storageKey, waypoints])
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasUnsavedChanges) return
|
||||
const warn = (event: BeforeUnloadEvent) => { event.preventDefault(); event.returnValue = '' }
|
||||
window.addEventListener('beforeunload', warn)
|
||||
return () => window.removeEventListener('beforeunload', warn)
|
||||
}, [hasUnsavedChanges])
|
||||
|
||||
const canSave = canEdit && !isSaving && hasUnsavedChanges && name.trim().length > 0 && status === 'ready'
|
||||
&& routeForKey === waypointKey && hasCompleteElevation(enrichedGeometry)
|
||||
|
||||
const save = useCallback(async () => {
|
||||
if (!mountedRef.current || saveInFlightRef.current || !editPermissionRef.current || !canSave || !hasCompleteElevation(enrichedGeometry)) return null
|
||||
invalidateDetailRequest()
|
||||
saveInFlightRef.current = true
|
||||
const requestId = ++saveRequestIdRef.current
|
||||
const submittedRevision = draftRevisionRef.current
|
||||
const submittedContextGeneration = contextGenerationRef.current
|
||||
const submittedTripId = String(tripId)
|
||||
const submittedPlaceId = editingPlaceId
|
||||
const payload = {
|
||||
name: name.trim(),
|
||||
tour_type: 'hike',
|
||||
route_geometry: enrichedGeometry.map(point => [point[0], point[1], point[2]]),
|
||||
waypoints: waypoints.map((point, sequence) => ({
|
||||
lat: point.lat,
|
||||
lng: point.lng,
|
||||
role: point.role,
|
||||
sequence,
|
||||
})),
|
||||
max_hiking_difficulty: maxHikingDifficulty,
|
||||
duration_seconds: durationSeconds,
|
||||
} as const
|
||||
setStatus('saving')
|
||||
setIsSaving(true)
|
||||
setError(null)
|
||||
const stillCurrent = () => mountedRef.current
|
||||
&& requestId === saveRequestIdRef.current
|
||||
&& String(tripIdRef.current) === submittedTripId
|
||||
&& editingPlaceIdRef.current === submittedPlaceId
|
||||
&& contextGenerationRef.current === submittedContextGeneration
|
||||
&& draftRevisionRef.current === submittedRevision
|
||||
try {
|
||||
const result = submittedPlaceId === null
|
||||
? await toursApi.create(tripId, payload)
|
||||
: await toursApi.update(tripId, submittedPlaceId, payload)
|
||||
if (stillCurrent()) {
|
||||
localStorage.removeItem(storageKey)
|
||||
setHasUnsavedChanges(false)
|
||||
setStatus('saved')
|
||||
setHistory({ past: [], future: [] })
|
||||
setEditingPlaceId(result.tour.place_id)
|
||||
editingPlaceIdRef.current = result.tour.place_id
|
||||
setSaveOutcome(result.tour)
|
||||
}
|
||||
if (mountedRef.current && String(tripIdRef.current) === submittedTripId) {
|
||||
try { await onSaved?.(result) } catch { return result }
|
||||
}
|
||||
return result
|
||||
} catch {
|
||||
if (stillCurrent()) {
|
||||
setStatus('ready')
|
||||
setError('save')
|
||||
}
|
||||
return null
|
||||
} finally {
|
||||
if (mountedRef.current && requestId === saveRequestIdRef.current) {
|
||||
saveInFlightRef.current = false
|
||||
setIsSaving(false)
|
||||
}
|
||||
}
|
||||
}, [canSave, durationSeconds, editingPlaceId, enrichedGeometry, invalidateDetailRequest, maxHikingDifficulty, name, onSaved, storageKey, tripId, waypoints])
|
||||
|
||||
return {
|
||||
canEdit, canAssign,
|
||||
name, setName, maxHikingDifficulty, setMaxHikingDifficulty,
|
||||
waypoints, selectedWaypointId, setSelectedWaypointId,
|
||||
addWaypoint, removeWaypoint, moveWaypoint,
|
||||
undo, redo, canUndo: history.past.length > 0, canRedo: history.future.length > 0,
|
||||
status, error, retry, isSaving,
|
||||
route, enrichedGeometry, routeAnalysis, distanceMeters, durationSeconds,
|
||||
routeProfileFocus, setRouteProfileFocus,
|
||||
mapBaseLayer, setMapBaseLayer,
|
||||
mode, readOnlyGpxTour, readOnlyGpxAnalysis, viewGpxTour, closeGpxTour,
|
||||
startNewTour, newTourConfirmationOpen, cancelNewTour,
|
||||
elevationProfileExpanded, toggleElevationProfile, newDraftGeneration, draftRestored,
|
||||
editingPlaceId, openingTourId, openTour,
|
||||
saveOutcome, hasUnsavedChanges, canSave, save, discard, returnToNeutral,
|
||||
}
|
||||
}
|
||||
|
||||
export type TourPlannerController = ReturnType<typeof useTourPlanner>
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { hikeSourceBadgeLabel, tourSource } from './tourPresentation'
|
||||
|
||||
describe('tourPresentation', () => {
|
||||
it('uses the source abstraction for TREK, GPX import, and wanderer badges', () => {
|
||||
const t = vi.fn((key: string) => key)
|
||||
|
||||
expect(tourSource({ wanderer_ref: null })).toBe('trek')
|
||||
expect(hikeSourceBadgeLabel({ wanderer_ref: null }, t)).toBe('tours.badge.trek')
|
||||
expect(tourSource({ wanderer_ref: null, has_waypoints: false })).toBe('gpx')
|
||||
expect(hikeSourceBadgeLabel({ wanderer_ref: null, has_waypoints: false }, t)).toBe('tours.badge.gpx')
|
||||
expect(tourSource({ wanderer_ref: 'wanderer:123' })).toBe('wanderer')
|
||||
expect(hikeSourceBadgeLabel({ wanderer_ref: 'wanderer:123' }, t)).toBe('tours.badge.wanderer')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { TourListItem } from '@trek/shared'
|
||||
|
||||
export type TourSource = 'trek' | 'gpx' | 'wanderer'
|
||||
|
||||
type Translate = (key: string, params?: Record<string, unknown>) => string
|
||||
|
||||
/**
|
||||
* Presentation-only source abstraction until provenance receives its own column.
|
||||
* A wanderer reference is authoritative. Planner-authored TREK tours persist
|
||||
* routing controls, while GPX imports intentionally remain geometry-only.
|
||||
*/
|
||||
export function tourSource(tour: Pick<TourListItem, 'wanderer_ref' | 'has_waypoints'>): TourSource {
|
||||
if (tour.wanderer_ref) return 'wanderer'
|
||||
return tour.has_waypoints === false ? 'gpx' : 'trek'
|
||||
}
|
||||
|
||||
export function hikeSourceBadgeLabel(
|
||||
tour: Pick<TourListItem, 'wanderer_ref' | 'has_waypoints'>,
|
||||
t: Translate,
|
||||
): string {
|
||||
return t(`tours.badge.${tourSource(tour)}`)
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import en from '@trek/shared/i18n/en'
|
||||
import de from '@trek/shared/i18n/de'
|
||||
import fr from '@trek/shared/i18n/fr'
|
||||
import type { TourListItem } from '@trek/shared'
|
||||
import { fireEvent, render, screen, waitFor } from '../../../tests/helpers/render'
|
||||
import { resetAllStores, seedStore } from '../../../tests/helpers/store'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { analyzeRouteGeometry } from '../../utils/routeGeometry'
|
||||
import TourListRow from './TourListRow'
|
||||
import { TourPlannerRail, TourPlannerToursRail } from './planner/TourPlannerPanels'
|
||||
import type { TourPlannerController } from './planner/useTourPlanner'
|
||||
|
||||
vi.mock('../../../../server/src/config', () => { throw new Error('Config initialization is forbidden in client tests') })
|
||||
vi.mock('../../../../server/src/db/database', () => { throw new Error('Legacy database imports are forbidden in client tests') })
|
||||
vi.mock('../../../../server/src/nest/database/database.service', () => { throw new Error('Database service imports are forbidden in client tests') })
|
||||
vi.mock('better-sqlite3', () => { throw new Error('SQLite imports are forbidden in client tests') })
|
||||
|
||||
const tour: TourListItem = {
|
||||
place_id: 42, name: 'Ridge walk', tour_type: 'hike', distance: 4,
|
||||
elevation_gain: 100, elevation_loss: 80, duration: 60, difficulty: null,
|
||||
wanderer_ref: null, match_confidence: 1, tour_group_id: null,
|
||||
max_hiking_difficulty: 2, planned: false, caution: false,
|
||||
}
|
||||
|
||||
function toursText(strings: typeof en, key: string): string {
|
||||
const value = strings[key]
|
||||
if (typeof value !== 'string') throw new Error(`Missing Tours text: ${key}`)
|
||||
return value
|
||||
}
|
||||
|
||||
function planner(overrides: Partial<TourPlannerController>): TourPlannerController {
|
||||
return {
|
||||
canEdit: true, canAssign: true,
|
||||
mode: { type: 'neutral' }, status: 'empty', error: null, name: '',
|
||||
maxHikingDifficulty: 2, waypoints: [], hasUnsavedChanges: false,
|
||||
draftRestored: false, newTourConfirmationOpen: false,
|
||||
readOnlyGpxTour: null, readOnlyGpxAnalysis: null,
|
||||
route: null, routeAnalysis: null, elevationProfileExpanded: true,
|
||||
...overrides,
|
||||
} as TourPlannerController
|
||||
}
|
||||
|
||||
function assertNoRawToursKeys() {
|
||||
const visible = [document.body.textContent, ...Array.from(document.querySelectorAll('[aria-label], [title], [placeholder]'))
|
||||
.flatMap(element => ['aria-label', 'title', 'placeholder'].map(attribute => element.getAttribute(attribute)))]
|
||||
.filter(Boolean).join(' ')
|
||||
expect(visible).not.toMatch(/\b(?:tours|tourTypes)\.[a-zA-Z]+/)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetAllStores()
|
||||
seedStore(useSettingsStore, { settings: { language: 'en', distance_unit: 'metric' } })
|
||||
})
|
||||
|
||||
describe('Tours English and German copy', () => {
|
||||
it('has exact merged Tours keys and matching interpolation parameters in both languages', () => {
|
||||
const keys = Object.keys(en).filter(key => key.startsWith('tours.') || key.startsWith('tourTypes.'))
|
||||
expect(keys.length).toBeGreaterThan(100)
|
||||
expect(toursText(de, 'trip.tabs.tourPlanner')).toBe('Touren')
|
||||
expect(Object.keys(de).filter(key => key.startsWith('tours.') || key.startsWith('tourTypes.')).sort()).toEqual(keys.sort())
|
||||
for (const key of keys) {
|
||||
const params = (text: string) => [...text.matchAll(/\{([^{}]+)\}/g)].map(match => match[1]).sort()
|
||||
expect(params(toursText(de, key)), key).toEqual(params(toursText(en, key)))
|
||||
}
|
||||
for (let level = 1; level <= 6; level++) {
|
||||
expect(en[`tours.planner.difficulty.t${level}`]).toMatch(new RegExp(`^T${level} `))
|
||||
expect(de[`tours.planner.difficulty.t${level}`]).toMatch(new RegExp(`^T${level} `))
|
||||
}
|
||||
expect(de['tours.planner.safetyNoteDetails']).toMatch(/OSM.*Wetter.*Sperrungen/)
|
||||
expect(de['tours.planner.difficulty.t3Warning']).toMatch(/Trittsicherheit/)
|
||||
expect(de['tours.planner.difficulty.alpineBody']).toMatch(/OSM/)
|
||||
})
|
||||
|
||||
for (const [language, neutral, newTitle, editTitle, gpxTitle, back] of [
|
||||
['en', 'Plan a tour', 'New tour', 'Edit tour', 'GPX tour', 'Back to Tours'],
|
||||
['de', 'Tour planen', 'Neue Tour', 'Tour bearbeiten', 'GPX-Tour', 'Zurück zu den Touren'],
|
||||
]) {
|
||||
it(`${language}: renders the four modes, status, safety and accessibility without raw keys`, async () => {
|
||||
seedStore(useSettingsStore, { settings: { language } })
|
||||
const { rerender } = render(<TourPlannerRail planner={planner({})} />)
|
||||
expect(await screen.findByText(neutral)).toBeInTheDocument()
|
||||
assertNoRawToursKeys()
|
||||
|
||||
const waypoint = { id: 'first', lat: 48, lng: 11, role: 'start' as const }
|
||||
rerender(<TourPlannerRail planner={planner({
|
||||
mode: { type: 'new-draft' }, status: 'routing', hasUnsavedChanges: true,
|
||||
draftRestored: true, waypoints: [waypoint], maxHikingDifficulty: 3,
|
||||
})} />)
|
||||
expect(screen.getByRole('heading', { name: newTitle })).toBeInTheDocument()
|
||||
const strings = language === 'de' ? de : en
|
||||
expect(screen.getByText(toursText(strings, 'tours.planner.restored'))).toBeInTheDocument()
|
||||
expect(screen.getByText(toursText(strings, 'tours.planner.status.routing'))).toBeInTheDocument()
|
||||
expect(screen.getByText(toursText(strings, 'tours.planner.difficulty.t3Warning'))).toBeInTheDocument()
|
||||
expect(screen.getByText((_, element) => element?.tagName === 'SPAN' && element.textContent?.includes(toursText(strings, 'tours.planner.safetyNoteDetails')) === true)).toBeInTheDocument()
|
||||
expect(screen.getByLabelText(language === 'de' ? 'Wegpunkt 1' : 'Waypoint 1')).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: language === 'de' ? 'Maximale Wegschwierigkeit' : 'Maximum trail difficulty' })).toBeInTheDocument()
|
||||
assertNoRawToursKeys()
|
||||
|
||||
rerender(<TourPlannerRail planner={planner({ mode: { type: 'edit-saved', placeId: 42 }, editingPlaceId: 42 })} />)
|
||||
expect(screen.getByRole('heading', { name: editTitle })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: back })).toHaveAttribute('aria-label', back)
|
||||
assertNoRawToursKeys()
|
||||
|
||||
const geometry = JSON.stringify([[48, 11, 500], [48.01, 11.02, 550]])
|
||||
rerender(<TourPlannerRail planner={planner({
|
||||
mode: { type: 'view-gpx', placeId: 42, tour },
|
||||
readOnlyGpxTour: { tour, routeGeometry: geometry },
|
||||
readOnlyGpxAnalysis: analyzeRouteGeometry(geometry),
|
||||
})} />)
|
||||
expect(screen.getByRole('heading', { name: gpxTitle })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: language === 'de' ? 'Höhenprofil einklappen' : 'Collapse elevation profile' })).toHaveAttribute('aria-expanded', 'true')
|
||||
assertNoRawToursKeys()
|
||||
})
|
||||
}
|
||||
|
||||
it('German ADD row and save outcome have localized badges, labels and day picker', async () => {
|
||||
seedStore(useSettingsStore, { settings: { language: 'de' } })
|
||||
const { rerender } = render(<TourListRow tour={tour} onSelect={() => {}} />)
|
||||
await waitFor(() => expect(screen.getByTitle(toursText(de, 'tours.planner.difficulty.t2'))).toBeInTheDocument())
|
||||
expect(screen.getByTitle(toursText(de, 'tours.planner.difficulty.t2'))).toBeInTheDocument()
|
||||
rerender(<TourPlannerToursRail planner={planner({ saveOutcome: tour, mode: { type: 'edit-saved', placeId: 42 } })} tours={[tour]} days={[{ id: 7, title: 'Gipfeltag', date: '2026-05-15' } as never]} loading={false} onAssignToDay={vi.fn()} onViewGpxTour={vi.fn()} />)
|
||||
expect(screen.getByText(toursText(de, 'tours.planner.saved'))).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: toursText(de, 'tours.planner.assignToDay') }))
|
||||
expect(screen.getByLabelText(toursText(de, 'tours.addToDay.pickDay'))).toBeInTheDocument()
|
||||
assertNoRawToursKeys()
|
||||
})
|
||||
|
||||
it('German routing, elevation, save errors and alpine acknowledgement use translated copy', async () => {
|
||||
seedStore(useSettingsStore, { settings: { language: 'de' } })
|
||||
const { rerender } = render(<TourPlannerRail planner={planner({ mode: { type: 'new-draft' } })} />)
|
||||
await screen.findByRole('heading', { name: toursText(de, 'tours.planner.newTitle') })
|
||||
for (const [status, key] of [
|
||||
['routing-failed', 'tours.planner.status.routingFailed'],
|
||||
['enriching-elevation', 'tours.planner.status.elevation'],
|
||||
['elevation-failed', 'tours.planner.status.elevationFailed'],
|
||||
['saving', 'tours.planner.status.saving'],
|
||||
] as const) {
|
||||
rerender(<TourPlannerRail planner={planner({ mode: { type: 'new-draft' }, status, error: null })} />)
|
||||
expect(screen.getByText(toursText(de, key))).toBeInTheDocument()
|
||||
assertNoRawToursKeys()
|
||||
}
|
||||
rerender(<TourPlannerRail planner={planner({ mode: { type: 'new-draft' }, status: 'ready', error: 'save' })} />)
|
||||
expect(screen.getByText(toursText(de, 'tours.planner.status.saveFailed'))).toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: toursText(de, 'tours.planner.maxDifficulty') }))
|
||||
fireEvent.click(screen.getByRole('button', { name: toursText(de, 'tours.planner.difficulty.t4') }))
|
||||
expect(screen.getByRole('heading', { name: toursText(de, 'tours.planner.difficulty.alpineTitle') })).toBeInTheDocument()
|
||||
expect(screen.getByText(toursText(de, 'tours.planner.difficulty.alpineBody'))).toBeInTheDocument()
|
||||
assertNoRawToursKeys()
|
||||
})
|
||||
|
||||
it('German dirty-draft confirmation and GPX missing-elevation text are localized', async () => {
|
||||
seedStore(useSettingsStore, { settings: { language: 'de' } })
|
||||
const { rerender } = render(<TourPlannerRail planner={planner({ mode: { type: 'new-draft' }, hasUnsavedChanges: true })} />)
|
||||
await screen.findByRole('heading', { name: toursText(de, 'tours.planner.newTitle') })
|
||||
fireEvent.click(screen.getByRole('button', { name: toursText(de, 'tours.planner.backToTours') }))
|
||||
expect(screen.getByRole('heading', { name: toursText(de, 'tours.planner.discardTitle') })).toBeInTheDocument()
|
||||
expect(screen.getByText(toursText(de, 'tours.planner.discardBody'))).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: toursText(de, 'tours.planner.discardUnsaved') })).toBeInTheDocument()
|
||||
assertNoRawToursKeys()
|
||||
|
||||
rerender(<TourPlannerRail planner={planner({
|
||||
mode: { type: 'view-gpx', placeId: tour.place_id, tour },
|
||||
readOnlyGpxTour: { tour, routeGeometry: null },
|
||||
})} />)
|
||||
expect(screen.getByText(toursText(de, 'tours.planner.gpxNoGeometry'))).toBeInTheDocument()
|
||||
expect(screen.getByText(toursText(de, 'tours.detail.gpxReadOnly'))).toBeInTheDocument()
|
||||
assertNoRawToursKeys()
|
||||
})
|
||||
|
||||
it('French Tours copy loads from the registered locale domain', async () => {
|
||||
seedStore(useSettingsStore, { settings: { language: 'fr' } })
|
||||
function Sample() {
|
||||
const { t } = useTranslation()
|
||||
return <span>{t('tours.planner.neutralTitle')}</span>
|
||||
}
|
||||
render(<Sample />)
|
||||
await waitFor(() => expect(document.documentElement.lang).toBe('fr'))
|
||||
expect(await screen.findByText(toursText(fr, 'tours.planner.neutralTitle'))).toBeInTheDocument()
|
||||
assertNoRawToursKeys()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,208 @@
|
||||
import { act, cleanup, fireEvent, render, renderHook, screen } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { TourListItem } from '@trek/shared'
|
||||
|
||||
vi.mock('../../../../server/src/config', () => { throw new Error('Config initialization is forbidden in client tests') })
|
||||
vi.mock('../../../../server/src/db/database', () => { throw new Error('Legacy database imports are forbidden in client tests') })
|
||||
vi.mock('../../../../server/src/nest/database/database.service', () => { throw new Error('Database service imports are forbidden in client tests') })
|
||||
vi.mock('better-sqlite3', () => { throw new Error('SQLite imports are forbidden in client tests') })
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
trip: { id: 7, user_id: 1 } as { id: number; user_id: number } | null,
|
||||
user: { id: 2, role: 'user' } as { id: number; role: string } | null,
|
||||
importGpx: vi.fn(),
|
||||
loadTrip: vi.fn(),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
detail: vi.fn(),
|
||||
route: vi.fn(),
|
||||
elevation: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../store/tripStore', () => ({ useTripStore: (selector: (store: unknown) => unknown) => selector({ trip: state.trip, loadTrip: state.loadTrip }) }))
|
||||
vi.mock('../../store/authStore', () => ({ useAuthStore: (selector: (store: unknown) => unknown) => selector({ user: state.user }) }))
|
||||
vi.mock('../../store/settingsStore', () => ({ useSettingsStore: (selector: (store: unknown) => unknown) => selector({ settings: { distance_unit: 'metric' } }) }))
|
||||
vi.mock('../../api/client', () => ({ toursApi: { importGpx: state.importGpx, create: state.create, update: state.update, detail: state.detail } }))
|
||||
vi.mock('./planner/tourRouting', () => ({ routeWalkingTour: state.route, enrichTourElevations: state.elevation }))
|
||||
vi.mock('../../i18n', () => ({ useTranslation: () => ({ t: (key: string) => key, locale: 'en' }), translateApiError: () => 'error' }))
|
||||
vi.mock('../shared/Toast', () => ({ useToast: () => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }) }))
|
||||
vi.mock('../shared/ConfirmDialog', () => ({ default: () => null }))
|
||||
vi.mock('../shared/EmptyState', () => ({ default: ({ action }: { action?: React.ReactNode }) => <div>{action}</div> }))
|
||||
vi.mock('../shared/CustomSelect', () => ({ default: ({ id, ariaLabel, disabled, value }: { id: string; ariaLabel: string; disabled: boolean; value: number }) => <select id={id} aria-label={ariaLabel} disabled={disabled} value={value} onChange={() => {}}><option value={value}>{value}</option></select> }))
|
||||
vi.mock('../shared/ElevationProfile', () => ({ default: () => null }))
|
||||
vi.mock('../shared/DetailShell', () => ({ default: ({ header, footer, children }: { header: React.ReactNode; footer: React.ReactNode; children: React.ReactNode }) => <div>{header}{children}{footer}</div> }))
|
||||
vi.mock('../shared/TrackColorPicker', () => ({ default: ({ onChange }: { onChange: (color: string) => void }) => <button onClick={() => onChange('#ff0000')}>color</button> }))
|
||||
vi.mock('../shared/NavigationMenu', () => ({ NavigationMenu: () => null }))
|
||||
vi.mock('../shared/markdownLink', () => ({ markdownLinkComponents: {} }))
|
||||
vi.mock('../../utils/fileDownload', () => ({ openFile: vi.fn() }))
|
||||
vi.mock('../Planner/placeNavigation', () => ({ getNavigationTargets: () => [], openNavigationTarget: vi.fn() }))
|
||||
|
||||
import { usePermissionsStore } from '../../store/permissionsStore'
|
||||
import { useTourPermissions } from './useTourPermissions'
|
||||
import ToursSidebar from './ToursSidebar'
|
||||
import { useTourPlanner } from './planner/useTourPlanner'
|
||||
import type { TourPlannerController } from './planner/useTourPlanner'
|
||||
import { TourPlannerRail, TourPlannerToursRail } from './planner/TourPlannerPanels'
|
||||
import TourDetailDialog from './TourDetailDialog'
|
||||
import MToursSelectionList from '../../mobile/screens/trip/places/MToursSelectionList'
|
||||
|
||||
const tour = { place_id: 42, name: 'Ridge', tour_type: 'hike', max_hiking_difficulty: 2, planned: false } as TourListItem
|
||||
const days = [{ id: 3, title: 'Summit' }] as never
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
state.trip = { id: 7, user_id: 1 }
|
||||
state.user = { id: 2, role: 'user' }
|
||||
state.importGpx.mockResolvedValue({ tours: [tour] })
|
||||
usePermissionsStore.setState({ permissions: { place_edit: 'admin', day_edit: 'admin' } })
|
||||
})
|
||||
afterEach(() => { cleanup(); vi.useRealTimers(); localStorage.clear() })
|
||||
|
||||
describe('Tours permissions without database setup', () => {
|
||||
it('revoking sidebar rights closes assignment choices and blocks file-input invocation', async () => {
|
||||
const assign = vi.fn()
|
||||
const props = { tripId: 7, days, tours: [tour], onAssignToDay: assign }
|
||||
const { container, rerender } = render(<ToursSidebar {...props} canEdit canAssign />)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'tours.addToDay' }))
|
||||
expect(screen.getByRole('button', { name: /Summit/ })).toBeTruthy()
|
||||
rerender(<ToursSidebar {...props} canEdit={false} canAssign={false} />)
|
||||
expect(screen.queryByRole('button', { name: /Summit/ })).toBeNull()
|
||||
await act(async () => { fireEvent.change(container.querySelector('input[type=file]')!, { target: { files: [new File(['gpx'], 'ridge.gpx')] } }) })
|
||||
expect(state.importGpx).not.toHaveBeenCalled()
|
||||
expect(assign).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each([[false, false], [true, false], [false, true], [true, true]])('update edit=%s assign=%s writes only with place rights and never assigns', async (canEdit, canAssign) => {
|
||||
vi.useFakeTimers()
|
||||
state.detail.mockResolvedValue({ tour, waypoints: [{ lat: 48, lng: 11, role: 'start' }, { lat: 49, lng: 12, role: 'end' }] })
|
||||
state.route.mockResolvedValue({ coordinates: [[48, 11], [49, 12]], distanceMeters: 1000, durationSeconds: 600 })
|
||||
state.elevation.mockResolvedValue([[48, 11, 500], [49, 12, 550]])
|
||||
state.update.mockResolvedValue({ tour, waypoints: [] })
|
||||
const saved = vi.fn()
|
||||
const { result } = renderHook(() => useTourPlanner({ tripId: 7, canEdit, canAssign, onSaved: saved }))
|
||||
await act(async () => { await result.current.openTour(tour) })
|
||||
expect(state.detail).toHaveBeenCalledWith(7, 42, expect.any(AbortSignal))
|
||||
act(() => result.current.setName('Updated ridge'))
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(450) })
|
||||
expect(result.current.canSave).toBe(canEdit)
|
||||
await act(async () => { await result.current.save() })
|
||||
expect(state.update).toHaveBeenCalledTimes(canEdit ? 1 : 0)
|
||||
expect(saved).toHaveBeenCalledTimes(canEdit ? 1 : 0)
|
||||
expect(state.create).not.toHaveBeenCalled()
|
||||
})
|
||||
it.each([[false, false], [true, false], [false, true], [true, true]])('detail/mobile edit=%s assign=%s gate independent actions and preserve viewing', async (canEdit, canAssign) => {
|
||||
const update = vi.fn()
|
||||
const remove = vi.fn()
|
||||
const assign = vi.fn()
|
||||
const del = vi.fn()
|
||||
const upload = vi.fn().mockResolvedValue(undefined)
|
||||
const place = { id: 42, trip_id: 7, name: 'Ridge', lat: 48, lng: 11, route_geometry: null } as never
|
||||
const props = { tour, place, selectedDayId: 3, canEdit, canAssign, onClose: vi.fn(), onUpdatePlace: update, onAssignToDay: assign, onRemoveAssignment: remove, onDelete: del, onFileUpload: upload }
|
||||
const { container, rerender } = render(<TourDetailDialog {...props} />)
|
||||
const uploadInput = container.querySelector('input[type=file]')
|
||||
expect(Boolean(uploadInput)).toBe(canEdit)
|
||||
if (uploadInput) await act(async () => { fireEvent.change(uploadInput, { target: { files: [new File(['file'], 'ridge.txt')] } }) })
|
||||
expect(upload).toHaveBeenCalledTimes(canEdit ? 1 : 0)
|
||||
expect(Boolean(screen.queryByRole('button', { name: 'common.edit' }))).toBe(canEdit)
|
||||
expect(Boolean(screen.queryByRole('button', { name: 'common.delete' }))).toBe(canEdit)
|
||||
expect(Boolean(screen.queryByRole('button', { name: 'inspector.addToDay' }))).toBe(canAssign)
|
||||
if (canEdit) {
|
||||
fireEvent.click(screen.getByRole('button', { name: 'color' }))
|
||||
expect(update).toHaveBeenCalledWith(42, { route_color: '#ff0000' })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'common.edit' }))
|
||||
fireEvent.change(screen.getByDisplayValue('Ridge'), { target: { value: 'Renamed' } })
|
||||
await act(async () => { fireEvent.click(screen.getByRole('button', { name: 'common.save' })) })
|
||||
expect(update).toHaveBeenCalledWith(42, { name: 'Renamed' })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'common.delete' }))
|
||||
expect(del).toHaveBeenCalledOnce()
|
||||
}
|
||||
if (canAssign) fireEvent.click(screen.getByRole('button', { name: 'inspector.addToDay' }))
|
||||
expect(assign).toHaveBeenCalledTimes(canAssign ? 1 : 0)
|
||||
rerender(<TourDetailDialog {...props} assignments={{ '3': [{ id: 9, place }] } as never} />)
|
||||
expect(Boolean(screen.queryByRole('button', { name: 'inspector.removeFromDay' }))).toBe(canAssign)
|
||||
if (canAssign) fireEvent.click(screen.getByRole('button', { name: 'inspector.removeFromDay' }))
|
||||
expect(remove).toHaveBeenCalledTimes(canAssign ? 1 : 0)
|
||||
const view = vi.fn()
|
||||
const openSheet = vi.fn()
|
||||
rerender(<MToursSelectionList planner={{ t: (key: string) => key, tours: [tour], handlePlaceClick: view, reloadTourPlaceIds: vi.fn() } as never} shell={{ sheet: 'other', openSheet } as never} filter="all" canEdit={canEdit} canAssign={canAssign} />)
|
||||
fireEvent.click(screen.getByRole('option'))
|
||||
expect(view).toHaveBeenCalledWith(42)
|
||||
const attach = screen.getByRole('button', { name: 'tours.addToDay' }) as HTMLButtonElement
|
||||
expect(attach.disabled).toBe(!canAssign)
|
||||
fireEvent.click(attach)
|
||||
expect(openSheet).toHaveBeenCalledTimes(canAssign ? 1 : 0)
|
||||
})
|
||||
it.each([[false, false], [true, false], [false, true], [true, true]])('rails edit=%s assign=%s separate save and existing-tour attach', (canEdit, canAssign) => {
|
||||
const planner = {
|
||||
mode: { type: 'new-draft' }, name: 'Ridge', status: 'ready', maxHikingDifficulty: 2,
|
||||
waypoints: [], canSave: true, save: vi.fn(), route: null, saveOutcome: tour,
|
||||
startNewTour: vi.fn(), openTour: vi.fn().mockResolvedValue(true),
|
||||
} as unknown as TourPlannerController
|
||||
const assign = vi.fn()
|
||||
render(<><TourPlannerRail planner={planner} canEdit={canEdit} canAssign={canAssign} /><TourPlannerToursRail planner={planner} tours={[tour]} days={days} loading={false} onAssignToDay={assign} onViewGpxTour={vi.fn()} canEdit={canEdit} canAssign={canAssign} /></>)
|
||||
const save = screen.getByRole('button', { name: 'tours.planner.save' }) as HTMLButtonElement
|
||||
expect(save.disabled).toBe(!canEdit)
|
||||
fireEvent.click(save)
|
||||
expect(planner.save).toHaveBeenCalledTimes(canEdit ? 1 : 0)
|
||||
expect((screen.getByRole('button', { name: 'tours.planner.assignToDay' }) as HTMLButtonElement).disabled).toBe(!canAssign)
|
||||
const picker = screen.queryByRole('combobox', { name: 'tours.addToDay: Ridge' })
|
||||
expect(Boolean(picker)).toBe(canAssign)
|
||||
if (picker) fireEvent.change(picker, { target: { value: '3' } })
|
||||
expect(assign).toHaveBeenCalledTimes(canAssign ? 1 : 0)
|
||||
fireEvent.click(screen.getByRole('option', { name: /Ridge/ }))
|
||||
expect(planner.openTour).toHaveBeenCalledWith(tour)
|
||||
})
|
||||
it.each([[false, false], [true, false], [false, true], [true, true]])('planner edit=%s assign=%s gates direct create and retained save after revocation', async (canEdit, canAssign) => {
|
||||
vi.useFakeTimers()
|
||||
state.route.mockResolvedValue({ coordinates: [[48, 11], [49, 12]], distanceMeters: 1000, durationSeconds: 600 })
|
||||
state.elevation.mockResolvedValue([[48, 11, 500], [49, 12, 550]])
|
||||
state.create.mockResolvedValue({ tour, waypoints: [] })
|
||||
const { result, rerender } = renderHook(({ edit }) => useTourPlanner({ tripId: 7, canEdit: edit, canAssign }), { initialProps: { edit: canEdit } })
|
||||
act(() => { result.current.setName('Ridge'); result.current.addWaypoint(48, 11); result.current.addWaypoint(49, 12) })
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(450) })
|
||||
expect(result.current.canSave).toBe(canEdit)
|
||||
expect(result.current.waypoints.length).toBe(canEdit ? 2 : 0)
|
||||
await act(async () => { await result.current.save() })
|
||||
expect(state.create).toHaveBeenCalledTimes(canEdit ? 1 : 0)
|
||||
expect(state.update).not.toHaveBeenCalled()
|
||||
if (canEdit) {
|
||||
act(() => result.current.setName('Updated'))
|
||||
const retainedSave = result.current.save
|
||||
rerender({ edit: false })
|
||||
await act(async () => { await retainedSave(); await result.current.save() })
|
||||
expect(state.update).not.toHaveBeenCalled()
|
||||
}
|
||||
})
|
||||
it.each([[false, false], [true, false], [false, true], [true, true]])('sidebar edit=%s assign=%s keeps reads available and gates writes', async (canEdit, canAssign) => {
|
||||
const assign = vi.fn()
|
||||
const select = vi.fn()
|
||||
const { container } = render(<ToursSidebar tripId={7} days={days} tours={[tour]} canEdit={canEdit} canAssign={canAssign} onAssignToDay={assign} onSelectTour={select} />)
|
||||
const row = screen.getByRole('option')
|
||||
fireEvent.click(row)
|
||||
expect(select).toHaveBeenCalledWith(tour, row)
|
||||
expect((screen.getByText('places.importFile').closest('button') as HTMLButtonElement).disabled).toBe(!canEdit)
|
||||
const attach = screen.getByRole('button', { name: 'tours.addToDay' }) as HTMLButtonElement
|
||||
expect(attach.disabled).toBe(!canAssign)
|
||||
fireEvent.click(attach)
|
||||
if (canAssign) fireEvent.click(screen.getByRole('button', { name: /Summit/ }))
|
||||
expect(assign).toHaveBeenCalledTimes(canAssign ? 1 : 0)
|
||||
await act(async () => { fireEvent.change(container.querySelector('input[type=file]')!, { target: { files: [new File(['gpx'], 'ridge.gpx')] } }) })
|
||||
expect(state.importGpx).toHaveBeenCalledTimes(canEdit ? 1 : 0)
|
||||
})
|
||||
|
||||
it('omitted props use actual configured rights and reject missing or mismatched trip context', () => {
|
||||
usePermissionsStore.setState({ permissions: { place_edit: 'trip_member', day_edit: 'trip_owner' } })
|
||||
const { result, rerender } = renderHook(() => useTourPermissions({ tripId: 7 }))
|
||||
expect(result.current).toEqual({ canEdit: true, canAssign: false })
|
||||
state.trip = { id: 8, user_id: 1 }
|
||||
rerender()
|
||||
expect(result.current).toEqual({ canEdit: false, canAssign: false })
|
||||
state.trip = null
|
||||
rerender()
|
||||
expect(result.current).toEqual({ canEdit: false, canAssign: false })
|
||||
state.trip = { id: 7, user_id: 1 }
|
||||
state.user = null
|
||||
rerender()
|
||||
expect(result.current).toEqual({ canEdit: false, canAssign: false })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,17 @@
|
||||
import { useCanDo } from '../../store/permissionsStore'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
|
||||
export interface TourPermissionProps {
|
||||
canEdit?: boolean
|
||||
canAssign?: boolean
|
||||
}
|
||||
|
||||
export function useTourPermissions({ canEdit, canAssign, tripId }: TourPermissionProps & { tripId?: number | string } = {}) {
|
||||
const can = useCanDo()
|
||||
const trip = useTripStore(state => state.trip)
|
||||
const hasTrip = trip != null && (tripId == null || String(trip.id) === String(tripId))
|
||||
return {
|
||||
canEdit: canEdit ?? (hasTrip && can('place_edit', trip)),
|
||||
canAssign: canAssign ?? (hasTrip && can('day_edit', trip)),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user