feat(tours): align the Tours UI with the planner redesign

The Tours surfaces now use the same building blocks as the rest of the
planner: tinted head bands, eyebrow labels, white field boxes and pills,
place-style list rows and the inspector frame for the map detail.

- Tour detail on the map uses the place inspector's frame, head band,
  labelled metric fields, collapsible track colour and footer buttons
- Tour rows in the Plan sidebar and the Tours tab look like place rows,
  with the facts as pills and a "+" that opens the trip's days as a menu
- Tours tab rails get the planner head bands, editor fields and
  waypoint rows in the day card style; notices share one look
- Map hint shortened to one line and the empty state reads as a single
  sentence in all locales
- New "tours" mascot scene with a pack, a trekking pole, hills and a
  trail, used by the Tours empty states
This commit is contained in:
Maurice
2026-10-05 12:04:49 +02:00
parent ccaed9f9ba
commit c92478c5ad
41 changed files with 893 additions and 669 deletions
@@ -1,7 +1,7 @@
import React from 'react'
import { MapPin, Mountain } from 'lucide-react'
import { useTranslation } from '../../i18n/TranslationContext'
import { NEUTRAL_TINT } from '../shared/DialogShell'
import { NEUTRAL_TINT, fs } from '../shared/DialogShell'
interface PlacesToursModeSwitchProps {
active: boolean
@@ -21,8 +21,8 @@ export default function PlacesToursModeSwitch({ active, onChange }: PlacesToursM
[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">
<div className="flex-none px-3 pb-0.5 pt-2.5" style={{ background: NEUTRAL_TINT }}>
<div role="tablist" aria-label={t('tours.mode.label')} className="flex w-full gap-0.5 rounded-[10px] bg-surface-tertiary p-[3px]">
{options.map(([value, label, Icon]) => {
const selected = active === value
return (
@@ -32,14 +32,12 @@ export default function PlacesToursModeSwitch({ active, onChange }: PlacesToursM
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'
style={fs(12.5, 'body')}
className={`flex flex-1 items-center justify-center gap-1.5 whitespace-nowrap rounded-[8px] px-3 py-1.5 font-medium transition-colors ${
selected ? 'bg-surface-card text-content shadow-sm' : 'text-content-muted hover:text-content'
}`}
>
<Icon size={13} strokeWidth={1.8} aria-hidden />
<Icon size={13} strokeWidth={2} aria-hidden />
<span className="truncate">{label}</span>
</button>
)
+183 -95
View File
@@ -1,5 +1,5 @@
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 { AlertTriangle, Check, ChevronDown, ChevronUp, File, FileImage, FileText, Info, MapPin, Mountain, Navigation, Pencil, Plus, Minus, Upload } from 'lucide-react'
import Markdown from 'react-markdown'
import remarkBreaks from 'remark-breaks'
import remarkGfm from 'remark-gfm'
@@ -8,18 +8,22 @@ import type { Assignment, AssignmentsMap, Day, Place, TripFile } from '../../typ
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 { DeleteButton, DialogButton, DialogSection, FooterSpacer, fs } from '../shared/DialogShell'
import { Tooltip } from '../shared/Tooltip'
import { BOX } from '../Planner/bookings/bookingParts'
import { SoftPill, TimePill, tintOf } from '../Planner/planParts'
import { analyzeRouteGeometry } from '../../utils/routeGeometry'
import { filesForPlace } from '../../utils/placeFiles'
import { openFile } from '../../utils/fileDownload'
import { getNavigationTargets, openNavigationTarget } from '../Planner/placeNavigation'
import { getNavigationTargets, navigationTargetLabel, openNavigationTarget } from '../Planner/placeNavigation'
import { hikeSourceBadgeLabel, tourSource } from './tourPresentation'
import { TourMetricFields, TourNotice, TourTile } from './tourParts'
import { useTourPermissions, type TourPermissionProps } from './useTourPermissions'
interface TourDetailDialogProps extends TourPermissionProps {
@@ -64,6 +68,12 @@ function assignmentForSelectedDay(
?? null
}
/**
* The card a tour opens over the map, in the place inspector's language: a head
* band tinted by the track colour with the tile, the name and the facts as
* pills, then each part of the tour under its own label, and the actions in a
* footer that stays in reach.
*/
export default function TourDetailDialog({
tour,
place,
@@ -94,9 +104,10 @@ export default function TourDetailDialog({
const [nameDraft, setNameDraft] = useState(place.name)
const [savingName, setSavingName] = useState(false)
const [filesExpanded, setFilesExpanded] = useState(false)
const [colorOpen, setColorOpen] = useState(false)
const [uploading, setUploading] = useState(false)
const [navigationOpen, setNavigationOpen] = useState(false)
const navigationButtonRef = useRef<HTMLButtonElement>(null)
const navigationAnchorRef = useRef<HTMLSpanElement>(null)
const fileInputRef = useRef<HTMLInputElement>(null)
const closeRef = useRef(onClose)
closeRef.current = onClose
@@ -124,7 +135,9 @@ export default function TourDetailDialog({
const assignment = assignmentForSelectedDay(assignments, selectedDayId, selectedAssignmentId, place.id)
const placeFiles = filesForPlace(files, place.id, [], assignment ? [assignment.id] : [])
const navigationTargets = getNavigationTargets(place)
const navigationLabel = navigationTargets.length === 1 ? navigationTargetLabel(navigationTargets[0], t) : t('inspector.navigation')
const source = tourSource(tour)
const colorLabel = place.route_color ? place.route_color.toUpperCase() : t('inspector.trackColorAuto')
const saveName = async () => {
if (!canEdit) return
@@ -161,128 +174,203 @@ export default function TourDetailDialog({
}
}
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>
const header = (
<>
<div className="flex-none rounded-full bg-surface-card p-[2.5px] shadow-sm">
<TourTile size={52} color={trackColor} />
</div>
<div className="min-w-0 flex-1 pt-0.5">
{canEdit && editingName ? (
<div className="flex items-center gap-1.5">
<input
autoFocus
value={nameDraft}
onChange={event => setNameDraft(event.target.value)}
onKeyDown={event => {
if (event.key === 'Enter') void saveName()
if (event.key === 'Escape') { event.preventDefault(); setNameDraft(place.name); setEditingName(false) }
}}
aria-label={t('places.formName')}
className="-mx-1.5 block min-w-0 flex-1 rounded-[8px] border-0 bg-surface-card px-1.5 py-0.5 font-bold tracking-[-0.01em] text-content shadow-sm outline-none"
style={fs(17, 'subtitle')}
/>
<Tooltip label={t('common.save')}>
<button type="button" onClick={() => void saveName()} disabled={savingName} aria-label={t('common.save')}
className="grid h-7 w-7 flex-none place-items-center rounded-full bg-accent text-accent-text disabled:opacity-50">
<Check size={14} strokeWidth={2.4} />
</button>
</Tooltip>
</div>
) : (
<div className="flex min-w-0 items-center gap-1.5">
<h2 className="m-0 min-w-0 break-words font-bold leading-snug tracking-[-0.01em] text-content" style={fs(17, 'subtitle')}>{place.name}</h2>
{canEdit && onUpdatePlace && (
<Tooltip label={t('common.edit')}>
<button type="button" onClick={() => { setNameDraft(place.name); setEditingName(true) }} aria-label={t('common.edit')}
className="grid h-6 w-6 flex-none place-items-center rounded-full text-content-faint transition-colors hover:bg-surface-card hover:text-content">
<Pencil size={12} strokeWidth={2.2} />
</button>
</Tooltip>
)}
</div>
)}
<div className="mt-2 flex flex-wrap items-center gap-1.5">
<SoftPill icon={<Mountain size={11} strokeWidth={2} className="flex-none" style={{ color: trackColor }} />}>{t(`tourTypes.${tour.tour_type}`)}</SoftPill>
{tour.difficulty && <SoftPill>{t('tours.detail.difficulty')}: {tour.difficulty}</SoftPill>}
{tour.duration != null && <TimePill>{t('tours.durationMinutes', { count: tour.duration })}</TimePill>}
<SoftPill>{hikeSourceBadgeLabel(tour, t)}</SoftPill>
{tour.caution && (
<Tooltip label={t('tours.caution.tooltip')}>
<span className="inline-flex">
<SoftPill tone="warning" icon={<AlertTriangle size={11} strokeWidth={2} className="flex-none" />}>{t('tours.caution.badge')}</SoftPill>
</span>
</Tooltip>
)}
</div>
</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')} />
<DialogButton onClick={() => { if (canAssign) onRemoveAssignment(selectedDayId, assignment.id) }} icon={<Minus size={14} strokeWidth={2} />} aria-label={t('inspector.removeFromDay')}>
<span className="max-sm:hidden">{t('inspector.removeFromDay')}</span>
</DialogButton>
) : (
onAssignToDay && <TourActionButton onClick={() => { if (canAssign) onAssignToDay(place.id) }} icon={<Plus size={13} />} label={t('inspector.addToDay')} primary />
onAssignToDay && (
<DialogButton variant="primary" onClick={() => { if (canAssign) onAssignToDay(place.id) }} icon={<Plus size={14} strokeWidth={2} />}>
{t('inspector.addToDay')}
</DialogButton>
)
))}
{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)} />}
<span ref={navigationAnchorRef} className="inline-flex">
<DialogButton
onClick={() => {
if (navigationTargets.length === 1) openNavigationTarget(navigationTargets[0])
else setNavigationOpen(open => !open)
}}
aria-label={navigationLabel}
aria-haspopup={navigationTargets.length > 1 ? 'menu' : undefined}
aria-expanded={navigationTargets.length > 1 ? navigationOpen : undefined}
icon={<Navigation size={14} strokeWidth={2} />}
>
<span className="max-sm:hidden">{navigationLabel}</span>
</DialogButton>
</span>
{navigationOpen && <NavigationMenu targets={navigationTargets} anchor={navigationAnchorRef.current} onClose={() => setNavigationOpen(false)} />}
</>
)}
<div style={{ flex: 1 }} />
{canEdit && onDelete && <TourActionButton onClick={() => { if (canEdit) onDelete() }} icon={<Trash2 size={13} />} label={t('common.delete')} danger />}
<FooterSpacer />
{canEdit && onDelete && <DeleteButton onClick={() => { if (canEdit) onDelete() }} />}
</>
return (
<DetailShell header={header} footer={footer} onClose={onClose} closeLabel={t('common.close')} leftWidth={leftWidth} rightWidth={rightWidth}
tint={tintOf(trackColor)}
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">
<TourNotice icon={<Info size={13} strokeWidth={2} className="text-content-faint" />}>
{t('tours.detail.gpxReadOnly')}
{/* TODO(tours-roadmap): add the planned left-rail “Convert to TREK Tour” action here. */}
</div>
</TourNotice>
)}
<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}`} />
</>
{analysis && (
<DialogSection className="flex-none" label={t('inspector.trackStats')}>
<div className="flex flex-col gap-2">
<TourMetricFields analysis={analysis} unit={distanceUnit} />
{analysis.distanceIndexedProfileSamples.length >= 2 && (
<div className={`${BOX} p-2`}>
<ElevationProfile samples={analysis.distanceIndexedProfileSamples} color={trackColor} gradientId={`tour-elevation-${place.id}`} />
</div>
)}
</div>
</DialogSection>
)}
<DialogSection className="flex-none" label={t('tours.detail.trackColor')}>
{canEdit && onUpdatePlace ? (
<div className={BOX}>
<button type="button" onClick={() => setColorOpen(open => !open)} aria-expanded={colorOpen}
className="flex w-full items-center gap-2 rounded-[10px] px-3 py-2 text-left transition-colors hover:bg-surface-hover">
<span className="h-4 w-4 flex-none rounded-full ring-1 ring-inset ring-edge" style={{ backgroundColor: trackColor }} />
<span className="min-w-0 flex-1 truncate font-medium text-content-secondary" style={fs(12, 'body')}>{colorLabel}</span>
{colorOpen ? <ChevronUp size={13} className="flex-none text-content-faint" /> : <ChevronDown size={13} className="flex-none text-content-faint" />}
</button>
{colorOpen && (
<div className="border-t border-edge-faint px-3 py-2.5">
<TrackColorPicker value={place.route_color ?? null} inheritedColor={inheritedColor} onChange={color => { if (canEdit) void onUpdatePlace(place.id, { route_color: color }) }} />
</div>
)}
</div>
) : (
<div className={`${BOX} flex items-center gap-2 px-3 py-2`}>
<span aria-label={t('tours.detail.trackColor')} className="h-4 w-4 flex-none rounded-full ring-1 ring-inset ring-edge" style={{ backgroundColor: trackColor }} />
<span className="min-w-0 flex-1 truncate font-medium text-content-secondary" style={fs(12, 'body')}>{colorLabel}</span>
</div>
)}
</div>
</DialogSection>
<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>
)}
{place.description && <DialogSection className="flex-none" label={t('places.formDescription')}><MarkdownBox>{place.description}</MarkdownBox></DialogSection>}
{place.notes && <DialogSection className="flex-none" label={t('places.formNotes')}><MarkdownBox>{place.notes}</MarkdownBox></DialogSection>}
{assignment?.notes && <DialogSection className="flex-none" label={t('places.assignmentNotes')}><MarkdownBox>{assignment.notes}</MarkdownBox></DialogSection>}
{(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>
<DialogSection
className="flex-none"
label={t('inspector.files')}
action={canEdit && onFileUpload && (
<label className="inline-flex cursor-pointer items-center gap-1 rounded-full bg-surface-card px-2 py-[2px] font-geist font-semibold text-content-muted shadow-sm transition-colors focus-within:ring-2 focus-within:ring-accent hover:text-content" style={fs(10.5)}>
<input ref={fileInputRef} type="file" multiple className="sr-only" onChange={uploadFiles} />
{uploading ? <span aria-live="polite">…</span> : <><Upload size={11} strokeWidth={2} />{t('common.upload')}</>}
</label>
)}
>
<div className={BOX}>
<button type="button" onClick={() => setFilesExpanded(expanded => !expanded)} aria-expanded={filesExpanded}
className="flex w-full items-center gap-2 rounded-[10px] px-3 py-2 text-left transition-colors hover:bg-surface-hover">
<FileText size={13} strokeWidth={2} className="flex-none text-content-faint" />
<span className="min-w-0 flex-1 truncate font-medium text-content-secondary" style={fs(12, 'body')}>
{placeFiles.length ? t('inspector.filesCount', { count: placeFiles.length }) : t('inspector.files')}
</span>
{filesExpanded ? <ChevronUp size={13} className="flex-none text-content-faint" /> : <ChevronDown size={13} className="flex-none text-content-faint" />}
</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>}
{filesExpanded && placeFiles.length > 0 && (
<div className="flex flex-col gap-0.5 border-t border-edge-faint p-1">
{placeFiles.map(file => (
<button type="button" key={file.id} onClick={() => void openFile(file.url)}
className="flex w-full items-center gap-2 rounded-[8px] px-2 py-1.5 text-left transition-colors hover:bg-surface-hover">
{(file.mime_type || '').startsWith('image/')
? <FileImage size={12} strokeWidth={2} className="flex-none text-content-muted" />
: <File size={12} strokeWidth={2} className="flex-none text-content-muted" />}
<span className="min-w-0 flex-1 truncate text-content-secondary" style={fs(12, 'body')}>{file.original_name}</span>
{file.file_size ? <span className="flex-none tabular-nums text-content-faint" style={fs(11)}>{formatFileSize(file.file_size)}</span> : null}
</button>
))}
</div>
)}
</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>
</DialogSection>
)}
{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>}
{navigationTargets.length > 0 && (
<div className="flex flex-none items-center gap-1.5 text-content-faint" style={fs(11)}>
<MapPin size={12} strokeWidth={2} className="flex-none" />
{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>
/** Markdown in a framed box, like the inspector's; long words wrap instead of widening the card. */
function MarkdownBox({ children }: { children: string }) {
return (
<div className={`${BOX} collab-note-md px-3 py-2 text-content-secondary`}
style={{ ...fs(12.5, 'body'), lineHeight: 1.5, wordBreak: 'break-word', overflowWrap: 'anywhere' }}>
<Markdown remarkPlugins={[remarkGfm, remarkBreaks]} components={markdownLinkComponents}>{children}</Markdown>
</div>
)
}
+19 -49
View File
@@ -1,10 +1,7 @@
import type { ReactNode } from 'react'
import { useId, 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'
import { fs } from '../shared/DialogShell'
import { TourFactPills, TourTile } from './tourParts'
interface TourListRowProps {
tour: TourListItem
@@ -15,65 +12,38 @@ interface TourListRowProps {
children?: ReactNode
}
/** Shared Tours list row used by both the ADD flow and the planner workspace. */
/** A tour in a list, shaped like a place row: tile, name, its facts as pills and the day action on the right. */
export default function TourListRow({ tour, selected = false, disabled = false, onSelect, action, children }: TourListRowProps) {
const { t } = useTranslation()
const distanceUnit = useSettingsStore(state => state.settings.distance_unit)
const nameId = useId()
const tone = selected ? 'bg-surface-selected' : disabled ? '' : 'hover:bg-surface-hover'
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' }}
aria-labelledby={nameId}
className={`group mb-px rounded-[12px] px-2.5 py-2 outline-none transition-colors focus-visible:ring-2 focus-visible:ring-[color:var(--text-primary)] ${tone} ${disabled ? 'cursor-default opacity-60' : 'cursor-pointer'}`}
onClick={event => { if (!disabled) onSelect(tour, event.currentTarget) }}
onKeyDown={event => {
if (disabled) return
if (disabled || event.target !== event.currentTarget) 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 className="flex items-start gap-2.5">
<TourTile />
<div className="min-w-0 flex-1 pt-px">
<span id={nameId} className="block min-w-0 truncate font-semibold leading-tight text-content" style={fs(13, 'body')}>{tour.name}</span>
<TourFactPills tour={tour} className="mt-1.5" />
</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>}
{action && (
<div data-testid="tour-action-row" role="presentation" className="flex flex-none items-center pt-1" onClick={event => event.stopPropagation()}>
{action}
</div>
)}
</div>
{children}
</li>
@@ -55,7 +55,7 @@ describe('ToursSidebar', () => {
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)' })
expect(row).toHaveClass('bg-surface-selected')
})
it('selects the tour from keyboard activation', () => {
@@ -69,7 +69,7 @@ describe('ToursSidebar', () => {
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) => {
])('keeps %s title, fact pills and the day action in one place-style row', (language, name) => {
seedStore(useSettingsStore, { settings: { language, distance_unit: 'metric' } })
const onAssignToDay = vi.fn()
const { container } = render(<ToursSidebar
@@ -85,20 +85,19 @@ describe('ToursSidebar', () => {
const row = screen.getByRole('option', { name: new RegExp(name) })
expect(row).toHaveAttribute('aria-selected', 'true')
expect(row.querySelector('span[title]')).toHaveAttribute('title', name)
expect(row).toHaveTextContent(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')
const labels = [...metrics.querySelectorAll('[aria-label]')].map(element => element.getAttribute('aria-label'))
expect(labels[0]).toContain('1.9 km')
expect(labels[1]).toContain('13 m')
expect(labels[2]).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(actionRow.querySelector('button')).toHaveAttribute('aria-haspopup', 'menu')
expect(container.querySelector('[data-testid="tour-metrics"]')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: /Add to day|Zum Tag hinzufügen/ }))
@@ -130,7 +129,8 @@ describe('ToursSidebar', () => {
expect(onToursChanged).not.toHaveBeenCalled()
})
it('keeps the day picker open and does not refresh when assignment fails', async () => {
it('neither refreshes nor reports success when assignment fails', async () => {
toast.success.mockClear()
const onToursChanged = vi.fn()
render(<ToursSidebar
canAssign={true}
@@ -145,7 +145,8 @@ describe('ToursSidebar', () => {
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())
await act(async () => {})
expect(toast.success).not.toHaveBeenCalled()
expect(onToursChanged).not.toHaveBeenCalled()
})
+12 -48
View File
@@ -1,5 +1,5 @@
import React, { useEffect, useRef, useState } from 'react'
import { Check, ChevronDown, FileDown, Mountain } from 'lucide-react'
import { Check, ChevronDown, FileDown } from 'lucide-react'
import type { TourListItem } from '@trek/shared'
import type { Day } from '../../types'
import { toursApi } from '../../api/client'
@@ -10,6 +10,8 @@ import TourListRow from './TourListRow'
import { useTourPermissions, type TourPermissionProps } from './useTourPermissions'
import { NEUTRAL_TINT, fs } from '../shared/DialogShell'
import { Tooltip } from '../shared/Tooltip'
import EmptyState from '../shared/EmptyState'
import { TourDayMenu } from './tourParts'
const MAX_FILE_BYTES = 10 * 1024 * 1024
@@ -27,10 +29,6 @@ interface ToursSidebarProps extends TourPermissionProps {
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
@@ -48,7 +46,6 @@ export default function ToursSidebar({ tripId, days, tours, loading = false, sel
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)
@@ -90,7 +87,6 @@ export default function ToursSidebar({ tripId, days, tours, loading = false, sel
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 }))
}
@@ -170,53 +166,21 @@ export default function ToursSidebar({ tripId, days, tours, loading = false, sel
</div>
</div>
<div style={{ flex: 1, overflowY: 'auto', padding: '10px 16px 16px' }}>
<div className="trek-stagger min-h-0 flex-1 overflow-y-auto px-2 pb-2 pt-1.5">
{!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>
<EmptyState scene="tours" size={92} fill surface="var(--bg-secondary)" title={t('tours.empty.title')}
action={<p className="m-0 max-w-[240px] text-content-faint" style={fs(12, 'body')}>{t('tours.empty.body')}</p>} />
) : (
<ul className="space-y-2">
{filtered.map((tour) => {
const isSelected = tour.place_id === selectedPlaceId
return (
<ul role="listbox" aria-label={t('tours.mode.tours')} className="m-0 list-none p-0">
{filtered.map(tour => (
<TourListRow
key={tour.place_id}
tour={tour}
selected={isSelected}
selected={tour.place_id === selectedPlaceId}
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>
)
})}
action={<TourDayMenu days={days} label={t('tours.addToDay')} disabled={!canAssign} onPick={(day, index) => { void handleAssign(tour, day, index) }} />}
/>
))}
</ul>
)}
</div>
@@ -146,23 +146,24 @@ describe('TourPlannerToursRail', () => {
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"]')
const dayOption = screen.getByRole('button', { name: /Summit day/ })
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' } })
fireEvent.click(dayOption)
await waitFor(() => expect(onAssignToDay).toHaveBeenCalledWith(42, 7))
})
it('keeps the saved Tour day picker open when assignment fails', async () => {
it('keeps the saved outcome and its day action 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' } })
fireEvent.click(screen.getByRole('button', { name: /Summit day/ }))
await waitFor(() => expect(onAssignToDay).toHaveBeenCalledWith(42, 7))
expect(screen.getByLabelText('Pick a day')).toBeInTheDocument()
expect(screen.getByRole('status')).toHaveTextContent('Tour saved')
expect(screen.getByRole('button', { name: 'Assign to a day' })).toBeEnabled()
})
it('TOUR-PLANNER-RAIL-004: protects a dirty draft before selecting a GPX Tour', () => {
@@ -345,9 +346,8 @@ describe('TourPlannerRail', () => {
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' })
expect(firstNumber).toHaveClass('bg-accent', 'text-accent-text', 'font-geist', 'tabular-nums', 'h-7', 'w-7')
expect(secondNumber).toHaveClass('bg-surface-card', 'text-content', 'font-geist', 'tabular-nums', 'h-7', 'w-7')
})
it('TOUR-PLANNER-RAIL-007: acknowledges alpine routing once per planner session', () => {
@@ -409,7 +409,7 @@ describe('TourPlannerRail', () => {
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()
expect(screen.getByText('Start a new tour and click the map to place its waypoints.')).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'Plan new tour' }))
expect(controller.startNewTour).toHaveBeenCalledOnce()
expect(screen.queryByLabelText('Tour name')).not.toBeInTheDocument()
@@ -1,21 +1,24 @@
import { useRef, useState } from 'react'
import { useRef, useState, type ReactNode } 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 { AlertTriangle, ArrowDown, ArrowLeft, ArrowUp, CheckCircle2, Info, MapPin, 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 { DialogButton, NEUTRAL_TINT, fs } from '../../shared/DialogShell'
import { INPUT, LABEL } from '../../shared/dialogParts'
import EmptyState from '../../shared/EmptyState'
import { useToast } from '../../shared/Toast'
import { BarButton } from '../../Planner/planParts'
import { Tooltip } from '../../shared/Tooltip'
import { BOX } from '../../Planner/bookings/bookingParts'
import { BarButton, SoftPill } from '../../Planner/planParts'
import TourListRow from '../TourListRow'
import ElevationProfile from '../../shared/ElevationProfile'
import { hikeSourceBadgeLabel, tourSource } from '../tourPresentation'
import type { RouteProfileFocus } from '../../../utils/routeGeometry'
import { FoldButton, TourDayMenu, TourMetricFields, TourNotice, TourSection } from '../tourParts'
import type { DistanceIndexedProfileSample, RouteProfileFocus } from '../../../utils/routeGeometry'
import type { TourPlannerController, TourPlannerStatus } from './useTourPlanner'
import { useTourPermissions, type TourPermissionProps } from '../useTourPermissions'
@@ -30,17 +33,35 @@ const STATUS_KEY: Partial<Record<TourPlannerStatus, string>> = {
saved: 'tours.planner.saved',
}
/** The tinted head band both rails open with, like every panel head in the planner. */
const RAIL_HEAD = 'flex flex-none items-start gap-2 border-b border-edge-faint px-3 py-2.5'
type Translate = (key: string, params?: Record<string, string | number | null>) => string
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 {
function profileFocusLabel(focus: RouteProfileFocus, t: Translate, unit: 'metric' | 'imperial'): string {
return t('tours.planner.inspector.profileFocus', {
distance: formatDistance(focus.distanceMeters / 1000, unit),
elevation: focus.elevationMeters == null ? '—' : formatElevation(focus.elevationMeters, unit),
elevation: focus.elevationMeters == null ? '-' : formatElevation(focus.elevationMeters, unit),
})
}
/** The title of a rail's head band, with an optional line under it. */
function RailTitle({ title, sub, aside }: { title: string; sub?: ReactNode; aside?: ReactNode }) {
return (
<div className="min-w-0 flex-1 pt-[5px]">
<div className="flex min-w-0 items-center gap-1.5">
<h2 className="m-0 min-w-0 truncate font-bold tracking-[-0.01em] text-content" style={fs(14, 'body')}>{title}</h2>
{aside}
</div>
{sub && <p className="m-0 mt-0.5 leading-snug text-content-faint" style={fs(11.5, 'body')}>{sub}</p>}
</div>
)
}
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()
@@ -59,25 +80,25 @@ export function TourPlannerRail({ planner, canEdit: editPermission, canAssign: a
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 className="flex h-full min-h-0 flex-col" aria-label={t('tours.planner.title')}>
<div className={RAIL_HEAD} style={{ background: NEUTRAL_TINT }}>
<button type="button" disabled={!canEdit} onClick={() => { if (canEdit) planner.startNewTour() }}
className="flex h-8 min-w-0 flex-1 items-center justify-center gap-1.5 overflow-hidden whitespace-nowrap 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')}>
<Plus size={14} strokeWidth={2.2} className="flex-none" />
<span className="truncate">{t('tours.planner.newTour')}</span>
</button>
</div>
<div className="min-h-0 flex-1 overflow-y-auto">
<EmptyState
scene="tours"
size={116}
fill
surface="var(--bg-secondary)"
title={t('tours.planner.neutralTitle')}
action={<p className="m-0 max-w-[260px] text-content-muted" style={fs(12, 'body')}>{t('tours.planner.neutralBody')}</p>}
/>
</div>
</section>
)
}
@@ -85,61 +106,34 @@ export function TourPlannerRail({ planner, canEdit: editPermission, canAssign: a
if (planner.mode.type === 'view-gpx') {
const { tour } = planner.readOnlyGpxTour
const analysis = planner.readOnlyGpxAnalysis
const extra = tour.duration != null
? [{ label: t('tours.planner.inspector.duration'), value: t('tours.durationMinutes', { count: Math.max(1, Math.round(tour.duration)) }) }]
: []
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} />
<section className="flex h-full min-h-0 flex-col" aria-label={tour.name}>
<div className={RAIL_HEAD} style={{ background: NEUTRAL_TINT }}>
<BarButton label={t('tours.planner.backToTours')} onClick={() => planner.returnToNeutral()} className="focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent">
<ArrowLeft size={16} strokeWidth={2} />
</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>
<RailTitle title={t('tours.planner.gpxTitle')} sub={tour.name} aside={<SoftPill>{hikeSourceBadgeLabel(tour, t)}</SoftPill>} />
</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>
<div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-3 py-3.5">
<TourNotice icon={<Info size={13} strokeWidth={2} className="text-content-faint" />}>{t('tours.detail.gpxReadOnly')}</TourNotice>
{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>
<>
<TourSection label={t('tours.planner.inspector.title')}>
<TourMetricFields analysis={analysis} unit={distanceUnit} extra={extra} columns={2} />
</TourSection>
<ElevationSection
id="tour-planner-gpx-elevation-profile"
samples={analysis.distanceIndexedProfileSamples}
gradientId={`planner-gpx-elevation-${tour.place_id}`}
planner={planner}
/>
</>
) : (
<p className="mt-5 text-xs text-content-secondary">{t('tours.planner.gpxNoGeometry')}</p>
<TourNotice>{t('tours.planner.gpxNoGeometry')}</TourNotice>
)}
</div>
</section>
@@ -149,125 +143,142 @@ export function TourPlannerRail({ planner, canEdit: editPermission, canAssign: a
}
const isSavedEdit = planner.mode.type === 'edit-saved'
const lastIndex = planner.waypoints.length - 1
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>}
<section className="flex h-full min-h-0 flex-col" aria-label={t('tours.planner.title')}>
<div className={RAIL_HEAD} style={{ background: NEUTRAL_TINT }}>
<BarButton label={t('tours.planner.backToTours')} onClick={() => requestClose()} disabled={isSaving} className="focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent">
<ArrowLeft size={16} strokeWidth={2} />
</BarButton>
<RailTitle title={t(isSavedEdit ? 'tours.planner.editTitle' : 'tours.planner.newTitle')} sub={t('tours.planner.mapHint')} />
<BarButton label={t('tours.planner.undo')} onClick={() => { if (canEdit && !isSaving) planner.undo() }} disabled={!canEdit || isSaving || !planner.canUndo}>
<Undo2 size={15} strokeWidth={2} />
</BarButton>
<BarButton label={t('tours.planner.redo')} onClick={() => { if (canEdit && !isSaving) planner.redo() }} disabled={!canEdit || isSaving || !planner.canRedo}>
<Redo2 size={15} strokeWidth={2} />
</BarButton>
</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>
<div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-3 py-3.5">
{planner.draftRestored && planner.hasUnsavedChanges && (
<TourNotice role="status" icon={<RotateCcw size={13} strokeWidth={2} className="text-content-faint" />}>{t('tours.planner.restored')}</TourNotice>
)}
<div className="flex flex-col gap-3">
<div className="min-w-0">
<label className={LABEL} 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={INPUT}
/>
</div>
<div className="min-w-0">
<label className={LABEL} 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}`) }))}
/>
</div>
{planner.maxHikingDifficulty === 3 && (
<TourNotice tone="warning" role="status" icon={<AlertTriangle size={13} strokeWidth={2} />}>{t('tours.planner.difficulty.t3Warning')}</TourNotice>
)}
</div>
<TourSection label={t('tours.planner.waypoints')}>
{planner.waypoints.length === 0 ? (
<div data-testid="tour-planner-empty-state" className="flex items-start gap-2 rounded-[12px] border border-dashed border-edge px-3 py-3 leading-snug text-content-muted" style={fs(12, 'body')}>
<MapPin size={14} strokeWidth={2} className="mt-px flex-none text-content-faint" />
<p className="m-0">{t('tours.planner.startingPoint')} {t('tours.planner.firstUseDetails')}</p>
</div>
) : (
<ol className="m-0 flex list-none flex-col gap-px p-0">
{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={`group flex w-full items-center gap-2.5 rounded-[12px] px-2 py-1.5 text-left outline-none transition-colors focus-visible:ring-2 focus-visible:ring-[color:var(--text-primary)] ${selected ? 'bg-surface-selected' : '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={`grid h-7 w-7 flex-none place-items-center rounded-[9px] font-geist font-semibold tabular-nums shadow-sm ${selected ? 'bg-accent text-accent-text' : 'bg-surface-card text-content'}`}
style={fs(11.5)}
>
{index + 1}
</span>
<span className="min-w-0 flex-1">
<span className="block font-semibold leading-tight text-content" style={fs(12.5, 'body')}>{roleLabel(point.role, t)}</span>
<span className="mt-0.5 block truncate font-geist tabular-nums text-content-faint" style={fs(10.5)}>{point.lat.toFixed(5)}, {point.lng.toFixed(5)}</span>
</span>
{canEdit && (
<span className={`flex flex-none items-center gap-0.5 transition-opacity ${selected ? '' : 'opacity-50 group-hover:opacity-100 group-focus-within:opacity-100'}`}>
<WaypointAction label={t('tours.planner.moveUp')} disabled={isSaving || index === 0} onAct={() => planner.moveWaypoint(point.id, -1)}>
<ArrowUp size={13} strokeWidth={2.2} />
</WaypointAction>
<WaypointAction label={t('tours.planner.moveDown')} disabled={isSaving || index === lastIndex} onAct={() => planner.moveWaypoint(point.id, 1)}>
<ArrowDown size={13} strokeWidth={2.2} />
</WaypointAction>
<WaypointAction label={t('tours.planner.remove')} disabled={isSaving} danger onAct={() => planner.removeWaypoint(point.id)}>
<Trash2 size={13} strokeWidth={2} />
</WaypointAction>
</span>
)}
</button>
</li>
)
})}
</ol>
)}
</TourSection>
{(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">
<TourNotice
role="status"
tone={planner.error ? 'warning' : 'neutral'}
icon={planner.error ? <AlertTriangle size={13} strokeWidth={2} /> : <Info size={13} strokeWidth={2} className="text-content-faint" />}
>
{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>
{canRetry && (
<button type="button" onClick={planner.retry}
className="ml-2 inline-flex items-center rounded-full bg-surface-card px-2 py-[1px] font-semibold text-content shadow-sm hover:bg-surface-secondary"
style={fs(11)}>
{t('tours.planner.retry')}
</button>
)}
</TourNotice>
)}
</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" />
<div className="flex flex-none flex-col gap-2.5 border-t border-edge-faint px-3 py-3">
<p className="m-0 flex items-start gap-1.5 leading-snug text-content-faint" style={fs(11)}>
<ShieldAlert size={13} strokeWidth={2} className="mt-px flex-none" />
<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)}>
<div className="grid grid-cols-[auto_1fr] gap-2 [&>button]:justify-center">
<DialogButton icon={<RotateCcw size={14} strokeWidth={2} />} 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}>
<DialogButton variant="primary" icon={<Save size={14} strokeWidth={2} />} onClick={() => { if (canEdit && !isSaving) void planner.save() }} disabled={!canEdit || isSaving || !planner.canSave}>
{t(isSavedEdit ? 'tours.planner.saveChanges' : 'tours.planner.save')}
</DialogButton>
</div>
@@ -301,22 +312,59 @@ export function TourPlannerRail({ planner, canEdit: editPermission, canAssign: a
)
}
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>
/** A quiet icon control on a waypoint row; a span, because the row itself is the button. */
function WaypointAction({ label, disabled, danger = false, onAct, children }: { label: string; disabled: boolean; danger?: boolean; onAct: () => void; children: ReactNode }) {
return (
<Tooltip label={label}>
<span
role="button"
tabIndex={disabled ? -1 : 0}
aria-label={label}
aria-disabled={disabled}
onClick={event => { event.stopPropagation(); if (!disabled) onAct() }}
onKeyDown={event => { if (!disabled && event.key === 'Enter') { event.stopPropagation(); onAct() } }}
className={`grid h-6 w-6 place-items-center rounded-full transition-colors ${disabled ? 'pointer-events-none opacity-25' : danger ? 'text-danger hover:bg-surface-card' : 'text-content-muted hover:bg-surface-card hover:text-content'}`}
>
{children}
</span>
</Tooltip>
)
}
function ElevationProfileToggle({ id, expanded, onToggle, t }: { id: string; expanded: boolean; onToggle: () => void; t: (key: string) => string }) {
/** The elevation profile under its label, folded away with the chevron beside it. */
function ElevationSection({ id, samples, gradientId, planner }: {
id: string
samples: DistanceIndexedProfileSample[]
gradientId: string
planner: TourPlannerController
}) {
const { t } = useTranslation()
const distanceUnit = useSettingsStore(state => state.settings.distance_unit)
if (samples.length < 2) {
return (
<TourSection label={t('tours.planner.inspector.elevation')}>
<TourNotice>{t('tours.planner.inspector.elevationPlaceholder')}</TourNotice>
</TourSection>
)
}
const expanded = planner.elevationProfileExpanded
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"
<TourSection
label={t('tours.planner.inspector.elevation')}
action={<FoldButton expanded={expanded} onToggle={planner.toggleElevationProfile} controls={id} label={t(expanded ? 'tours.planner.collapseElevation' : 'tours.planner.expandElevation')} />}
>
<ChevronDown size={15} className={expanded ? '' : '-rotate-90'} />
</button>
<div id={id} hidden={!expanded} className={`${BOX} p-2`}>
{expanded && <ElevationProfile
samples={samples}
color="var(--text-secondary)"
gradientId={gradientId}
ariaLabel={t('tours.planner.inspector.elevation')}
focus={planner.routeProfileFocus}
onFocusChange={planner.setRouteProfileFocus}
formatFocus={focus => profileFocusLabel(focus, t, distanceUnit)}
/>}
</div>
</TourSection>
)
}
@@ -343,19 +391,12 @@ interface TourPlannerToursRailProps extends TourPermissionProps {
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 { t } = 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
@@ -385,135 +426,87 @@ export function TourPlannerToursRail({ planner, tours, days, loading, onAssignTo
if (!canAssign || !savedTour) return
setAssigning(true)
try {
const assigned = await onAssignToDay(savedTour.place_id, dayId)
if (assigned === false) return
setDayPickerOpen(false)
await onAssignToDay(savedTour.place_id, dayId)
} finally {
setAssigning(false)
}
}
const walkingTime = { label: t('tours.planner.inspector.duration'), value: t('tours.durationMinutes', { count: Math.max(1, Math.round((planner.durationSeconds ?? 0) / 60)) }) }
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>}
</>
)}
<aside className="flex h-full min-h-0 flex-col" aria-label={t('tours.planner.tripTours')}>
<div className={RAIL_HEAD} style={{ background: NEUTRAL_TINT }}>
<RailTitle title={t('tours.planner.tripTours')} sub={t('tours.subtitle')} />
</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}
<div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-3 py-3.5">
{hasRoute && (
<>
<TourSection label={t('tours.planner.inspector.title')}>
<TourMetricFields analysis={routeAnalysis} unit={distanceUnit} extra={[walkingTime]} columns={2} />
</TourSection>
{routeAnalysis && (
<ElevationSection
id="tour-planner-editable-elevation-profile"
samples={routeAnalysis.distanceIndexedProfileSamples}
gradientId={`planner-editable-elevation-${planner.editingPlaceId ?? 'draft'}`}
planner={planner}
/>
))}
</ul>
)}
</>
)}
{planner.saveOutcome && (
<div className={`${BOX} flex flex-col gap-3 p-3`} role="status">
<div className="flex items-center gap-2 font-semibold text-content" style={fs(13, 'body')}>
<CheckCircle2 size={16} strokeWidth={2} className="flex-none text-success" />
{t('tours.planner.saved')}
</div>
<div className="flex flex-wrap gap-2">
<DialogButton onClick={() => { if (canEdit && !isSaving) planner.startNewTour() }} disabled={!canEdit || isSaving}>
{t('tours.planner.planAnother')}
</DialogButton>
<TourDayMenu
variant="button"
primary
days={days}
label={t('tours.planner.assignToDay')}
disabled={!canAssign || assigning}
onPick={day => { void assignSavedTour(day.id) }}
/>
</div>
</div>
)}
<TourSection label={t('tours.mode.tours')}>
{loading && tours.length === 0 ? (
<p className="m-0 py-6 text-center text-content-faint" style={fs(12, 'body')}>{t('common.loading')}</p>
) : tours.length === 0 ? (
<EmptyState scene="tours" size={80} surface="var(--bg-secondary)" title={t('tours.empty.title')}
className="!py-6"
action={<p className="m-0 max-w-[240px] text-content-faint" style={fs(12, 'body')}>{t('tours.empty.body')}</p>} />
) : (
<ul role="listbox" aria-label={t('tours.planner.tripTours')} className="-mx-1 m-0 list-none p-0">
{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 ? (
<TourDayMenu
days={days}
label={`${t('tours.addToDay')}: ${tour.name}`}
onPick={day => { if (canAssign) void onAssignToDay(tour.place_id, day.id) }}
/>
) : undefined}
/>
))}
</ul>
)}
</TourSection>
</div>
<ConfirmDialog
+182
View File
@@ -0,0 +1,182 @@
import type { ReactNode } from 'react'
import type { TourListItem } from '@trek/shared'
import { AlertTriangle, ArrowDown, ArrowUp, ChevronDown, Mountain, Plus, Ruler } from 'lucide-react'
import type { Day, DistanceUnit } from '../../types'
import type { RouteGeometryAnalysis } from '../../utils/routeGeometry'
import { useTranslation } from '../../i18n'
import { useSettingsStore } from '../../store/settingsStore'
import { formatDistance, formatElevation } from '../../utils/units'
import { formatDate } from '../../utils/formatters'
import { ContextMenu, useContextMenu } from '../shared/ContextMenu'
import { DialogButton, fs } from '../shared/DialogShell'
import { Tooltip } from '../shared/Tooltip'
import { BOX, Eyebrow } from '../Planner/bookings/bookingParts'
import { SoftPill } from '../Planner/planParts'
import { hikeSourceBadgeLabel } from './tourPresentation'
type Translate = (key: string, params?: Record<string, unknown>) => string
/** The round tile a tour stands behind in a list, where a place has its avatar. */
export function TourTile({ size = 34, color, raised = false }: { size?: number; color?: string; raised?: boolean }) {
return (
<span className={`grid flex-none place-items-center rounded-full ${raised ? 'bg-surface-card shadow-sm' : 'bg-surface-tertiary'}`} style={{ width: size, height: size }}>
<Mountain size={Math.round(size * 0.44)} strokeWidth={1.9} style={{ color: color ?? 'var(--text-muted)' }} />
</span>
)
}
/** The facts of a tour as white pills: how far, how much up and down, how hard, where it came from. */
export function TourFactPills({ tour, className = '' }: { tour: TourListItem; className?: string }) {
const { t } = useTranslation()
const unit = useSettingsStore(state => state.settings.distance_unit)
const difficulty = t(`tours.planner.difficulty.t${tour.max_hiking_difficulty}`)
return (
<div data-testid="tour-metrics" className={`flex min-w-0 flex-wrap items-center gap-1 ${className}`}>
<SoftPill className="tabular-nums" icon={<Ruler size={10} strokeWidth={2.2} className="flex-none text-content-faint" />}>
<span aria-label={`${t('tours.detail.distance')}: ${formatDistance(tour.distance ?? 0, unit)}`}>{formatDistance(tour.distance ?? 0, unit)}</span>
</SoftPill>
{tour.elevation_gain != null && (
<SoftPill className="tabular-nums" icon={<ArrowUp size={10} strokeWidth={2.2} className="flex-none text-content-faint" />}>
<span aria-label={`${t('tours.detail.ascent')}: ${formatElevation(tour.elevation_gain, unit)}`}>{formatElevation(tour.elevation_gain, unit)}</span>
</SoftPill>
)}
{tour.elevation_loss != null && (
<SoftPill className="tabular-nums" icon={<ArrowDown size={10} strokeWidth={2.2} className="flex-none text-content-faint" />}>
<span aria-label={`${t('tours.detail.descent')}: ${formatElevation(tour.elevation_loss, unit)}`}>{formatElevation(tour.elevation_loss, unit)}</span>
</SoftPill>
)}
<Tooltip label={difficulty}>
<span aria-label={difficulty} className="inline-flex">
<SoftPill>T{tour.max_hiking_difficulty}</SoftPill>
</span>
</Tooltip>
<SoftPill>{hikeSourceBadgeLabel(tour, t)}</SoftPill>
{tour.caution && (
<Tooltip label={t('tours.caution.tooltip')}>
<span aria-label={t('tours.caution.badge')} className="inline-flex">
<SoftPill tone="warning" icon={<AlertTriangle size={10} strokeWidth={2.2} className="flex-none" />}>{t('tours.caution.badge')}</SoftPill>
</span>
</Tooltip>
)}
</div>
)
}
/** "Day 2, Tue, Jul 8: Lakes" as far as the day has a date and a title. */
function dayMenuLabel(day: Day, index: number, t: Translate, locale: string): string {
const date = formatDate(day.date, locale)
const head = date ? `${t('dayplan.dayN', { n: index + 1 })}, ${date}` : t('dayplan.dayN', { n: index + 1 })
return day.title ? `${head}: ${day.title}` : head
}
/**
* Putting a tour on a day: a round "+" on a row, or a footer button with a
* chevron, both opening the trip's days as a menu.
*/
export function TourDayMenu({ days, onPick, disabled = false, label, variant = 'round', primary = false }: {
days: Day[]
onPick: (day: Day, index: number) => void
disabled?: boolean
label: string
variant?: 'round' | 'button'
primary?: boolean
}) {
const { t, locale } = useTranslation()
const menu = useContextMenu()
const items = days.map((day, index) => ({ label: dayMenuLabel(day, index, t, locale), onClick: () => onPick(day, index) }))
const open = (event: React.MouseEvent<HTMLButtonElement>) => {
if (disabled || items.length === 0) return
if (menu.menu) { event.stopPropagation(); menu.close(); return }
menu.open(event, items, true)
}
return (
<>
{variant === 'round' ? (
<Tooltip label={label} disabled={!!menu.menu}>
<button type="button" onClick={open} disabled={disabled || items.length === 0} aria-label={label} aria-haspopup="menu" aria-expanded={!!menu.menu}
className={`grid h-[26px] w-[26px] flex-none place-items-center rounded-full shadow-sm ring-1 transition-colors disabled:cursor-default disabled:opacity-40 ${menu.menu ? 'bg-accent text-accent-text ring-transparent' : 'bg-surface-card text-content-muted ring-edge-faint enabled:hover:bg-accent enabled:hover:text-accent-text enabled:hover:ring-transparent'}`}>
<Plus size={13} strokeWidth={2.4} />
</button>
</Tooltip>
) : (
<DialogButton variant={primary ? 'primary' : 'secondary'} onClick={open} disabled={disabled || items.length === 0}
aria-haspopup="menu" aria-expanded={!!menu.menu} icon={<Plus size={14} strokeWidth={2} />}>
{label}
<ChevronDown size={13} strokeWidth={2.2} className={`transition-transform ${menu.menu ? 'rotate-180' : ''}`} />
</DialogButton>
)}
<ContextMenu menu={disabled ? null : menu.menu} onClose={menu.close} />
</>
)
}
/** A labelled block of a tour panel: the eyebrow, an optional control on its right, then the content. */
export function TourSection({ label, action, children, className = '' }: { label: ReactNode; action?: ReactNode; children: ReactNode; className?: string }) {
return (
<section className={className}>
<div className="mb-2 flex min-h-[18px] items-center gap-2">
<Eyebrow>{label}</Eyebrow>
{action && <span className="ml-auto flex items-center">{action}</span>}
</div>
{children}
</section>
)
}
/** One sentence the panel has to say (read-only, a warning, a status), in the card look. */
export function TourNotice({ tone = 'neutral', icon, children, role }: { tone?: 'neutral' | 'warning'; icon?: ReactNode; children: ReactNode; role?: 'status' }) {
const look = tone === 'warning'
? 'border-transparent bg-warning-soft text-warning'
: 'border-edge-faint bg-surface-card text-content-muted'
return (
<div role={role} className={`flex items-start gap-2 rounded-[10px] border px-3 py-2 leading-snug ${look}`} style={fs(12, 'body')}>
{icon && <span className="mt-[2px] flex-none">{icon}</span>}
<div className="min-w-0 flex-1">{children}</div>
</div>
)
}
/** The chevron that folds a section away, quiet like the rest of a panel's controls. */
export function FoldButton({ expanded, onToggle, controls, label }: { expanded: boolean; onToggle: () => void; controls: string; label: string }) {
return (
<Tooltip label={label}>
<button type="button" onClick={onToggle} aria-expanded={expanded} aria-controls={controls} aria-label={label}
className="grid h-6 w-6 place-items-center rounded-full text-content-faint transition-colors hover:bg-surface-card hover:text-content focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent">
<ChevronDown size={14} strokeWidth={2.2} className={`transition-transform ${expanded ? '' : '-rotate-90'}`} />
</button>
</Tooltip>
)
}
/**
* A tour's numbers as labelled fields, the way a booking card shows its facts:
* distance, any extra the caller has (the walking time), then the altitudes.
*/
export function TourMetricFields({ analysis, unit, extra = [], columns }: {
analysis: Pick<RouteGeometryAnalysis, 'distanceKm' | 'minEle' | 'maxEle' | 'gain' | 'loss'> | null
unit?: DistanceUnit
extra?: Array<{ label: string; value: string }>
/** A fixed column count for a narrow rail; the inspector lets the fields flow. */
columns?: 2
}) {
const { t } = useTranslation()
const fields: Array<{ label: string; value: string }> = [
{ label: t('tours.detail.distance'), value: analysis ? formatDistance(analysis.distanceKm, unit) : '-' },
...extra,
]
if (analysis?.minEle != null) fields.push({ label: t('tours.detail.minAltitude'), value: formatElevation(analysis.minEle, unit) })
if (analysis?.maxEle != null) fields.push({ label: t('tours.detail.maxAltitude'), value: formatElevation(analysis.maxEle, unit) })
if (analysis?.gain != null) fields.push({ label: t('tours.detail.ascent'), value: formatElevation(analysis.gain, unit) })
if (analysis?.loss != null) fields.push({ label: t('tours.detail.descent'), value: formatElevation(analysis.loss, unit) })
const grid = columns === 2 ? 'grid-cols-2' : 'grid-cols-[repeat(auto-fit,minmax(104px,1fr))]'
return (
<dl className={`m-0 grid gap-2 ${grid}`}>
{fields.map(field => (
<div key={field.label} className="min-w-0">
<dt><Eyebrow className="mb-[3px] truncate">{field.label}</Eyebrow></dt>
<dd className={`${BOX} m-0 truncate px-[10px] py-[7px] text-center font-semibold tabular-nums text-content`} style={fs(12.5, 'body')}>{field.value}</dd>
</div>
))}
</dl>
)
}
@@ -118,12 +118,11 @@ describe('Tours English and German copy', () => {
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()
await waitFor(() => expect(screen.getByLabelText(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()
expect(screen.getByRole('button', { name: /Tag 1.*Gipfeltag/ })).toBeInTheDocument()
assertNoRawToursKeys()
})
@@ -107,6 +107,7 @@ describe('Tours permissions without database setup', () => {
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: 'inspector.trackColorAuto' }))
fireEvent.click(screen.getByRole('button', { name: 'color' }))
expect(update).toHaveBeenCalledWith(42, { route_color: '#ff0000' })
fireEvent.click(screen.getByRole('button', { name: 'common.edit' }))
@@ -145,9 +146,12 @@ describe('Tours permissions without database setup', () => {
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' })
const picker = screen.queryByRole('button', { name: 'tours.addToDay: Ridge' })
expect(Boolean(picker)).toBe(canAssign)
if (picker) fireEvent.change(picker, { target: { value: '3' } })
if (picker) {
fireEvent.click(picker)
fireEvent.click(screen.getByRole('button', { name: /Summit/ }))
}
expect(assign).toHaveBeenCalledTimes(canAssign ? 1 : 0)
fireEvent.click(screen.getByRole('option', { name: /Ridge/ }))
expect(planner.openTour).toHaveBeenCalledWith(tour)
@@ -72,7 +72,7 @@ describe('CustomSelect consumer contracts', () => {
expect(setDifficulty).toHaveBeenLastCalledWith(4)
})
it('keeps the labelled native post-save day picker resolving numeric day ids', async () => {
it('keeps the post-save day menu resolving numeric day ids', async () => {
const user = userEvent.setup()
const onAssignToDay = vi.fn().mockResolvedValue(undefined)
render(<TranslationProvider><TourPlannerToursRail
@@ -81,9 +81,7 @@ describe('CustomSelect consumer contracts', () => {
tours={[tour]} days={days} loading={false} onAssignToDay={onAssignToDay} onViewGpxTour={vi.fn()}
/></TranslationProvider>)
await user.click(screen.getByRole('button', { name: 'Assign to a day' }))
const picker = screen.getByRole('combobox', { name: 'Pick a day' })
expect(picker).toHaveAttribute('id', 'tour-planner-assign-day')
await user.selectOptions(picker, '7')
await user.click(screen.getByRole('button', { name: /Day 1/ }))
expect(onAssignToDay).toHaveBeenCalledWith(42, 7)
})
+23 -38
View File
@@ -1,5 +1,7 @@
import type { CSSProperties, ReactNode } from 'react'
import type { ReactNode } from 'react'
import { X } from 'lucide-react'
import { NEUTRAL_TINT } from './DialogShell'
import { Tooltip } from './Tooltip'
interface DetailShellProps {
header: ReactNode
@@ -9,13 +11,17 @@ interface DetailShellProps {
closeLabel: string
leftWidth?: number
rightWidth?: number
headerStyle?: CSSProperties
contentStyle?: CSSProperties
/** The head band's background; the neutral accent wash when left out. */
tint?: string
closeButtonClassName?: string
testId?: string
}
/** Shared map-detail surface: panel-aware positioning, chrome and scrolling. */
/**
* The card a selected item opens over the map, in the place inspector's frame:
* centred between the planner panels, a tinted head band with the close button,
* a body that scrolls and a footer that stays in reach.
*/
export default function DetailShell({
header,
children,
@@ -24,8 +30,7 @@ export default function DetailShell({
closeLabel,
leftWidth = 0,
rightWidth = 0,
headerStyle,
contentStyle,
tint = NEUTRAL_TINT,
closeButtonClassName = '',
testId,
}: DetailShellProps) {
@@ -41,43 +46,23 @@ export default function DetailShell({
fontFamily: 'var(--font-system)',
}}
>
<div
className="bg-surface-elevated text-content"
style={{
backdropFilter: 'blur(40px) saturate(180%)',
WebkitBackdropFilter: 'blur(40px) saturate(180%)',
borderRadius: 20,
boxShadow: '0 8px 40px rgba(0,0,0,0.14), 0 0 0 1px rgba(0,0,0,0.06)',
overflow: 'hidden',
maxHeight: '60vh',
display: 'flex',
flexDirection: 'column',
}}
>
<div className="border-b border-edge-faint" style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '18px 16px 14px', flexShrink: 0, ...headerStyle }}>
<div className="flex max-h-[60vh] flex-col overflow-hidden rounded-[20px] border border-edge-faint bg-surface-elevated text-content shadow-popover backdrop-blur-[40px] backdrop-saturate-[1.8]">
<header className="flex flex-none items-start gap-3.5 border-b border-edge-faint px-4 pb-3 pt-3.5" style={{ background: tint }}>
{header}
<button
type="button"
onClick={onClose}
aria-label={closeLabel}
className={`bg-surface-hover ${closeButtonClassName}`}
style={{ width: 28, height: 28, borderRadius: '50%', border: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', flexShrink: 0, alignSelf: 'flex-start', transition: 'background 0.15s' }}
onMouseEnter={event => { event.currentTarget.style.background = 'var(--bg-tertiary)' }}
onMouseLeave={event => { event.currentTarget.style.background = 'var(--bg-hover)' }}
>
<X size={14} strokeWidth={2} color="var(--text-secondary)" />
</button>
</div>
<div
data-testid={testId}
style={{ flex: '1 1 auto', minHeight: 0, overflowY: 'auto', WebkitOverflowScrolling: 'touch', overscrollBehavior: 'contain', padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: 10, ...contentStyle }}
>
<Tooltip label={closeLabel}>
<button type="button" onClick={onClose} aria-label={closeLabel}
className={`grid h-8 w-8 flex-none place-items-center rounded-full bg-surface-card text-content-muted shadow-sm transition-colors hover:text-content ${closeButtonClassName}`}>
<X size={15} strokeWidth={2.2} />
</button>
</Tooltip>
</header>
<div data-testid={testId} className="flex min-h-0 flex-1 flex-col gap-3.5 overflow-y-auto overscroll-contain px-4 py-3.5">
{children}
</div>
{footer && (
<div className="border-t border-edge-faint" style={{ padding: '10px 16px', display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap', flexShrink: 0 }}>
<footer className="flex flex-none flex-wrap items-center gap-2 border-t border-edge-faint px-4 py-2.5">
{footer}
</div>
</footer>
)}
</div>
</div>