feat(tours): add non-motorized day tour planning

This commit is contained in:
elmocito
2026-10-04 12:59:55 +02:00
parent c93cf2bce9
commit 9e475f447a
202 changed files with 16129 additions and 383 deletions
@@ -234,7 +234,7 @@ export default function MSettingsGeneral() {
title={t('settings.startTripTab')}
value={startTripTab}
onSelect={(v) => save('start_trip_tab', v)}
options={TRIP_TAB_IDS.map((id) => ({ value: id, label: t(TRIP_TAB_LABEL_KEYS[id]) }))}
options={TRIP_TAB_IDS.filter(id => id !== 'tour-planner').map((id) => ({ value: id, label: t(TRIP_TAB_LABEL_KEYS[id]) }))}
/>
</>
)
@@ -286,6 +286,10 @@ export default function MTripShell({
const trTab = planner.activeTab
useEffect(() => {
if (trTab === 'tour-planner') planner.handleTabChange('plan')
}, [trTab, planner.handleTabChange])
const setTrTab = (tabId: string) => {
planner.handleTabChange(tabId)
if (mode === 'browse') setMode('go')
@@ -404,9 +408,10 @@ export default function MTripShell({
}
if (!trip) return null
const enabledTabIds = new Set(planner.TRIP_TABS.map(tab => tab.id))
const mobileTabs = planner.TRIP_TABS.filter(tab => !tab.desktopOnly)
const enabledTabIds = new Set(mobileTabs.map(tab => tab.id))
const dockTabs = pickDockTabs(enabledTabIds)
const tabLabel = (id: string) => planner.TRIP_TABS.find(tab => tab.id === id)?.label ?? id
const tabLabel = (id: string) => mobileTabs.find(tab => tab.id === id)?.label ?? id
// While the trip runs, today's chip carries a ring and a button jumps back to it
// from wherever the rail was scrolled (#2392). Null outside the trip's dates.
@@ -21,7 +21,10 @@ import { useTranslation } from '../../../../i18n'
import type { Place } from '../../../../types'
import MPlacesBulkCategorySheet from './MPlacesBulkCategorySheet'
import MPlacesSaveToCollectionSheet from './MPlacesSaveToCollectionSheet'
import MPlacesToursModeSwitch from './MPlacesToursModeSwitch'
import MToursSelectionList from './MToursSelectionList'
import { filterPool, firstPlannedDayNumbers, plannedPlaceIds } from './placesBrowserModel'
import { useTourPlaceIds } from '../../../../hooks/useTourPlaceIds'
/**
* Fullscreen places pool (mode === 'browse'): All/Unplanned/Tracks filter
@@ -35,11 +38,19 @@ import { filterPool, firstPlannedDayNumbers, plannedPlaceIds } from './placesBro
* it. The header ellipsis opens the 'import' sheet (sheets/MImportSheet).
*/
export default function MPlacesBrowser({ planner, shell }: MPlacesBrowserProps) {
const { t, places, categories, assignments, days, trip } = planner
const { t, places, categories, assignments, days, trip, tripId } = planner
// The planner hook carries `t` but not the locale; day labels need both.
const { locale } = useTranslation()
const canEditPlaces = planner.can('place_edit', trip)
const collectionsEnabled = useAddonStore(s => s.isEnabled('collections'))
const toursEnabled = useAddonStore(s => s.isEnabled('tours'))
// Places that are tours (a `tours` facet row exists) — kept out of the
// Places pool entirely while the addon is on.
const { tourPlaceIds } = useTourPlaceIds(tripId, toursEnabled)
// Top level of the places browser, mirroring the desktop right add-panel's
// Places <-> Tours switch placement.
const [toursMode, setToursMode] = useState(false)
const [toursFilter, setToursFilter] = useState<'all' | 'unplanned' | 'planned'>('all')
const filter = useTripStore(s => s.placesFilter)
const setFilter = useTripStore(s => s.setPlacesFilter)
@@ -61,7 +72,7 @@ export default function MPlacesBrowser({ planner, shell }: MPlacesBrowserProps)
if (shell.browseFromEdit) setFilter('unplanned')
}, [shell.browseFromEdit, setFilter])
const hasTracks = useMemo(() => places.some(p => p.route_geometry), [places])
const hasTracks = useMemo(() => !toursEnabled && places.some(p => p.route_geometry), [places, toursEnabled])
useEffect(() => {
if (filter === 'tracks' && !hasTracks) setFilter('all')
}, [filter, hasTracks, setFilter])
@@ -73,10 +84,10 @@ export default function MPlacesBrowser({ planner, shell }: MPlacesBrowserProps)
[assignments, planner.tripAccommodations, planner.reservations],
)
const dayNumberByPlace = useMemo(() => firstPlannedDayNumbers(assignments, days), [assignments, days])
const filtered = useMemo(
() => filterPool(places, { filter, categoryFilters, search, plannedIds }),
[places, filter, categoryFilters, search, plannedIds],
)
const filtered = useMemo(() => {
const pool = toursEnabled ? places.filter(p => !tourPlaceIds.has(p.id)) : places
return filterPool(pool, { filter, categoryFilters, search, plannedIds })
}, [places, filter, categoryFilters, search, plannedIds, toursEnabled, tourPlaceIds])
// A bulk delete (or a remote edit) can remove selected places — drop the
// stale ids so the toolbar count stays honest.
@@ -120,10 +131,11 @@ export default function MPlacesBrowser({ planner, shell }: MPlacesBrowserProps)
// Compare the ids, not just the counts: a place removed remotely while another
// one is selected keeps the sizes equal without the sets matching.
const allSelected = filtered.length > 0 && filtered.every(p => selectedIds.has(p.id))
const selectablePlaces = filtered.filter(place => !planner.isTourPlace(place.id))
const allSelected = selectablePlaces.length > 0 && selectablePlaces.every(p => selectedIds.has(p.id))
const toggleAllVisible = () => {
if (allSelected) setSelectedIds(new Set())
else setSelectedIds(new Set(filtered.map(p => p.id)))
else setSelectedIds(new Set(selectablePlaces.map(p => p.id)))
}
const toggleCategory = (catId: string) => {
@@ -142,17 +154,39 @@ export default function MPlacesBrowser({ planner, shell }: MPlacesBrowserProps)
const openRow = (place: Place) => {
if (selectMode) {
if (planner.isTourPlace(place.id)) {
planner.handlePlaceClick(place.id)
return
}
toggleSelected(place.id)
return
}
shell.openSheet('bract', { placeId: place.id, dayPicker: false })
}
const selectedTours = [...selectedIds].filter(planner.isTourPlace)
const hasUncategorized = places.some(p => p.category_id == null)
return (
<div className="flex h-full flex-col">
<div className="min-h-0 flex-1 overflow-y-auto px-4 pb-[calc(var(--bottom-nav-h,84px)+22px)] pt-[calc(var(--m-safe-top,12px)+58px)]">
{toursEnabled && (
<MPlacesToursModeSwitch active={toursMode} onChange={setToursMode} />
)}
{toursEnabled && toursMode ? (
<>
{/* All / Unplanned / Planned only — no Tracks chip, no Import/Add/Select
buttons: tours are attached here, never created or bulk-managed. */}
<div className="flex items-center gap-[6px]">
<FilterChip active={toursFilter === 'all'} label={t('places.all')} onClick={() => setToursFilter('all')} />
<FilterChip active={toursFilter === 'unplanned'} label={t('places.unplanned')} onClick={() => setToursFilter('unplanned')} />
<FilterChip active={toursFilter === 'planned'} label={t('places.planned')} onClick={() => setToursFilter('planned')} />
</div>
<MToursSelectionList planner={planner} shell={shell} filter={toursFilter} />
</>
) : (
<>
{/* ── Filter chips + Import (Add sits in the search row below to free space) ── */}
<div className="flex items-center gap-[6px]">
<FilterChip
@@ -266,24 +300,24 @@ export default function MPlacesBrowser({ planner, shell }: MPlacesBrowserProps)
<BulkBtn label={allSelected ? t('common.deselectAll') : t('common.selectAll')} onClick={toggleAllVisible}>
<CheckCheck size={14} strokeWidth={2} />
</BulkBtn>
<BulkBtn label={t('places.changeCategory')} disabled={selectedIds.size === 0} onClick={() => setCategoryPickerOpen(true)}>
<BulkBtn label={t('places.changeCategory')} disabled={selectedIds.size === 0 || selectedTours.length > 0} onClick={() => setCategoryPickerOpen(true)}>
<Tag size={14} strokeWidth={2} />
</BulkBtn>
{collectionsEnabled && (
<BulkBtn label={t('inspector.saveToCollection')} disabled={selectedIds.size === 0} onClick={() => setSaveToListOpen(true)}>
<BulkBtn label={t('inspector.saveToCollection')} disabled={selectedIds.size === 0 || selectedTours.length > 0} onClick={() => setSaveToListOpen(true)}>
<Bookmark size={14} strokeWidth={2} />
</BulkBtn>
)}
{collectionsEnabled && (
<BulkBtn
label={t('collections.markVisitedSelection')}
disabled={selectedIds.size === 0 || markVisitedBusy}
disabled={selectedIds.size === 0 || selectedTours.length > 0 || markVisitedBusy}
onClick={markSelectionVisited}
>
{markVisitedBusy ? <Loader2 size={14} className="animate-spin" /> : <CheckCircle2 size={14} strokeWidth={2} />}
</BulkBtn>
)}
<BulkBtn label={t('places.deleteSelected')} disabled={selectedIds.size === 0} onClick={() => setConfirmDeleteOpen(true)}>
<BulkBtn label={t('places.deleteSelected')} disabled={selectedIds.size === 0 || selectedTours.length > 0} onClick={() => setConfirmDeleteOpen(true)}>
<Trash2 size={14} strokeWidth={2} />
</BulkBtn>
</div>
@@ -349,7 +383,7 @@ export default function MPlacesBrowser({ planner, shell }: MPlacesBrowserProps)
return (
<div key={place.id} className="flex items-center gap-[11px] border-b border-[color:var(--m-rowbr)] px-[2px] py-[9px]">
<button type="button" onClick={() => openRow(place)} className="flex min-w-0 flex-1 items-center gap-[11px] text-left">
{selectMode && <SquareCheck big checked={selectedIds.has(place.id)} />}
{selectMode && !planner.isTourPlace(place.id) && <SquareCheck big checked={selectedIds.has(place.id)} />}
<PlaceAvatar place={place} category={cat} size={40} />
<div className="min-w-0 flex-1">
<span className="flex items-center gap-[6px]">
@@ -389,6 +423,8 @@ export default function MPlacesBrowser({ planner, shell }: MPlacesBrowserProps)
)
})
)}
</>
)}
</div>
<MPlacesBulkCategorySheet
@@ -418,8 +454,12 @@ export default function MPlacesBrowser({ planner, shell }: MPlacesBrowserProps)
open={confirmDeleteOpen}
onClose={() => setConfirmDeleteOpen(false)}
title={t('places.deleteSelected')}
message={t('trip.confirm.deletePlaces', { count: selectedIds.size })}
confirmLabel={t('common.delete')}
message={selectedTours.length > 0
? t('tours.delete.bulkConfirmBody')
: t('trip.confirm.deletePlaces', { count: selectedIds.size })}
confirmLabel={selectedTours.length > 0
? t('tours.delete.confirmAction')
: t('common.delete')}
cancelLabel={t('common.cancel')}
danger
onConfirm={async () => {
@@ -0,0 +1,43 @@
import { MapPin, Mountain } from 'lucide-react'
import { useTranslation } from '../../../../i18n/TranslationContext'
interface MPlacesToursModeSwitchProps {
active: boolean
onChange: (tours: boolean) => void
}
/** Mobile counterpart of PlacesToursModeSwitch: top-level "Places <-> Tours"
* switch of the places browser, with m-token styling to match the browser chrome. */
export default function MPlacesToursModeSwitch({ active, onChange }: MPlacesToursModeSwitchProps) {
const { t } = useTranslation()
const options: [boolean, string, typeof MapPin][] = [
[false, t('tours.mode.places'), MapPin],
[true, t('tours.mode.tours'), Mountain],
]
return (
<div
role="tablist"
aria-label={t('tours.mode.label')}
className="mb-3 flex gap-1 rounded-[12px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] 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)}
className={`flex h-[34px] flex-1 items-center justify-center gap-1.5 rounded-[10px] px-2 text-[0.78125rem] transition-colors ${
selected ? 'bg-m-card font-semibold text-m-ink shadow-sm' : 'font-medium text-m-muted'
}`}
>
<Icon size={14} strokeWidth={1.8} aria-hidden />
<span className="truncate">{label}</span>
</button>
)
})}
</div>
)
}
@@ -0,0 +1,137 @@
import { render, screen } from '../../../../../tests/helpers/render'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { TourListItem } from '@trek/shared'
import en from '@trek/shared/i18n/en'
import de from '@trek/shared/i18n/de'
import { resetAllStores, seedStore } from '../../../../../tests/helpers/store'
import { useSettingsStore } from '../../../../store/settingsStore'
import type { TripPlanner, MTripShellApi } from '../MTripShell'
import MToursSelectionList from './MToursSelectionList'
const tour: TourListItem = {
place_id: 42,
name: 'Camping tour with a deliberately long readable name',
tour_type: 'hike',
distance: 12.5,
elevation_gain: 420,
elevation_loss: 390,
duration: null,
difficulty: null,
wanderer_ref: null,
match_confidence: null,
tour_group_id: null,
has_waypoints: true,
max_hiking_difficulty: 2,
planned: false,
caution: false,
}
const reloadTourPlaceIds = vi.fn().mockResolvedValue(undefined)
const handlePlaceClick = vi.fn()
const openSheet = vi.fn()
function planner(): TripPlanner {
return {
t: (key: string) => {
const value = en[key]
return typeof value === 'string' ? value : key
},
tripId: 7,
tours: [tour],
selectedPlaceId: null,
selectedPlace: null,
selectedTour: null,
selectedDayId: null,
selectedAssignmentId: null,
assignments: {},
days: [],
files: [],
canUploadFiles: false,
reloadTourPlaceIds,
handlePlaceClick,
} as unknown as TripPlanner
}
function shell(sheet: MTripShellApi['sheet'] = null): MTripShellApi {
return {
sheet,
openSheet,
} as unknown as MTripShellApi
}
beforeEach(() => {
resetAllStores()
vi.clearAllMocks()
seedStore(useSettingsStore, { settings: { distance_unit: 'metric' } })
})
describe('MToursSelectionList', () => {
it('shows German ADD, difficulty and empty-state text without raw Tours keys', () => {
const germanPlanner = { ...planner(), t: (key: string) => {
const value = de[key] ?? en[key]
return typeof value === 'string' ? value : key
} }
const { rerender } = render(<MToursSelectionList planner={germanPlanner} shell={shell()} filter="all" />)
expect(screen.getByRole('button', { name: 'Zum Tag hinzufügen' })).toBeInTheDocument()
expect(screen.getByTitle('T2 – Bergwandern')).toHaveAttribute('aria-label', 'T2 – Bergwandern')
expect(screen.getByText(germanPlanner.t('tours.planner.mobileHint'))).toBeInTheDocument()
rerender(<MToursSelectionList planner={{ ...germanPlanner, tours: [] }} shell={shell()} filter="all" />)
expect(screen.getByText('Noch keine Touren')).toBeInTheDocument()
expect(screen.getByText(germanPlanner.t('tours.empty.body'))).toBeInTheDocument()
expect(document.body.textContent).not.toMatch(/\btours\.[a-zA-Z]/)
})
it('gives a tour name the full row and up to two lines', () => {
render(<MToursSelectionList planner={planner()} shell={shell()} filter="all" />)
const name = screen.getByText(tour.name)
expect(name).toHaveClass('line-clamp-2', 'break-words')
expect(name).toHaveAttribute('title', tour.name)
expect(name).not.toHaveClass('truncate')
})
it('keeps metrics atomic and gives the mobile day action a separate full-width row', () => {
const { container } = render(<MToursSelectionList planner={{ ...planner(), selectedPlaceId: tour.place_id }} shell={shell()} filter="all" canAssign />)
expect(screen.getByRole('option', { name: new RegExp(tour.name) })).toHaveAttribute('aria-selected', 'true')
const metrics = screen.getByTestId('mobile-tour-metrics')
expect(metrics).toHaveTextContent('12.5 km')
expect(metrics).toHaveTextContent('420 m')
expect(metrics).toHaveTextContent('390 m')
for (const metric of metrics.children) expect(metric).toHaveClass('whitespace-nowrap')
expect(metrics.children[0].getAttribute('aria-label')).toContain('12.5 km')
expect(metrics.children[1].getAttribute('aria-label')).toContain('420 m')
expect(metrics.children[2].getAttribute('aria-label')).toContain('390 m')
expect(screen.getByText('TREK')).toBeInTheDocument()
expect(screen.getByTitle(en['tours.planner.difficulty.t2'] as string)).toHaveAttribute('aria-label', en['tours.planner.difficulty.t2'])
const add = screen.getByRole('button', { name: 'Add to day' })
expect(add).toHaveClass('w-full')
add.click()
expect(openSheet).toHaveBeenCalledWith('bract', { placeId: tour.place_id, dayPicker: true })
expect(container.querySelector('[data-testid="mobile-tour-metrics"]')).toBeTruthy()
})
it('keeps a long German name and source/difficulty labels intact', () => {
const germanPlanner = {
...planner(),
tours: [{ ...tour, name: 'Eine sehr lange deutsche Wanderung durch das abgelegene Gebirge', has_waypoints: false }],
t: (key: string) => {
const value = de[key] ?? en[key]
return typeof value === 'string' ? value : key
},
}
render(<MToursSelectionList planner={germanPlanner} shell={shell()} filter="all" />)
expect(screen.getByRole('option', { name: /Eine sehr lange deutsche Wanderung/ })).toBeInTheDocument()
expect(screen.getByText('GPX-Import')).toBeInTheDocument()
expect(screen.getByLabelText('T2 – Bergwandern')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Zum Tag hinzufügen' })).toHaveClass('w-full')
})
it('does not refresh Tours merely because the mobile assignment sheet closes', () => {
const { rerender } = render(<MToursSelectionList planner={planner()} shell={shell({ id: 'bract' })} filter="all" />)
rerender(<MToursSelectionList planner={planner()} shell={shell()} filter="all" />)
expect(reloadTourPlaceIds).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,121 @@
import { ArrowDown, ArrowUp, Mountain, AlertTriangle, CalendarDays } from 'lucide-react'
import type { TourListItem } from '@trek/shared'
import { useSettingsStore } from '../../../../store/settingsStore'
import { formatDistance, formatElevation } from '../../../../utils/units'
import { hikeSourceBadgeLabel } from '../../../../components/Tours/tourPresentation'
import type { TripPlanner, MTripShellApi } from '../MTripShell'
import { useTourPermissions, type TourPermissionProps } from '../../../../components/Tours/useTourPermissions'
interface MToursSelectionListProps extends TourPermissionProps {
planner: TripPlanner
shell: MTripShellApi
/** All / Unplanned / Planned — same three states as the Places pool. */
filter: 'all' | 'unplanned' | 'planned'
}
/**
* Tours mode of the mobile places browser: a selection list that mirrors
* the desktop ToursSidebar's data, with viewing and day assignment only.
* This list does not provide GPX import.
*
* "Add to day" reuses the existing 'bract' place-actions sheet's day picker
* (the same one MPlacesBrowser's unplanned-place rows open) — a tour is a
* Place under the hood, so no new linking code is needed here either.
*/
export default function MToursSelectionList({ planner, shell, filter, canEdit, canAssign: assignPermission }: MToursSelectionListProps) {
const { canAssign } = useTourPermissions({ tripId: planner.tripId, canEdit, canAssign: assignPermission })
const { t } = planner
const distanceUnit = useSettingsStore(s => s.settings.distance_unit)
const tours: TourListItem[] = planner.tours
const filtered = tours.filter(tr => {
if (filter === 'unplanned') return !tr.planned
if (filter === 'planned') return tr.planned
return true
})
if (filtered.length === 0) {
return (
<>
<p className="mt-3 rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-3 py-2 font-geist text-[0.75rem] text-m-muted">
{t('tours.planner.mobileHint')}
</p>
<div className="mt-3 rounded-2xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] p-6 text-center">
<Mountain className="mx-auto mb-2 h-6 w-6 text-m-faint" strokeWidth={1.6} />
<p className="font-semibold text-m-ink">{t('tours.empty.title')}</p>
<p className="mt-1 font-geist text-[0.78125rem] text-m-muted">{t('tours.empty.body')}</p>
</div>
</>
)
}
return (
<>
<p className="mt-3 rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] px-3 py-2 font-geist text-[0.75rem] text-m-muted">
{t('tours.planner.mobileHint')}
</p>
<ul className="mt-3 space-y-2">
{filtered.map(tour => {
const isSelected = planner.selectedPlaceId === tour.place_id
return (
<li
key={tour.place_id}
role="option"
tabIndex={0}
aria-selected={isSelected}
onClick={() => planner.handlePlaceClick(tour.place_id)}
onKeyDown={event => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); planner.handlePlaceClick(tour.place_id) } }}
className="rounded-2xl border border-[color:var(--m-rowbr)] p-3"
style={{ background: isSelected ? 'var(--border-faint)' : 'var(--m-ic)' }}
>
<div className="min-w-0">
<span className="block min-w-0 line-clamp-2 break-words font-semibold text-m-ink" title={tour.name}>{tour.name}</span>
<div className="mt-1 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 font-geist text-[0.75rem] text-m-muted">
<span className="shrink-0 rounded-md border border-[color:var(--m-rowbr)] px-1.5 py-0.5 text-[10px] font-medium text-m-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-[color:var(--m-rowbr)] px-1.5 py-0.5 text-[10px] font-semibold text-m-muted"
>T{tour.max_hiking_difficulty}</span>
{tour.caution && (
<span className="inline-flex shrink-0 items-center gap-1 rounded-md border border-[color:var(--warning)] px-1.5 py-0.5 text-[10px] text-[color:var(--warning)]" aria-label={t('tours.caution.badge')} title={t('tours.caution.tooltip')}>
<AlertTriangle className="h-3 w-3" strokeWidth={2} aria-hidden="true" />{t('tours.caution.badge')}
</span>
)}
</div>
<div data-testid="mobile-tour-metrics" className="mt-1 flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 font-geist text-[0.75rem] text-m-muted">
<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>
<button
type="button"
disabled={!canAssign}
onClick={(e) => { e.stopPropagation(); if (canAssign) shell.openSheet('bract', { placeId: tour.place_id, dayPicker: true }) }}
className="mt-2 inline-flex min-h-9 w-full items-center justify-center gap-1 rounded-lg border border-[color:var(--m-rowbr)] px-3 py-1.5 text-[0.8125rem] font-medium text-m-ink"
>
<CalendarDays className="h-3.5 w-3.5" strokeWidth={2} />
{t('tours.addToDay')}
</button>
</div>
</li>
)
})}
</ul>
</>
)
}
@@ -163,6 +163,11 @@ export default function MPlanTimeline({ planner, shell }: MPlanTimelineProps) {
className="absolute left-4 right-4 overflow-y-auto overscroll-contain rounded-[22px] border border-[color:var(--m-cbr)] bg-[color:var(--m-card)] px-3.5 pb-2 pt-1 backdrop-blur-[24px] backdrop-saturate-[1.6] bottom-[calc(env(safe-area-inset-bottom,0px)+90px)]"
style={{ top: `calc(var(--m-safe-top, 12px) + ${editing ? 140 : tl.upNext ? 216 : 102}px)` }}
>
{planner.toursEnabled && tl.rows.some(row => row.kind === 'place' && row.invalidTour) && (
<div role="status" className="border-b border-[color:var(--warning)] p-2 text-sm text-[color:var(--warning)]">
{t('tours.dayRoute.endpointUnknown')}
</div>
)}
{day && (
<TimelineHeader
tl={tl}
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest'
import { buildPlanRows } from './planTimelineModel'
import type { MergedItem } from '../../../../utils/dayMerge'
import type { Reservation } from '../../../../types'
import type { Reservation, RouteSegment } from '../../../../types'
// FE-MOBILE-PLANROWS-001 to FE-MOBILE-PLANROWS-003
@@ -47,4 +47,22 @@ describe('buildPlanRows', () => {
if (place.kind !== 'place') throw new Error('expected a place row')
expect(place.linkedReservations).toEqual([])
})
it('shows the incoming and outgoing connectors at opposite Tour endpoints', () => {
const start: [number, number] = [48.103, 11.103]
const end: [number, number] = [48.12, 11.12]
const before: [number, number] = [48.1, 11.1]
const after: [number, number] = [48.13, 11.13]
const merged = [
{ type: 'place', sortKey: 0, data: { id: 11, place: { id: 1, lat: before[0], lng: before[1] } } },
{ type: 'place', sortKey: 1, data: { id: 12, tour_place_id: 2,
tour_route_geometry: JSON.stringify([start, end]), place: { id: 2, lat: start[0], lng: start[1] } } },
{ type: 'place', sortKey: 2, data: { id: 13, place: { id: 3, lat: after[0], lng: after[1] } } },
] as unknown as MergedItem[]
const segment = (from: [number, number], to: [number, number]) => ({ from, to }) as RouteSegment
const segments = [segment(before, start), segment(end, after)]
const rows = buildPlanRows({ merged, reservations: [], routeSegments: segments, dayId: 5, toursEnabled: true })
expect(rows.filter(row => row.kind === 'conn').map(row => row.seg)).toEqual(segments)
expect(buildPlanRows({ merged, reservations: [], routeSegments: segments, dayId: 5 }).some(row => row.kind === 'conn' && row.seg.from[0] === end[0])).toBe(false)
})
})
@@ -7,7 +7,8 @@ import {
import { getDayBookendHotels, isDayInAccommodationRange } from '../../../../utils/dayOrder'
import type { MergedItem } from '../../../../utils/dayMerge'
import type { TransitLegDisplay } from '../../../../components/Planner/transitDisplay'
import type { Accommodation, Assignment, Day, DayNote, Reservation, RouteSegment, TranslationFn } from '../../../../types'
import { projectDayItinerary } from '../../../../components/Map/dayTourProjection'
import type { Accommodation, Assignment, Day, DayNote, Place, Reservation, RouteSegment, TranslationFn } from '../../../../types'
/**
* Pure derivations for the mobile plan timeline: merged-item → row mapping,
@@ -27,7 +28,7 @@ export interface TransitMeta {
}
export type PlanRow =
| { key: string; kind: 'place'; item: MergedItem; assignment: Assignment; linkedReservations: Reservation[] }
| { key: string; kind: 'place'; item: MergedItem; assignment: Assignment; linkedReservations: Reservation[]; invalidTour?: boolean }
| { key: string; kind: 'transport'; item: MergedItem; res: TransportEntry }
| { key: string; kind: 'transit'; item: MergedItem; res: TransportEntry; transit: TransitMeta }
| { key: string; kind: 'note'; item: MergedItem; note: DayNote }
@@ -87,9 +88,16 @@ export function buildPlanRows(opts: {
reservations: Reservation[]
routeSegments: RouteSegment[]
dayId: number
toursEnabled?: boolean
places?: Place[]
}): PlanRow[] {
const { merged, reservations, routeSegments, dayId } = opts
const pool = routeSegments.filter(s => !s.hotelBookend)
const projected = new Map(projectDayItinerary(
merged.flatMap(item => item.type === 'place' ? [item.data as Assignment] : []),
opts.toursEnabled ?? false,
opts.places,
).map(item => [item.assignment.id, item]))
const takeSegment = (from: [number, number], to: [number, number]): RouteSegment | null => {
const idx = pool.findIndex(s => sameCoord(s.from, from) && sameCoord(s.to, to))
return idx >= 0 ? pool.splice(idx, 1)[0] : null
@@ -99,6 +107,7 @@ export function buildPlanRows(opts: {
for (const item of merged) {
if (item.type === 'place') {
const assignment = item.data as Assignment
const itineraryItem = projected.get(assignment.id)
base.push({
key: `pl-${assignment.id}`,
kind: 'place',
@@ -108,6 +117,7 @@ export function buildPlanRows(opts: {
// attraction, and getTransportForDay keeps every linked booking out of the
// timeline, so anything dropped here is gone from the plan tab (#2201).
linkedReservations: getAssignmentReservations(reservations, assignment.id),
invalidTour: itineraryItem?.kind === 'tour' && !itineraryItem.valid,
})
} else if (item.type === 'note') {
const note = item.data as DayNote
@@ -156,9 +166,17 @@ export function buildPlanRows(opts: {
const row = base[i]
if (row.kind === 'place') {
const place = row.assignment.place
if (place?.lat == null || place?.lng == null) continue
// Out of the route (#2532): the drive passes it by, so no leg starts or ends here.
if (row.assignment.route_excluded) continue
const itineraryItem = projected.get(row.assignment.id)
if (itineraryItem?.kind === 'tour') {
if (itineraryItem.start) connect(prev, [itineraryItem.start.lat, itineraryItem.start.lng])
prev = itineraryItem.end
? { at: [itineraryItem.end.lat, itineraryItem.end.lng], row: i, assignmentId: row.assignment.id }
: null
continue
}
if (place?.lat == null || place?.lng == null) continue
const at: [number, number] = [place.lat, place.lng]
connect(prev, at)
// The leg's mode is stored on its ORIGIN place assignment (#1281), so carry
@@ -82,8 +82,8 @@ export function useMPlanTimeline(planner: TripPlanner) {
const rows = useMemo<PlanRow[]>(() => {
if (!day) return []
return buildPlanRows({ merged, reservations, routeSegments: connSegments, dayId: day.id })
}, [day, merged, reservations, connSegments])
return buildPlanRows({ merged, reservations, routeSegments: connSegments, dayId: day.id, toursEnabled: planner.toursEnabled, places: planner.places })
}, [day, merged, reservations, connSegments, planner.toursEnabled, planner.places])
// Accommodation bookend legs (hotel → first stop, last stop → hotel). The
// segments already sit in connSegments; hotelLegsForDay picks the two out.
@@ -26,6 +26,7 @@ export default function MBrowseActionsSheet({ planner, shell }: MTripSheetsProps
const canEditPlaces = planner.can('place_edit', planner.trip)
const canEditDays = planner.can('day_edit', planner.trip)
const isTourPlace = (placeId: number) => planner.isTourPlace(placeId)
const collectionsEnabled = useAddonStore(s => s.isEnabled('collections'))
const openSavePicker = useSaveToCollectionStore(s => s.open)
@@ -56,9 +57,9 @@ export default function MBrowseActionsSheet({ planner, shell }: MTripSheetsProps
openSavePicker(collectionTargetFromPlace(place))
}
const assignToDay = (dayId: number) => {
shell.closeSheet()
planner.handleAssignToDay(place.id, dayId)
const assignToDay = async (dayId: number) => {
const assigned = await planner.handleAssignToDay(place.id, dayId)
if (assigned !== false) shell.closeSheet()
}
const deletePlace = () => {
@@ -84,13 +85,13 @@ export default function MBrowseActionsSheet({ planner, shell }: MTripSheetsProps
<Eye size={16} strokeWidth={2} className="flex-none text-m-muted" />
{t('mobileTrip.viewDetails')}
</button>
{canEditPlaces && (
{canEditPlaces && !isTourPlace(place.id) && (
<button type="button" onClick={editPlace} className={rowCls}>
<Pencil size={16} strokeWidth={2} className="flex-none text-m-muted" />
{t('common.edit')}
</button>
)}
{collectionsEnabled && (
{collectionsEnabled && !isTourPlace(place.id) && (
<button type="button" onClick={saveToCollection} className={rowCls}>
<Bookmark size={16} strokeWidth={2} className="flex-none text-m-muted" />
{t('inspector.saveToCollection')}
@@ -111,7 +112,7 @@ export default function MBrowseActionsSheet({ planner, shell }: MTripSheetsProps
<button
key={d.id}
type="button"
onClick={() => assignToDay(d.id)}
onClick={() => { void assignToDay(d.id) }}
className={`flex w-full items-center gap-2 px-3 py-[10px] text-left ${i > 0 ? 'border-t border-[color:var(--m-rowbr)]' : ''}`}
>
<span className="min-w-0 flex-1 truncate text-[0.78125rem] font-semibold">
@@ -131,7 +132,7 @@ export default function MBrowseActionsSheet({ planner, shell }: MTripSheetsProps
)}
</>
)}
{canEditPlaces && (
{canEditPlaces && !isTourPlace(place.id) && (
<button type="button" onClick={deletePlace} className={`${rowCls} text-[color:var(--m-st-danger)]`}>
<Trash2 size={16} strokeWidth={2} className="flex-none" />
{t('common.delete')}
@@ -6,6 +6,7 @@ import MIconBtn from '../../../components/MIconBtn'
import { FormSheetHeader } from './PlSheetChrome'
import ImpFileStep from './ImpFileStep'
import ImpListStep from './ImpListStep'
import { useAddonStore } from '../../../../store/addonStore'
import type { TripPlanner } from '../MTripShell'
export interface MImportSheetProps {
@@ -24,6 +25,9 @@ type ImportStep = 'menu' | 'file' | 'list'
export default function MImportSheet({ planner, open, onClose }: MImportSheetProps) {
const { t } = planner
const [step, setStep] = useState<ImportStep>('menu')
// File import (GPX/KML/KMZ) belongs to Tours mode while the addon is on;
// list import stays here in both states.
const toursEnabled = useAddonStore(s => s.isEnabled('tours'))
useEffect(() => {
if (open) setStep('menu')
@@ -50,12 +54,14 @@ export default function MImportSheet({ planner, open, onClose }: MImportSheetPro
{step === 'menu' && (
<div className="px-[14px] pb-[14px] pt-1">
{!toursEnabled && (
<ImpMenuRow
icon={FileDown}
title={t('places.importFile')}
sub="GPX · KML · KMZ"
onClick={() => setStep('file')}
/>
)}
<ImpMenuRow
icon={MapPin}
title={t('places.importList')}
@@ -28,8 +28,9 @@ export default function MMehrSheet({ planner, shell }: MTripSheetsProps) {
// Derived from the same priority list the dock seats itself from, so a section
// can never show up in both places at once.
const seated = dockTabIds(new Set(planner.TRIP_TABS.map(tab => tab.id)))
const gridTabs = planner.TRIP_TABS.filter(tab => !seated.has(tab.id))
const mobileTabs = planner.TRIP_TABS.filter(tab => !tab.desktopOnly)
const seated = dockTabIds(new Set(mobileTabs.map(tab => tab.id)))
const gridTabs = mobileTabs.filter(tab => !seated.has(tab.id))
const tileStat = (id: string): string | null => {
if (id === 'dateien') {
@@ -331,7 +331,9 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
// Two-tap confirm: arming also stages the id the planner's confirm reads.
setDeletePlaceId(sheetPlace.id)
setDeleteArmed(true)
toast.warning(t('mobileTrip.tapAgainToDelete'))
toast.warning(planner.isTourPlace(sheetPlace.id)
? t('tours.delete.confirmBody')
: t('mobileTrip.tapAgainToDelete'))
return
}
await confirmDeletePlace()
@@ -490,7 +492,9 @@ export default function MPlaceEditSheet({ planner, onOpenExpense }: MPlaceEditSh
<FormSheetFooter
onDelete={sheetPlace ? handleDelete : undefined}
deleteLabel={t('common.delete')}
deleteLabel={deleteArmed && sheetPlace && planner.isTourPlace(sheetPlace.id)
? t('tours.delete.confirmAction')
: t('common.delete')}
deleteArmed={deleteArmed}
onCancel={handleClose}
cancelLabel={t('common.cancel')}
@@ -0,0 +1,102 @@
import { render, screen } from '../../../../../tests/helpers/render'
import type { ReactNode } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { buildPlace } from '../../../../../tests/helpers/factories'
import type { TripPlanner, MTripShellApi } from '../MTripShell'
import MPlaceSheet from './MPlaceSheet'
vi.mock('../../../components/MSheet', () => ({
default: ({ open, children, ariaLabel }: { open: boolean; children?: ReactNode; ariaLabel?: string }) => (
<div data-testid="mobile-place-sheet" data-open={String(open)}>{open && <div role="dialog" aria-label={ariaLabel}>{children}</div>}</div>
),
}))
const place = buildPlace({ id: 42, name: 'Ridge walk' })
function planner(overrides: Partial<TripPlanner> = {}): TripPlanner {
return {
selectedPlace: place,
selectedTour: null,
toursEnabled: false,
tourDataReady: false,
can: () => false,
trip: {},
categories: [],
days: [],
assignments: {},
selectedDayId: null,
selectedAssignmentId: null,
reservations: [],
files: [],
tripMembers: [],
language: 'en',
isTourPlace: () => false,
canUploadFiles: false,
...overrides,
} as unknown as TripPlanner
}
const shell = {} as MTripShellApi
beforeEach(() => {
vi.clearAllMocks()
})
describe('MPlaceSheet tour exclusion', () => {
it('keeps ordinary place details open when Tours is off', () => {
render(<MPlaceSheet planner={planner()} shell={shell} />)
expect(screen.getByTestId('mobile-place-sheet')).toHaveAttribute('data-open', 'true')
})
it('waits for the Tours facet before choosing a detail surface', () => {
render(<MPlaceSheet planner={planner({ toursEnabled: true, tourDataReady: false })} shell={shell} />)
expect(screen.getByTestId('mobile-place-sheet')).toHaveAttribute('data-open', 'false')
})
it('does not open underneath the purpose-built dialog for a selected tour', () => {
render(<MPlaceSheet planner={planner({
toursEnabled: true,
tourDataReady: true,
selectedTour: { place_id: place.id } as TripPlanner['selectedTour'],
})} shell={shell} />)
expect(screen.getByTestId('mobile-place-sheet')).toHaveAttribute('data-open', 'false')
})
it('opens for an ordinary place after the Tours facet is ready', () => {
render(<MPlaceSheet planner={planner({ toursEnabled: true, tourDataReady: true })} shell={shell} />)
expect(screen.getByTestId('mobile-place-sheet')).toHaveAttribute('data-open', 'true')
})
it('keeps a dormant facet-backed Tour view-only while retaining day assignment controls', () => {
const tourPlace = buildPlace({ id: 42, name: 'Ridge walk', route_geometry: '[[48,11,500],[48.01,11.01,510]]', image_url: '/uploads/cover.jpg' })
const plannerWithTour = planner({
selectedPlace: tourPlace,
toursEnabled: false,
can: (permission: string) => permission === 'place_edit' || permission === 'day_edit',
isTourPlace: (placeId: number) => placeId === tourPlace.id,
days: [{ id: 7, day_number: 1, title: 'Day 1' } as never],
selectedDayId: 7,
selectedAssignmentId: 8,
assignments: { '7': [{ id: 8, day_id: 7, place: tourPlace, route_excluded: false }] as never },
tripActions: {
uploadPlaceImage: vi.fn(), updatePlace: vi.fn(), addFile: vi.fn(),
setAssignmentRouteExcluded: vi.fn(),
} as never,
canUploadFiles: true,
})
render(<MPlaceSheet planner={plannerWithTour} shell={shell} />)
expect(screen.getByRole('dialog', { name: 'Ridge walk' })).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'common.edit' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'common.delete' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'common.upload' })).not.toBeInTheDocument()
expect(screen.queryByRole('radiogroup', { name: 'places.yourRating' })).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'dayplan.excludeFromRoute' })).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Remove from Day' })).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'inspector.addToDay' })).not.toBeInTheDocument()
})
})
@@ -38,10 +38,15 @@ import { ActionCircle, Eyebrow, INNER_CLS } from './MTripSheetUi'
export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
const { t } = useTranslation()
const place = planner.selectedPlace ?? null
const open = !!place
// Match the desktop inspector gate: while the Tours facet is loading, wait
// before choosing a surface; once identified as a tour, its purpose-built
// dialog is the only detail surface that should open.
const open = !!place && (!planner.toursEnabled || planner.tourDataReady) && !planner.selectedTour
const canEditPlaces = planner.can('place_edit', planner.trip)
const canEditDays = planner.can('day_edit', planner.trip)
const isTourPlace = place != null && planner.isTourPlace(place.id)
const canManagePlace = canEditPlaces && !isTourPlace
const collectionsEnabled = useAddonStore(s => s.isEnabled('collections'))
const openSavePicker = useSaveToCollectionStore(s => s.open)
@@ -166,7 +171,7 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
const handleImagePick = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
e.target.value = ''
if (!file || !place) return
if (!file || !place || isTourPlace) return
setImgBusy(true)
try {
await planner.tripActions.uploadPlaceImage(planner.tripId, place.id, await normalizeImageFile(file))
@@ -178,7 +183,7 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
}
const handleTrackColor = async (color: string | null) => {
if (!place) return
if (!place || isTourPlace) return
try {
await planner.tripActions.updatePlace(planner.tripId, place.id, { route_color: color })
} catch (err: unknown) {
@@ -187,7 +192,7 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
}
const handleImageRemove = async () => {
if (!place) return
if (!place || isTourPlace) return
setImgBusy(true)
try {
await planner.tripActions.updatePlace(planner.tripId, place.id, { image_url: null })
@@ -200,7 +205,7 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
const selected = Array.from(e.target.files || [])
if (!selected.length || !place) return
if (!selected.length || !place || isTourPlace) return
setUploading(true)
try {
for (const file of selected) {
@@ -267,7 +272,7 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
<CatIcon size={20} strokeWidth={1.8} className="text-m-muted" />
</div>
)}
{canEditPlaces && (
{canManagePlace && (
<>
{/* Tap the thumbnail to set a custom image (#1136). */}
<button
@@ -339,7 +344,7 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
{/* Collaborative rating (#1435) — tap a star to cast/clear your vote. */}
<div className={`mt-[10px] rounded-[14px] px-3 py-[10px] ${INNER_CLS}`}>
<PlaceRating ratings={place.ratings ?? []} ratingAvg={place.rating_avg} onRate={handleRate} size={18} />
<PlaceRating ratings={place.ratings ?? []} ratingAvg={place.rating_avg} onRate={isTourPlace ? undefined : handleRate} size={18} />
</div>
{place.description && (
@@ -362,33 +367,37 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
<>
<Eyebrow className="mb-[6px] mt-3">{t('inspector.trackColor')}</Eyebrow>
<div className={`rounded-[14px] px-3 py-[10px] ${INNER_CLS}`}>
<button
type="button"
onClick={() => setColorPickerOpen(v => !v)}
aria-expanded={colorPickerOpen}
className="flex w-full items-center justify-between gap-3"
>
{/* The eyebrow above already names the section — this row says
which colour is in effect, not the same word again. */}
<span className="flex min-w-0 items-center gap-2">
<Route size={14} className="shrink-0 text-m-muted" />
<span className="truncate font-geist text-[0.75rem] font-medium">
{place.route_color ?? t('inspector.trackColorAuto')}
</span>
</span>
<span
className="h-6 w-6 shrink-0 rounded-full ring-1 ring-inset ring-black/10 dark:ring-white/15"
style={{ background: resolveTrackColor(place) }}
/>
</button>
{colorPickerOpen && (
<div className="mt-[10px] border-t border-[color:var(--m-faint)] pt-[10px]">
<TrackColorPicker
value={place.route_color ?? null}
inheritedColor={inheritedTrackColor(place)}
onChange={handleTrackColor}
/>
</div>
{isTourPlace ? (
<span aria-label={t('inspector.trackColor')} style={{ display: 'block', width: 24, height: 24, borderRadius: 12, background: resolveTrackColor(place) }} />
) : (
<>
<button
type="button"
onClick={() => setColorPickerOpen(v => !v)}
aria-expanded={colorPickerOpen}
className="flex w-full items-center justify-between gap-3"
>
<span className="flex min-w-0 items-center gap-2">
<Route size={14} className="shrink-0 text-m-muted" />
<span className="truncate font-geist text-[0.75rem] font-medium">
{place.route_color ?? t('inspector.trackColorAuto')}
</span>
</span>
<span
className="h-6 w-6 shrink-0 rounded-full ring-1 ring-inset ring-black/10 dark:ring-white/15"
style={{ background: resolveTrackColor(place) }}
/>
</button>
{colorPickerOpen && (
<div className="mt-[10px] border-t border-[color:var(--m-faint)] pt-[10px]">
<TrackColorPicker
value={place.route_color ?? null}
inheritedColor={inheritedTrackColor(place)}
onChange={handleTrackColor}
/>
</div>
)}
</>
)}
</div>
</>
@@ -403,7 +412,7 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
className={`flex items-center gap-1 rounded-full py-1 pl-[10px] text-[0.75rem] font-semibold ${INNER_CLS} ${canEditDays ? 'pr-1' : 'pr-[10px]'}`}
>
{day.title || t('planner.dayN', { n: (day.day_number ?? planner.days.indexOf(day) + 1) || '?' })}
{canEditDays && place.lat != null && place.lng != null && (
{canEditDays && !isTourPlace && place.lat != null && place.lng != null && (
// In or out of that day's route (#2532); the icon says which it is.
<button
type="button"
@@ -511,7 +520,7 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
)}
{/* ── Participants of the selected day's assignment ── */}
{assignmentInDay && members.length > 1 && (
{!isTourPlace && assignmentInDay && members.length > 1 && (
<>
<Eyebrow className="mb-[6px] mt-3">{t('inspector.participants')}</Eyebrow>
<div className="flex flex-wrap items-center gap-[6px]">
@@ -580,7 +589,7 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
<span className="min-w-0 flex-1 truncate text-[0.78125rem] font-semibold">
{placeFiles.length > 0 ? t('inspector.filesCount', { count: placeFiles.length }) : t('inspector.files')}
</span>
{planner.canUploadFiles && (
{planner.canUploadFiles && !isTourPlace && (
<button
type="button"
onClick={e => { e.stopPropagation(); fileInputRef.current?.click() }}
@@ -612,7 +621,7 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
{/* ── Action row ── */}
<div className="mt-[14px] flex items-center gap-[7px]">
{collectionsEnabled && (
{collectionsEnabled && !isTourPlace && (
<ActionCircle onClick={saveToCollection} label={t('inspector.saveToCollection')}>
<Bookmark size={15} strokeWidth={2} />
</ActionCircle>
@@ -649,7 +658,7 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
<ExternalLink size={15} strokeWidth={2} />
</ActionCircle>
)}
{canEditPlaces && (
{canManagePlace && (
<ActionCircle
onClick={() => { planner.openPlaceEditor(place, assignmentInDay?.id ?? null); close() }}
label={t('common.edit')}
@@ -659,7 +668,7 @@ export default function MPlaceSheet({ planner, shell }: MTripSheetsProps) {
<Pencil size={15} strokeWidth={2} />
</ActionCircle>
)}
{canEditPlaces && (
{canManagePlace && (
<ActionCircle
onClick={() => { planner.handleDeletePlace(place.id); close() }}
label={t('common.delete')}
@@ -0,0 +1,111 @@
import { fireEvent, render, screen } 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 type { TripPlanner } from '../MTripShell'
import { MSelectedTourDetail } from './MTripSheets'
const place = buildPlace({
id: 42,
name: 'Ridge walk',
route_geometry: JSON.stringify([
[48, 11, 500],
[48, 11.01, 550],
[48, 11.03, 520],
]),
})
const tour: TourListItem = {
place_id: place.id,
name: place.name,
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,
}
function planner(overrides: Partial<TripPlanner> = {}): TripPlanner {
return {
selectedPlace: place,
selectedTour: tour,
selectedDayId: null,
selectedAssignmentId: null,
assignments: {},
days: [],
files: [],
tripId: 7,
can: vi.fn<TripPlanner['can']>((actionKey) => actionKey === 'day_edit'),
canUploadFiles: false,
setSelectedPlaceId: vi.fn(),
reloadTourPlaceIds: vi.fn().mockResolvedValue(undefined),
tripActions: {
updatePlace: vi.fn().mockResolvedValue(undefined),
addFile: vi.fn().mockResolvedValue(undefined),
},
handleAssignToDay: vi.fn(),
handleRemoveAssignment: vi.fn(),
handleDeletePlace: vi.fn(),
...overrides,
} as unknown as TripPlanner
}
beforeEach(() => {
resetAllStores()
vi.clearAllMocks()
seedStore(useSettingsStore, { settings: { distance_unit: 'metric' } })
})
describe('MSelectedTourDetail', () => {
it('is the single mobile modal owner for Escape, focus containment, scroll lock and focus return', () => {
const opener = document.createElement('button')
opener.textContent = 'Open mobile Tour'
document.body.appendChild(opener)
opener.focus()
const setSelectedPlaceId = vi.fn()
const view = render(<MSelectedTourDetail planner={planner({ setSelectedPlaceId })} />)
const dialog = screen.getByRole('dialog', { name: 'Ridge walk' })
expect(dialog).toHaveAttribute('aria-modal', 'true')
expect(document.querySelectorAll('[aria-modal="true"]')).toHaveLength(1)
expect(document.body.style.overflow).toBe('hidden')
expect(document.activeElement).toBe(dialog)
expect(fireEvent.keyDown(dialog, { key: 'Tab', shiftKey: true })).toBe(false)
const nestedSheet = document.createElement('div')
nestedSheet.dataset.mSheet = 'open'
document.body.appendChild(nestedSheet)
fireEvent.keyDown(document, { key: 'Escape' })
expect(setSelectedPlaceId).not.toHaveBeenCalled()
document.body.removeChild(nestedSheet)
fireEvent.keyDown(document, { key: 'Escape' })
expect(setSelectedPlaceId).toHaveBeenCalledWith(null)
view.unmount()
expect(document.activeElement).toBe(opener)
expect(document.body.style.overflow).not.toBe('hidden')
document.body.removeChild(opener)
})
it('renders the selected tour through the shared detail dialog and elevation profile', () => {
render(<MSelectedTourDetail planner={planner()} />)
expect(screen.getAllByText('Track Stats')).toHaveLength(1)
expect(document.querySelector('#tour-elevation-42')).toBeInTheDocument()
})
it('renders nothing for an ordinary selected place', () => {
render(<MSelectedTourDetail planner={planner({ selectedTour: null })} />)
expect(screen.queryByText('Track Stats')).not.toBeInTheDocument()
})
})
@@ -1,9 +1,11 @@
import { useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import TransitJourneyModal from '../../../../components/Planner/TransitJourneyModal'
import BookingImportModal from '../../../../components/Planner/BookingImportModal'
import AirTrailImportModal from '../../../../components/Planner/AirTrailImportModal'
import TripFormModal from '../../../../components/Trips/TripFormModal'
import TripMembersModal from '../../../../components/Trips/TripMembersModal'
import TourDetailDialog from '../../../../components/Tours/TourDetailDialog'
import type { ExpensePrefill } from '../../../../components/Budget/CostsPanel'
import { expenseEditorFor } from '../../../../components/Budget/CostsPanel.helpers'
import { useAuthStore } from '../../../../store/authStore'
@@ -34,6 +36,62 @@ import MRtDraftSheet from '../roadtrip/MRtDraftSheet'
import type { BookingExpenseRequest } from '../../../../components/Planner/BookingCostsSection.types'
import type { BudgetItem } from '../../../../types'
import type { MTripSheetsProps } from '../MTripShell'
import { lockBodyScroll } from '../../../../utils/bodyScrollLock'
import { focusDialog, trapTab } from '../../../../components/shared/dialogFocus'
/** The one global mobile tour-detail owner, independent of which surface selected it. */
export function MSelectedTourDetail({ planner }: Pick<MTripSheetsProps, 'planner'>) {
const panelRef = useRef<HTMLDivElement>(null)
const selectedTourId = planner.selectedTour?.place_id ?? null
const selectedPlaceId = planner.selectedPlace?.id ?? null
useEffect(() => {
if (selectedTourId == null || selectedPlaceId == null) return
const previous = document.activeElement as HTMLElement | null
const release = lockBodyScroll()
const panel = panelRef.current
if (panel) focusDialog(panel)
const onKeyDown = (event: KeyboardEvent) => {
if (event.key !== 'Escape' || event.defaultPrevented) return
const openPanels = document.querySelectorAll('[data-m-sheet="open"]')
if (openPanels.length && openPanels[openPanels.length - 1] !== panel) return
event.preventDefault()
planner.setSelectedPlaceId(null)
}
document.addEventListener('keydown', onKeyDown)
return () => {
document.removeEventListener('keydown', onKeyDown)
release()
if (previous?.isConnected) previous.focus()
}
}, [planner.setSelectedPlaceId, selectedPlaceId, selectedTourId])
if (!planner.selectedTour || !planner.selectedPlace) return null
return createPortal(
<div className="bg-[rgba(0,0,0,0.3)]" style={{ position: 'fixed', inset: 0, zIndex: 9999, display: 'flex', alignItems: 'flex-end', justifyContent: 'center', paddingBottom: 'var(--bottom-nav-h)' }} role="presentation" onClick={() => planner.setSelectedPlaceId(null)}>
<div ref={panelRef} style={{ width: '100%', maxHeight: '85vh' }} role="dialog" aria-modal="true" aria-label={planner.selectedPlace.name}
data-m-sheet="open"
tabIndex={-1} onClick={event => event.stopPropagation()} onKeyDown={event => trapTab(event, panelRef.current!)}>
<TourDetailDialog
tour={planner.selectedTour}
place={planner.selectedPlace}
days={planner.days}
selectedDayId={planner.selectedDayId}
selectedAssignmentId={planner.selectedAssignmentId}
assignments={planner.assignments}
files={planner.files}
readOnly
canEdit={false}
canAssign={planner.can('day_edit', planner.trip)}
onClose={() => planner.setSelectedPlaceId(null)}
onAssignToDay={planner.handleAssignToDay}
onRemoveAssignment={planner.handleRemoveAssignment}
/>
</div>
</div>,
document.body,
)
}
/**
* Sheet host of the mobile trip screen — always mounted below the shell. Two
@@ -66,6 +124,7 @@ export default function MTripSheets({ planner, shell }: MTripSheetsProps) {
<>
{/* ── Mobile sheets (shell.sheet routing + the place selection) ── */}
<MPlaceSheet planner={planner} shell={shell} />
<MSelectedTourDetail planner={planner} />
<MDaySheet planner={planner} shell={shell} />
<MDaysSheet planner={planner} shell={shell} />
<MAccommodationSheet planner={planner} shell={shell} />
@@ -191,13 +250,19 @@ export default function MTripSheets({ planner, shell }: MTripSheetsProps) {
open={planner.deletePlaceId != null && !planner.showPlaceForm}
onClose={() => planner.setDeletePlaceId(null)}
title={t('common.delete')}
message={planner.deletePlaceNote ? (
message={planner.deletePlaceId != null && planner.isTourPlace(planner.deletePlaceId) ? (
<>
<span className="block">{t('tours.delete.confirmBody')}</span>
{planner.deletePlaceNote && <span className="mt-1 block">{planner.deletePlaceNote}</span>}
</>
) : planner.deletePlaceNote ? (
<>
<span className="block">{t('trip.confirm.deletePlace')}</span>
<span className="mt-1 block">{planner.deletePlaceNote}</span>
</>
) : t('trip.confirm.deletePlace')}
confirmLabel={t('common.delete')}
confirmLabel={planner.deletePlaceId != null && planner.isTourPlace(planner.deletePlaceId)
? t('tours.delete.confirmAction') : t('common.delete')}
cancelLabel={t('common.cancel')}
danger
onConfirm={() => {