feat(tours): bike tours in the planner, CyclOSM, and the planned cards' last points (BIK-01 to BIK-06, RTE-01, IO-01, LIB-02)

The tour type is a dropdown; a bike tour picks its profile, routes for it,
says when a point lies off every way, and shows what it runs on: surfaces,
kinds of way and, for a mountain bike, the trail grades, each pointed at on
the map. A type's own map (OpenHikingMap for a hike, CyclOSM for a bike tour)
is offered while a tour of that type is open, with an admin switch each.

From the planned cards: a hike avoids steep climbs, steps or ferries, nothing
else; a saved tour can be shared where the platform takes GPX files; and the
tours rail adds a tour from one menu: plan new, import GPX, or take one over
from another trip.
This commit is contained in:
Maurice
2026-10-19 21:33:49 +02:00
parent adcaca3c5f
commit 73237ffedb
85 changed files with 3728 additions and 647 deletions
@@ -1,5 +1,5 @@
import { HIKING_PREFERENCE_KEYS, type HikingPreferenceKey } from '@trek/shared';
import { ChartNoAxesColumnIncreasing, Footprints, Ruler, Ship } from 'lucide-react';
import { ChartNoAxesColumnIncreasing, Mountain, Ship } from 'lucide-react';
import type { ComponentType } from 'react';
import { useTranslation } from '../../../i18n';
import { BOX } from '../../Planner/bookings/bookingParts';
@@ -9,10 +9,9 @@ import { InfoDot } from '../tourParts';
import type { TourPlannerController } from './useTourPlanner';
const ICON: Record<HikingPreferenceKey, ComponentType<{ size?: number; strokeWidth?: number; className?: string }>> = {
avoid_climbs: Mountain,
avoid_steps: ChartNoAxesColumnIncreasing,
avoid_ferries: Ship,
prefer_paths: Footprints,
shortest: Ruler,
};
/**
@@ -0,0 +1,96 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '../../../../tests/helpers/render';
import type { TourGpxImport } from '../useTourGpxImport';
import { TourAddMenu } from './TourAddMenu';
const library = vi.hoisted(() => ({ show: vi.fn(), options: null as unknown }));
vi.mock('../library/useTourLibrary', () => ({
useTourLibrary: (options: unknown) => {
library.options = options;
return { show: library.show };
},
}));
vi.mock('../library/TourLibraryDialog', () => ({ TourLibraryDialog: () => <div data-testid="library-dialog" /> }));
// FE-TOUR-ADD-001 to FE-TOUR-ADD-005
function planner(mode: 'neutral' | 'new-draft' = 'new-draft', overrides: Record<string, unknown> = {}) {
return {
tripId: 5,
mode: { type: mode },
hasUnsavedChanges: false,
openTour: vi.fn(),
startNewTour: vi.fn(),
...overrides,
} as unknown as Parameters<typeof TourAddMenu>[0]['planner'];
}
const gpxImport = (importing = false) => ({ pick: vi.fn(), importing }) as unknown as TourGpxImport;
const entries = () => screen.getAllByRole('button').filter((button) => button.closest('[role="group"]'));
const open = () => fireEvent.click(screen.getByTestId('tour-rail-add'));
afterEach(() => vi.clearAllMocks());
describe('TourAddMenu (LIB-02)', () => {
it('FE-TOUR-ADD-001: one button opens the three ways to add a tour, in order', () => {
render(<TourAddMenu planner={planner()} gpxImport={gpxImport()} onTakenOver={vi.fn()} disabled={false} />);
const button = screen.getByTestId('tour-rail-add');
expect(button).toHaveAccessibleName('Add tour');
expect(button).toHaveAttribute('aria-expanded', 'false');
open();
expect(button).toHaveAttribute('aria-expanded', 'true');
expect(entries().map((entry) => entry.textContent)).toEqual([
'Plan new tour',
'Import GPX',
'Take over a tour from another trip',
]);
});
it('FE-TOUR-ADD-002: each entry does its own thing and closes the menu', () => {
const p = planner();
const gpx = gpxImport();
render(<TourAddMenu planner={p} gpxImport={gpx} onTakenOver={vi.fn()} disabled={false} />);
open();
fireEvent.click(screen.getByText('Plan new tour'));
expect(p.startNewTour).toHaveBeenCalledTimes(1);
expect(screen.queryByRole('group')).toBeNull();
open();
fireEvent.click(screen.getByText('Import GPX'));
expect(gpx.pick).toHaveBeenCalledTimes(1);
open();
fireEvent.click(screen.getByText('Take over a tour from another trip'));
expect(library.show).toHaveBeenCalledTimes(1);
});
it('FE-TOUR-ADD-003: with no tour open the map is already planning one, so that entry is left out', () => {
render(<TourAddMenu planner={planner('neutral')} gpxImport={gpxImport()} onTakenOver={vi.fn()} disabled={false} />);
open();
expect(entries().map((entry) => entry.textContent)).toEqual(['Import GPX', 'Take over a tour from another trip']);
});
it('FE-TOUR-ADD-004: a tour taken over comes in, and opens unless the editor holds unsaved work', async () => {
const onTakenOver = vi.fn().mockResolvedValue(undefined);
const p = planner();
const { rerender } = render(<TourAddMenu planner={p} onTakenOver={onTakenOver} disabled={false} />);
const take = (library.options as { onTakenOver: (tour: unknown) => Promise<void> }).onTakenOver;
await take({ place_id: 9 });
expect(onTakenOver).toHaveBeenCalledWith({ place_id: 9 });
expect(p.openTour).toHaveBeenCalledWith({ place_id: 9 });
const busy = planner('new-draft', { hasUnsavedChanges: true });
rerender(<TourAddMenu planner={busy} onTakenOver={onTakenOver} disabled={false} />);
await (library.options as { onTakenOver: (tour: unknown) => Promise<void> }).onTakenOver({ place_id: 10 });
expect(busy.openTour).not.toHaveBeenCalled();
expect(screen.getByTestId('library-dialog')).toBeInTheDocument();
});
it('FE-TOUR-ADD-005: waits while saving or importing, and is not there with nothing to offer', () => {
const { rerender } = render(<TourAddMenu planner={planner()} gpxImport={gpxImport(true)} disabled={false} />);
expect(screen.getByTestId('tour-rail-add')).toBeDisabled();
rerender(<TourAddMenu planner={planner()} gpxImport={gpxImport()} disabled />);
expect(screen.getByTestId('tour-rail-add')).toBeDisabled();
rerender(<TourAddMenu planner={planner('neutral')} disabled={false} />);
expect(screen.queryByTestId('tour-rail-add')).toBeNull();
expect(screen.queryByTestId('library-dialog')).toBeNull();
});
});
@@ -0,0 +1,111 @@
import type { TourListItem } from '@trek/shared';
import { FileDown, Library, Loader2, PenLine, Plus } from 'lucide-react';
import type { ReactNode } from 'react';
import { useTranslation } from '../../../i18n';
import { PopoverItem } from '../../Packing/PackingPopover';
import { BarButton } from '../../Planner/planParts';
import { PopoverListPanel } from '../../shared/dialogParts';
import { usePopoverList } from '../../shared/usePopoverList';
import { TourLibraryDialog } from '../library/TourLibraryDialog';
import { useTourLibrary } from '../library/useTourLibrary';
import type { TourGpxImport } from '../useTourGpxImport';
import type { TourPlannerController } from './useTourPlanner';
interface AddEntry {
key: string;
icon: ReactNode;
label: string;
run: () => void;
}
/**
* LIB-02: the tours rail's one way to add a tour, as a menu: plan a new one
* (while another is open; with none open the map is already planning one),
* import GPX files, or take one over from another trip, whose dialog opens
* from here. A tour taken over comes into the trip and opens in the editor,
* unless the editor holds unsaved work.
*/
export function TourAddMenu({
planner,
gpxImport,
onTakenOver,
disabled,
}: {
planner: Pick<TourPlannerController, 'tripId' | 'mode' | 'hasUnsavedChanges' | 'openTour' | 'startNewTour'>;
gpxImport?: TourGpxImport;
/** Where a tour of another trip goes into this one; without it that entry is left out. */
onTakenOver?: (tour: TourListItem) => Promise<void>;
disabled: boolean;
}) {
const { t } = useTranslation();
const list = usePopoverList(0, { estimatedHeight: 140 });
const library = useTourLibrary({
tripId: Number(planner.tripId),
onTakenOver: async (tour) => {
await onTakenOver?.(tour);
if (!planner.hasUnsavedChanges) void planner.openTour(tour);
},
});
const importing = gpxImport?.importing ?? false;
const entries: AddEntry[] = [];
if (planner.mode.type !== 'neutral') {
entries.push({
key: 'new',
icon: <PenLine size={14} strokeWidth={2} />,
label: t('tours.planner.newTour'),
run: () => planner.startNewTour(),
});
}
if (gpxImport) {
entries.push({
key: 'gpx',
icon: <FileDown size={14} strokeWidth={2} />,
label: t('tours.import.button'),
run: gpxImport.pick,
});
}
if (onTakenOver) {
entries.push({
key: 'library',
icon: <Library size={14} strokeWidth={2} />,
label: t('tours.library.open'),
run: library.show,
});
}
if (entries.length === 0) return null;
// Run inside the click that picked it: the file picker opens only from a user's own tap.
const pick = (entry: AddEntry) => {
list.close();
entry.run();
};
return (
<>
<BarButton
ref={list.triggerRef}
label={t('tours.planner.addTour')}
tooltip={t('tours.planner.addTourHint')}
testId="tour-rail-add"
disabled={disabled || importing}
onClick={list.toggle}
ariaExpanded={list.open}
active={list.open}
className="focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent"
>
{importing ? (
<Loader2 size={15} strokeWidth={2} className="animate-spin" />
) : (
<Plus size={16} strokeWidth={2} />
)}
</BarButton>
<PopoverListPanel list={list} label={t('tours.planner.addTour')} className="min-w-[240px]">
{entries.map((entry) => (
<PopoverItem key={entry.key} icon={entry.icon} label={entry.label} onClick={() => pick(entry)} />
))}
</PopoverListPanel>
{onTakenOver && <TourLibraryDialog library={library} />}
</>
);
}
@@ -74,7 +74,13 @@ export function TourNameField({ planner, locked }: TourFieldProps) {
if (!locked) planner.setName(event.target.value);
}}
maxLength={255}
placeholder={t('tours.planner.namePlaceholder')}
placeholder={
{
hike: t('tours.planner.namePlaceholder'),
bike: t('tours.planner.namePlaceholder.bike'),
kayak: t('tours.planner.namePlaceholder.kayak'),
}[planner.tourType]
}
className={INPUT}
/>
</div>
@@ -350,7 +356,7 @@ export function TourDetailsSection({
<TourDescriptionField planner={planner} locked={locked} />
<TourWebsiteField planner={planner} locked={locked} />
{/* A paddle tour is not graded on the hiking scale. */}
{!planner.isPaddle && (
{planner.tourType === 'hike' && (
<>
<TourDifficultyField planner={planner} locked={locked} onDifficultyChange={onDifficultyChange} />
<HikingPreferencesField planner={planner} locked={locked} />
@@ -1,6 +1,6 @@
import { useEffect, useRef, useState, type ReactNode } from 'react'
import type { TourListItem } from '@trek/shared'
import { AlertTriangle, ArrowLeft, Circle, FileDown, History, Loader2, Mountain, Plus, Redo2, RotateCcw, Route, Save, Trash2, Undo2 } from 'lucide-react'
import { AlertTriangle, ArrowLeft, Circle, History, Loader2, MapPin, Mountain, Plus, Redo2, RotateCcw, Route, Save, Trash2, Undo2 } from 'lucide-react'
import type { Day } from '../../../types'
import { useTranslation } from '../../../i18n'
import { useSettingsStore } from '../../../store/settingsStore'
@@ -36,6 +36,7 @@ import TourConversionSection from '../conversion/TourConversionSection'
import type { GpxConversion } from '../conversion/useGpxConversion'
import type { RecordedTrack } from '../useRecordedTrack'
import type { TourGpxImport } from '../useTourGpxImport'
import { TourAddMenu } from './TourAddMenu'
import { type AssignTourToDay, useTourDayAssignment } from '../useTourDayAssignment'
import WandererMark from '../wanderer/WandererMark'
import { TourGpxExportBarButton } from '../TourGpxExportButton'
@@ -43,8 +44,8 @@ import { TourRemoteChangeNotice, TourRevisionConflictDialog } from './TourRevisi
import TourListFilterMenu, { TourFilterEmpty } from '../TourListFilterMenu'
import { TourScopeSummary } from '../TourScopeSummary'
import { useTourListFilters } from '../useTourListFilters'
import { TourLibraryEntry } from '../library/TourLibraryDialog'
import { TourPoiSearchCard } from '../poi/TourPoiSearchCard'
import { BikeWaysCard } from '../bike/BikeWaysCard'
const STATUS_KEY: Partial<Record<TourPlannerStatus, string>> = {
dirty: 'tours.planner.status.dirty',
@@ -131,13 +132,15 @@ function StatusDot({ label, tone, children }: { label: string; tone: 'neutral' |
/** Whether the head offers to try again; a paddle leg that failed has its own actions on its row (PAD-11). */
function retryable(planner: TourPlannerController): boolean {
if (planner.error === 'paddle-route') return false
// A point no way reaches stays unreachable until it moves; asking again changes nothing.
if (planner.error === 'paddle-route' || planner.error === 'unreachable') return false
return planner.status === 'routing-failed' || planner.status === 'elevation-failed'
}
/** The status in words; a paddle tour with legs the router could not plan says how many (PAD-11). */
function statusText(planner: TourPlannerController, key: string, t: Translate): string {
if (planner.error === 'paddle-route') return t('tours.paddle.status.unrouted', { count: planner.paddleRoute?.failures.length ?? 1 })
if (planner.unreachable) return t('tours.planner.status.unreachable', { point: planner.unreachable.unreachable + 1 })
return t(key)
}
@@ -275,8 +278,8 @@ function GpxViewRail({
}) {
const { t } = useTranslation()
const distanceUnit = useSettingsStore((state) => state.settings.distance_unit)
if (planner.mode.type !== 'view-gpx') return null
const { readOnlyGpxTour } = planner
if (planner.mode.type !== 'view-gpx' || !readOnlyGpxTour) return null
const { tour } = readOnlyGpxTour
const fromWanderer = tourSource(tour) === 'wanderer'
const analysis = planner.readOnlyGpxAnalysis
@@ -440,8 +443,12 @@ export function TourPlannerRail({ planner,
{recordedTrack?.available && <RecordedTrackCard recordedTrack={recordedTrack} disabled={isSaving} />}
<UnreachableNotice planner={planner} />
<TourWaypointList planner={planner} canEdit={canEdit} isSaving={isSaving} tourPlaceIds={tourPlaceIds} />
<BikeWaysCard planner={planner} />
<TourPoiSearchCard planner={planner} />
<PaddleEditorCards planner={planner} locked={locked} checklist={paddleChecklist} />
@@ -586,23 +593,6 @@ function NewTourConfirmDialog({ planner, canEdit }: { planner: TourPlannerContro
)
}
/** The GPX import in the tours rail's head, an icon like the editor's; the file drop on the workspace does the same. */
function RailImportButton({ gpxImport, disabled }: { gpxImport: TourGpxImport; disabled: boolean }) {
const { t } = useTranslation()
return (
<BarButton
label={t('tours.import.button')}
tooltip={t('tours.import.hint')}
testId="tour-rail-import-gpx"
disabled={gpxImport.importing || disabled}
onClick={gpxImport.pick}
className="focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent"
>
{gpxImport.importing ? <Loader2 size={15} strokeWidth={2} className="animate-spin" /> : <FileDown size={15} strokeWidth={2} />}
</BarButton>
)
}
interface TourPlannerToursRailProps extends TourPermissionProps {
planner: TourPlannerController
tours: TourListItem[]
@@ -611,26 +601,55 @@ interface TourPlannerToursRailProps extends TourPermissionProps {
onAssignToDay: AssignTourToDay
onViewGpxTour: (tour: TourListItem) => void
onDeleteTour?: (placeId: number) => void
/** The workspace's GPX import; its button sits beside "New tour". */
/** The workspace's GPX import, an entry of "Add tour". */
gpxImport?: TourGpxImport
/** LIB-02: takes a tour of another trip in; its button sits beside the import. */
/** LIB-02: takes a tour of another trip in, an entry of "Add tour". */
onTakenOver?: (tour: TourListItem) => Promise<void>
}
/** The time facts of the overview: the estimate (walking, or paddling for a paddle tour), the breaks and the planned total. */
/** The words of the time estimate: walking, riding (BIK-01) or paddling, each saying how it is reckoned. */
const ESTIMATE_KEYS = {
hike: { labelKey: 'tours.planner.walkingEstimated', shortKey: 'tours.planner.walkingEstimatedShort', infoLabelKey: 'tours.planner.walkingEstimatedInfoLabel', infoKey: 'tours.planner.walkingEstimatedInfo' },
bike: { labelKey: 'tours.bike.timeEstimated', shortKey: 'tours.bike.timeEstimatedShort', infoLabelKey: 'tours.bike.timeEstimatedInfoLabel', infoKey: 'tours.bike.timeEstimatedInfo' },
kayak: { labelKey: 'tours.paddle.timeEstimated', shortKey: 'tours.paddle.timeEstimatedShort', infoLabelKey: 'tours.paddle.timeEstimatedInfoLabel', infoKey: 'tours.paddle.timeEstimatedInfo' },
} as const
/**
* A point no way of the tour's type reaches: the router would have bound it
* that far off, so no route is drawn to a place the tour does not go. The
* notice names the point and what helps; the last route that was planned stays.
*/
function UnreachableNotice({ planner }: { planner: TourPlannerController }) {
const { t } = useTranslation()
const distanceUnit = useSettingsStore(state => state.settings.distance_unit)
const point = planner.unreachable
if (!point) return null
const select = () => planner.setSelectedWaypointId(planner.waypoints[point.unreachable]?.id ?? null)
return (
<TourNotice tone="warning" icon={<AlertTriangle size={13} strokeWidth={2} />}>
<span className="flex flex-col items-start gap-1.5">
<span data-testid="tour-planner-unreachable">
{t(planner.isBike ? 'tours.planner.unreachable.bike' : 'tours.planner.unreachable.hike', {
point: point.unreachable + 1,
distance: formatDistance(point.snappedMeters / 1000, distanceUnit),
})}
</span>
<CardAction icon={<MapPin size={12} strokeWidth={2} />} onClick={select}>
{t('tours.planner.unreachable.show', { point: point.unreachable + 1 })}
</CardAction>
</span>
</TourNotice>
)
}
/** The time facts of the overview: the estimate (walking, riding or paddling), the breaks and the planned total. */
function plannerTimeFields(planner: TourPlannerController, t: Translate) {
const keys = ESTIMATE_KEYS[planner.tourType]
return [
planner.isPaddle ? {
label: t('tours.paddle.timeEstimated'),
shortLabel: t('tours.paddle.timeEstimatedShort'),
info: { label: t('tours.paddle.timeEstimatedInfoLabel'), description: t('tours.paddle.timeEstimatedInfo') },
value: planner.walkingDurationMinutes == null
? t('tours.planner.walkingTimeUnknown')
: formatPlannedTourDuration(planner.walkingDurationMinutes),
} : {
label: t('tours.planner.walkingEstimated'),
shortLabel: t('tours.planner.walkingEstimatedShort'),
info: { label: t('tours.planner.walkingEstimatedInfoLabel'), description: t('tours.planner.walkingEstimatedInfo') },
{
label: t(keys.labelKey),
shortLabel: t(keys.shortKey),
info: { label: t(keys.infoLabelKey), description: t(keys.infoKey) },
value: planner.walkingDurationMinutes == null
? t('tours.planner.walkingTimeUnknown')
: formatPlannedTourDuration(planner.walkingDurationMinutes),
@@ -698,15 +717,7 @@ export function TourPlannerToursRail({ planner, tours, days, loading, onAssignTo
<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')} />
{canEdit && gpxImport && <RailImportButton gpxImport={gpxImport} disabled={isSaving} />}
{canEdit && <TourLibraryEntry planner={planner} onTakenOver={onTakenOver} disabled={isSaving} />}
{canEdit && planner.mode.type !== 'neutral' && (
<BarButton label={t('tours.planner.newTour')} testId="tour-rail-new-tour" disabled={isSaving}
onClick={() => { if (!isSaving) planner.startNewTour() }}
className="focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent">
<Plus size={16} strokeWidth={2} />
</BarButton>
)}
{canEdit && <TourAddMenu planner={planner} gpxImport={gpxImport} onTakenOver={onTakenOver} disabled={isSaving} />}
</div>
<div className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto px-3 py-3.5">
@@ -21,10 +21,39 @@ describe('TourTypeFields (PAD-01)', () => {
const hike = planner({ tourType: 'hike', isPaddle: false });
render(<TourTypeFields planner={hike} locked={false} />);
expect(screen.queryByTestId('tour-planner-paddle-fields')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /Paddle tour/ }));
expect(screen.queryByTestId('tour-planner-bike-fields')).not.toBeInTheDocument();
fireEvent.click(screen.getByTestId('tour-type-select'));
fireEvent.click(screen.getByTestId('tour-type-option-kayak'));
expect(hike.setTourType).toHaveBeenCalledWith('kayak');
});
it('BIK-01: the type is one field that lists every type with what it plans, the one chosen marked', () => {
const hike = planner({ tourType: 'hike', isPaddle: false });
render(<TourTypeFields planner={hike} locked={false} />);
const field = screen.getByTestId('tour-type-select');
expect(field).toHaveTextContent('Hike');
expect(field).toHaveAttribute('aria-expanded', 'false');
fireEvent.click(field);
expect(field).toHaveAttribute('aria-expanded', 'true');
expect(screen.getByTestId('tour-type-option-hike')).toHaveAttribute('aria-pressed', 'true');
expect(screen.getByTestId('tour-type-option-bike')).toHaveTextContent(
'By bike, routed for touring, road, gravel or MTB'
);
fireEvent.click(screen.getByTestId('tour-type-option-bike'));
expect(hike.setTourType).toHaveBeenCalledWith('bike');
expect(field).toHaveAttribute('aria-expanded', 'false');
});
it('BIK-01 to BIK-04: a bike tour names its profile like a boat, with what the profile asks for', () => {
const bike = planner({ tourType: 'bike', isPaddle: false, isBike: true, bikeProfile: 'gravel' });
render(<TourTypeFields planner={bike} locked={false} />);
expect(screen.queryByTestId('tour-planner-paddle-fields')).not.toBeInTheDocument();
const fields = screen.getByTestId('tour-planner-bike-fields');
expect(fields).toHaveTextContent('Takes gravel and farm tracks, not technical singletrails.');
fireEvent.click(screen.getByRole('button', { name: 'MTB' }));
expect(bike.setBikeProfile).toHaveBeenCalledWith('mtb');
});
it('a paddle tour asks for exactly one boat and its water, and says so until both are chosen', () => {
const paddleTour = planner({ paddleIncomplete: true });
render(<TourTypeFields planner={paddleTour} locked={false} />);
@@ -1,10 +1,11 @@
import {
BIKE_PROFILES,
MAX_PADDLE_SPEED_KMH,
type BikeProfile,
type PaddleBoatType,
type PaddleWaterContext,
type PlannableTourType,
} from '@trek/shared';
import { Info, Mountain, Waves } from 'lucide-react';
import { Info } from 'lucide-react';
import { useState } from 'react';
import { useTranslation } from '../../../i18n';
import { SoftPill } from '../../Planner/planParts';
@@ -13,6 +14,7 @@ import { fs } from '../../shared/DialogShell';
import { crossesLake } from '../paddle/lakeStyleAdvice';
import { PaddleLakeStyleField } from '../paddle/PaddleLakeStyleField';
import { TourNotice } from '../tourParts';
import { TourTypeSelect } from './TourTypeSelect';
import type { TourPlannerController } from './useTourPlanner';
const BOATS: readonly PaddleBoatType[] = ['kayak', 'canoe', 'sup', 'other'];
@@ -78,10 +80,34 @@ function PaddleSpeedInput({ planner, locked }: TourTypeFieldsProps) {
}
/**
* PAD-01: what the tour is. A hike keeps its fields where they were; a paddle
* tour asks for exactly one boat and the water it is on, and offers the
* boat's planning speed beside the paddler's own. Nothing here routes the
* tour or puts it on a day.
* BIK-01 to BIK-04: what a bike tour is ridden on, the way a paddle tour names
* its boat, with a line on what the profile asks the router for. A profile
* plans the route again; it says nothing about whether a way can be ridden.
*/
function BikeProfileField({ planner }: { planner: TourPlannerController }) {
const { t } = useTranslation();
return (
<div data-testid="tour-planner-bike-fields" className="min-w-0">
<span className={LABEL}>{t('tours.bike.profile')}</span>
<Segmented<BikeProfile>
value={planner.bikeProfile}
onChange={planner.setBikeProfile}
label={t('tours.bike.profile')}
fill
options={BIKE_PROFILES.map((profile) => ({ value: profile, label: t(`tours.bike.profile.${profile}`) }))}
/>
<span className="mt-1.5 block text-content-faint" style={fs(11, 'body')}>
{t(`tours.bike.profileHint.${planner.bikeProfile}`)}
</span>
</div>
);
}
/**
* PAD-01, BIK-01: what the tour is. A hike keeps its fields where they were; a
* bike tour names its profile; a paddle tour asks for exactly one boat and the
* water it is on, and offers the boat's planning speed beside the paddler's
* own. Nothing here puts the tour on a day.
*/
export function TourTypeFields({ planner, locked }: TourTypeFieldsProps) {
const { t } = useTranslation();
@@ -94,18 +120,16 @@ export function TourTypeFields({ planner, locked }: TourTypeFieldsProps) {
<span className={LABEL} id="tour-planner-type-label">
{t('tours.planner.tourType')}
</span>
<Segmented<PlannableTourType>
<TourTypeSelect
value={planner.tourType}
onChange={planner.setTourType}
label={t('tours.planner.tourType')}
fill
options={[
{ value: 'hike', label: t('tourTypes.hike'), icon: <Mountain size={13} strokeWidth={2} /> },
{ value: 'kayak', label: t('tourTypes.kayak'), icon: <Waves size={13} strokeWidth={2} /> },
]}
disabled={locked}
labelId="tour-planner-type-label"
/>
</div>
{planner.isBike && <BikeProfileField planner={planner} />}
{planner.isPaddle && (
<div data-testid="tour-planner-paddle-fields" className="flex min-w-0 flex-col gap-3">
<div className="min-w-0">
@@ -0,0 +1,110 @@
import { plannableTourTypeSchema, type PlannableTourType } from '@trek/shared';
import { Check, ChevronDown } from 'lucide-react';
import { createElement, useId } from 'react';
import { useTranslation } from '../../../i18n';
import { fs } from '../../shared/DialogShell';
import { PopoverListPanel } from '../../shared/dialogParts';
import { usePopoverList } from '../../shared/usePopoverList';
import { tourDayRowIcon } from '../tourDayRowIcon';
/** The types the planner offers, in the order the contract lists them. */
const PLANNER_TOUR_TYPES = plannableTourTypeSchema.options;
function TypeTile({ type, active = false }: { type: PlannableTourType; active?: boolean }) {
return (
<span
aria-hidden="true"
className={`grid h-8 w-8 flex-none place-items-center rounded-[9px] ${active ? 'bg-accent text-accent-text' : 'bg-surface-tertiary text-content-secondary'}`}
>
{createElement(tourDayRowIcon(type), { size: 15, strokeWidth: 2 })}
</span>
);
}
/**
* What the tour is, as one field that opens the types with what each one
* plans: a hike on footpaths within its limit, a bike tour on its profile, a
* paddle tour on the water. Room for the types still to come without the row
* of buttons it was growing too long for.
*/
export function TourTypeSelect({
value,
onChange,
disabled = false,
labelId,
}: {
value: PlannableTourType;
onChange: (type: PlannableTourType) => void;
disabled?: boolean;
/** The label over the field, read before the type chosen. */
labelId: string;
}) {
const { t } = useTranslation();
const valueId = useId();
const list = usePopoverList(PLANNER_TOUR_TYPES.indexOf(value), { estimatedHeight: 220 });
const { open, toggle, triggerRef, listId } = list;
const label = t('tours.planner.tourType');
const pick = (type: PlannableTourType) => {
list.close();
onChange(type);
};
return (
<>
<button
ref={triggerRef}
type="button"
data-testid="tour-type-select"
onClick={toggle}
disabled={disabled}
aria-expanded={open}
aria-controls={open ? listId : undefined}
aria-labelledby={`${labelId} ${valueId}`}
className="flex w-full min-w-0 items-center gap-2.5 rounded-[10px] border border-edge bg-surface-input py-1.5 pe-3 ps-1.5 text-start hover:border-content-faint disabled:cursor-default disabled:opacity-50"
>
<TypeTile type={value} />
<span id={valueId} className="min-w-0 flex-1">
<span className="block truncate font-semibold text-content" style={fs(13, 'body')}>
{t(`tourTypes.${value}`)}
</span>
<span className="block truncate text-content-faint" style={fs(11, 'body')}>
{t(`tours.planner.tourTypeHint.${value}`)}
</span>
</span>
<ChevronDown
size={14}
strokeWidth={2.2}
aria-hidden="true"
className={`flex-none text-content-faint transition-transform ${open ? 'rotate-180' : ''}`}
/>
</button>
<PopoverListPanel list={list} label={label} className="flex min-w-[260px] flex-col gap-0.5">
{PLANNER_TOUR_TYPES.map((type) => {
const active = type === value;
return (
<button
key={type}
type="button"
data-testid={`tour-type-option-${type}`}
aria-pressed={active}
onClick={() => pick(type)}
className={`flex w-full items-center gap-2.5 rounded-[9px] px-2 py-1.5 text-start hover:bg-surface-tertiary focus-visible:bg-surface-tertiary focus-visible:outline-none ${active ? 'bg-surface-tertiary' : ''}`}
>
<TypeTile type={type} active={active} />
<span className="min-w-0 flex-1">
<span className="block font-semibold text-content" style={fs(12.5, 'body')}>
{t(`tourTypes.${type}`)}
</span>
<span className="block text-content-muted" style={fs(11, 'body')}>
{t(`tours.planner.tourTypeHint.${type}`)}
</span>
</span>
{active && (
<Check size={14} strokeWidth={2.2} aria-hidden="true" className="flex-none text-content-muted" />
)}
</button>
);
})}
</PopoverListPanel>
</>
);
}
@@ -3,42 +3,46 @@ import { describe, expect, it, vi } from 'vitest';
import { HikingPreferencesField } from './HikingPreferencesField';
import { hikingCostingOptions } from './tourRouting';
describe('hikingCostingOptions (MF-08)', () => {
describe('hikingCostingOptions (MF-08, RTE-01)', () => {
it('asks the router only for what was switched on, in the options it was checked with', () => {
expect(hikingCostingOptions(null)).toEqual({});
expect(hikingCostingOptions({ avoid_steps: false })).toEqual({});
expect(
hikingCostingOptions({ avoid_steps: true, avoid_ferries: true, prefer_paths: true, shortest: true })
).toEqual({ step_penalty: 600, use_ferry: 0, walkway_factor: 0.5, shortest: true });
expect(hikingCostingOptions({ avoid_climbs: true, avoid_steps: true, avoid_ferries: true })).toEqual({
use_hills: 0.2,
step_penalty: 600,
use_ferry: 0,
});
});
});
describe('HikingPreferencesField (MF-08)', () => {
it('shows each checked preference with what it does, and switching one keeps the others', () => {
describe('HikingPreferencesField (MF-08, RTE-01)', () => {
it('shows the three preferences in order with what each does, and switching one keeps the others', () => {
const setHikingPreferences = vi.fn();
render(
<HikingPreferencesField
planner={{ hikingPreferences: { prefer_paths: true }, setHikingPreferences }}
planner={{ hikingPreferences: { avoid_climbs: true }, setHikingPreferences }}
locked={false}
/>
);
const names = ['avoid_climbs', 'avoid_steps', 'avoid_ferries'].map((key) => `tours.preferences.${key}`);
const switches = screen.getAllByRole('button').filter((button) => button.hasAttribute('aria-pressed'));
expect(switches.map((button) => button.getAttribute('aria-label'))).toEqual(names);
const steps = screen.getByRole('button', { name: 'tours.preferences.avoid_steps' });
expect(steps).toHaveAttribute('aria-pressed', 'false');
expect(steps).toHaveAccessibleDescription('tours.preferences.avoid_stepsHint');
expect(screen.getByRole('button', { name: 'tours.preferences.prefer_paths' })).toHaveAttribute(
'aria-pressed',
'true'
);
const climbs = screen.getByRole('button', { name: 'tours.preferences.avoid_climbs' });
expect(climbs).toHaveAttribute('aria-pressed', 'true');
expect(climbs).toHaveAccessibleDescription('tours.preferences.avoid_climbsHint');
fireEvent.click(steps);
expect(setHikingPreferences).toHaveBeenCalledWith({ prefer_paths: true, avoid_steps: true });
fireEvent.click(screen.getByRole('button', { name: 'tours.preferences.prefer_paths' }));
expect(setHikingPreferences).toHaveBeenLastCalledWith({ prefer_paths: false });
expect(setHikingPreferences).toHaveBeenCalledWith({ avoid_climbs: true, avoid_steps: true });
fireEvent.click(climbs);
expect(setHikingPreferences).toHaveBeenLastCalledWith({ avoid_climbs: false });
});
it('changes nothing while the tour is locked', () => {
const setHikingPreferences = vi.fn();
render(<HikingPreferencesField planner={{ hikingPreferences: null, setHikingPreferences }} locked />);
fireEvent.click(screen.getByRole('button', { name: 'tours.preferences.shortest' }));
fireEvent.click(screen.getByRole('button', { name: 'tours.preferences.avoid_climbs' }));
expect(setHikingPreferences).not.toHaveBeenCalled();
});
});
@@ -1,8 +1,10 @@
import {
bikeProfileSchema,
hikingPreferencesSchema,
MAX_PLANNED_TOUR_DURATION_MINUTES,
paddleLockSchema,
plannableTourTypeSchema,
type BikeProfile,
type HikingPreferences,
type PlannableTourType,
type TourMaxHikingDifficulty,
@@ -17,7 +19,7 @@ import type { PaddleFieldValues } from './usePaddleFields';
* half read.
*/
export interface DraftPayload {
version: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
version: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;
name: string;
description?: string;
website?: string;
@@ -34,9 +36,11 @@ export interface DraftPayload {
baseRevision?: number | null;
/** MF-08: what the hike asks the router for besides its limit. */
hikingPreferences?: HikingPreferences | null;
/** BIK-01: the profile a bike tour is routed for. */
bikeProfile?: BikeProfile;
}
const DRAFT_VERSIONS: ReadonlyArray<DraftPayload['version']> = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const DRAFT_VERSIONS: ReadonlyArray<DraftPayload['version']> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function optionalString(value: unknown): boolean {
return value === undefined || typeof value === 'string';
@@ -70,6 +74,16 @@ function validDraftWaypoint(point: TourPlannerWaypoint): boolean {
);
}
/** The type of a draft and what its route is planned by, each one absent in a draft older than it. */
function validRouteChoices(draft: Partial<DraftPayload>): boolean {
return (
(draft.tourType === undefined || plannableTourTypeSchema.safeParse(draft.tourType).success) &&
(draft.bikeProfile === undefined || bikeProfileSchema.safeParse(draft.bikeProfile).success) &&
(draft.hikingPreferences == null || hikingPreferencesSchema.safeParse(draft.hikingPreferences).success) &&
optionalDifficulty(draft.maxHikingDifficulty)
);
}
export function validDraft(value: unknown): value is DraftPayload {
if (!value || typeof value !== 'object') return false;
const draft = value as Partial<DraftPayload>;
@@ -84,9 +98,7 @@ export function validDraft(value: unknown): value is DraftPayload {
optionalPlaceId(draft.editingPlaceId) &&
optionalPlaceId(draft.derivedFromPlaceId) &&
optionalPlaceId(draft.baseRevision) &&
(draft.hikingPreferences == null || hikingPreferencesSchema.safeParse(draft.hikingPreferences).success) &&
optionalDifficulty(draft.maxHikingDifficulty) &&
(draft.tourType === undefined || plannableTourTypeSchema.safeParse(draft.tourType).success) &&
validRouteChoices(draft) &&
Array.isArray(draft.waypoints) &&
draft.waypoints.every(validDraftWaypoint)
);
@@ -1,6 +1,8 @@
import {
MAX_PLANNED_TOUR_DURATION_MINUTES,
plannableTourTypeSchema,
tourWebsiteSchema,
type BikeProfile,
type HikingPreferences,
type PaddleBoatType,
type PaddleLakeStyle,
@@ -22,7 +24,9 @@ export function openedTourFields(tour: TourListItem) {
breakAdditionalMinutes: tour.break_additional_minutes ?? null,
difficulty: tour.max_hiking_difficulty ?? 2,
preferences: tour.hiking_preferences ?? null,
tourType: (tour.tour_type === 'kayak' ? 'kayak' : 'hike') as PlannableTourType,
// A type nobody can plan (an import of another kind) opens as a hike, as it always has.
tourType: plannableTourTypeSchema.catch('hike').parse(tour.tour_type) as PlannableTourType,
bikeProfile: (tour.bike_profile ?? 'touring') as BikeProfile,
};
}
@@ -32,6 +36,8 @@ export interface TourPlannerFactsInput {
maxHikingDifficulty: TourMaxHikingDifficulty;
/** MF-08: what the hike asks the router for besides its limit. */
hikingPreferences: HikingPreferences | null;
/** BIK-01: the profile a bike tour is routed for. */
bikeProfile: BikeProfile;
website: string;
plannedDurationMinutes: number | null;
breakAdditionalMinutes: number | null;
@@ -46,7 +52,7 @@ export interface TourPlannerFactsInput {
/** A paddle tour's estimate on the water; null for a hike. */
paddleEstimate: { waterMinutes: number | null; estimateMinutes: number | null } | null;
routeAnalysis: RouteGeometryAnalysis | null;
/** The router's own time, seconds; stands in for a hike until the heights are in. */
/** The router's own time, seconds: a bike tour's riding time; stands in for a hike until the heights are in. */
durationSeconds: number | null;
}
@@ -54,28 +60,63 @@ function invalidMinutes(value: number | null): boolean {
return value !== null && (!Number.isInteger(value) || value < 0 || value > MAX_PLANNED_TOUR_DURATION_MINUTES);
}
/**
* The time on the move: a paddle tour on the water at its speed, a bike tour
* by the router, which rides the profile at its speed and weighs the climbs, a
* hike by the signposts' rule over distance, climb and descent once the route
* has its heights, and by the router's own time before that.
*/
function movingMinutes(input: TourPlannerFactsInput, routerMinutes: number | null): number | null {
const { paddleEstimate, routeAnalysis } = input;
if (paddleEstimate) return paddleEstimate.waterMinutes === null ? null : paddleEstimate.estimateMinutes;
if (input.tourType === 'bike') return routerMinutes;
return routeAnalysis?.gain != null && routeAnalysis.loss != null
? hikingTimeMinutes(routeAnalysis.distanceKm, routeAnalysis.gain, routeAnalysis.loss)
: routerMinutes;
}
/** What the type adds to a save: a hike its routing limit, a bike tour its profile, a paddle tour its boat, water and speed. */
function typeFieldsOf(input: TourPlannerFactsInput) {
const isBike = input.tourType === 'bike';
if (input.tourType === 'kayak') {
const { boatType, waterContext, speedKmh, portageSpeedKmh, lakeStyle } = input.paddle;
return {
tour_type: input.tourType,
max_hiking_difficulty: null,
bike_profile: null,
boat_type: boatType,
water_context: waterContext,
paddle_speed_kmh: speedKmh,
portage_speed_kmh: portageSpeedKmh,
paddle_lake_style: lakeStyle,
hiking_preferences: null,
};
}
return {
tour_type: input.tourType,
max_hiking_difficulty: isBike ? null : input.maxHikingDifficulty,
bike_profile: isBike ? input.bikeProfile : null,
boat_type: null,
water_context: null,
paddle_speed_kmh: null,
portage_speed_kmh: null,
paddle_lake_style: null,
hiking_preferences: isBike ? null : input.hikingPreferences,
};
}
/**
* What the planner derives from its draft, worked out in one place: whether
* the fields hold, the times, and the fields the tour type adds to a save.
* A paddle tour is timed on the water at its speed; a hike by the signposts'
* rule over distance, climb and descent once the route has its heights, and
* by the router's own time before that.
*/
export function tourPlannerFacts(input: TourPlannerFactsInput) {
const isPaddle = input.tourType === 'kayak';
const { paddleEstimate, routeAnalysis, durationSeconds, breakAdditionalMinutes, plannedDurationMinutes } = input;
const walkingDurationMinutes = paddleEstimate
? paddleEstimate.waterMinutes === null
? null
: paddleEstimate.estimateMinutes
: routeAnalysis?.gain != null && routeAnalysis.loss != null
? hikingTimeMinutes(routeAnalysis.distanceKm, routeAnalysis.gain, routeAnalysis.loss)
: durationSeconds === null
? null
: Math.round(durationSeconds / 60);
const { durationSeconds, breakAdditionalMinutes, plannedDurationMinutes } = input;
const routerMinutes = durationSeconds === null ? null : Math.round(durationSeconds / 60);
const walkingDurationMinutes = movingMinutes(input, routerMinutes);
const automaticPlannedTotalMinutes =
walkingDurationMinutes === null ? null : walkingDurationMinutes + (breakAdditionalMinutes ?? 0);
const { boatType, waterContext, speedKmh, portageSpeedKmh, lakeStyle } = input.paddle;
const { boatType, waterContext } = input.paddle;
return {
isPaddle,
websiteInvalid: input.website.trim().length > 0 && !tourWebsiteSchema.safeParse(input.website).success,
@@ -92,27 +133,6 @@ export function tourPlannerFacts(input: TourPlannerFactsInput) {
// The router's own time stands in for a hike without heights; a paddle tour has only its speed.
savedDurationSeconds:
walkingDurationMinutes === null ? (isPaddle ? null : durationSeconds) : walkingDurationMinutes * 60,
// What the type adds to a save: a hike its routing limit, a paddle tour its boat, water and speed.
typeFields: isPaddle
? {
tour_type: input.tourType,
max_hiking_difficulty: null,
boat_type: boatType,
water_context: waterContext,
paddle_speed_kmh: speedKmh,
portage_speed_kmh: portageSpeedKmh,
paddle_lake_style: lakeStyle,
hiking_preferences: null,
}
: {
tour_type: input.tourType,
max_hiking_difficulty: input.maxHikingDifficulty,
boat_type: null,
water_context: null,
paddle_speed_kmh: null,
portage_speed_kmh: null,
paddle_lake_style: null,
hiking_preferences: input.hikingPreferences,
},
typeFields: typeFieldsOf(input),
};
}
@@ -8,6 +8,7 @@ const hike = (overrides: Partial<TourPlannerFactsInput> = {}): TourPlannerFactsI
tourType: 'hike',
maxHikingDifficulty: 3,
hikingPreferences: null,
bikeProfile: 'touring',
website: '',
plannedDurationMinutes: null,
breakAdditionalMinutes: null,
@@ -20,6 +21,28 @@ const hike = (overrides: Partial<TourPlannerFactsInput> = {}): TourPlannerFactsI
});
describe('tourPlannerFacts', () => {
it('times a bike tour by the router even with its heights in, and saves its profile and nothing of a hike', () => {
const analysis = { distanceKm: 30, gain: 400, loss: 400 } as TourPlannerFactsInput['routeAnalysis'];
const facts = tourPlannerFacts(
hike({
tourType: 'bike',
bikeProfile: 'gravel',
routeAnalysis: analysis,
durationSeconds: 5_400,
hikingPreferences: { avoid_steps: true },
})
);
expect(facts.walkingDurationMinutes).toBe(90);
expect(facts.typeFields).toMatchObject({
tour_type: 'bike',
bike_profile: 'gravel',
max_hiking_difficulty: null,
hiking_preferences: null,
boat_type: null,
});
expect(tourPlannerFacts(hike()).typeFields).toMatchObject({ bike_profile: null, max_hiking_difficulty: 3 });
});
it('times a hike by the router until its heights are in, then by the signposts, breaks on top', () => {
expect(tourPlannerFacts(hike({ durationSeconds: 3_570 })).walkingDurationMinutes).toBe(60);
const analysis = { distanceKm: 8, gain: 600, loss: 600 } as TourPlannerFactsInput['routeAnalysis'];
@@ -63,6 +63,13 @@ export function unlinkedPoint<T extends TourPlannerWaypoint>(point: T): T {
}
/** Roles from the order; free legs follow their points, and a paddle tour keeps its portages and locks. */
/** BIK-01: a bike tour rides no via ferrata; a leg that followed one is planned by the router again. */
export function ridablePoints(points: TourPlannerWaypoint[]): TourPlannerWaypoint[] {
return points.some((point) => point.fixedLeg?.kind === 'ferrata')
? points.map((point) => (point.fixedLeg?.kind === 'ferrata' ? { ...point, fixedLeg: null } : point))
: points;
}
export function normalizePlannerWaypoints(points: TourPlannerWaypoint[], paddle = false): TourPlannerWaypoint[] {
return keepJoinedFixedLegs(alignFreeLegs(points, paddle)).map((point, index) => ({
...point,
@@ -0,0 +1,20 @@
import type { TourRouteResult } from './tourRouting';
/**
* A point the router found no way for at all: it bound the point to a way
* this far off (or put the whole run on one spot), which would draw a route
* that is not where the tour was planned. `unreachable` is the point's place
* along the tour, counted from 0.
*/
export interface TourRouteUnreachable {
unreachable: number;
snappedMeters: number;
}
/** Whether the router's answer is a route, rather than nothing or a point it could not reach. */
export function isTourRoute(value: TourRouteResult | TourRouteUnreachable | null): value is TourRouteResult {
return !!value && !('unreachable' in value);
}
/** How far the router may move a point onto its way before the point counts as unreachable for the tour's type. */
export const MAX_TOUR_SNAP_M = 300;
@@ -12,7 +12,10 @@ vi.mock('../../Map/valhallaRoute', () => ({
valhallaTurn,
}))
import { enrichTourElevations, parseValhallaElevation, routeWalkingTour } from './tourRouting'
import { enrichTourElevations, parseValhallaElevation, routeBikeTour, routeWalkingTour, type TourRouteResult } from './tourRouting'
/** A route as the planner reads it, for the cases that expect one. */
const route = async (...args: Parameters<typeof routeWalkingTour>) => (await routeWalkingTour(...args)) as TourRouteResult | null
const waypoints = [
{ lat: 47.3822621, lng: 10.9888935 },
@@ -36,12 +39,12 @@ describe('routeWalkingTour', () => {
})
it('TOUR-ROUTING-030: asks the router for the preferences of a hike beside its limit (MF-08)', async () => {
await routeWalkingTour(waypoints, undefined, 3, { avoid_steps: true, shortest: true })
await routeWalkingTour(waypoints, undefined, 3, { avoid_climbs: true, avoid_steps: true })
expect(valhallaRun).toHaveBeenCalledWith(waypoints, 'walking', [], undefined, {
max_hiking_difficulty: 3,
use_hills: 0.2,
step_penalty: 600,
shortest: true,
})
})
@@ -53,10 +56,10 @@ describe('routeWalkingTour', () => {
geometry: [[47.39, 11.01], [47.391, 11.011], [47.392, 11.012]] as [number, number][],
}
valhallaRun
.mockResolvedValueOnce({ total: { coordinates: [[47.38, 11.0], [47.39, 11.01]], distance: 1500, duration: 1200 } })
.mockResolvedValueOnce({ total: { coordinates: [[47.392, 11.012], [47.4, 11.02]], distance: 1000, duration: 800 } })
.mockResolvedValueOnce({ total: { coordinates: [[47.38, 11.0], [47.39, 11.01]], distance: 1500, duration: 1200 }, snapped: [] })
.mockResolvedValueOnce({ total: { coordinates: [[47.392, 11.012], [47.4, 11.02]], distance: 1000, duration: 800 }, snapped: [] })
const routed = await routeWalkingTour([
const routed = await route([
{ lat: 47.38, lng: 11.0 },
{ lat: 47.39, lng: 11.01, fixedLeg: leg },
{ lat: 47.392, lng: 11.012 },
@@ -72,7 +75,7 @@ describe('routeWalkingTour', () => {
it('TOUR-ROUTING-021: a tour that is all fixed leg asks the router nothing, and a failed run fails the whole route', async () => {
const leg = { kind: 'ferrata' as const, ref: 'way/1', name: null, geometry: [[47.39, 11.01], [47.392, 11.012]] as [number, number][] }
const fixedOnly = await routeWalkingTour([{ lat: 47.39, lng: 11.01, fixedLeg: leg }, { lat: 47.392, lng: 11.012 }])
const fixedOnly = await route([{ lat: 47.39, lng: 11.01, fixedLeg: leg }, { lat: 47.392, lng: 11.012 }])
expect(valhallaRun).not.toHaveBeenCalled()
expect(fixedOnly?.coordinates).toEqual([[47.39, 11.01], [47.392, 11.012]])
@@ -82,9 +85,9 @@ describe('routeWalkingTour', () => {
it('TOUR-ROUTING-022: hand-drawn legs ask no router and come back as their own parts, routed runs as theirs', async () => {
const free = (from: [number, number], to: [number, number]) => ({ kind: 'free' as const, geometry: [from, to] })
valhallaRun.mockResolvedValueOnce({ total: { coordinates: [[47.392, 11.012], [47.395, 11.015], [47.4, 11.02]], distance: 900, duration: 700 } })
valhallaRun.mockResolvedValueOnce({ total: { coordinates: [[47.392, 11.012], [47.395, 11.015], [47.4, 11.02]], distance: 900, duration: 700 }, snapped: [] })
const routed = await routeWalkingTour([
const routed = await route([
{ lat: 47.38, lng: 11.0, fixedLeg: free([47.38, 11.0], [47.39, 11.01]) },
{ lat: 47.39, lng: 11.01, fixedLeg: free([47.39, 11.01], [47.392, 11.012]) },
{ lat: 47.392, lng: 11.012 },
@@ -105,7 +108,7 @@ describe('routeWalkingTour', () => {
it('TOUR-ROUTING-023: a tour drawn wholly by hand, a paddle tour, never asks the router', async () => {
const free = (from: [number, number], to: [number, number]) => ({ kind: 'free' as const, geometry: [from, to] })
const routed = await routeWalkingTour([
const routed = await route([
{ lat: 53.3, lng: 12.9, fixedLeg: free([53.3, 12.9], [53.31, 12.92]) },
{ lat: 53.31, lng: 12.92 },
])
@@ -186,3 +189,44 @@ describe('routeWalkingTour', () => {
await expect(enrichTourElevations(coordinates)).resolves.toEqual(coordinates)
})
})
describe('routing on land, bike profiles and unreachable points (BIK-01)', () => {
beforeEach(() => {
valhallaRun.mockReset().mockResolvedValue(null)
valhallaBase.mockReset().mockReturnValue('https://valhalla.test')
})
const run = (snappedMeters: number[]) => ({
total: { coordinates: [[47, 11], [47.01, 11.01]], distance: 1500, duration: 300 },
snapped: snappedMeters.map((meters) => ({ asked: [47, 11], at: [47, 11], meters })),
})
it('TOUR-ROUTING-030: asks the bicycle costing with each profile\'s own options', async () => {
valhallaRun.mockResolvedValue(run([3, 4]))
for (const profile of ['touring', 'road', 'gravel', 'mtb'] as const) {
await routeBikeTour(waypoints, profile)
}
expect(valhallaRun.mock.calls.map((call) => [call[1], (call[4] as { bicycle_type: string }).bicycle_type])).toEqual([
['cycling', 'Hybrid'],
['cycling', 'Road'],
['cycling', 'Cross'],
['cycling', 'Mountain'],
])
})
it('TOUR-ROUTING-031: a point the router could only bind far off is named, not routed to', async () => {
valhallaRun.mockResolvedValueOnce(run([12, 2900]))
expect(await routeBikeTour(waypoints, 'touring')).toEqual({ unreachable: 1, snappedMeters: 2900 })
// Within the limit the route stands.
valhallaRun.mockResolvedValueOnce(run([12, 280]))
expect(await routeBikeTour(waypoints, 'touring')).toMatchObject({ distanceMeters: 1500 })
})
it('TOUR-ROUTING-032: a point after a fixed leg is counted along the whole tour', async () => {
const free = { kind: 'free' as const, geometry: [[47.39, 11.01], [47.392, 11.012]] as [number, number][] }
valhallaRun.mockResolvedValueOnce(run([400, 5]))
expect(
await routeWalkingTour([{ lat: 47.39, lng: 11.01, fixedLeg: free }, { lat: 47.392, lng: 11.012 }, { lat: 47.4, lng: 11.02 }])
).toEqual({ unreachable: 1, snappedMeters: 400 })
})
})
@@ -1,7 +1,8 @@
import type { HikingPreferences, TourFixedLeg } from '@trek/shared'
import type { BikeProfile, HikingPreferences, TourFixedLeg } from '@trek/shared'
import type { Waypoint } from '../../../types'
import { valhallaBase, valhallaRun, valhallaTurn } from '../../Map/valhallaRoute'
import { valhallaBase, valhallaRun, valhallaTurn, type CostingOptions } from '../../Map/valhallaRoute'
import { densifyLine, lineLengthM } from './tourFixedLegs'
import { MAX_TOUR_SNAP_M, type TourRouteUnreachable } from './tourRouteOutcome'
export interface TourRoutePart {
coordinates: [number, number][]
@@ -33,53 +34,104 @@ const TOURS_MAX_HIKING_DIFFICULTY = 2
/** How fast a fixed leg is reckoned until the heights are in: a via ferrata climbs slowly, a free leg is walked. */
const FIXED_LEG_KM_PER_HOUR = { ferrata: 1.5, free: 4, portage: 2 } as const
/** A leg drawn by hand on a bike tour is reckoned at an easy riding pace: no router saw it. */
const FREE_LEG_RIDING_KM_PER_HOUR = 15
/**
* MF-08: a hike's preferences as Valhalla's pedestrian costing options. Each
* one was checked against the public instance before it was offered, and is a
* weighting that gives way where there is no other path:
* MF-08, RTE-01: a hike's preferences as Valhalla's pedestrian costing
* options. Each one was checked against the public instance before it was
* offered, and is a weighting that gives way where there is no other path:
* - avoid_climbs, `use_hills` 0.2: Freiburg Martinstor to the Schlossberg went
* from 1.64 km with a 37 % pitch and 30 m over 25 % to 1.73 km whose steepest
* stretch is 23 % (heights every 30 m). It weighs the grade, not the climb in
* sum: the same height is still gained. 0.1 and below sent Garmisch station
* to the Eckbauer round a 10 km detour with more steep metres, 0.25 and up
* left Freiburg as it was; 0.2 does neither.
* - avoid_steps, `step_penalty` 600 s: Würzburg Altstadt to the Festung went
* from four flights of steps over 1.49 km to one over 2.67 km.
* - avoid_ferries, `use_ferry` 0: Kiel Reventlou to Dietrichsdorf went from the
* Förde ferry (2.7 km) round the fjord on land (8.3 km); Hamburg
* Landungsbrücken to Steinwerder through the old Elbe tunnel instead of the ferry.
* - prefer_paths, `walkway_factor` 0.5: footpaths of their own weigh half of a
* road, which moved Garmisch station to the Partnachklamm onto the paths.
* - shortest, `shortest`: the way by its length, not its time (Garmisch to the
* Eckbauer 5.09 km to 4.96 km); it still honours the penalties above.
* Left out because the router showed no effect on foot: `use_hills` and
* `use_tracks`; nor has it any option for marked, paved or rough ways.
* The router has no option for marked, paved or rough ways on foot.
*/
export function hikingCostingOptions(preferences: HikingPreferences | null | undefined): Record<string, number | boolean> {
export function hikingCostingOptions(preferences: HikingPreferences | null | undefined): Record<string, number> {
return {
...(preferences?.avoid_climbs ? { use_hills: 0.2 } : {}),
...(preferences?.avoid_steps ? { step_penalty: 600 } : {}),
...(preferences?.avoid_ferries ? { use_ferry: 0 } : {}),
...(preferences?.prefer_paths ? { walkway_factor: 0.5 } : {}),
...(preferences?.shortest ? { shortest: true } : {}),
}
}
/**
* BIK-01 to BIK-04: what each bike profile asks Valhalla's bicycle costing for.
* Every one was checked against the public instance with trace_attributes over
* the routes it gave, before it was offered (shares of the length):
* - touring, Hybrid with bad surfaces avoided: Garmisch station to the Eckbauer
* 92 % asphalt and no gravel, where gravel took 18 % gravel on farm tracks.
* - road, Road at full surface avoidance: Herrsching to Andechs 100 % asphalt
* over 6.2 km, where touring took 4.98 km with 7 % dirt and 10 % compacted.
* - gravel, Cross with surfaces barely avoided: Munich Marienplatz to the
* Englischer Garten 39 % compacted paths along the Isar, touring 9 %.
* - mtb, Mountain with no surface avoidance and roads least wanted: Garmisch
* to the Eckbauer 63 % tracks and 38 % gravel.
* `use_roads` and the bicycle type also set the router's riding speed, so the
* time it gives is the profile's. None of it says a way is rideable or safe.
*/
export const BIKE_COSTING: Record<BikeProfile, Readonly<CostingOptions>> = {
touring: { bicycle_type: 'Hybrid', use_roads: 0.2, avoid_bad_surfaces: 1 },
road: { bicycle_type: 'Road', use_roads: 0.5, avoid_bad_surfaces: 1 },
gravel: { bicycle_type: 'Cross', use_roads: 0.1, avoid_bad_surfaces: 0.25 },
mtb: { bicycle_type: 'Mountain', use_roads: 0, avoid_bad_surfaces: 0 },
}
type LandWaypoint = Pick<Waypoint, 'lat' | 'lng'> & { fixedLeg?: TourFixedLeg | null }
/**
* Tours deliberately bypasses the OSRM-first RouteCalculator. A waypoint whose
* leg is fixed (a via ferrata on the tour) hands its own line over for that
* leg; the router only plans the runs between fixed legs, one request each.
*/
export async function routeWalkingTour(
waypoints: Array<Pick<Waypoint, 'lat' | 'lng'> & { fixedLeg?: TourFixedLeg | null }>,
waypoints: LandWaypoint[],
signal?: AbortSignal,
maxHikingDifficulty = TOURS_MAX_HIKING_DIFFICULTY,
preferences: HikingPreferences | null = null,
): Promise<TourRouteResult | null> {
): Promise<TourRouteResult | TourRouteUnreachable | null> {
return routeOnLand(waypoints, 'walking', {
max_hiking_difficulty: maxHikingDifficulty,
...hikingCostingOptions(preferences),
}, signal)
}
/** BIK-01: a bike tour, routed for its profile; a leg drawn by hand is kept as drawn. */
export async function routeBikeTour(
waypoints: LandWaypoint[],
profile: BikeProfile,
signal?: AbortSignal,
): Promise<TourRouteResult | TourRouteUnreachable | null> {
return routeOnLand(waypoints, 'cycling', BIKE_COSTING[profile], signal)
}
async function routeOnLand(
waypoints: LandWaypoint[],
mode: 'walking' | 'cycling',
costingOptions: Readonly<CostingOptions>,
signal?: AbortSignal,
): Promise<TourRouteResult | TourRouteUnreachable | null> {
const lines: TourRoutePart[] = []
let distanceMeters = 0
let durationSeconds = 0
const routeRun = async (run: Array<Pick<Waypoint, 'lat' | 'lng'>>) => {
let unreachable: TourRouteUnreachable | null = null
// `first`: where the run starts along the tour, so a point it cannot reach is named by its place in the tour.
const routeRun = async (run: Array<Pick<Waypoint, 'lat' | 'lng'>>, first: number) => {
if (run.length < 2) return true
const routed = await valhallaRun(run.map(({ lat, lng }) => ({ lat, lng })), 'walking', [], signal, {
max_hiking_difficulty: maxHikingDifficulty,
...hikingCostingOptions(preferences),
})
const routed = await valhallaRun(run.map(({ lat, lng }) => ({ lat, lng })), mode, [], signal, costingOptions)
if (!routed) return false
const far = routed.snapped.findIndex((point) => point.meters > MAX_TOUR_SNAP_M)
if (far >= 0) {
unreachable = { unreachable: first + far, snappedMeters: Math.round(routed.snapped[far].meters) }
return false
}
lines.push({ coordinates: routed.total.coordinates, free: false })
distanceMeters += routed.total.distance
durationSeconds += routed.total.duration
@@ -87,23 +139,26 @@ export async function routeWalkingTour(
}
let run: Array<Pick<Waypoint, 'lat' | 'lng'>> = waypoints.slice(0, 1)
let runStart = 0
for (let i = 0; i < waypoints.length - 1; i += 1) {
const leg = waypoints[i].fixedLeg
if (!leg) {
run.push(waypoints[i + 1])
continue
}
if (!(await routeRun(run))) return null
if (!(await routeRun(run, runStart))) return unreachable
const drawn = leg.geometry.map(([lat, lng]): [number, number] => [lat, lng])
// A hand-drawn leg is sampled along its length, so its heights follow the ground between its ends.
const line = leg.kind === 'ferrata' ? drawn : densifyLine(drawn)
const length = lineLengthM(line)
const kmPerHour = mode === 'cycling' && leg.kind === 'free' ? FREE_LEG_RIDING_KM_PER_HOUR : FIXED_LEG_KM_PER_HOUR[leg.kind]
lines.push({ coordinates: line, free: leg.kind !== 'ferrata', ...(leg.kind === 'portage' ? { land: true } : {}) })
distanceMeters += length
durationSeconds += (length / 1000 / FIXED_LEG_KM_PER_HOUR[leg.kind]) * 3600
durationSeconds += (length / 1000 / kmPerHour) * 3600
run = [waypoints[i + 1]]
runStart = i + 1
}
if (!(await routeRun(run))) return null
if (!(await routeRun(run, runStart))) return unreachable
if (lines.length === 0) return null
// One line: each part after the first starts where the one before it ended, so its first point goes.
@@ -0,0 +1,193 @@
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const { routeWalkingTour, routeBikeTour, enrichTourElevations, createTour, detailTour, updateTour } = vi.hoisted(
() => ({
routeWalkingTour: vi.fn(),
routeBikeTour: vi.fn(),
enrichTourElevations: vi.fn(),
createTour: vi.fn(),
detailTour: vi.fn(),
updateTour: vi.fn(),
})
);
vi.mock('./tourRouting', () => ({ routeWalkingTour, routeBikeTour, enrichTourElevations }));
vi.mock('../../../repo/tourRepo', () => ({ tourRepo: { create: createTour, detail: detailTour, update: updateTour } }));
vi.mock('../useTourPermissions', () => ({ useTourPermissions: () => ({ canEdit: true, canAssign: true }) }));
import { useTourPlanner } from './useTourPlanner';
// FE-TOUR-BIKE-001 to FE-TOUR-BIKE-005
const routed = {
coordinates: [
[48, 11],
[48.01, 11.02],
] as [number, number][],
parts: [
{
coordinates: [
[48, 11],
[48.01, 11.02],
] as [number, number][],
free: false,
},
],
distanceMeters: 9000,
durationSeconds: 1800,
};
const enriched = [
[48, 11, 500],
[48.01, 11.02, 560],
] as [number, number, number][];
const savedBike = {
place_id: 77,
name: 'Gravel loop',
tour_type: 'bike' as const,
bike_profile: 'gravel' as const,
distance: 9,
elevation_gain: 60,
elevation_loss: 0,
duration: 30,
difficulty: null,
wanderer_ref: null,
match_confidence: 1,
max_hiking_difficulty: null,
planned: false,
caution: false,
revision: 3,
};
const ferrata = {
kind: 'ferrata' as const,
ref: 'way/9',
name: 'Steig',
geometry: [
[48, 11],
[48.01, 11.02],
] as Array<[number, number]>,
};
async function settle() {
await act(async () => {
await vi.advanceTimersByTimeAsync(450);
});
}
describe('useTourPlanner, bike tours (BIK-01)', () => {
beforeEach(() => {
vi.useFakeTimers();
localStorage.clear();
routeWalkingTour.mockReset().mockResolvedValue(routed);
routeBikeTour.mockReset().mockResolvedValue(routed);
enrichTourElevations.mockReset().mockResolvedValue(enriched);
createTour.mockReset();
detailTour.mockReset();
updateTour.mockReset();
});
afterEach(() => vi.useRealTimers());
it('FE-TOUR-BIKE-001: a bike tour is routed for its profile, touring first, and never on foot', async () => {
const { result } = renderHook(() => useTourPlanner({ tripId: 51 }));
act(() => {
result.current.addWaypoint(48, 11);
result.current.addWaypoint(48.01, 11.02);
});
act(() => result.current.setTourType('bike'));
expect(result.current.isBike).toBe(true);
expect(result.current.bikeProfile).toBe('touring');
routeWalkingTour.mockClear();
await settle();
expect(routeBikeTour).toHaveBeenLastCalledWith(expect.any(Array), 'touring', expect.any(AbortSignal));
expect(routeWalkingTour).not.toHaveBeenCalled();
expect(result.current.status).toBe('ready');
// The router's riding time is the tour's time, heights or not.
expect(result.current.walkingDurationMinutes).toBe(30);
});
it('FE-TOUR-BIKE-002: a profile is one step of the history, kept in the draft, and plans the route again', async () => {
const { result } = renderHook(() => useTourPlanner({ tripId: 52 }));
act(() => {
result.current.addWaypoint(48, 11);
result.current.addWaypoint(48.01, 11.02);
result.current.setTourType('bike');
});
await settle();
act(() => result.current.setBikeProfile('road'));
expect(JSON.parse(localStorage.getItem('tour-draft-52') || 'null')).toMatchObject({
version: 10,
tourType: 'bike',
bikeProfile: 'road',
});
await settle();
expect(routeBikeTour).toHaveBeenLastCalledWith(expect.any(Array), 'road', expect.any(AbortSignal));
// The same profile again is no step; an undo takes it back.
act(() => result.current.setBikeProfile('road'));
act(() => result.current.undo());
expect(result.current.bikeProfile).toBe('touring');
act(() => result.current.redo());
expect(result.current.bikeProfile).toBe('road');
});
it('FE-TOUR-BIKE-003: a failed route keeps the last one planned and says so', async () => {
const { result } = renderHook(() => useTourPlanner({ tripId: 53 }));
act(() => {
result.current.addWaypoint(48, 11);
result.current.addWaypoint(48.01, 11.02);
result.current.setTourType('bike');
});
await settle();
expect(result.current.route).toEqual(routed.coordinates);
routeBikeTour.mockResolvedValueOnce(null);
act(() => result.current.setBikeProfile('mtb'));
await settle();
expect(result.current.status).toBe('routing-failed');
expect(result.current.error).toBe('routing');
expect(result.current.route).toEqual(routed.coordinates);
expect(result.current.canSave).toBe(false);
});
it('FE-TOUR-BIKE-004: switching to a bike tour drops a via ferrata, the router plans that leg', () => {
const { result } = renderHook(() => useTourPlanner({ tripId: 54 }));
act(() => result.current.appendFixedLeg(ferrata));
expect(result.current.waypoints[0].fixedLeg?.kind).toBe('ferrata');
act(() => result.current.setTourType('bike'));
expect(result.current.waypoints.some((point) => point.fixedLeg)).toBe(false);
act(() => result.current.undo());
expect(result.current.waypoints[0].fixedLeg?.kind).toBe('ferrata');
});
it('FE-TOUR-BIKE-005: opens a saved bike tour with its profile and saves it with nothing of a hike', async () => {
detailTour.mockResolvedValue({
tour: savedBike,
waypoints: [
{ lat: 48, lng: 11, role: 'start', sequence: 0 },
{ lat: 48.01, lng: 11.02, role: 'end', sequence: 1 },
],
});
updateTour.mockResolvedValue({ tour: { ...savedBike, revision: 4 }, waypoints: [] });
const { result } = renderHook(() => useTourPlanner({ tripId: 55 }));
await act(async () => {
await result.current.openTour({ place_id: 77 });
});
expect(result.current.tourType).toBe('bike');
expect(result.current.bikeProfile).toBe('gravel');
act(() => result.current.setName('Gravel loop, longer'));
await settle();
await act(async () => {
await result.current.save();
});
expect(updateTour).toHaveBeenCalledWith(
55,
77,
expect.objectContaining({
tour_type: 'bike',
bike_profile: 'gravel',
max_hiking_difficulty: null,
hiking_preferences: null,
expected_revision: 3,
})
);
});
});
@@ -293,6 +293,11 @@ describe('useTourPlanner route tools', () => {
act(() => result.current.paddle.setBoatType('canoe'));
act(() => result.current.paddle.setWaterContext('lake'));
// A route planned for another boat is not this one's: Save waits for the canoe's.
expect(result.current.canSave).toBe(false);
await act(async () => {
await vi.advanceTimersByTimeAsync(450);
});
expect(result.current.canSave).toBe(true);
await act(async () => {
await result.current.save();
@@ -324,6 +329,9 @@ describe('useTourPlanner route tools', () => {
act(() => result.current.paddle.setSpeedKmh(6));
act(() => result.current.paddle.setBoatType('other'));
await act(async () => {
await vi.advanceTimersByTimeAsync(450);
});
expect(result.current.paddle.speedKmh).toBe(6);
expect(result.current.walkingDurationMinutes).toBe(12);
@@ -1459,7 +1459,7 @@ describe('useTourPlanner', () => {
result.current.addWaypoint(48, 11)
result.current.addWaypoint(48.01, 11.02)
})
act(() => result.current.setHikingPreferences({ avoid_steps: true, shortest: false }))
act(() => result.current.setHikingPreferences({ avoid_steps: true, avoid_climbs: false }))
expect(result.current.hikingPreferences).toEqual({ avoid_steps: true })
expect(JSON.parse(localStorage.getItem('tour-draft-41') || 'null')).toMatchObject({ hikingPreferences: { avoid_steps: true } })
await act(async () => { await vi.advanceTimersByTimeAsync(450) })
@@ -1618,7 +1618,7 @@ describe('useTourPlanner', () => {
expect(result.current.mode).toEqual({ type: 'new-draft' })
expect(JSON.parse(localStorage.getItem('tour-draft-23') || 'null')).toMatchObject({
version: 9,
version: 10,
tourType: 'hike',
name: '',
waypoints: [],
@@ -1,12 +1,12 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { hikingPreferencesOf, paddleSpeedKmhSchema, tourWebsiteSchema, type HikingPreferences, type PlannableTourType, type TourCreateResponse, type TourFixedLeg, type TourListItem, type TourMaxHikingDifficulty } from '@trek/shared'
import { hikingPreferencesOf, paddleSpeedKmhSchema, tourWebsiteSchema, type BikeProfile, type HikingPreferences, type PlannableTourType, type TourCreateResponse, type TourFixedLeg, type TourListItem, type TourMaxHikingDifficulty } from '@trek/shared'
import { paddleRouteRepo } from '../../../repo/paddleRouteRepo'
import { tourRepo } from '../../../repo/tourRepo'
import { randomId } from '../../../utils/randomId'
import { analyzeRouteGeometry, type RouteProfileFocus } from '../../../utils/routeGeometry'
import { enrichTourElevations, routeWalkingTour, type TourElevationPoint, type TourRoutePart } from './tourRouting'
import { closeLoop, isClosedLoop, reverseRoute, toggleFreeLeg, withPointAppended } from './tourRouteActions'
import { normalizePlannerWaypoints, plannerWaypointsOf, sameWaypointSnapshot, savedWaypointsOf, tourWaypointKey, unlinkedPoint, type TourPlannerWaypoint } from './tourPlannerWaypoints'
import { hasCompleteElevation, useTourRoute } from './useTourRoute'
import { normalizePlannerWaypoints, plannerWaypointsOf, ridablePoints, sameWaypointSnapshot, savedWaypointsOf, unlinkedPoint, type TourPlannerWaypoint } from './tourPlannerWaypoints'
import { openedTourFields, tourPlannerFacts } from './tourPlannerFacts'
import { usePlannerHistory } from './usePlannerHistory'
import { useTourDraftStorage } from './useTourDraftStorage'
@@ -15,7 +15,7 @@ import { useRouteShaping } from './useRouteShaping'
import { useTourMapView } from './useTourMapView'
import type { DraftPayload } from './tourPlannerDraft'
import { paddleEstimateOf } from './paddlePlanOf'
import { adoptChangedPoints, planPaddleStep, type PaddleTourRoute } from './paddleRouting'
import { adoptChangedPoints } from './paddleRouting'
import { NO_PADDLE_FIELDS, paddleFieldsOf, usePaddleFields, type PaddleFieldValues } from './usePaddleFields'
import { useTourPermissions, type TourPermissionProps } from '../useTourPermissions'
@@ -35,9 +35,10 @@ export interface DerivedTourDraft {
inPlace: boolean
/** P2C-03: the import's revision, which a save planned over in place names. */
revision?: number
/** A paddle import stays a paddle tour, with its boat and water. */
/** A paddle import stays a paddle tour, with its boat and water, and a bike import a bike tour with its profile. */
tourType?: PlannableTourType
paddle?: PaddleFieldValues
bikeProfile?: BikeProfile
}
export type TourPlannerStatus =
@@ -52,12 +53,9 @@ export type TourPlannerStatus =
| 'saved'
/** One step of the history: the route, and what the route depends on. */
interface HistoryEntry { waypoints: TourPlannerWaypoint[]; difficulty: TourMaxHikingDifficulty; preferences: HikingPreferences | null; tourType: PlannableTourType }
const ROUTE_DEBOUNCE_MS = 450
function hasCompleteElevation(points: TourElevationPoint[] | null): points is [number, number, number][] {
return !!points && points.every(point => point.length === 3 && Number.isFinite(point[2]))
interface HistoryEntry {
waypoints: TourPlannerWaypoint[]; difficulty: TourMaxHikingDifficulty; preferences: HikingPreferences | null; bikeProfile: BikeProfile
tourType: PlannableTourType
}
/** Where a new tour was planned from; an edit leaves it as it was saved. */
@@ -113,6 +111,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
const [waypoints, setWaypoints] = useState<TourPlannerWaypoint[]>(restored?.waypoints ?? [])
const [maxHikingDifficulty, setMaxHikingDifficultyState] = useState<TourMaxHikingDifficulty>(restored?.maxHikingDifficulty ?? 2)
const [hikingPreferences, setHikingPreferencesState] = useState<HikingPreferences | null>(restored?.hikingPreferences ?? null)
const [bikeProfile, setBikeProfileState] = useState<BikeProfile>(restored?.bikeProfile ?? 'touring')
const [tourType, setTourTypeState] = useState<PlannableTourType>(restored?.tourType ?? 'hike')
const [selectedWaypointId, setSelectedWaypointId] = useState<string | null>(restored?.waypoints[0]?.id ?? null)
const history = usePlannerHistory<HistoryEntry>()
@@ -120,13 +119,6 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
const revision = useTourRevisionGuard(restored?.baseRevision ?? null)
const { adopt: adoptRevision, refuse: refuseRevision, baseRef: revisionBaseRef } = revision
const [status, setStatus] = useState<TourPlannerStatus>(restored?.waypoints.length ? 'dirty' : 'empty')
const [route, setRoute] = useState<[number, number][] | null>(null)
const [routeParts, setRouteParts] = useState<TourRoutePart[] | null>(null)
const [paddleRoute, setPaddleRoute] = useState<PaddleTourRoute | null>(null)
const [enrichedGeometry, setEnrichedGeometry] = useState<TourElevationPoint[] | null>(null)
const [routeForKey, setRouteForKey] = useState<string | null>(null)
const [distanceMeters, setDistanceMeters] = useState<number | null>(null)
const [durationSeconds, setDurationSeconds] = useState<number | null>(null)
const [error, setError] = useState<string | null>(null)
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(Boolean(restored))
const [isSaving, setIsSaving] = useState(false)
@@ -143,8 +135,6 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
const [routeProfileFocus, setRouteProfileFocus] = useState<RouteProfileFocus | null>(null)
const [newDraftGeneration, setNewDraftGeneration] = useState(0)
const [mapFocusKey, setMapFocusKey] = useState(0)
const abortRef = useRef<AbortController | null>(null)
const generationRef = useRef(0)
const draftRevisionRef = useRef(0)
const saveRequestIdRef = useRef(0)
const saveInFlightRef = useRef(false)
@@ -165,10 +155,14 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
const waypointsRef = useRef(waypoints)
const difficultyRef = useRef(maxHikingDifficulty)
const preferencesRef = useRef(hikingPreferences)
const bikeProfileRef = useRef(bikeProfile)
const tourTypeRef = useRef(tourType)
waypointsRef.current = waypoints
difficultyRef.current = maxHikingDifficulty
const snapshot = useCallback((): HistoryEntry => ({ waypoints: waypointsRef.current, difficulty: difficultyRef.current, preferences: preferencesRef.current, tourType: tourTypeRef.current }), [])
const snapshot = useCallback((): HistoryEntry => ({
waypoints: waypointsRef.current, difficulty: difficultyRef.current, preferences: preferencesRef.current,
bikeProfile: bikeProfileRef.current, tourType: tourTypeRef.current,
}), [])
useEffect(() => {
mountedRef.current = true
@@ -199,11 +193,36 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
invalidateDetailRequest()
}, [tripId, invalidateDetailRequest])
const interruptRouting = useCallback(() => {
generationRef.current += 1
abortRef.current?.abort()
abortRef.current = null
/** A field other than the route changed: the draft is unsaved again, and a finished save is no longer current. */
const markEdited = useCallback(() => {
if (!editPermissionRef.current) return false
invalidateDetailRequest()
draftRevisionRef.current += 1
setHasUnsavedChanges(true)
setSaveOutcome(null)
setStatus(current => current === 'saved' || current === 'saving' ? (waypointsRef.current.length < 2 ? 'dirty' : 'ready') : current)
return true
}, [invalidateDetailRequest])
const paddle = usePaddleFields(restored?.paddle ?? NO_PADDLE_FIELDS, markEdited)
const loadPaddle = paddle.load
const paddleBoat = paddle.boatType
// The router's own default where the tour names none, so a plan and its cache key agree.
const paddleLakeStyle = paddle.lakeStyle ?? 'direct'
// A point the router set (a paddle tour's) is laid in without a step of the history.
const patchWaypoints = useCallback((next: TourPlannerWaypoint[]) => {
waypointsRef.current = next
setWaypoints(next)
}, [])
const forgetFocus = useCallback(() => setRouteProfileFocus(null), [])
const routing = useTourRoute({
tripId, waypoints, tourType, maxHikingDifficulty, hikingPreferences, bikeProfile, paddleBoat, paddleLakeStyle, retryToken,
error, setStatus, setError, onCleared: forgetFocus, patchWaypoints,
})
const { route, routeParts, paddleRoute, enrichedGeometry, routeCurrent, distanceMeters, durationSeconds,
unreachable, interruptRouting, clearRoute } = routing
const commitWaypoints = useCallback((nextValue: TourPlannerWaypoint[] | ((current: TourPlannerWaypoint[]) => TourPlannerWaypoint[])) => {
if (!editPermissionRef.current) return
@@ -238,20 +257,29 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
setStatus('dirty')
}, [interruptRouting])
/** A hike's routing choices, its limit and its preferences (MF-08), as one step of the history; the route is planned again. */
const setRoutingChoice = useCallback((change: { difficulty?: TourMaxHikingDifficulty; preferences?: HikingPreferences | null }) => {
/**
* The routing choices, as one step of the history: a hike's limit and its
* preferences (MF-08), a bike tour's profile (BIK-01). The route is planned again.
*/
const setRoutingChoice = useCallback((change: {
difficulty?: TourMaxHikingDifficulty; preferences?: HikingPreferences | null; bikeProfile?: BikeProfile
}) => {
if (!editPermissionRef.current) return
const difficulty = change.difficulty ?? difficultyRef.current
const preferences = change.preferences === undefined ? preferencesRef.current : hikingPreferencesOf(change.preferences)
if (difficulty === difficultyRef.current && JSON.stringify(preferences) === JSON.stringify(preferencesRef.current)) return
const profile = change.bikeProfile ?? bikeProfileRef.current
if (difficulty === difficultyRef.current && profile === bikeProfileRef.current
&& JSON.stringify(preferences) === JSON.stringify(preferencesRef.current)) return
invalidateDetailRequest()
interruptRouting()
draftRevisionRef.current += 1
recordStep(snapshot())
difficultyRef.current = difficulty
preferencesRef.current = preferences
bikeProfileRef.current = profile
setMaxHikingDifficultyState(difficulty)
setHikingPreferencesState(preferences)
setBikeProfileState(profile)
setHasUnsavedChanges(true)
setSaveOutcome(null)
setStatus('dirty')
@@ -259,6 +287,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
}, [recordStep, invalidateDetailRequest, interruptRouting, snapshot])
const setMaxHikingDifficulty = useCallback((difficulty: TourMaxHikingDifficulty) => setRoutingChoice({ difficulty }), [setRoutingChoice])
const setHikingPreferences = useCallback((preferences: HikingPreferences | null) => setRoutingChoice({ preferences }), [setRoutingChoice])
const setBikeProfile = useCallback((profile: BikeProfile) => setRoutingChoice({ bikeProfile: profile }), [setRoutingChoice])
const addWaypoint = useCallback((lat: number, lng: number) => {
if (!editPermissionRef.current) return
@@ -368,10 +397,12 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
waypointsRef.current = entry.waypoints
difficultyRef.current = entry.difficulty
preferencesRef.current = entry.preferences
bikeProfileRef.current = entry.bikeProfile
tourTypeRef.current = entry.tourType
setWaypoints(entry.waypoints)
setMaxHikingDifficultyState(entry.difficulty)
setHikingPreferencesState(entry.preferences)
setBikeProfileState(entry.bikeProfile)
setTourTypeState(entry.tourType)
setSelectedWaypointId(id => entry.waypoints.some(point => point.id === id) ? id : entry.waypoints[0]?.id ?? null)
setHasUnsavedChanges(true)
@@ -392,16 +423,6 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
if (next) restoreStep(next)
}, [redoStep, restoreStep, snapshot])
/** A field other than the route changed: the draft is unsaved again, and a finished save is no longer current. */
const markEdited = useCallback(() => {
if (!editPermissionRef.current) return false
invalidateDetailRequest()
draftRevisionRef.current += 1
setHasUnsavedChanges(true)
setSaveOutcome(null)
setStatus(current => current === 'saved' || current === 'saving' ? (waypointsRef.current.length < 2 ? 'dirty' : 'ready') : current)
return true
}, [invalidateDetailRequest])
const setName = useCallback((value: string) => {
if (value !== name && markEdited()) setNameState(value)
@@ -423,15 +444,11 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
if (value !== breakAdditionalMinutes && markEdited()) setBreakAdditionalMinutesState(value)
}, [breakAdditionalMinutes, markEdited])
const paddle = usePaddleFields(restored?.paddle ?? NO_PADDLE_FIELDS, markEdited)
const loadPaddle = paddle.load
const paddleBoat = paddle.boatType
const paddleLakeStyle = paddle.lakeStyle
/**
* PAD-01: hike or paddle tour, as one step of the history with the route,
* since a paddle tour draws every leg by hand. Nothing is routed or put on
* a day by the choice itself.
* PAD-01, BIK-01: hike, bike or paddle tour, as one step of the history with
* the route, since a paddle tour draws every leg by hand and a bike tour
* rides no via ferrata. Nothing is put on a day by the choice itself.
*/
const setTourType = useCallback((value: PlannableTourType) => {
if (!editPermissionRef.current || saveInFlightRef.current || value === tourTypeRef.current) return
@@ -441,7 +458,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
recordStep(snapshot())
tourTypeRef.current = value
setTourTypeState(value)
const next = normalizePlannerWaypoints(waypointsRef.current, value === 'kayak')
const next = normalizePlannerWaypoints(value === 'bike' ? ridablePoints(waypointsRef.current) : waypointsRef.current, value === 'kayak')
waypointsRef.current = next
setWaypoints(next)
setHasUnsavedChanges(true)
@@ -458,14 +475,14 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
const paddleSpeedInvalid = paddle.speedKmh !== null && !paddleSpeedKmhSchema.safeParse(paddle.speedKmh).success
const { effectiveSpeedKmh, portageSpeedKmh, boatType, waterContext, speedKmh, lakeStyle } = paddle
// The routed length of each leg while the route is the current points' (PAD-11); straight lines before that.
const routedLegLengths = paddleRoute && routeForKey === tourWaypointKey(waypoints) ? paddleRoute.legLengths : undefined
const routedLegLengths = paddleRoute && routeCurrent ? paddleRoute.legLengths : undefined
const paddleEstimate = useMemo(() => isPaddle ? paddleEstimateOf(waypoints, { effectiveSpeedKmh, portageSpeedKmh }, paddleSpeedInvalid, routedLegLengths) : null,
[effectiveSpeedKmh, isPaddle, paddleSpeedInvalid, portageSpeedKmh, routedLegLengths, waypoints])
const facts = useMemo(() => tourPlannerFacts({
tourType, maxHikingDifficulty, hikingPreferences, website, plannedDurationMinutes, breakAdditionalMinutes,
tourType, maxHikingDifficulty, hikingPreferences, bikeProfile, website, plannedDurationMinutes, breakAdditionalMinutes,
paddle: { boatType, waterContext, speedKmh, portageSpeedKmh, lakeStyle },
paddleSpeedInvalid, paddleEstimate, routeAnalysis, durationSeconds,
}), [boatType, breakAdditionalMinutes, durationSeconds, hikingPreferences, lakeStyle, maxHikingDifficulty, paddleEstimate, paddleSpeedInvalid,
}), [bikeProfile, boatType, breakAdditionalMinutes, durationSeconds, hikingPreferences, lakeStyle, maxHikingDifficulty, paddleEstimate, paddleSpeedInvalid,
plannedDurationMinutes, portageSpeedKmh, routeAnalysis, speedKmh, tourType, waterContext, website])
const { websiteInvalid, plannedDurationInvalid, breakAdditionalInvalid, paddleIncomplete, walkingDurationMinutes,
plannedTotalMinutes, plannedTotalInvalid, savedDurationSeconds, typeFields } = facts
@@ -491,17 +508,13 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
difficultyRef.current = 2
preferencesRef.current = null
setHikingPreferencesState(null)
bikeProfileRef.current = 'touring'
setBikeProfileState('touring')
tourTypeRef.current = 'hike'
setSelectedWaypointId(null)
clearHistory()
setStatus('empty')
setRoute(null)
setRouteParts(null)
setPaddleRoute(null)
setEnrichedGeometry(null)
setRouteForKey(null)
setDistanceMeters(null)
setDurationSeconds(null)
clearRoute()
setError(null)
setHasUnsavedChanges(false)
setDraftRestored(false)
@@ -516,7 +529,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
setElevationProfileExpanded(true)
setNewDraftGeneration(generation => generation + 1)
setMapFocusKey(key => key + 1)
}, [adoptRevision, clearHistory, invalidateDetailRequest, interruptRouting, loadPaddle, forgetDraft])
}, [adoptRevision, clearHistory, clearRoute, invalidateDetailRequest, interruptRouting, loadPaddle, forgetDraft])
const forgetDeletedTour = useCallback((placeId: number) => {
deletedTourPlaceIdsRef.current.add(placeId)
@@ -561,6 +574,10 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
tourTypeRef.current = type
setTourTypeState(type)
if (draft.paddle) loadPaddle(draft.paddle)
if (draft.bikeProfile) {
bikeProfileRef.current = draft.bikeProfile
setBikeProfileState(draft.bikeProfile)
}
setNameState(draft.name)
setDescriptionState(draft.description ?? '')
setWebsiteState(draft.website ?? '')
@@ -656,17 +673,13 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
difficultyRef.current = opened.difficulty
preferencesRef.current = opened.preferences
setHikingPreferencesState(opened.preferences)
bikeProfileRef.current = opened.bikeProfile
setBikeProfileState(opened.bikeProfile)
tourTypeRef.current = opened.tourType
setSelectedWaypointId(nextWaypoints[0]?.id ?? null)
clearHistory()
setStatus('dirty')
setRoute(null)
setRouteParts(null)
setPaddleRoute(null)
setEnrichedGeometry(null)
setRouteForKey(null)
setDistanceMeters(null)
setDurationSeconds(null)
clearRoute()
setHasUnsavedChanges(false)
setDraftRestored(false)
setEditingPlaceId(result.tour.place_id)
@@ -686,7 +699,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
setOpeningTourId(null)
}
}
}, [adoptRevision, clearHistory, interruptRouting, loadPaddle, forgetDraft, tripId])
}, [adoptRevision, clearHistory, clearRoute, interruptRouting, loadPaddle, forgetDraft, tripId])
const retry = useCallback(() => {
if (waypointsRef.current.length < 2) return
@@ -705,7 +718,6 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
paddleRouteRepo.forget(tripId, from, to, { boat: paddleBoat ?? 'kayak', lakeStyle: paddleLakeStyle }), [paddleBoat, paddleLakeStyle, tripId]),
})
const waypointKey = useMemo(() => tourWaypointKey(waypoints), [waypoints])
const readOnlyGpxAnalysis = useMemo(
() => analyzeRouteGeometry(readOnlyGpxTour?.routeGeometry),
[readOnlyGpxTour?.routeGeometry],
@@ -714,116 +726,18 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
const focusOwner = mode.type === 'view-gpx' || mode.type === 'edit-saved' ? `${mode.type}:${mode.placeId}` : mode.type
useEffect(() => { setRouteProfileFocus(null) }, [focusOwner, routeAnalysis, readOnlyGpxAnalysis, readOnlyGpxTour])
useEffect(() => {
if (waypoints.length < 2) {
interruptRouting()
setStatus(waypoints.length === 0 ? 'empty' : 'dirty')
setRoute(null)
setRouteParts(null)
setRouteForKey(null)
setEnrichedGeometry(null)
setDistanceMeters(null)
setDurationSeconds(null)
setRouteProfileFocus(null)
setError(null)
return
}
const generation = ++generationRef.current
const controller = new AbortController()
abortRef.current?.abort()
abortRef.current = controller
const stale = () => controller.signal.aborted || generation !== generationRef.current
// Points the router set, changed by its own planning and not by the paddler: no step of the history.
const patch = (next: TourPlannerWaypoint[]) => {
waypointsRef.current = next
setWaypoints(next)
}
// PAD-11: a paddle tour is planned on the water by the server's router; its heights are no concern.
const routePaddle = async () => {
setStatus('routing')
const step = await planPaddleStep(waypoints, tripId, { boat: paddleBoat ?? 'kayak', lakeStyle: paddleLakeStyle }, controller.signal, randomId)
if (stale()) return
if ('points' in step) return patch(normalizePlannerWaypoints(step.points, true))
const planned = step.route
setRoute(planned.coordinates)
setRouteParts(planned.parts)
setPaddleRoute(planned)
setDistanceMeters(planned.distanceMeters)
setDurationSeconds(null)
setRouteForKey(waypointKey)
setEnrichedGeometry(planned.coordinates.map(([lat, lng]): [number, number, number] => [lat, lng, 0]))
if (planned.failures.length > 0) {
setStatus('routing-failed')
setError('paddle-route')
return
}
setStatus('ready')
setError(null)
}
const routeHike = async () => {
setStatus('routing')
const routed = await routeWalkingTour(waypoints, controller.signal, maxHikingDifficulty, hikingPreferences)
if (stale()) return
if (!routed) {
setStatus('routing-failed')
setError('routing')
return
}
setRoute(routed.coordinates)
setRouteParts(routed.parts)
setPaddleRoute(null)
setDistanceMeters(routed.distanceMeters)
setDurationSeconds(routed.durationSeconds)
setRouteForKey(waypointKey)
setEnrichedGeometry(null)
setStatus('enriching-elevation')
const enriched = await enrichTourElevations(routed.coordinates, controller.signal)
if (stale()) return
if (!enriched) {
setStatus('elevation-failed')
setError('elevation')
return
}
setEnrichedGeometry(enriched)
if (!hasCompleteElevation(enriched)) {
setStatus('elevation-failed')
setError('elevation')
return
}
setStatus('ready')
setError(null)
}
const timer = window.setTimeout(() => {
const run = isPaddle ? routePaddle() : routeHike()
run.catch(() => {
if (stale()) return
setStatus('routing-failed')
setError('routing')
})
}, ROUTE_DEBOUNCE_MS)
return () => {
window.clearTimeout(timer)
controller.abort()
}
}, [hikingPreferences, interruptRouting, isPaddle, maxHikingDifficulty, paddleBoat, paddleLakeStyle, retryToken, tripId, waypointKey, waypoints])
useEffect(() => {
if (!hasUnsavedChanges) return
const draft: DraftPayload = { version: 9, name, description, website, plannedDurationMinutes, breakAdditionalMinutes, waypoints, maxHikingDifficulty, editingPlaceId,
derivedFromPlaceId, tourType, baseRevision: revision.base, hikingPreferences,
const draft: DraftPayload = { version: 10, name, description, website, plannedDurationMinutes, breakAdditionalMinutes, waypoints, maxHikingDifficulty, editingPlaceId,
derivedFromPlaceId, tourType, baseRevision: revision.base, hikingPreferences, bikeProfile,
paddle: { boatType: paddle.boatType, waterContext: paddle.waterContext, speedKmh: paddle.speedKmh, portageSpeedKmh: paddle.portageSpeedKmh, lakeStyle: paddle.lakeStyle },
}
keepDraft(draft)
}, [breakAdditionalMinutes,
derivedFromPlaceId, description, editingPlaceId, hasUnsavedChanges, maxHikingDifficulty, name, plannedDurationMinutes, keepDraft, waypoints, website,
tourType, paddle.boatType, paddle.waterContext, paddle.speedKmh, paddle.portageSpeedKmh, paddle.lakeStyle, revision.base, hikingPreferences])
tourType, paddle.boatType, paddle.waterContext, paddle.speedKmh, paddle.portageSpeedKmh, paddle.lakeStyle, revision.base, hikingPreferences,
bikeProfile])
useEffect(() => {
if (!hasUnsavedChanges) return
@@ -833,7 +747,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
}, [hasUnsavedChanges])
const canSave = canEdit && !isSaving && hasUnsavedChanges && name.trim().length > 0 && status === 'ready'
&& routeForKey === waypointKey && hasCompleteElevation(enrichedGeometry)
&& routeCurrent && hasCompleteElevation(enrichedGeometry)
&& description.length <= 2000 && !websiteInvalid && !plannedDurationInvalid && !breakAdditionalInvalid && !plannedTotalInvalid
&& !paddleIncomplete && !(isPaddle && paddleSpeedInvalid)
@@ -915,6 +829,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
return {
tripId, canEdit, canAssign,
name, setName, maxHikingDifficulty, setMaxHikingDifficulty, hikingPreferences, setHikingPreferences,
bikeProfile, setBikeProfile, isBike: tourType === 'bike',
tourType, setTourType, isPaddle, paddle, paddleSpeedInvalid, paddleIncomplete,
description, setDescription, website, setWebsite, websiteInvalid,
plannedDurationMinutes, setPlannedDurationMinutes, plannedDurationInvalid,
@@ -923,10 +838,10 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
waypoints, selectedWaypointId, setSelectedWaypointId,
addWaypoint, appendFixedLeg, setWaypointPosition, removeWaypoint, moveWaypoint, reorderWaypoint, editWaypoints: commitWaypoints,
reverse, returnToStart, isLoop: isClosedLoop(waypoints), toggleWaypointFreeLeg, editPaddlePoints, amendWaypoints, paddleEstimate,
...shaping, paddleRoute, routeCurrent: routeForKey === waypointKey,
...shaping, paddleRoute, routeCurrent,
undo, redo, canUndo: history.canUndo, canRedo: history.canRedo,
status, error, retry, isSaving,
route, routeParts, enrichedGeometry, routeAnalysis, distanceMeters, durationSeconds,
route, routeParts, enrichedGeometry, routeAnalysis, distanceMeters, durationSeconds, unreachable,
routeProfileFocus, setRouteProfileFocus,
...mapView,
mode, readOnlyGpxTour, readOnlyGpxAnalysis, viewGpxTour, closeGpxTour,
@@ -0,0 +1,264 @@
import type {
BikeProfile,
HikingPreferences,
PaddleBoatType,
PaddleLakeStyle,
PlannableTourType,
TourMaxHikingDifficulty,
} from '@trek/shared';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { randomId } from '../../../utils/randomId';
import { planPaddleStep, type PaddleTourRoute } from './paddleRouting';
import { normalizePlannerWaypoints, tourWaypointKey, type TourPlannerWaypoint } from './tourPlannerWaypoints';
import { isTourRoute, type TourRouteUnreachable } from './tourRouteOutcome';
import {
enrichTourElevations,
routeBikeTour,
routeWalkingTour,
type TourElevationPoint,
type TourRoutePart,
} from './tourRouting';
import type { TourPlannerStatus } from './useTourPlanner';
const ROUTE_DEBOUNCE_MS = 450;
/** What the route of a draft is planned from: its points, its type and the choices the router is asked for. */
export interface TourRouteInputs {
tripId: number | string;
waypoints: TourPlannerWaypoint[];
tourType: PlannableTourType;
maxHikingDifficulty: TourMaxHikingDifficulty;
hikingPreferences: HikingPreferences | null;
bikeProfile: BikeProfile;
paddleBoat: PaddleBoatType | null;
paddleLakeStyle: PaddleLakeStyle;
/** Raised to plan the same points again. */
retryToken: number;
/** The planner's error, so a point found unreachable is only named while that is the error. */
error: string | null;
setStatus: (status: TourPlannerStatus) => void;
setError: (error: string | null) => void;
onCleared: () => void;
/** Points the router set itself (a paddle tour's), laid in without a step of the history. */
patchWaypoints: (next: TourPlannerWaypoint[]) => void;
}
/** A route as planned, and what it was planned for (`forKey`). */
interface PlannedRoute {
route: [number, number][] | null;
routeParts: TourRoutePart[] | null;
paddleRoute: PaddleTourRoute | null;
enrichedGeometry: TourElevationPoint[] | null;
distanceMeters: number | null;
durationSeconds: number | null;
forKey: string | null;
}
const NO_ROUTE: PlannedRoute = {
route: null,
routeParts: null,
paddleRoute: null,
enrichedGeometry: null,
distanceMeters: null,
durationSeconds: null,
forKey: null,
};
/** One planning run: what it plans from, whether it went stale, and where it writes. */
interface RouteRun {
inputs: Omit<TourRouteInputs, 'retryToken' | 'error' | 'onCleared'>;
plannedKey: string;
signal: AbortSignal;
stale: () => boolean;
setPlanned: (next: PlannedRoute | ((current: PlannedRoute) => PlannedRoute)) => void;
setUnreachable: (unreachable: TourRouteUnreachable | null) => void;
}
// PAD-11: a paddle tour is planned on the water by the server's router; its heights are no concern.
async function routePaddle({ inputs, plannedKey, signal, stale, setPlanned }: RouteRun) {
const { waypoints, tripId, paddleBoat, paddleLakeStyle, setStatus, setError } = inputs;
setStatus('routing');
const profile = { boat: paddleBoat ?? 'kayak', lakeStyle: paddleLakeStyle } as const;
const step = await planPaddleStep(waypoints, tripId, profile, signal, randomId);
if (stale()) return;
if ('points' in step) return inputs.patchWaypoints(normalizePlannerWaypoints(step.points, true));
const planned = step.route;
setPlanned({
route: planned.coordinates,
routeParts: planned.parts,
paddleRoute: planned,
enrichedGeometry: planned.coordinates.map(([lat, lng]): [number, number, number] => [lat, lng, 0]),
distanceMeters: planned.distanceMeters,
durationSeconds: null,
forKey: plannedKey,
});
const failed = planned.failures.length > 0;
setStatus(failed ? 'routing-failed' : 'ready');
setError(failed ? 'paddle-route' : null);
}
// A hike or a bike tour on land, then the heights along it.
async function routeOnLand({ inputs, plannedKey, signal, stale, setPlanned, setUnreachable }: RouteRun) {
const { waypoints, tourType, bikeProfile, maxHikingDifficulty, hikingPreferences, setStatus, setError } = inputs;
setStatus('routing');
const routed =
tourType === 'bike'
? await routeBikeTour(waypoints, bikeProfile, signal)
: await routeWalkingTour(waypoints, signal, maxHikingDifficulty, hikingPreferences);
if (stale()) return;
if (!isTourRoute(routed)) {
setUnreachable(routed);
setStatus('routing-failed');
setError(routed ? 'unreachable' : 'routing');
return;
}
setUnreachable(null);
setPlanned({
route: routed.coordinates,
routeParts: routed.parts,
paddleRoute: null,
enrichedGeometry: null,
distanceMeters: routed.distanceMeters,
durationSeconds: routed.durationSeconds,
forKey: plannedKey,
});
setStatus('enriching-elevation');
const enriched = await enrichTourElevations(routed.coordinates, signal);
if (stale()) return;
if (enriched) setPlanned((current) => ({ ...current, enrichedGeometry: enriched }));
if (!hasCompleteElevation(enriched)) {
setStatus('elevation-failed');
setError('elevation');
return;
}
setStatus('ready');
setError(null);
}
/**
* The route of the planner's draft, planned again a moment after its points
* or its choices change: a hike on foot within its limit, a bike tour for its
* profile (BIK-01), a paddle tour on the water by the server's router. A hike
* and a bike tour then get their heights; a later change makes an answer
* still on its way stale, and a failure keeps the last route that was planned.
*/
export function useTourRoute(inputs: TourRouteInputs) {
const {
tripId,
waypoints,
tourType,
maxHikingDifficulty,
hikingPreferences,
bikeProfile,
paddleBoat,
paddleLakeStyle,
retryToken,
error,
setStatus,
setError,
onCleared,
patchWaypoints,
} = inputs;
const [planned, setPlanned] = useState<PlannedRoute>(NO_ROUTE);
// A point no way of the tour's type reaches, and how far off the router would have bound it.
const [unreachable, setUnreachable] = useState<TourRouteUnreachable | null>(null);
const abortRef = useRef<AbortController | null>(null);
const generationRef = useRef(0);
/** Any answer still on its way is stale from here on. */
const interruptRouting = useCallback(() => {
generationRef.current += 1;
abortRef.current?.abort();
abortRef.current = null;
}, []);
/** No route at all, as for an empty draft. */
const clearRoute = useCallback(() => setPlanned(NO_ROUTE), []);
const waypointKey = useMemo(() => tourWaypointKey(waypoints), [waypoints]);
// What a route was planned for besides its points: a route of another type or profile is not this one's.
const choices = [tourType, bikeProfile, maxHikingDifficulty, hikingPreferences, paddleBoat, paddleLakeStyle];
const plannedKey = `${waypointKey}#${JSON.stringify(choices)}`;
useEffect(() => {
if (waypoints.length < 2) {
interruptRouting();
setStatus(waypoints.length === 0 ? 'empty' : 'dirty');
clearRoute();
onCleared();
setError(null);
return;
}
const generation = ++generationRef.current;
const controller = new AbortController();
abortRef.current?.abort();
abortRef.current = controller;
const stale = () => controller.signal.aborted || generation !== generationRef.current;
const run: RouteRun = {
inputs: {
tripId,
waypoints,
tourType,
maxHikingDifficulty,
hikingPreferences,
bikeProfile,
paddleBoat,
paddleLakeStyle,
setStatus,
setError,
patchWaypoints,
},
plannedKey,
signal: controller.signal,
stale,
setPlanned,
setUnreachable,
};
const timer = window.setTimeout(() => {
(tourType === 'kayak' ? routePaddle(run) : routeOnLand(run)).catch(() => {
if (stale()) return;
setStatus('routing-failed');
setError('routing');
});
}, ROUTE_DEBOUNCE_MS);
return () => {
window.clearTimeout(timer);
controller.abort();
};
}, [
bikeProfile,
clearRoute,
hikingPreferences,
interruptRouting,
maxHikingDifficulty,
onCleared,
paddleBoat,
paddleLakeStyle,
patchWaypoints,
plannedKey,
retryToken,
setError,
setStatus,
tourType,
tripId,
waypoints,
]);
const { forKey, ...shown } = planned;
return {
...shown,
/** The route shown was planned for these points and these choices. */
routeCurrent: forKey === plannedKey,
unreachable: error === 'unreachable' ? unreachable : null,
interruptRouting,
clearRoute,
};
}
export function hasCompleteElevation(points: TourElevationPoint[] | null): points is [number, number, number][] {
return !!points && points.every((point) => point.length === 3 && Number.isFinite(point[2]));
}