feat(tours): hiking-rule walking time, source marks in the map search, tour rows and status badges reworked, ferrata card in the map glass

This commit is contained in:
Maurice
2026-10-14 17:45:31 +02:00
parent a805b4b882
commit 6d43f3a4e6
42 changed files with 385 additions and 120 deletions
@@ -1,12 +1,11 @@
import { AlertTriangle, Info } from 'lucide-react';
import { useId, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
import { AlertTriangle } from 'lucide-react';
import { useLayoutEffect, useRef, useState, type ReactNode } from 'react';
import { useTranslation } from '../../../i18n';
import { SoftPill } from '../../Planner/planParts';
import CustomSelect from '../../shared/CustomSelect';
import { INPUT, LABEL } from '../../shared/dialogParts';
import { fs } from '../../shared/DialogShell';
import { Tooltip } from '../../shared/Tooltip';
import { FoldButton, TourNotice, TourSection } from '../tourParts';
import { FoldButton, InfoDot, TourNotice, TourSection } from '../tourParts';
import { TOUR_DURATION_INPUT_MAX_LENGTH, formatTourDuration, parseTourDuration } from './tourDurationInput';
import type { TourPlannerController } from './useTourPlanner';
@@ -39,26 +38,6 @@ function writeDetailsOpen(open: boolean) {
}
}
/** The round info dot beside a label; hover, focus and a tap show the explanation as a tooltip. */
export function InfoDot({ description, label }: { description: string; label: string }) {
const id = useId();
return (
<Tooltip label={description}>
<button
type="button"
aria-label={label}
aria-describedby={id}
className="grid h-5 w-5 flex-none 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"
>
<Info size={13} strokeWidth={2} aria-hidden="true" />
<span id={id} className="sr-only">
{description}
</span>
</button>
</Tooltip>
);
}
/** A field label with what belongs beside it (an info dot, a badge) on the same line. */
function FieldLabel({ htmlFor, children, aside }: { htmlFor: string; children: ReactNode; aside?: ReactNode }) {
return (
@@ -195,7 +195,6 @@ describe('TourPlannerToursRail', () => {
fireEvent.click(screen.getByRole('button', { name: /Summit day/ }))
await waitFor(() => expect(onAssignToDay).toHaveBeenCalledWith(42, 7))
expect(screen.getByRole('status')).toHaveTextContent('Tour saved')
expect(screen.queryByRole('button', { name: 'Assign to a day' })).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Add to day: Saved ridge walk' })).toBeEnabled()
})
@@ -563,7 +562,7 @@ describe('TourPlannerRail', () => {
expect(screen.getAllByLabelText('Move waypoint up').every(element => element.getAttribute('aria-disabled') === 'true')).toBe(true)
expect(screen.getAllByLabelText('Move waypoint down').every(element => element.getAttribute('aria-disabled') === 'true')).toBe(true)
expect(screen.getAllByLabelText('Remove waypoint').every(element => element.getAttribute('aria-disabled') === 'true')).toBe(true)
expect(screen.getByRole('status')).toHaveTextContent('Saving…')
expect(within(screen.getByRole('status')).getByLabelText('Saving…')).toBeInTheDocument()
})
it('TOUR-PLANNER-RAIL-006: places the safety note beside Save and numbers rows like map pins', () => {
@@ -813,12 +812,10 @@ describe('TourPlannerRail', () => {
it('TOUR-PLANNER-RAIL-019: restored new and saved drafts show a non-blocking notice', () => {
const { rerender } = render(<TourPlannerRail planner={planner({ draftRestored: true, hasUnsavedChanges: true, mode: { type: 'new-draft' } })} />)
expect(screen.getByRole('status')).toHaveTextContent('Draft')
expect(screen.getByLabelText('Unsaved draft restored')).toBeInTheDocument()
expect(screen.getByRole('heading', { name: 'New tour' })).toBeInTheDocument()
rerender(<TourPlannerRail planner={planner({ draftRestored: true, hasUnsavedChanges: true, editingPlaceId: tour.place_id, mode: { type: 'edit-saved', placeId: tour.place_id } })} />)
expect(screen.getByRole('status')).toHaveTextContent('Draft')
expect(screen.getByLabelText('Unsaved draft restored')).toBeInTheDocument()
expect(screen.getByRole('heading', { name: 'Edit tour' })).toBeInTheDocument()
})
@@ -1,6 +1,6 @@
import { useEffect, useRef, useState, type ReactNode } from 'react'
import type { TourListItem } from '@trek/shared'
import { AlertTriangle, ArrowLeft, Info, Plus, Redo2, RotateCcw, Save, Trash2, Undo2 } from 'lucide-react'
import { AlertTriangle, ArrowLeft, Circle, Info, Loader2, Plus, Redo2, RotateCcw, Save, Trash2, Undo2 } from 'lucide-react'
import type { Day } from '../../../types'
import { useTranslation } from '../../../i18n'
import { useSettingsStore } from '../../../store/settingsStore'
@@ -58,9 +58,21 @@ function RailTitle({ title, sub, aside }: { title: string; sub?: ReactNode; asid
)
}
/** A status as a small round icon beside the title, its words in the tooltip and for a screen reader. */
function StatusDot({ label, tone, children }: { label: string; tone: 'neutral' | 'info' | 'warning'; children: ReactNode }) {
const look = tone === 'warning' ? 'text-warning' : tone === 'info' ? 'text-info' : 'text-content-muted'
return (
<Tooltip label={label}>
<span aria-label={label} className={`grid h-[20px] w-[20px] flex-none place-items-center rounded-full bg-surface-card shadow-sm ring-1 ring-inset ring-edge-faint ${look}`}>
{children}
</span>
</Tooltip>
)
}
/**
* What the editor is doing right now, as badges under the head's title: a
* restored draft, routing or saving, and a failure with its retry. Nothing
* What the editor is doing right now, as icon badges beside the head's title:
* a restored draft, routing or saving, and a failure with its retry. Nothing
* when there is nothing to say.
*/
function RailStatusBadges({ planner }: { planner: TourPlannerController }) {
@@ -71,19 +83,21 @@ function RailStatusBadges({ planner }: { planner: TourPlannerController }) {
const canRetry = planner.status === 'routing-failed' || planner.status === 'elevation-failed'
if (!restored && !statusKey && !failed) return null
const warning = planner.error != null || canRetry
const statusLabel = failed ? t('tours.planner.status.saveFailed') : statusKey ? t(statusKey) : null
const busy = planner.isSaving || planner.status === 'routing' || planner.status === 'enriching-elevation'
return (
<div role="status" data-testid="tour-planner-status" className="mt-1 flex min-w-0 flex-wrap items-center gap-1">
<span role="status" data-testid="tour-planner-status" className="ms-1.5 flex flex-none items-center gap-1">
{restored && (
<Tooltip label={t('tours.planner.restored')}>
<span className="inline-flex" aria-label={t('tours.planner.restored')}>
<SoftPill tone="info" icon={<RotateCcw size={10} strokeWidth={2.2} className="flex-none" />}>{t('tours.planner.restoredShort')}</SoftPill>
</span>
</Tooltip>
<StatusDot label={t('tours.planner.restored')} tone="info">
<RotateCcw size={11} strokeWidth={2.2} />
</StatusDot>
)}
{(failed || statusKey) && (
<SoftPill tone={warning ? 'warning' : 'neutral'} icon={warning ? <AlertTriangle size={10} strokeWidth={2.2} className="flex-none" /> : undefined}>
{failed ? t('tours.planner.status.saveFailed') : statusKey ? t(statusKey) : null}
</SoftPill>
{statusLabel && (
<StatusDot label={statusLabel} tone={warning ? 'warning' : 'neutral'}>
{warning
? <AlertTriangle size={11} strokeWidth={2.2} />
: busy ? <Loader2 size={11} strokeWidth={2.2} className="animate-spin" /> : <Circle size={7} strokeWidth={3} />}
</StatusDot>
)}
{canRetry && (
<button type="button" onClick={planner.retry}
@@ -92,7 +106,7 @@ function RailStatusBadges({ planner }: { planner: TourPlannerController }) {
{t('tours.planner.retry')}
</button>
)}
</div>
</span>
)
}
@@ -187,7 +201,7 @@ export function TourPlannerRail({ planner, canEdit: editPermission, canAssign: a
<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={<RailStatusBadges planner={planner} />} />
<RailTitle title={t(isSavedEdit ? 'tours.planner.editTitle' : 'tours.planner.newTitle')} aside={<RailStatusBadges planner={planner} />} />
<BarButton label={t('tours.planner.undo')} onClick={() => { if (canEdit && !isSaving) planner.undo() }} disabled={!canEdit || isSaving || !planner.canUndo}>
<Undo2 size={15} strokeWidth={2} />
</BarButton>
@@ -315,9 +329,14 @@ export function TourPlannerToursRail({ planner, tours, days, loading, onAssignTo
const routeAnalysis = planner.routeAnalysis
// A finished save is said once, as the app says it everywhere: a toast.
// Once per save: the toast helper and t are fresh objects on every render, so the
// effect reruns often; only a save it has not announced yet gets the toast.
const savedTour = planner.saveOutcome
const announced = useRef<typeof savedTour>(null)
useEffect(() => {
if (savedTour) toast.success(t('tours.planner.saved'))
if (!savedTour || announced.current === savedTour) return
announced.current = savedTour
toast.success(t('tours.planner.saved'))
}, [savedTour, t, toast])
const openTour = async (tour: TourListItem) => {
@@ -341,7 +360,9 @@ export function TourPlannerToursRail({ planner, tours, days, loading, onAssignTo
const tourTimeFields = [
{
label: t('tours.planner.inspector.duration'),
label: t('tours.planner.walkingEstimated'),
shortLabel: t('tours.planner.walkingEstimatedShort'),
info: { label: t('tours.planner.walkingEstimatedInfoLabel'), description: t('tours.planner.walkingEstimatedInfo') },
value: planner.walkingDurationMinutes == null
? t('tours.planner.walkingTimeUnknown')
: formatPlannedTourDuration(planner.walkingDurationMinutes),
@@ -20,6 +20,8 @@ vi.mock('../../../repo/tourRepo', () => ({ tourRepo: { create: createTour, detai
vi.mock('../useTourPermissions', () => ({ useTourPermissions: ({ canEdit = true, canAssign = true }: { canEdit?: boolean; canAssign?: boolean }) => ({ canEdit, canAssign }) }))
import { useTourPlanner } from './useTourPlanner'
import { hikingTimeMinutes } from '../hikingTime'
import { analyzeRouteGeometry } from '../../../utils/routeGeometry'
import { TourPlannerRail } from './TourPlannerPanels'
const routed = {
@@ -28,6 +30,9 @@ const routed = {
durationSeconds: 1800,
}
const enriched = [[48, 11, 500], [48.01, 11.02, 550]] as [number, number, number][]
// With the heights in, the walking time is the hiking rule over the enriched line, not the router's.
const enrichedAnalysis = analyzeRouteGeometry(JSON.stringify(enriched))!
const enrichedWalkingSeconds = hikingTimeMinutes(enrichedAnalysis.distanceKm, enrichedAnalysis.gain!, enrichedAnalysis.loss!) * 60
const savedTour = {
place_id: 42,
name: 'Saved ridge',
@@ -299,7 +304,7 @@ describe('useTourPlanner', () => {
expect(result.current.canSave).toBe(true)
await act(async () => { await result.current.save() })
expect(createTour).toHaveBeenCalledWith(73, expect.objectContaining({
duration_seconds: routed.durationSeconds,
duration_seconds: enrichedWalkingSeconds,
planned_duration_minutes: 95,
break_additional_minutes: 40,
}))
@@ -311,13 +316,15 @@ describe('useTourPlanner', () => {
act(() => result.current.setPlannedDurationMinutes(null))
await act(async () => { await result.current.save() })
expect(updateTour).toHaveBeenCalledWith(73, savedTour.place_id, expect.objectContaining({
duration_seconds: routed.durationSeconds,
duration_seconds: enrichedWalkingSeconds,
planned_duration_minutes: null,
break_additional_minutes: 40,
}))
})
it('RS-02: recalculates automatic total when route changes but preserves a manual override', async () => {
// No heights for this line, so the router's time stands and each new route brings its own.
enrichTourElevations.mockResolvedValue(routed.coordinates)
routeWalkingTour
.mockResolvedValueOnce({ ...routed, durationSeconds: 3600 })
.mockResolvedValueOnce({ ...routed, durationSeconds: 5400 })
@@ -5,6 +5,7 @@ import { randomId } from '../../../utils/randomId'
import type { TourBaseLayer } from '../../Map/MapLayerSwitcher'
import { analyzeRouteGeometry, type RouteProfileFocus } from '../../../utils/routeGeometry'
import { enrichTourElevations, routeWalkingTour, type TourElevationPoint } from './tourRouting'
import { hikingTimeMinutes } from '../hikingTime'
import { useTourPermissions, type TourPermissionProps } from '../useTourPermissions'
export interface TourPlannerWaypoint {
@@ -417,7 +418,15 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
const websiteInvalid = website.trim().length > 0 && !tourWebsiteSchema.safeParse(website).success
const plannedDurationInvalid = plannedDurationMinutes !== null
&& (!Number.isInteger(plannedDurationMinutes) || plannedDurationMinutes < 0 || plannedDurationMinutes > MAX_PLANNED_TOUR_DURATION_MINUTES)
const walkingDurationMinutes = durationSeconds === null ? null : Math.round(durationSeconds / 60)
const routeAnalysis = useMemo(
() => analyzeRouteGeometry(JSON.stringify(enrichedGeometry ?? route)),
[enrichedGeometry, route],
)
// The router's time only stands in until the route has its heights; from then on the
// walking time is the signposts' rule over distance, climb and descent.
const walkingDurationMinutes = routeAnalysis?.gain != null && routeAnalysis.loss != null
? hikingTimeMinutes(routeAnalysis.distanceKm, routeAnalysis.gain, routeAnalysis.loss)
: durationSeconds === null ? null : Math.round(durationSeconds / 60)
const automaticPlannedTotalMinutes = walkingDurationMinutes === null
? null
: walkingDurationMinutes + (breakAdditionalMinutes ?? 0)
@@ -603,10 +612,6 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
}, [interruptRouting])
const waypointKey = useMemo(() => tourWaypointKey(waypoints), [waypoints])
const routeAnalysis = useMemo(
() => analyzeRouteGeometry(JSON.stringify(enrichedGeometry ?? route)),
[enrichedGeometry, route],
)
const readOnlyGpxAnalysis = useMemo(
() => analyzeRouteGeometry(readOnlyGpxTour?.routeGeometry),
[readOnlyGpxTour?.routeGeometry],
@@ -713,7 +718,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
sequence,
})),
max_hiking_difficulty: maxHikingDifficulty,
duration_seconds: durationSeconds,
duration_seconds: walkingDurationMinutes === null ? durationSeconds : walkingDurationMinutes * 60,
planned_duration_minutes: plannedDurationMinutes,
break_additional_minutes: breakAdditionalMinutes,
} as const
@@ -755,7 +760,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
setIsSaving(false)
}
}
}, [breakAdditionalMinutes, canSave, description, durationSeconds, editingPlaceId, enrichedGeometry, invalidateDetailRequest, maxHikingDifficulty, name, onSaved, plannedDurationMinutes, storageKey, tripId, waypoints, website])
}, [breakAdditionalMinutes, canSave, description, durationSeconds, walkingDurationMinutes, editingPlaceId, enrichedGeometry, invalidateDetailRequest, maxHikingDifficulty, name, onSaved, plannedDurationMinutes, storageKey, tripId, waypoints, website])
return {
canEdit, canAssign,