The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
import { useEffect, useRef, useState } from 'react'
import { ArrowRight, Footprints, Pencil, Route as RouteIcon, Trash2 } from 'lucide-react'
import MSheet from '../../../components/MSheet'
import MWalletButton from '../../../components/MWalletButton'
import type { MTripSheetsProps } from '../MTripShell'
import { useTranslation } from '../../../../i18n'
import { useSettingsStore } from '../../../../store/settingsStore'
import { RES_ICONS } from '../../../../components/Planner/DayPlanSidebar.constants'
import { splitReservationDateTime } from '../../../../utils/formatters'
import { getFlightLegs, getTrainLegs, seatLabel, seatsOfLegs, usesStationRoute, type FlightLeg, type TrainLeg } from '../../../../utils/flightLegs'
import { runsOnDay } from '../../../../utils/reservationRoutes'
import { filesFor } from '../../../../utils/reservationFiles'
import { bookingDayLabel, segmentCodeLabel } from '../../../../components/Planner/transportDetailModel'
import type { Reservation } from '../../../../types'
import { useSearchParams } from 'react-router'
import { isTransportReservationType } from '@trek/shared'
import { useBookingLink } from '../../../../hooks/useBookingLink'
import { bookingFacts, stayStats } from '../../../../components/Planner/bookings/bookingFacts'
import { bookingDates, parseMeta } from '../../../../components/Planner/bookings/bookingsModel'
import { ActionCircle, Eyebrow, INNER_CLS, StatBox, TileHeader, displayTime } from './MTripSheetUi'
import { CardFiles } from '../tabs/MReservationCardParts'
import { downloadAttachment, openAttachment } from '../../../../components/Planner/bookings/openAttachment'
import { flowText } from '../../../../utils/flowText'
import { useFlightLiveCardLegs } from '../../../../components/Planner/flightLive/useFlightLiveCard'
import MFlightLiveCard from './MFlightLiveCard'
import MReviewNotice from './MReviewNotice'
interface TransportSheetPayload {
reservationId?: number
/** The leg of a multi-leg train or flight the day plan row stood for (#2701). */
legIndex?: number
}
interface TransitLeg {
mode?: string
line?: string | null
line_color?: string | null
line_text_color?: string | null
headsign?: string | null
duration?: number
stops?: number
from?: { name?: string; time?: string | null }
to?: { name?: string; time?: string | null }
}
interface TransportMeta {
airline?: string
flight_number?: string
train_number?: string
seat?: string
platform?: string
transit?: { legs?: TransitLeg[] }
}
function parseMetadata(res: Reservation): TransportMeta {
try {
return (typeof res.metadata === 'string' ? JSON.parse(res.metadata || '{}') : (res.metadata || {})) as TransportMeta
} catch {
return {}
}
}
/**
* Transport detail sheet ('transport', payload { reservationId }): endpoints +
* times, per-type meta (seat/platform/flight number), transit itinerary legs,
* status + booking code (blurrable), notes, attached files and the
* on-map/edit/delete actions.
*/
export default function MTransportSheet({ planner, shell }: MTripSheetsProps) {
const { t, locale } = useTranslation()
const open = shell.sheet?.id === 'transport'
const payload = (shell.sheet?.payload ?? {}) as TransportSheetPayload
const liveRes = planner.reservations.find(r => r.id === payload.reservationId) ?? null
// The map with a booking's route drawn on it: the route switched on, the sheet
// closed, the plan tab and the map shown. The map draws the day on the chips, and
// the Transports tab lists the whole trip, so the booking may run on a different
// day. Moved last, because entering the map picks the day the shell was already
// holding. A day inside the booking's span, the all-days view and a booking bound
// to no day are left as they are.
const revealOnMap = (r: Reservation) => {
if (!planner.visibleConnections.includes(r.id)) planner.toggleConnection(r.id)
shell.closeSheet()
if (shell.trTab !== 'plan') shell.setTrTab('plan')
if (shell.view !== 'map') shell.toggleView()
const bookingDayId = r.day_id ?? r.end_day_id
if (planner.selectedDayId != null && bookingDayId != null && !runsOnDay(r, planner.selectedDayId, planner.days)) {
planner.handleSelectDay(bookingDayId, false)
planner.setExpandedDayIds(new Set([bookingDayId]))
}
}
// A transport the chat points at (?booking=) opens here, or with &map=1 its route on
// the map; any other booking stays on its tab.
const [searchParams, setSearchParams] = useSearchParams()
useBookingLink({
searchParams,
setSearchParams,
tripId: planner.tripId,
reservations: planner.reservations,
loaded: !planner.isLoading && planner.trip?.id === planner.tripId,
take: (booking, toMap) => {
if (!isTransportReservationType(booking.type)) return
if (toMap) revealOnMap(booking)
else shell.openSheet('transport', { reservationId: booking.id })
},
})
const canEditDays = planner.can('day_edit', planner.trip)
const canEditBookings = planner.can('reservation_edit', planner.trip)
const timeFormat = useSettingsStore(s => s.settings.time_format) || '24h'
const blurCodes = useSettingsStore(s => s.settings.blur_booking_codes)
const [codeRevealed, setCodeRevealed] = useState(false)
// Only legs with a card: a flight long over keeps its time boxes below.
const liveLegs = useFlightLiveCardLegs(planner.tripId, payload.reservationId ?? -1)
useEffect(() => { if (!open) setCodeRevealed(false) }, [open])
// Hold the last reservation so the card content survives the exit animation.
const heldRef = useRef<Reservation | null>(null)
if (liveRes) heldRef.current = liveRes
const res = liveRes ?? heldRef.current
if (!res) {
return <MSheet open={false} onClose={shell.closeSheet} variant="card" material="glass" />
}
const meta = parseMetadata(res)
// A transport is part of the day plan, a stay, a table or a ticket a booking:
// each is edited under its own permission, as in the tab it belongs to. Read off
// the live booking, so a sheet on its way out offers nothing to edit.
const canEdit = liveRes != null && (isTransportReservationType(liveRes.type) ? canEditDays : canEditBookings)
const ResIcon = RES_ICONS[res.type as keyof typeof RES_ICONS] || RES_ICONS.other
const endpoints = res.endpoints || []
const from = endpoints.find(e => e.role === 'from')
const to = endpoints.find(e => e.role === 'to')
const { time: startTime } = splitReservationDateTime(res.reservation_time)
const { time: endTime } = splitReservationDateTime(res.reservation_end_time)
const bookingDepTime = from?.local_time || startTime
const bookingArrTime = to?.local_time || endTime
// Per-segment booking codes (#1943), only on a real stopover booking: the
// single-leg fallback would just echo the booking's own code shown below.
const isFlight = res.type === 'flight'
const routeLegs: (FlightLeg | TrainLeg)[] = isFlight ? getFlightLegs(res) : usesStationRoute(res.type) ? getTrainLegs(res) : []
const legCodes = routeLegs.length > 1 ? routeLegs.filter(l => l.confirmation_number) : []
// Opened from one leg's row, the sheet shows that leg's own number, seat,
// platform and times rather than the first leg's (#2701).
const leg = routeLegs.length > 1 && payload.legIndex != null ? routeLegs[payload.legIndex] ?? null : null
const legDetail = (leg ?? {}) as Partial<FlightLeg & TrainLeg>
const depTime = leg ? leg.dep_time || '' : bookingDepTime
const arrTime = leg ? leg.arr_time || '' : bookingArrTime
const depLabel = (leg ? leg.from : from?.name) || t('reservations.time')
const arrLabel = (leg ? leg.to : to?.name) || t('reservations.time')
// The calendar date each time falls on (#3122): a time alone cannot be placed
// when the sheet is opened from a compact list that shows nothing else.
const legDate = (dayId?: number | null) => (dayId != null ? planner.days.find(d => d.id === dayId)?.date : null) || null
const dates = leg ? { start: legDate(leg.dep_day_id), end: legDate(leg.arr_day_id) } : bookingDates(res, planner.days)
const depDate = dates.start ? bookingDayLabel(dates.start, locale) : null
const arrDate = dates.end ? bookingDayLabel(dates.end, locale) : null
const subParts: string[] = []
const airline = leg ? legDetail.airline : meta.airline
const flightNumber = leg ? legDetail.flight_number : meta.flight_number
const trainNumber = leg ? legDetail.train_number : meta.train_number
if (airline) subParts.push(airline)
if (flightNumber) subParts.push(flightNumber)
if (trainNumber) subParts.push(trainNumber)
if (leg && (leg.from || leg.to)) subParts.push(flowText([leg.from, leg.to].filter((n): n is string => !!n)))
else if (from?.name && to?.name) subParts.push(flowText([from.name, to.name]))
// Opened from a leg, that leg's own seat; the whole booking lists the seat of
// every leg that has one, each under its route, rather than only the first's.
const seats: { route: string | null; seat: string }[] = leg ? (legDetail.seat ? [{ route: null, seat: legDetail.seat }] : []) : seatsOfLegs(routeLegs, meta.seat)
const ownSeat = seats.find(s => s.route == null)?.seat
const legSeats = seats.filter(s => s.route != null)
// A flight's legs carry no platform of their own, so that stays the booking's.
const platform = leg && !isFlight ? legDetail.platform : meta.platform
const transitLegs: TransitLeg[] = Array.isArray(meta.transit?.legs) ? meta.transit.legs : []
// Opened from one leg's row, only that leg's live card; from the booking, every followed leg.
const shownLive = leg ? liveLegs.filter(l => l.leg_index === payload.legIndex) : liveLegs
const showTimes = shownLive.length === 0
// A shown time box carries its own date. Without one (no time entered yet, or the
// live card in its place) the subline names the day, route and airline or not.
const datedTime = showTimes && ((depTime && depDate) || (arrTime && arrDate))
if (depDate && !datedTime) subParts.push(depDate)
const resFiles = filesFor(res, planner.files || [])
const confirmed = res.status === 'confirmed'
const codeBlurred = blurCodes && !codeRevealed
// The plan map only draws a switched-on booking on the days it runs on, so from any
// other day the button reads off, as the map does, and a tap takes the map to the
// booking instead of switching off a route that is not drawn here anyway.
const switchedOn = planner.visibleConnections.includes(res.id)
const onMap = switchedOn && runsOnDay(res, planner.selectedDayId, planner.days)
// First tap draws the overlay and jumps to the map; while drawn, the same
// button hides it again (per-booking overlay toggle, desktop parity).
const showOnMap = () => {
if (onMap) {
planner.toggleConnection(res.id)
return
}
revealOnMap(res)
}
// A stay shows its check-in, check-out and nights, as the desktop dialog does.
const hotelStats = res.type === 'hotel'
? stayStats(
bookingFacts(res, { t, locale, timeFormat, days: planner.days, assignmentLookup: {}, hasLinkedCost: false }),
parseMeta(res),
t,
locale,
)
: []
// The times, platform and booking seat; each leg's seat gets a row of its own below it.
const statRow = hotelStats.length === 0 && ((showTimes && (depTime || arrTime)) || !!ownSeat || !!platform)
// The editor that fits the booking: transports have their own, everything
// else (a stay, a table, a ticket) the booking editor, as in the Bookings tab.
const editTransport = () => {
if (isTransportReservationType(res.type)) {
planner.setEditingTransport(res)
planner.setTransportModalDayId(res.day_id ?? null)
planner.setShowTransportModal(true)
} else {
planner.setEditingReservation(res)
planner.setShowReservationModal(true)
}
shell.closeSheet()
}
const deleteTransport = () => {
void planner.handleDeleteReservation(res.id)
shell.closeSheet()
}
return (
<MSheet open={open && !!liveRes} onClose={shell.closeSheet} variant="card" material="glass" ariaLabel={res.title}>
<div className="flex-none px-[18px] pt-4">
<TileHeader
icon={<ResIcon size={19} strokeWidth={1.8} />}
title={<span dir="auto" className="min-w-0 break-words text-[1rem] [overflow-wrap:anywhere]">{res.title}</span>}
sub={subParts.length > 0 ? subParts.join(' · ') : undefined}
subWrap
onClose={shell.closeSheet}
closeLabel={t('common.close')}
/>
</div>
<div className="m-scroll-fade mt-2 min-h-0 flex-1 overflow-y-auto px-[18px] pb-[18px] pt-[14px]">
{/* ── An import could not read every detail for sure ── */}
{!!liveRes?.needs_review && (
<MReviewNotice
onConfirm={canEdit ? () => {
planner.tripActions.updateReservation(planner.tripId, liveRes.id, { needs_review: 0 })
.then(() => planner.toast.success(t('reservations.reviewConfirmed')))
.catch(() => planner.toast.error(t('reservations.toast.updateError')))
} : undefined}
/>
)}
{/* ── A stay: check-in, check-out, nights ── */}
{hotelStats.length > 0 && (
<div className="mt-[14px] flex gap-[6px]">
{hotelStats.map(s => <StatBox key={s.label} value={s.value} label={s.label} />)}
</div>
)}
{/* ── Live flight: the leg opened from, or every followed leg of the booking ── */}
{shownLive.map(l => (
<MFlightLiveCard
key={l.leg_index}
tripId={planner.tripId}
reservationId={res.id}
legIndex={l.leg_index}
legLabel={!leg && routeLegs.length > 1 ? t('flightLive.legOf', { n: l.leg_index + 1, total: routeLegs.length }) : undefined}
/>
))}
{/* ── Times / seat stats (the live card already shows the times) ── */}
{statRow && (
<div className="mt-[14px] flex gap-[6px]">
{showTimes && depTime && (
<StatBox caption={depDate} value={displayTime(depTime, locale, timeFormat)} label={depLabel} />
)}
{showTimes && arrTime && (
<StatBox caption={arrDate} value={displayTime(arrTime, locale, timeFormat)} label={arrLabel} />
)}
{platform && <StatBox value={platform} label={t('reservations.meta.platform')} />}
{ownSeat && <StatBox value={ownSeat} label={t('reservations.meta.seat')} />}
</div>
)}
{hotelStats.length === 0 && legSeats.length > 0 && (
<div className={`${statRow ? 'mt-[6px]' : 'mt-[14px]'} flex gap-[6px]`}>
{legSeats.map((s, i) => <StatBox key={i} value={s.seat} label={seatLabel(t('reservations.meta.seat'), s.route)} />)}
</div>
)}
{/* ── Transit itinerary (#1065): one row per leg ── */}
{transitLegs.length > 0 && (
<div className={`mt-3 flex flex-col gap-2 rounded-[14px] px-3 py-[10px] ${INNER_CLS}`}>
{transitLegs.map((leg, i) => {
const isWalk = leg.mode === 'WALK'
const mins = leg.duration ? Math.round(leg.duration / 60) : null
return (
<div key={i} className="flex items-start gap-2">
{isWalk ? (
<Footprints size={12} strokeWidth={2} className="mt-[2px] flex-none text-m-faint" />
) : (
<span
className="flex-none rounded-[5px] px-[6px] py-px text-[0.625rem] font-bold"
style={{
background: leg.line_color || 'var(--m-ic)',
color: leg.line_color ? (leg.line_text_color || '#fff') : 'var(--m-ink)',
}}
>
{leg.line || leg.mode}
</span>
)}
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-1 text-[0.71875rem] font-medium">
{isWalk ? (
<span className="text-m-muted">{t('transit.walkTo', { name: leg.to?.name || '' })}</span>
) : (
<>
<span dir="auto" className="min-w-0 break-words [overflow-wrap:anywhere]">{leg.from?.name}</span>
<ArrowRight size={10} strokeWidth={2} className="flex-none text-m-faint" />
<span dir="auto" className="min-w-0 break-words [overflow-wrap:anywhere]">{leg.to?.name}</span>
</>
)}
</div>
<div className="mt-px font-geist text-[0.625rem] text-m-faint">
{[
leg.from?.time && !isWalk ? `${leg.from.time}${leg.to?.time ? ` – ${leg.to.time}` : ''}` : null,
mins ? t('transit.min', { count: mins }) : null,
!isWalk && leg.stops ? t('transit.stops', { count: leg.stops }) : null,
].filter(Boolean).join(' · ')}
</div>
</div>
</div>
)
})}
</div>
)}
{/* ── Status + booking code ── */}
<div className={`mt-3 flex items-center gap-2 rounded-[13px] px-3 py-[9px] ${INNER_CLS}`}>
<span
className="h-2 w-2 flex-none rounded-full"
style={{ background: confirmed ? 'var(--m-st-confirmed)' : 'var(--m-st-pending)' }}
/>
<span className="min-w-0 flex-1 truncate text-[0.78125rem] font-semibold">
{confirmed ? t('reservations.confirmed') : t('reservations.pending')}
</span>
{res.confirmation_number && (
<button
type="button"
onClick={() => { if (blurCodes) setCodeRevealed(v => !v) }}
className={`flex-none font-geist text-[0.71875rem] tabular-nums text-m-muted ${codeBlurred ? 'blur-[4px] select-none' : ''}`}
>
#{res.confirmation_number}
</button>
)}
</div>
{/* ── Per-segment booking codes ── */}
{legCodes.length > 0 && (
<div className={`mt-3 flex flex-col gap-[7px] rounded-[13px] px-3 py-[9px] ${INNER_CLS}`}>
{legCodes.map((leg, i) => (
<div key={i} className="flex items-center gap-2">
<span className="min-w-0 flex-1 truncate text-[0.71875rem] font-medium">
{segmentCodeLabel(leg, t)}
</span>
<button
type="button"
onClick={() => { if (blurCodes) setCodeRevealed(v => !v) }}
className={`flex-none font-geist text-[0.71875rem] tabular-nums text-m-muted ${codeBlurred ? 'blur-[4px] select-none' : ''}`}
>
#{leg.confirmation_number}
</button>
</div>
))}
</div>
)}
{/* ── Notes ── */}
{res.notes && (
<>
<Eyebrow className="mb-[6px] mt-3">{t('reservations.notes')}</Eyebrow>
<div className={`rounded-[14px] px-3 py-[10px] ${INNER_CLS}`}>
<div className="whitespace-pre-wrap font-geist text-[0.75rem] leading-[1.5] text-m-muted">{res.notes}</div>
</div>
</>
)}
{/* ── Files: their own rows, so a long name never pushes the actions onto a second line ── */}
<CardFiles
files={resFiles}
card={{
openFile: openAttachment,
downloadFile: f => downloadAttachment(f, () => planner.toast.error(t('files.downloadError'))),
}}
t={t}
/>
{/* ── Actions: icons only, the names are their labels ── */}
<div className="mt-[14px] flex items-center gap-[7px]">
<ActionCircle onClick={showOnMap} label={t('mobileTrip.onMap')} pressed={onMap}>
<RouteIcon size={15} strokeWidth={2} />
</ActionCircle>
<MWalletButton tripId={planner.tripId} reservationId={payload.reservationId} onError={planner.toast.error} />
{canEdit && (
<ActionCircle onClick={editTransport} label={t('common.edit')} primary className="ms-auto">
<Pencil size={15} strokeWidth={2} />
</ActionCircle>
)}
{canEdit && (
<ActionCircle onClick={deleteTransport} label={t('common.delete')} danger>
<Trash2 size={15} strokeWidth={2} />
</ActionCircle>
)}
</div>
</div>
</MSheet>
)
}