feat(tours): route paddle tours on the water, shaping points and auto-loaded regions

Paddle tours are planned on the water by TREK's own router: a water network
per paddle region, built from the same Geofabrik extract as the obstacles and
searched in a worker thread of the server (no sidecar). Rivers, canals and
lakes (direct or along the shore), portages round weirs, locks by policy,
whitewater by boat, gaps marked. Found portages and locks become points of
their own; an unplannable leg says why and offers a way out.

- Shaping points: a click on the line sets a point that steers the route
  without being a stop (hikes and paddle tours); recompute a single leg.
- Lake style direct/shore, suggested from the wind forecast.
- Regions load by themselves where a paddler plans (admin setting: automatic,
  on request, off; size cap and a daily count), with requests for the admins,
  a notification, and the load followed on the leg.
- Portage from the last point, portages follow footways via the walking
  router (or stay straight), "put in here" on slipways and put-ins.
- MCP plan_paddle_route with the REST route's rules.
This commit is contained in:
Maurice
2026-10-18 01:13:24 +02:00
parent b76a298bb3
commit 1bc82f97fd
321 changed files with 14675 additions and 471 deletions
@@ -926,6 +926,24 @@ describe('the paddle checklist in the rails (PAD-06)', () => {
expect(safetyRow()).toBeInTheDocument()
})
it('PCR-006: legs the water router could not plan are counted in the head, without the retry the rows already offer', () => {
const failed = paddleEditor({
status: 'routing-failed',
error: 'paddle-route',
paddleRoute: { coordinates: [], parts: [], distanceMeters: 0, legs: [], legLengths: [], failures: [
{ index: 0, code: 'not_on_water', at: null },
{ index: 1, code: 'busy', at: null },
] },
})
const { rerender } = render(<TourPlannerRail planner={failed} />)
expect(within(screen.getByTestId('tour-planner-status')).getByLabelText('2 legs not planned')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'Retry' })).not.toBeInTheDocument()
rerender(<TourPlannerRail planner={planner({ mode: { type: 'new-draft' }, status: 'routing-failed', error: 'routing' })} />)
expect(within(screen.getByTestId('tour-planner-status')).getByLabelText('Route calculation failed. The last good route is still shown.')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument()
})
it('PCR-005: a recorded kayak track scrolls its checklist before the wind and keeps the safety row in a footer; a recorded hike neither', () => {
const { rerender } = render(<TourPlannerRail planner={recorded(kayak)} paddleChecklist={checklist} />)
@@ -19,6 +19,7 @@ import { formatPlannedTourDuration, hikeSourceBadgeLabel, tourSource } from '../
import { CardAction, FoldButton, RailCard, RailFacts, TourDayMenu, TourListCard, TourNotice, TourSection } from '../tourParts'
import { movingTimeLabel, tourMetricFacts, withoutHeights } from '../tourFacts'
import { TourDetailsSection, TourNameField } from './TourEditorFields'
import { crossesLake } from '../paddle/lakeStyleAdvice'
import { PaddleCheckCard } from '../paddle/PaddleCheckCard'
import { PaddleSafetyRow } from '../paddle/PaddleSafety'
import { PaddleTimeCard } from '../paddle/PaddleTimeCard'
@@ -121,6 +122,18 @@ 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
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 })
return t(key)
}
/**
* What the editor is doing right now, as icon badges beside the head's title:
* a restored draft, routing or saving, and a failure with its retry. Nothing
@@ -132,10 +145,10 @@ function RailStatusBadges({ planner }: { planner: TourPlannerController }) {
const restored = planner.draftRestored && planner.hasUnsavedChanges
const onFerrata = useTourFerrataCrossingStore(state => state.crossings.length > 0)
const failed = planner.error === 'save'
const canRetry = planner.status === 'routing-failed' || planner.status === 'elevation-failed'
const canRetry = retryable(planner)
if (!restored && !statusKey && !failed && !onFerrata) return null
const warning = planner.error != null || canRetry
const statusLabel = failed ? t('tours.planner.status.saveFailed') : statusKey ? t(statusKey) : null
const statusLabel = failed ? t('tours.planner.status.saveFailed') : statusKey ? statusText(planner, statusKey, t) : null
const busy = planner.isSaving || planner.status === 'routing' || planner.status === 'enriching-elevation'
return (
<span role="status" data-testid="tour-planner-status" className="ms-1.5 flex flex-none items-center gap-1">
@@ -326,7 +339,11 @@ function PaddleEditorCards({ planner, locked, checklist }: {
<>
{checklist && <PaddleCheckCard checklist={checklist} />}
<PaddleTimeCard planner={planner} locked={locked} />
<PaddleWindSection placeId={planner.editingPlaceId} start={planner.waypoints[0] ?? null} />
<PaddleWindSection
placeId={planner.editingPlaceId}
start={planner.waypoints[0] ?? null}
lakes={!locked && crossesLake(planner.paddleRoute) ? { value: planner.paddle.lakeStyle, onChoose: planner.paddle.setLakeStyle } : undefined}
/>
</>
)
}
@@ -75,3 +75,33 @@ describe('TourTypeFields (PAD-01)', () => {
expect(screen.getByText(/enter a speed|speed of your own/i)).toBeInTheDocument();
});
});
describe('TourTypeFields lake style (PAD-11)', () => {
it('asks how to cross lakes on lake water or a route over a lake, straight over by default, and hands a change on', () => {
const river = planner({}, { waterContext: 'river' });
const { rerender } = render(<TourTypeFields planner={river} locked={false} />);
expect(screen.queryByTestId('tour-planner-lake-style')).not.toBeInTheDocument();
const lake = planner({}, { waterContext: 'lake' });
rerender(<TourTypeFields planner={lake} locked={false} />);
expect(screen.getByRole('button', { name: 'Straight over' })).toHaveAttribute('aria-pressed', 'true');
expect(screen.getByText('The shortest line across open water.')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Near the shore' }));
expect(lake.paddle.setLakeStyle).toHaveBeenCalledWith('shore');
const lakeLeg = {
status: 'ok',
geometry: [
[53.4, 12.7],
[53.5, 12.7],
],
segments: [{ kind: 'lake', from: 0, to: 1, name: null, source: null, osm_ref: null, grade: null }],
distance_m: 11000,
snapped_m: { from: 0, to: 0 },
};
const crossing = planner({ paddleRoute: { legs: [lakeLeg] } }, { waterContext: 'river', lakeStyle: 'shore' });
rerender(<TourTypeFields planner={crossing} locked={false} />);
expect(screen.getByRole('button', { name: 'Near the shore' })).toHaveAttribute('aria-pressed', 'true');
expect(screen.getByText('Stays near the bank, for windy days: longer, but land is never far.')).toBeInTheDocument();
});
});
@@ -10,6 +10,8 @@ import { useTranslation } from '../../../i18n';
import { SoftPill } from '../../Planner/planParts';
import { INPUT, LABEL, Segmented } from '../../shared/dialogParts';
import { fs } from '../../shared/DialogShell';
import { crossesLake } from '../paddle/lakeStyleAdvice';
import { PaddleLakeStyleField } from '../paddle/PaddleLakeStyleField';
import { TourNotice } from '../tourParts';
import type { TourPlannerController } from './useTourPlanner';
@@ -126,6 +128,9 @@ export function TourTypeFields({ planner, locked }: TourTypeFieldsProps) {
options={WATERS.map((water) => ({ value: water, label: t(`tours.paddle.water.${water}`) }))}
/>
</div>
{(paddle.waterContext === 'lake' || crossesLake(planner.paddleRoute)) && (
<PaddleLakeStyleField value={paddle.lakeStyle} onChange={paddle.setLakeStyle} />
)}
<div className="min-w-0">
<div className="mb-[5px] flex min-h-5 min-w-0 items-center gap-1.5">
<label className={`${LABEL} !mb-0 min-w-0 truncate leading-5`} htmlFor="tour-planner-paddle-speed">
@@ -0,0 +1,167 @@
// FE-TOUR-WAYPOINT-LIST-001 to FE-TOUR-WAYPOINT-LIST-006: shaping points and the water router's answers in the list (P2A-03, P2A-05, PAD-11).
import userEvent from '@testing-library/user-event';
import type { PaddleRouteLeg } from '@trek/shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { render, screen, within } from '../../../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../../../tests/helpers/store';
import { hikePlannerDefaults } from '../../../../tests/helpers/tourPlannerStub';
import { useSettingsStore } from '../../../store/settingsStore';
import type { PaddleTourRoute } from './paddleRouting';
import TourWaypointList from './TourWaypointList';
import type { TourPlannerController } from './useTourPlanner';
vi.mock('./useWaypointPlaceNames', () => ({ useWaypointPlaceNames: () => ({}) }));
const START = { id: 'a', lat: 49.1, lng: 12.1, role: 'start' as const };
const SHAPE = { id: 's', lat: 49.08, lng: 12.11, role: 'via' as const, shaping: true };
const STOP = { id: 'b', lat: 49.05, lng: 12.12, role: 'via' as const };
const END = { id: 'c', lat: 49.0, lng: 12.1, role: 'end' as const };
const segment = (kind: 'water' | 'rapids' | 'pass' | 'gap', from: number, to: number, grade: number | null = null) => ({
kind,
from,
to,
name: null,
source: null,
osm_ref: null,
grade,
});
const WHITEWATER: PaddleRouteLeg = {
status: 'ok',
geometry: [
[49.05, 12.12],
[49.04, 12.12],
[49.03, 12.115],
[49.0, 12.1],
],
segments: [segment('water', 0, 1), segment('rapids', 1, 2, 2), segment('gap', 2, 3)],
distance_m: 5800,
snapped_m: { from: 0, to: 0 },
};
function planner(overrides: Partial<TourPlannerController> = {}): TourPlannerController {
return {
...hikePlannerDefaults(),
waypoints: [START, SHAPE, STOP, END],
selectedWaypointId: null,
setSelectedWaypointId: vi.fn(),
reorderWaypoint: vi.fn(),
moveWaypoint: vi.fn(),
removeWaypoint: vi.fn(),
...overrides,
} as unknown as TourPlannerController;
}
function paddleRoute(legs: PaddleTourRoute['legs'], failures: PaddleTourRoute['failures'] = []): PaddleTourRoute {
return { coordinates: [], parts: [], distanceMeters: 0, legs, legLengths: legs.map(() => 0), failures };
}
beforeEach(() => {
resetAllStores();
seedStore(useSettingsStore, { settings: { distance_unit: 'metric' } });
});
describe('TourWaypointList', () => {
it('FE-TOUR-WAYPOINT-LIST-001: numbers the stops only; a shaping point is a dot and does not count', () => {
render(<TourWaypointList planner={planner()} canEdit isSaving={false} />);
const rows = screen.getAllByTestId('tour-planner-waypoint-row');
expect(rows).toHaveLength(4);
expect(within(rows[1]!).getByLabelText('Shaping point')).toHaveAttribute('data-waypoint-shaping', 'true');
expect(
[...document.querySelectorAll('[data-waypoint-number]')].map((el) => el.getAttribute('data-waypoint-number'))
).toEqual(['1', '2', '3']);
expect(screen.getByText('Click the route on the map to add a shaping point there.')).toBeInTheDocument();
});
it('FE-TOUR-WAYPOINT-LIST-002: the menu plans a routed leg again, draws it by hand, and turns a stop into a shaping point', async () => {
const controller = planner({ selectedWaypointId: 'b' });
render(<TourWaypointList planner={controller} canEdit isSaving={false} />);
const row = screen.getAllByTestId('tour-planner-waypoint-row')[2]!;
await userEvent.click(within(row).getByRole('button', { name: 'More actions' }));
await userEvent.click(screen.getByRole('button', { name: 'Plan the next leg again' }));
expect(controller.recomputeLeg).toHaveBeenCalledWith('b');
await userEvent.click(within(row).getByRole('button', { name: 'More actions' }));
await userEvent.click(screen.getByRole('button', { name: 'Make it a shaping point' }));
expect(controller.setWaypointShaping).toHaveBeenCalledWith('b', true);
await userEvent.click(within(row).getByRole('button', { name: 'More actions' }));
await userEvent.click(screen.getByRole('button', { name: 'Draw the next leg by hand' }));
expect(controller.toggleWaypointFreeLeg).toHaveBeenCalledWith('b');
});
it('FE-TOUR-WAYPOINT-LIST-003: a shaping point becomes a stop again; the first point offers no shaping', async () => {
const controller = planner({ selectedWaypointId: 's' });
const { rerender } = render(<TourWaypointList planner={controller} canEdit isSaving={false} />);
await userEvent.click(
within(screen.getAllByTestId('tour-planner-waypoint-row')[1]!).getByRole('button', { name: 'More actions' })
);
await userEvent.click(screen.getByRole('button', { name: 'Make it a stop' }));
expect(controller.setWaypointShaping).toHaveBeenCalledWith('s', false);
rerender(<TourWaypointList planner={planner({ selectedWaypointId: 'a' })} canEdit isSaving={false} />);
await userEvent.click(
within(screen.getAllByTestId('tour-planner-waypoint-row')[0]!).getByRole('button', { name: 'More actions' })
);
expect(screen.queryByRole('button', { name: 'Make it a shaping point' })).not.toBeInTheDocument();
});
it('FE-TOUR-WAYPOINT-LIST-004: a paddle leg shows its whitewater and its data gap with their lengths', () => {
const route = paddleRoute([null, null, WHITEWATER]);
render(
<TourWaypointList
planner={planner({ ...{ isPaddle: true, tourType: 'kayak' }, paddleRoute: route, routeCurrent: true })}
canEdit
isSaving={false}
/>
);
const notes = screen.getByTestId('tour-planner-leg-notes');
expect(within(notes).getByText('Whitewater 2')).toBeInTheDocument();
expect(within(notes).getByText('Gap in the map data')).toBeInTheDocument();
});
it('FE-TOUR-WAYPOINT-LIST-005: a leg the router could not plan says why and offers the way out', async () => {
const route = paddleRoute(
[{ status: 'failed', code: 'busy', at: null }, null, null],
[{ index: 0, code: 'busy', at: null }]
);
const controller = planner({ isPaddle: true, tourType: 'kayak', paddleRoute: route, routeCurrent: true });
render(<TourWaypointList planner={controller} canEdit isSaving={false} />);
const failure = screen.getByTestId('tour-planner-leg-failure');
expect(within(failure).getByRole('alert')).toHaveTextContent('The route planner is busy. Try again in a moment.');
await userEvent.click(within(failure).getByRole('button', { name: 'Try again' }));
expect(controller.recomputeLeg).toHaveBeenCalledWith('a');
await userEvent.click(within(failure).getByRole('button', { name: 'Draw straight' }));
expect(controller.toggleWaypointFreeLeg).toHaveBeenCalledWith('a');
});
it('FE-TOUR-WAYPOINT-LIST-006: a point off the water offers no retry; legs drawn by hand can go back to the water in one step', async () => {
const drawn = {
kind: 'free' as const,
geometry: [
[49.1, 12.1],
[49.08, 12.11],
] as [number, number][],
};
const route = paddleRoute(
[null, { status: 'failed', code: 'not_on_water', at: null }, null],
[{ index: 1, code: 'not_on_water', at: null }]
);
const auto = { from: { id: 'a', lat: 49.1, lng: 12.1 }, to: { id: 'c', lat: 49.0, lng: 12.1 } };
const controller = planner({
isPaddle: true,
tourType: 'kayak',
paddleRoute: route,
routeCurrent: true,
waypoints: [{ ...START, fixedLeg: drawn }, SHAPE, { ...STOP, auto }, END],
});
render(<TourWaypointList planner={controller} canEdit isSaving={false} />);
expect(
within(screen.getByTestId('tour-planner-leg-failure')).queryByRole('button', { name: 'Try again' })
).toBeNull();
expect(screen.getByTestId('tour-planner-auto-point')).toHaveAttribute('aria-label', 'Found');
await userEvent.click(screen.getByTestId('tour-planner-route-on-water'));
expect(controller.routeDrawnLegsOnWater).toHaveBeenCalled();
});
});
@@ -1,16 +1,24 @@
import { paddleLayoutOfPoints, type PaddleLayout, type PaddleRole, type TourFixedLeg } from '@trek/shared';
import {
paddleLayoutOfPoints,
type PaddleLayout,
type PaddleRegionLoadState,
type PaddleRole,
type TourFixedLeg,
} from '@trek/shared';
import {
ArrowDown,
ArrowDownUp,
ArrowUp,
GripVertical,
Info,
MapPin,
MapPinPlus,
MoreHorizontal,
Navigation,
RefreshCw,
Repeat,
Spline,
Trash2,
Waves,
} from 'lucide-react';
import { Fragment, useState, type MouseEvent, type ReactNode } from 'react';
import { useTranslation } from '../../../i18n';
@@ -28,10 +36,15 @@ import { ContextMenu, useContextMenu } from '../../shared/ContextMenu';
import { fs } from '../../shared/DialogShell';
import { Tooltip } from '../../shared/Tooltip';
import { LockIcon, PortageIcon } from '../paddle/PaddleGlyph';
import { LockRow, PaddleRolePill, PortageLegRow } from '../paddle/PaddleWaypointParts';
import { AutoPointPill, PaddleLegFailureRow, PaddleLegNotes } from '../paddle/PaddleLegParts';
import { isRegionLoadPending, PaddleRegionLoadRow, regionLoadFailure } from '../paddle/PaddleRegionLoadRow';
import { LockRow, PaddleRolePill, PendingPortageRow, PortageLegRow } from '../paddle/PaddleWaypointParts';
import { usePaddleRegionLoad } from '../paddle/usePaddleRegionLoad';
import { usePaddleWaypointActions } from '../paddle/usePaddleWaypointActions';
import { RailCard, TourNotice } from '../tourParts';
import { usePortageRouting, usePortageWay } from '../paddle/usePortageRouting';
import { RailCard } from '../tourParts';
import { paddlePlanPoints, paddleRolesById } from './paddlePlanOf';
import type { PaddleLegFailure } from './paddleRouting';
import { lineLengthM } from './tourFixedLegs';
import type { TourPlannerController } from './useTourPlanner';
import { useWaypointPlaceNames } from './useWaypointPlaceNames';
@@ -207,18 +220,35 @@ function FerrataLegRow({ crossing }: { crossing: TourFerrataCrossing }) {
* by the tooltip.
*/
function WaypointNumber({
index,
stop,
selected,
ferrata,
loopEnd = false,
shaping = false,
}: {
index: number;
/** The stop's number; shaping points do not count, as on the map. */
stop: number;
selected: boolean;
ferrata: TourWaypointFerrata | null;
/** The way back to the start of a loop: shown as the return, not as one more stop. */
loopEnd?: boolean;
/** P2A-03: a shaping point, a small dot as on the map. */
shaping?: boolean;
}) {
const { t } = useTranslation();
if (shaping) {
return (
<span
aria-label={t('tours.planner.shapingPoint')}
data-waypoint-shaping="true"
className="grid h-7 w-7 flex-none place-items-center"
>
<span
className={`h-3 w-3 rounded-full ring-2 ring-surface-card ${selected ? 'bg-accent' : 'bg-content-faint'}`}
/>
</span>
);
}
if (loopEnd) {
return (
<span
@@ -230,16 +260,16 @@ function WaypointNumber({
</span>
);
}
const label = t('tours.planner.waypointLabel', { n: index + 1 });
const label = t('tours.planner.waypointLabel', { n: stop });
const number = (
<span
aria-label={ferrata ? `${label}, ${t('tours.ferrata.waypointAtEnd', { name: ferrata.name })}` : label}
data-waypoint-number={index + 1}
data-waypoint-number={stop}
data-ferrata-end={ferrata ? 'true' : undefined}
className={`relative grid h-7 w-7 flex-none place-items-center rounded-full font-geist font-semibold tabular-nums ${selected ? 'bg-accent text-accent-text' : 'bg-edge text-content'} ${ferrata ? 'ring-2 ring-inset ring-[color:var(--map-ferrata)]' : ''}`}
style={fs(11.5)}
>
{index + 1}
{stop}
{ferrata && <FerrataGlyph size={22} className="absolute -bottom-2.5 -start-2.5" />}
</span>
);
@@ -278,9 +308,18 @@ function WaypointRowLabel({
>
{name ?? coordinates}
</span>
{paddleRole !== undefined
? paddleRole && !loopEnd && <PaddleRolePill role={paddleRole} />
: point.role !== 'via' && !loopEnd && <SoftPill>{t(ROLE_KEY[point.role])}</SoftPill>}
{point.shaping ? (
<Tooltip label={t('tours.planner.shapingHint')}>
<span className="inline-flex">
<SoftPill>{t('tours.planner.shapingPoint')}</SoftPill>
</span>
</Tooltip>
) : paddleRole !== undefined ? (
paddleRole && !loopEnd && <PaddleRolePill role={paddleRole} />
) : (
point.role !== 'via' && !loopEnd && <SoftPill>{t(ROLE_KEY[point.role])}</SoftPill>
)}
{point.auto && <AutoPointPill />}
</span>
{name && !loopEnd && (
<span
@@ -302,6 +341,82 @@ function WaypointRowLabel({
* and remove beside it. Two controls keep the place name readable in a narrow
* rail however many tools a tour type adds.
*/
type MenuItems = Parameters<ReturnType<typeof useContextMenu>['open']>[1];
type Translate = ReturnType<typeof useTranslation>['t'];
type WaypointPoint = TourPlannerController['waypoints'][number];
/**
* The tools for the leg after a point: drawn by hand or routed (on a paddle
* tour: on the water), planned again (P2A-05), and the point a stop or a
* shaping point (P2A-03; never the first or the last).
*/
function routeMenuItems(
planner: TourPlannerController,
point: WaypointPoint,
index: number,
lastIndex: number,
t: Translate
): MenuItems {
const hasLeg = index < lastIndex;
const free = point.fixedLeg?.kind === 'free';
const routed = hasLeg && !point.fixedLeg;
const items: MenuItems = [];
if (free || routed) {
const routeAgain = planner.isPaddle ? t('tours.paddle.routeOnWater') : t('tours.planner.routeLeg');
items.push(
{ divider: true },
{
label: free ? routeAgain : t('tours.planner.freeLeg'),
icon: free && planner.isPaddle ? Waves : Spline,
onClick: () => planner.toggleWaypointFreeLeg(point.id),
}
);
}
if (routed)
items.push({
label: t('tours.planner.recomputeLeg'),
icon: RefreshCw,
onClick: () => planner.recomputeLeg(point.id),
});
if (index > 0 && index < lastIndex) {
items.push({
label: t(point.shaping ? 'tours.planner.makeStop' : 'tours.planner.makeShaping'),
icon: Navigation,
onClick: () => planner.setWaypointShaping(point.id, !point.shaping),
});
}
return items;
}
/** A paddle tour's tools at a point: carry the boat from here, and a lock here. */
function paddleMenuItems(
paddle: ReturnType<typeof usePaddleWaypointActions>,
point: WaypointPoint,
hasLeg: boolean,
t: Translate
): MenuItems {
const portage = point.fixedLeg?.kind === 'portage';
const items: MenuItems = [{ divider: true }];
// At the last point too: the portage starts here and reaches the point set next.
items.push({
label: t(
!hasLeg && point.carryNext
? 'tours.paddle.portagePendingOff'
: portage
? 'tours.paddle.portageOff'
: 'tours.paddle.portageOn'
),
icon: PortageIcon,
onClick: () => paddle.togglePortage(point.id),
});
items.push({
label: t(point.lock ? 'tours.paddle.lockRemove' : 'tours.paddle.lockAdd'),
icon: LockIcon,
onClick: () => paddle.setLock(point.id, point.lock ? null : { wait_minutes: null, transit_minutes: null }),
});
return items;
}
function WaypointRowActions({
planner,
point,
@@ -311,7 +426,7 @@ function WaypointRowActions({
isSaving,
}: {
planner: TourPlannerController;
point: TourPlannerController['waypoints'][number];
point: WaypointPoint;
index: number;
lastIndex: number;
selected: boolean;
@@ -320,10 +435,7 @@ function WaypointRowActions({
const { t } = useTranslation();
const menu = useContextMenu();
const paddle = usePaddleWaypointActions(planner);
const free = point.fixedLeg?.kind === 'free';
const portage = point.fixedLeg?.kind === 'portage';
const hasLeg = index < lastIndex;
const items = [
const items: MenuItems = [
{
label: t('tours.planner.moveUp'),
icon: ArrowUp,
@@ -336,35 +448,8 @@ function WaypointRowActions({
disabled: index === lastIndex,
onClick: () => planner.moveWaypoint(point.id, 1),
},
...(!planner.isPaddle && hasLeg && point.fixedLeg?.kind !== 'ferrata'
? [
{ divider: true },
{
label: t(free ? 'tours.planner.routeLeg' : 'tours.planner.freeLeg'),
icon: Spline,
onClick: () => planner.toggleWaypointFreeLeg(point.id),
},
]
: []),
...(planner.isPaddle
? [
{ divider: true },
...(hasLeg
? [
{
label: t(portage ? 'tours.paddle.portageOff' : 'tours.paddle.portageOn'),
icon: PortageIcon,
onClick: () => paddle.togglePortage(point.id),
},
]
: []),
{
label: t(point.lock ? 'tours.paddle.lockRemove' : 'tours.paddle.lockAdd'),
icon: LockIcon,
onClick: () => paddle.setLock(point.id, point.lock ? null : { wait_minutes: null, transit_minutes: null }),
},
]
: []),
...routeMenuItems(planner, point, index, lastIndex, t),
...(planner.isPaddle ? paddleMenuItems(paddle, point, index < lastIndex, t) : []),
];
return (
<span
@@ -402,24 +487,29 @@ function PaddleRowExtras({
index,
layout,
editable,
routing,
}: {
planner: TourPlannerController;
point: TourPlannerController['waypoints'][number];
index: number;
layout: PaddleLayout;
editable: boolean;
routing: ReturnType<typeof usePortageRouting>;
}) {
const paddle = usePaddleWaypointActions(planner);
const way = usePortageWay(planner.waypoints, routing, index);
const portage = layout.stretches.find((stretch) => stretch.kind === 'portage' && stretch.startIndex === index);
const lock = point.lock ? layout.locks.find((stop) => stop.index === index) : undefined;
return (
<>
{point.carryNext && <PendingPortageRow disabled={!editable} onRemove={() => paddle.togglePortage(point.id)} />}
{portage && (
<PortageLegRow
lengthM={portage.toM - portage.fromM}
extraMinutes={portage.extraMinutes}
disabled={!editable}
onExtraChange={(minutes) => paddle.setPortageExtra(point.id, minutes)}
way={point.auto ? undefined : way}
/>
)}
{point.lock && (
@@ -463,6 +553,154 @@ function AddPointRow({ disabled }: { disabled: boolean }) {
* reorderable by drag or by the arrow controls on each row. The coordinates
* stand in for the name while it loads, offline, or when the lookup has none.
*/
/** P2A-03: how a shaping point is set, said once under the list while there is a route to click. */
function ShapeOnLineHint({ planner, canEdit }: { planner: TourPlannerController; canEdit: boolean }) {
const { t } = useTranslation();
if (!canEdit || planner.waypoints.length < 2) return null;
return (
<p className="m-0 mt-1.5 px-1.5 text-content-faint" style={fs(11, 'body')}>
{t('tours.planner.shapeOnLine')}
</p>
);
}
/** Stops are numbered on their own, as on the map: a shaping point (P2A-03) takes no number. */
function stopNumbersOf(points: ReadonlyArray<WaypointPoint>): Map<string, number> {
const numbers = new Map<string, number>();
for (const point of points) if (!point.shaping) numbers.set(point.id, numbers.size + 1);
return numbers;
}
/** The route tools in the card head: reverse, plan the drawn legs on the water (PAD-11), back to the start. */
function WaypointListTools({ planner, isSaving }: { planner: TourPlannerController; isSaving: boolean }) {
const { t } = useTranslation();
const hasDrawnLegs = planner.isPaddle && planner.waypoints.some((point) => point.fixedLeg?.kind === 'free');
return (
<span className="flex flex-none items-center gap-0.5">
<RouteToolButton
testId="tour-planner-reverse"
label={t('tours.planner.reverse')}
disabled={isSaving || planner.waypoints.length < 2}
onAct={planner.reverse}
>
<ArrowDownUp size={13} strokeWidth={2.2} />
</RouteToolButton>
{hasDrawnLegs && (
<RouteToolButton
testId="tour-planner-route-on-water"
label={t('tours.paddle.routeAllOnWater')}
disabled={isSaving}
onAct={planner.routeDrawnLegsOnWater}
>
<Waves size={13} strokeWidth={2.2} />
</RouteToolButton>
)}
<RouteToolButton
testId="tour-planner-return-to-start"
label={t(planner.isLoop ? 'tours.planner.alreadyLoop' : 'tours.planner.returnToStart')}
disabled={isSaving || planner.waypoints.length < 2 || planner.isLoop}
onAct={planner.returnToStart}
>
<Repeat size={13} strokeWidth={2.2} />
</RouteToolButton>
</span>
);
}
/**
* A leg the router could not plan. Where it lacked the water data of the
* region (PAD-11C), the row follows the data instead: loading or asked for,
* the leg waits calmly; declined, failed or not to be had, it says why.
*/
function LegFailure({
code,
load,
disabled,
onDrawStraight,
onRetry,
onLoadRetry,
}: {
code: PaddleLegFailure;
load: PaddleRegionLoadState | undefined;
disabled: boolean;
onDrawStraight: () => void;
onRetry: () => void;
onLoadRetry: () => void;
}) {
const { t } = useTranslation();
if (isRegionLoadPending(load)) {
return <PaddleRegionLoadRow state={load} disabled={disabled} onDrawStraight={onDrawStraight} />;
}
return (
<PaddleLegFailureRow
code={code}
disabled={disabled}
onDrawStraight={onDrawStraight}
onRetry={onRetry}
message={regionLoadFailure(load, t)}
onLoadRetry={load?.state === 'failed' ? onLoadRetry : undefined}
/>
);
}
/**
* The rows under a waypoint for the leg that starts there: the via ferrata it
* crosses, a line drawn by hand, and on a paddle tour what the router found on
* the way (PAD-11) or why it could not plan it, plus the portage and lock rows.
*/
function WaypointLegRows({
planner,
point,
index,
crossings = [],
routedLegs,
paddleLayout,
editable,
portageRouting,
regionLoad,
}: {
planner: TourPlannerController;
point: WaypointPoint;
index: number;
crossings?: TourFerrataCrossing[];
routedLegs: TourPlannerController['paddleRoute'] | null;
paddleLayout: ReturnType<typeof paddleLayoutOfPoints> | null;
editable: boolean;
portageRouting: ReturnType<typeof usePortageRouting>;
regionLoad: ReturnType<typeof usePaddleRegionLoad>;
}) {
const failure = routedLegs?.failures.find((candidate) => candidate.index === index);
return (
<>
{crossings.map((crossing) => (
<FerrataLegRow key={`${crossing.id}-${crossing.fromM}`} crossing={crossing} />
))}
{point.fixedLeg?.kind === 'free' && <FreeLegRow leg={point.fixedLeg} />}
{routedLegs && <PaddleLegNotes leg={routedLegs.legs[index]} />}
{failure && (
<LegFailure
code={failure.code}
load={regionLoad.byLeg.get(index)}
disabled={!editable}
onDrawStraight={() => planner.toggleWaypointFreeLeg(point.id)}
onRetry={() => planner.recomputeLeg(point.id)}
onLoadRetry={regionLoad.retry}
/>
)}
{paddleLayout && (
<PaddleRowExtras
planner={planner}
point={point}
index={index}
layout={paddleLayout}
editable={editable}
routing={portageRouting}
/>
)}
</>
);
}
export default function TourWaypointList({
planner,
canEdit,
@@ -489,34 +727,22 @@ export default function TourWaypointList({
// A hike keeps its start and end badges (undefined); a paddle tour names each point for the paddler.
const paddleRoleOf = (id: string) => (paddleRoles ? (paddleRoles.get(id) ?? null) : undefined);
const paddleLayout = planner.isPaddle ? paddleLayoutOfPoints(paddlePlanPoints(planner.waypoints)) : null;
// PAD-03: portages the paddler sets follow the ways on land.
const portageRouting = usePortageRouting(planner, canEdit && !isSaving);
// The router's answer per leg, while it still belongs to these points (PAD-11).
const routedLegs = planner.isPaddle && planner.routeCurrent ? planner.paddleRoute : null;
// PAD-11C: where a leg lacks the water data of its region, TREK fetches it and plans the leg again.
const regionLoad = usePaddleRegionLoad(routedLegs?.failures, planner.retry);
const stopNumbers = stopNumbersOf(planner.waypoints);
const endDrag = () => {
setDraggedWaypointId(null);
setDropTarget(null);
};
// One card like a day in the plan: the head counts the points, the rows sit below.
const tools = canEdit && planner.waypoints.length > 0 && (
<span className="flex flex-none items-center gap-0.5">
<RouteToolButton
testId="tour-planner-reverse"
label={t('tours.planner.reverse')}
disabled={isSaving || planner.waypoints.length < 2}
onAct={planner.reverse}
>
<ArrowDownUp size={13} strokeWidth={2.2} />
</RouteToolButton>
<RouteToolButton
testId="tour-planner-return-to-start"
label={t(planner.isLoop ? 'tours.planner.alreadyLoop' : 'tours.planner.returnToStart')}
disabled={isSaving || planner.waypoints.length < 2 || planner.isLoop}
onAct={planner.returnToStart}
>
<Repeat size={13} strokeWidth={2.2} />
</RouteToolButton>
</span>
);
// The way back of a loop is no stop of its own, so the count leaves it out.
const stops = planner.waypoints.length - (planner.isLoop ? 1 : 0);
const tools = canEdit && planner.waypoints.length > 0 && <WaypointListTools planner={planner} isSaving={isSaving} />;
// The way back of a loop is no stop of its own, and a shaping point no stop at all, so the count leaves them out.
const stops = stopNumbers.size - (planner.isLoop ? 1 : 0);
const card = (children: ReactNode) => (
<RailCard
icon={<MapPin size={14} strokeWidth={2} />}
@@ -608,10 +834,11 @@ export default function TourWaypointList({
<GripVertical size={14} strokeWidth={1.8} />
</span>
<WaypointNumber
index={index}
stop={stopNumbers.get(point.id) ?? index + 1}
selected={selected}
ferrata={ferrataEnds[point.id] ?? null}
loopEnd={loopEnd}
shaping={!!point.shaping}
/>
<button
type="button"
@@ -638,30 +865,23 @@ export default function TourWaypointList({
)}
</div>
</li>
{(legCrossings.get(point.id) ?? []).map((crossing) => (
<FerrataLegRow key={`${crossing.id}-${crossing.fromM}`} crossing={crossing} />
))}
{/* A paddle tour is drawn by hand throughout; the notice says it once instead of on every leg. */}
{point.fixedLeg?.kind === 'free' && !planner.isPaddle && <FreeLegRow leg={point.fixedLeg} />}
{paddleLayout && (
<PaddleRowExtras
planner={planner}
point={point}
index={index}
layout={paddleLayout}
editable={canEdit && !isSaving}
/>
)}
<WaypointLegRows
planner={planner}
point={point}
index={index}
crossings={legCrossings.get(point.id)}
routedLegs={routedLegs}
paddleLayout={paddleLayout}
editable={canEdit && !isSaving}
portageRouting={portageRouting}
regionLoad={regionLoad}
/>
</Fragment>
);
})}
</ol>
{canEdit && <AddPointRow disabled={isSaving} />}
{planner.isPaddle && (
<div className="mt-2">
<TourNotice icon={<Info size={13} strokeWidth={2} />}>{t('tours.paddle.drawnByHand')}</TourNotice>
</div>
)}
<ShapeOnLineHint planner={planner} canEdit={canEdit} />
</>
);
}
@@ -6,7 +6,7 @@ import {
type PaddleRole,
type PaddleTimeEstimate,
} from '@trek/shared';
import type { TourPlannerWaypoint } from './useTourPlanner';
import type { TourPlannerWaypoint } from './tourPlannerWaypoints';
/** The planner's control points as the shared paddle plan reads them. */
export function paddlePlanPoints(points: readonly TourPlannerWaypoint[]): PaddlePlanPoint[] {
@@ -26,15 +26,17 @@ export function paddleRolesById(points: readonly TourPlannerWaypoint[]): Map<str
/**
* PAD-07: the estimate of a paddle tour as planned, without its breaks (the
* planner adds those as it does for a hike). A speed the paddler typed that
* planner adds those as it does for a hike), with the routed length of each
* leg where the router planned it (PAD-11). A speed the paddler typed that
* does not hold leaves the water time unknown rather than wrong.
*/
export function paddleEstimateOf(
points: readonly TourPlannerWaypoint[],
paddle: { effectiveSpeedKmh: number | null; portageSpeedKmh: number | null },
speedInvalid: boolean
speedInvalid: boolean,
legLengths?: ReadonlyArray<number | null>
): PaddleTimeEstimate {
return estimatePaddleTime(paddleLayoutOfPoints(paddlePlanPoints(points)), {
return estimatePaddleTime(paddleLayoutOfPoints(paddlePlanPoints(points), legLengths), {
paddleSpeedKmh: speedInvalid ? null : paddle.effectiveSpeedKmh,
portageSpeedKmh: paddle.portageSpeedKmh,
breakMinutes: null,
@@ -0,0 +1,207 @@
// FE-PADDLE-ROUTING-001 to FE-PADDLE-ROUTING-010: a paddle tour's route put together from the water router's legs (PAD-11).
import type { PaddleRouteLeg, PaddleRouteSegment } from '@trek/shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { paddleRouteRepo } from '../../../repo/paddleRouteRepo';
import {
adoptChangedPoints,
materializePaddleLegs,
planPaddleStep,
pruneAutoPoints,
routePaddleTour,
type PaddlePoint,
} from './paddleRouting';
vi.mock('../../../repo/paddleRouteRepo', () => ({ paddleRouteRepo: { plan: vi.fn(), forget: vi.fn() } }));
const KAYAK = { boat: 'kayak' as const, lakeStyle: 'direct' as const };
const A: PaddlePoint = { id: 'a', lat: 49.1, lng: 12.1 };
const B: PaddlePoint = { id: 'b', lat: 49.05, lng: 12.12 };
const C: PaddlePoint = { id: 'c', lat: 49.0, lng: 12.1 };
function segment(kind: PaddleRouteSegment['kind'], from: number, to: number, extra: Partial<PaddleRouteSegment> = {}) {
return { kind, from, to, name: null, source: null, osm_ref: null, grade: null, ...extra };
}
/** A routed leg through five points: water, a portage round a weir, water, a lock, water. */
const WEIR_AND_LOCK: PaddleRouteLeg = {
status: 'ok',
geometry: [
[49.1, 12.1],
[49.09, 12.11],
[49.08, 12.11],
[49.07, 12.115],
[49.06, 12.118],
[49.05, 12.12],
],
segments: [
segment('water', 0, 1),
segment('portage', 1, 2, { source: 'tagged' }),
segment('water', 2, 3),
segment('lock', 3, 4, { name: 'Schleuse' }),
segment('water', 4, 5),
],
distance_m: 6100,
snapped_m: { from: 0, to: 0 },
};
const straight = (from: PaddlePoint, to: PaddlePoint, distance = 1000): PaddleRouteLeg => ({
status: 'ok',
geometry: [
[from.lat, from.lng],
[to.lat, to.lng],
],
segments: [segment('water', 0, 1)],
distance_m: distance,
snapped_m: { from: 0, to: 0 },
});
let ids = 0;
const newId = () => `auto-${(ids += 1)}`;
beforeEach(() => {
ids = 0;
vi.mocked(paddleRouteRepo.plan).mockReset();
});
describe('routePaddleTour', () => {
it('FE-PADDLE-ROUTING-001: asks only for the legs without a line, and keeps a drawn or carried leg as it is', async () => {
vi.mocked(paddleRouteRepo.plan).mockResolvedValue([straight(B, C, 5500)]);
const drawn = {
kind: 'free' as const,
geometry: [
[A.lat, A.lng],
[B.lat, B.lng],
] as [number, number][],
};
const route = await routePaddleTour([{ ...A, fixedLeg: drawn }, B, C], 7, KAYAK);
expect(vi.mocked(paddleRouteRepo.plan).mock.calls[0]?.[1]).toEqual([{ from: B, to: C }]);
expect(route.legs[0]).toBeNull();
expect(route.legs[1]?.status).toBe('ok');
expect(route.parts.map((part) => [part.free, !!part.land])).toEqual([
[true, false],
[false, false],
]);
expect(route.legLengths[1]).toBe(5500);
expect(route.distanceMeters).toBeCloseTo(route.legLengths[0]! + 5500);
expect(route.coordinates[0]).toEqual([A.lat, A.lng]);
expect(route.coordinates[route.coordinates.length - 1]).toEqual([C.lat, C.lng]);
});
it('FE-PADDLE-ROUTING-002: draws a portage as land, whitewater and a boat pass amber, a gap red, and merges the rest', async () => {
const marked: PaddleRouteLeg = {
...WEIR_AND_LOCK,
segments: [
segment('water', 0, 1),
segment('portage', 1, 2),
segment('rapids', 2, 3, { grade: 2 }),
segment('pass', 3, 4),
segment('gap', 4, 5),
],
};
vi.mocked(paddleRouteRepo.plan).mockResolvedValue([marked]);
const route = await routePaddleTour([A, B], 7, KAYAK);
expect(route.parts.map((part) => part.land ?? part.mark ?? 'water')).toEqual(['water', true, 'rapids', 'gap']);
// Whitewater and the boat pass next to it are one amber line.
expect(route.parts[2]?.coordinates).toHaveLength(3);
});
it('FE-PADDLE-ROUTING-003: a leg the router could not plan stays a straight unrouted stretch, counted as a failure', async () => {
vi.mocked(paddleRouteRepo.plan).mockResolvedValue([
straight(A, B),
{ status: 'failed', code: 'not_on_water', at: { lat: C.lat, lng: C.lng } },
]);
const route = await routePaddleTour([A, B, C], 7, KAYAK);
expect(route.failures).toEqual([{ index: 1, code: 'not_on_water', at: { lat: C.lat, lng: C.lng } }]);
expect(route.parts[route.parts.length - 1]).toMatchObject({
mark: 'unrouted',
coordinates: [
[B.lat, B.lng],
[C.lat, C.lng],
],
});
// The straight line counts in the length, so the time does not shrink while a leg waits.
expect(route.legLengths[1]).toBeGreaterThan(5000);
});
it('FE-PADDLE-ROUTING-004: a leg the answer leaves out is unrouted, never silently straight water', async () => {
vi.mocked(paddleRouteRepo.plan).mockResolvedValue([]);
const route = await routePaddleTour([A, B], 7, KAYAK);
expect(route.failures).toEqual([{ index: 0, code: 'no_water_path', at: null }]);
});
it('FE-PADDLE-ROUTING-005: a tour with every leg drawn asks nothing', async () => {
const carried = {
kind: 'portage' as const,
geometry: [
[A.lat, A.lng],
[B.lat, B.lng],
] as [number, number][],
extra_minutes: null,
};
const route = await routePaddleTour([{ ...A, fixedLeg: carried }, B], 7, KAYAK);
expect(paddleRouteRepo.plan).not.toHaveBeenCalled();
expect(route.parts[0]?.land).toBe(true);
});
});
describe('automatic points', () => {
it("FE-PADDLE-ROUTING-006: sets a portage pair and a lock where the router found them, on the paddler's own leg", () => {
const points = materializePaddleLegs([A, B], { legs: [WEIR_AND_LOCK] }, newId);
expect(points.map((point) => point.id)).toEqual(['a', 'auto-1', 'auto-2', 'auto-3', 'b']);
expect(points[1]).toMatchObject({ lat: 49.09, lng: 12.11, fixedLeg: { kind: 'portage', extra_minutes: null } });
expect(points[2]).toMatchObject({ lat: 49.08, lng: 12.11 });
expect(points[2]?.fixedLeg).toBeUndefined();
expect(points[3]).toMatchObject({ lock: { wait_minutes: null, transit_minutes: null } });
expect(points[1]?.auto).toEqual({
from: { id: 'a', lat: A.lat, lng: A.lng },
to: { id: 'b', lat: B.lat, lng: B.lng },
});
});
it('FE-PADDLE-ROUTING-007: planning the same leg again keeps the ids, and a leg at an automatic point adds nothing', () => {
const once = materializePaddleLegs([A, B], { legs: [WEIR_AND_LOCK] }, newId);
const legs = once.slice(0, -1).map(() => WEIR_AND_LOCK);
const twice = materializePaddleLegs(once, { legs }, newId);
expect(twice).toEqual(once);
});
it('FE-PADDLE-ROUTING-008: drops the automatic points of a leg whose end moved or went, and keeps them otherwise', () => {
const points = materializePaddleLegs([A, B, C], { legs: [WEIR_AND_LOCK, straight(B, C)] }, newId);
expect(pruneAutoPoints(points)).toEqual(points);
const moved = points.map((point) => (point.id === 'b' ? { ...point, lat: point.lat + 0.01 } : point));
expect(pruneAutoPoints(moved).map((point) => point.id)).toEqual(['a', 'b', 'c']);
const shaped = [points[0]!, { id: 's', lat: 49.095, lng: 12.105, shaping: true }, ...points.slice(1)];
expect(pruneAutoPoints(shaped).map((point) => point.id)).toEqual(['a', 's', 'b', 'c']);
});
it('FE-PADDLE-ROUTING-009: a point the paddler moves or edits is theirs; an untouched one stays automatic', () => {
const points = materializePaddleLegs([A, B], { legs: [WEIR_AND_LOCK] }, newId);
const edited = points.map((point) =>
point.id === 'auto-3' ? { ...point, lock: { wait_minutes: 20, transit_minutes: null } } : point
);
const adopted = adoptChangedPoints(points, edited);
expect(adopted.find((point) => point.id === 'auto-3')?.auto).toBeUndefined();
expect(adopted.find((point) => point.id === 'auto-1')?.auto).toBeDefined();
});
});
describe('planPaddleStep', () => {
it('FE-PADDLE-ROUTING-010: prunes first, then sets what the router found, then answers the route', async () => {
const signal = new AbortController().signal;
vi.mocked(paddleRouteRepo.plan).mockResolvedValue([WEIR_AND_LOCK]);
const first = await planPaddleStep([A, B], 7, KAYAK, signal, newId);
expect('points' in first && first.points).toHaveLength(5);
const found = 'points' in first ? first.points : [];
vi.mocked(paddleRouteRepo.plan).mockResolvedValue(found.slice(0, -1).map(() => straight(A, B, 1500)));
const second = await planPaddleStep(found, 7, KAYAK, signal, newId);
expect('route' in second && second.route.legLengths).toHaveLength(4);
const stale = found.map((point) => (point.id === 'a' ? { ...point, lng: point.lng + 0.01 } : point));
vi.mocked(paddleRouteRepo.plan).mockClear();
const third = await planPaddleStep(stale, 7, KAYAK, signal, newId);
expect('points' in third && third.points.map((point) => point.id)).toEqual(['a', 'b']);
expect(paddleRouteRepo.plan).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,262 @@
import type { PaddleLock, PaddleRouteFailureCode, PaddleRouteLeg, TourFixedLeg } from '@trek/shared';
import { paddleRouteRepo, type PaddleLegAnswer, type PaddleRouteProfile } from '../../../repo/paddleRouteRepo';
import { haversineKm } from '../../../utils/geo';
import { lineLengthM } from './tourFixedLegs';
import type { TourRoutePart } from './tourRouting';
/**
* PAD-11: a paddle tour's route in the planner. A leg without a line of its
* own is planned on the water by the server's router, as a hike's legs are by
* Valhalla; a leg drawn by hand or carried as a portage keeps its line. Where
* the router carries round a weir or goes through a lock between two of the
* paddler's own points, the planner sets points of its own there (`auto`), so
* the portage and the lock count like any planned by hand: in the time, in the
* checklist, on the map. They are derived again whenever the points they came
* from change, and become the paddler's own once touched.
*/
/** Where an automatic point came from: the two points of the paddler's leg it was found on, as they were. */
export interface AutoBase {
from: { id: string; lat: number; lng: number };
to: { id: string; lat: number; lng: number };
}
export interface PaddlePoint {
id: string;
lat: number;
lng: number;
fixedLeg?: TourFixedLeg | null;
lock?: PaddleLock | null;
shaping?: boolean;
/** Set by the planner where the router found a portage or a lock; gone once the paddler touches the point. */
auto?: AutoBase;
}
export type PaddleLegFailure = PaddleRouteFailureCode | 'offline';
export interface PaddleTourRoute {
coordinates: [number, number][];
parts: TourRoutePart[];
distanceMeters: number;
/** Per leg (index of its first point): the router's answer, or null for a leg with a line of its own. */
legs: Array<PaddleLegAnswer | null>;
/** The routed length of every leg, metres, for the time estimate. */
legLengths: number[];
failures: Array<{ index: number; code: PaddleLegFailure; at: { lat: number; lng: number } | null }>;
}
/** What a leg holds when its answer is somehow missing: unrouted, never silently straight. */
const NOT_ASKED: PaddleLegAnswer = { status: 'failed', code: 'no_water_path', at: null };
/** Two points this close are one spot, in degrees (about ten centimetres). */
const SAME_SPOT = 1e-6;
function samePlace(a: { lat: number; lng: number }, b: { lat: number; lng: number }): boolean {
return Math.abs(a.lat - b.lat) < SAME_SPOT && Math.abs(a.lng - b.lng) < SAME_SPOT;
}
type PartKind = 'water' | 'rapids' | 'gap' | 'unrouted' | 'land' | 'manual';
function partOf(kind: PartKind, coordinates: [number, number][]): TourRoutePart {
if (kind === 'land') return { coordinates, free: false, land: true };
if (kind === 'manual') return { coordinates, free: true };
return { coordinates, free: false, ...(kind === 'water' ? {} : { mark: kind }) };
}
/** The parts of one routed leg: water as one line, carried and marked stretches as their own. */
function routedParts(leg: Extract<PaddleRouteLeg, { status: 'ok' }>): TourRoutePart[] {
return leg.segments.map((segment) => {
const line = leg.geometry.slice(segment.from, segment.to + 1) as [number, number][];
if (segment.kind === 'portage') return partOf('land', line);
if (segment.kind === 'rapids' || segment.kind === 'pass') return partOf('rapids', line);
if (segment.kind === 'gap') return partOf('gap', line);
return partOf('water', line);
});
}
/** Neighbouring parts drawn alike as one line, as the hike's route does. */
function mergeParts(parts: TourRoutePart[]): TourRoutePart[] {
const merged: TourRoutePart[] = [];
for (const part of parts) {
const previous = merged[merged.length - 1];
if (previous && previous.free === part.free && !!previous.land === !!part.land && previous.mark === part.mark) {
previous.coordinates = [...previous.coordinates, ...part.coordinates.slice(1)];
} else {
merged.push({ ...part, coordinates: [...part.coordinates] });
}
}
return merged;
}
/** Plans the legs that need it and puts the whole line together. */
export async function routePaddleTour(
points: readonly PaddlePoint[],
tripId: number | string,
profile: PaddleRouteProfile,
signal?: AbortSignal
): Promise<PaddleTourRoute> {
const routed = points.slice(0, -1).flatMap((point, index) => (point.fixedLeg ? [] : [index]));
const answers = routed.length
? await paddleRouteRepo.plan(
tripId,
routed.map((index) => ({ from: points[index], to: points[index + 1] })),
profile,
signal
)
: [];
const byLeg = new Map(routed.map((index, at) => [index, answers[at]]));
const parts: TourRoutePart[] = [];
const legs: PaddleTourRoute['legs'] = [];
const legLengths: number[] = [];
const failures: PaddleTourRoute['failures'] = [];
for (let index = 0; index < points.length - 1; index += 1) {
const point = points[index];
const next = points[index + 1];
const leg = point.fixedLeg;
if (leg) {
const line = leg.geometry.map(([lat, lng]): [number, number] => [lat, lng]);
parts.push(partOf(leg.kind === 'portage' ? 'land' : 'manual', line));
legs.push(null);
legLengths.push(lineLengthM(line));
continue;
}
const answer = byLeg.get(index) ?? NOT_ASKED;
legs.push(answer);
if (answer.status === 'ok') {
parts.push(...routedParts(answer));
legLengths.push(answer.distance_m);
continue;
}
// A leg the router could not plan stays visible as what it is: a straight stretch nobody checked.
failures.push({ index, code: answer.code, at: answer.at });
parts.push(
partOf('unrouted', [
[point.lat, point.lng],
[next.lat, next.lng],
])
);
legLengths.push(haversineKm(point, next) * 1000);
}
const lines = mergeParts(parts);
const coordinates = lines.flatMap((part, index) => (index === 0 ? part.coordinates : part.coordinates.slice(1)));
return {
coordinates,
parts: lines,
distanceMeters: legLengths.reduce((sum, length) => sum + length, 0),
legs,
legLengths,
failures,
};
}
function baseOf(points: readonly PaddlePoint[], index: number): AutoBase {
const from = points[index];
const to = points[index + 1];
return { from: { id: from.id, lat: from.lat, lng: from.lng }, to: { id: to.id, lat: to.lat, lng: to.lng } };
}
/**
* The automatic points that no longer stand on the leg they were found on
* (an end of it moved, or went), dropped; the next plan finds them again
* where they belong.
*/
export function pruneAutoPoints<T extends PaddlePoint>(points: readonly T[]): T[] {
const own = points.filter((point) => !point.auto);
return points.filter((point) => {
const base = point.auto;
if (!base) return true;
const from = own.find((candidate) => candidate.id === base.from.id);
const to = own.find((candidate) => candidate.id === base.to.id);
if (!from || !to || !samePlace(from, base.from) || !samePlace(to, base.to)) return false;
return own.indexOf(to) === own.indexOf(from) + 1;
});
}
/**
* Sets the portages and locks the router found on the paddler's own legs as
* points. An existing automatic point at the same spot keeps its id, so
* planning the same leg again changes nothing.
*/
export function materializePaddleLegs<T extends PaddlePoint>(
points: readonly T[],
route: Pick<PaddleTourRoute, 'legs'>,
newId: () => string
): T[] {
const existing = points.filter((point) => point.auto);
const idAt = (lat: number, lng: number) => existing.find((point) => samePlace(point, { lat, lng }))?.id ?? newId();
const result: T[] = [];
points.forEach((point, index) => {
result.push(point);
const next = points[index + 1];
const answer = route.legs[index];
// Only a leg between two of the paddler's own points: a leg at an automatic point is part of one already set.
if (!next || point.auto || next.auto || !answer || answer.status !== 'ok') return;
const base = baseOf(points, index);
const last = answer.geometry.length - 1;
for (const segment of answer.segments) {
if (segment.kind === 'portage' && segment.from > 0 && segment.to < last) {
const line = answer.geometry.slice(segment.from, segment.to + 1) as [number, number][];
const [outLat, outLng] = line[0];
const [inLat, inLng] = line[line.length - 1];
result.push(
{
id: idAt(outLat, outLng),
lat: outLat,
lng: outLng,
auto: base,
fixedLeg: { kind: 'portage', geometry: line, extra_minutes: null },
} as unknown as T,
{ id: idAt(inLat, inLng), lat: inLat, lng: inLng, auto: base } as unknown as T
);
}
if (segment.kind === 'lock' && segment.from > 0 && segment.to < last) {
const [lat, lng] = answer.geometry[Math.round((segment.from + segment.to) / 2)];
result.push({
id: idAt(lat, lng),
lat,
lng,
auto: base,
lock: { wait_minutes: null, transit_minutes: null },
} as unknown as T);
}
}
});
return result;
}
/** A point the paddler changed is theirs from then on: it loses its automatic mark. */
export function adoptChangedPoints<T extends PaddlePoint>(before: readonly T[], after: readonly T[]): T[] {
const previous = new Map(before.map((point) => [point.id, point]));
return after.map((point) => {
if (!point.auto) return point;
const was = previous.get(point.id);
const same =
!!was &&
samePlace(was, point) &&
JSON.stringify(was.lock ?? null) === JSON.stringify(point.lock ?? null) &&
JSON.stringify(was.fixedLeg ?? null) === JSON.stringify(point.fixedLeg ?? null);
if (same) return point;
const { auto: _auto, ...own } = point;
return own as T;
});
}
/**
* One run of the paddle router over the points: either points to set first
* (automatic ones dropped from a leg that changed, or found on a planned
* leg), after which the planner runs again, or the finished route.
*/
export async function planPaddleStep<T extends PaddlePoint>(
points: readonly T[],
tripId: number | string,
profile: PaddleRouteProfile,
signal: AbortSignal,
newId: () => string
): Promise<{ points: T[] } | { route: PaddleTourRoute }> {
const pruned = pruneAutoPoints(points);
if (pruned.length !== points.length) return { points: pruned };
const route = await routePaddleTour(points, tripId, profile, signal);
// Points are only ever added: the same count means nothing new was found.
const materialized = materializePaddleLegs(points, route, newId);
return materialized.length !== points.length ? { points: materialized } : { route };
}
@@ -0,0 +1,34 @@
// FE-ROUTE-LEG-AT-001 to FE-ROUTE-LEG-AT-003: which leg a click on the drawn route lands in (P2A-03).
import { describe, expect, it } from 'vitest';
import { legStartAt } from './routeLegAt';
const A = { id: 'a', lat: 49.0, lng: 12.0 };
const B = { id: 'b', lat: 49.0, lng: 12.1 };
const C = { id: 'c', lat: 49.1, lng: 12.1 };
// The route bends between the points, as a river does.
const LINE: [number, number][] = [
[49.0, 12.0],
[49.01, 12.05],
[49.0, 12.1],
[49.05, 12.11],
[49.1, 12.1],
];
describe('legStartAt', () => {
it('FE-ROUTE-LEG-AT-001: a spot on the line belongs to the leg whose two points enclose it', () => {
expect(legStartAt([A, B, C], LINE, 49.009, 12.05)).toBe('a');
expect(legStartAt([A, B, C], LINE, 49.05, 12.11)).toBe('b');
});
it('FE-ROUTE-LEG-AT-002: a loop keeps its order, so a spot near the start on the way back is the last leg', () => {
const back = { id: 'back', lat: A.lat, lng: A.lng };
const loop: [number, number][] = [...LINE, [49.05, 12.02], [49.0, 12.0]];
expect(legStartAt([A, B, C, back], loop, 49.05, 12.02)).toBe('c');
});
it('FE-ROUTE-LEG-AT-003: without a line or a leg there is nothing to shape', () => {
expect(legStartAt([A, B], null, 49, 12.05)).toBeNull();
expect(legStartAt([A], LINE, 49, 12.05)).toBeNull();
expect(legStartAt([A, B], [[49, 12]], 49, 12.05)).toBeNull();
});
});
@@ -0,0 +1,55 @@
/**
* P2A-03: which leg of a tour a spot on its drawn route belongs to. Every
* waypoint is placed along the line (searching on from where the one before
* lay, so a loop or a route that passes a point twice keeps its order), then
* the spot; the leg is the one whose two points enclose it.
*/
/** Where a spot falls along a line, as the distance from its start in the line's own degrees (flat earth is plenty for ordering). */
function alongLine(
line: readonly [number, number][],
lat: number,
lng: number,
fromIndex: number
): { at: number; index: number } {
const cos = Math.cos((lat * Math.PI) / 180);
let travelled = 0;
let best = { at: 0, index: fromIndex, distance: Infinity };
for (let i = 0; i < line.length - 1; i += 1) {
const [aLat, aLng] = line[i];
const [bLat, bLng] = line[i + 1];
const dx = (bLng - aLng) * cos;
const dy = bLat - aLat;
const length = Math.hypot(dx, dy);
if (i >= fromIndex) {
const t =
length === 0 ? 0 : Math.max(0, Math.min(1, ((lng - aLng) * cos * dx + (lat - aLat) * dy) / (length * length)));
const distance = Math.hypot(aLng * cos + dx * t - lng * cos, aLat + dy * t - lat);
if (distance < best.distance) best = { at: travelled + length * t, index: i, distance };
}
travelled += length;
}
return { at: best.at, index: best.index };
}
/** The id of the waypoint that starts the leg holding the spot, or null when the route has no such leg. */
export function legStartAt(
points: ReadonlyArray<{ id: string; lat: number; lng: number }>,
line: readonly [number, number][] | null,
lat: number,
lng: number
): string | null {
if (!line || line.length < 2 || points.length < 2) return null;
const positions: number[] = [];
let from = 0;
for (const point of points) {
const placed = alongLine(line, point.lat, point.lng, from);
positions.push(placed.at);
from = placed.index;
}
const spot = alongLine(line, lat, lng, 0).at;
for (let i = 0; i < points.length - 1; i += 1) {
if (spot >= positions[i] && spot <= positions[i + 1]) return points[i].id;
}
return null;
}
@@ -5,8 +5,8 @@ import {
type PlannableTourType,
type TourMaxHikingDifficulty,
} from '@trek/shared';
import type { TourPlannerWaypoint } from './tourPlannerWaypoints';
import type { PaddleFieldValues } from './usePaddleFields';
import type { TourPlannerWaypoint } from './useTourPlanner';
/**
* The tour planner's draft as it is kept in local storage between visits, and
@@ -15,7 +15,7 @@ import type { TourPlannerWaypoint } from './useTourPlanner';
* half read.
*/
export interface DraftPayload {
version: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
version: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
name: string;
description?: string;
website?: string;
@@ -30,7 +30,7 @@ export interface DraftPayload {
paddle?: PaddleFieldValues;
}
const DRAFT_VERSIONS: ReadonlyArray<DraftPayload['version']> = [1, 2, 3, 4, 5, 6, 7, 8];
const DRAFT_VERSIONS: ReadonlyArray<DraftPayload['version']> = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function optionalString(value: unknown): boolean {
return value === undefined || typeof value === 'string';
@@ -0,0 +1,83 @@
// FE-TOUR-WAYPOINTS-001 to FE-TOUR-WAYPOINTS-005: the editor's waypoint model, shaping points and drawn legs (P2A-03, PAD-11).
import { describe, expect, it } from 'vitest';
import {
normalizePlannerWaypoints,
sameWaypointSnapshot,
tourWaypointKey,
withDrawnLegsRouted,
withShaping,
withShapingPoint,
type TourPlannerWaypoint,
} from './tourPlannerWaypoints';
const A: TourPlannerWaypoint = { id: 'a', lat: 49, lng: 12, role: 'start' };
const B: TourPlannerWaypoint = { id: 'b', lat: 49.01, lng: 12.01, role: 'via' };
const C: TourPlannerWaypoint = { id: 'c', lat: 49.02, lng: 12.02, role: 'end' };
describe('tourPlannerWaypoints', () => {
it('FE-TOUR-WAYPOINTS-001: a shaping point goes into the leg after the point named, and nowhere past the end', () => {
const shaped = withShapingPoint([A, B, C], 'b', { id: 's', lat: 49.015, lng: 12.015 });
expect(shaped.map((point) => point.id)).toEqual(['a', 'b', 's', 'c']);
expect(shaped[2]).toEqual({ id: 's', lat: 49.015, lng: 12.015, role: 'via', shaping: true });
const points = [A, B, C];
expect(withShapingPoint(points, 'c', { id: 's', lat: 0, lng: 0 })).toBe(points);
expect(withShapingPoint(points, 'missing', { id: 's', lat: 0, lng: 0 })).toBe(points);
});
it('FE-TOUR-WAYPOINTS-002: a stop becomes a shaping point and back; the ends always stay stops', () => {
const shaped = withShaping([A, B, C], 'b', true);
expect(shaped[1]?.shaping).toBe(true);
expect(withShaping(shaped, 'b', false)[1]).not.toHaveProperty('shaping');
expect(withShaping([A, B, C], 'a', true)[0]).toBe(A);
expect(withShaping([A, B, C], 'c', true)[2]).toBe(C);
});
it('FE-TOUR-WAYPOINTS-003: every drawn leg goes back to the router; a portage stays', () => {
const free = {
kind: 'free' as const,
geometry: [
[49, 12],
[49.01, 12.01],
] as [number, number][],
};
const carried = {
kind: 'portage' as const,
geometry: [
[49.01, 12.01],
[49.02, 12.02],
] as [number, number][],
extra_minutes: 5,
};
const routed = withDrawnLegsRouted([{ ...A, fixedLeg: free }, { ...B, fixedLeg: carried }, C]);
expect(routed[0]).not.toHaveProperty('fixedLeg');
expect(routed[1]?.fixedLeg).toEqual(carried);
});
it('FE-TOUR-WAYPOINTS-004: the key changes when a point shapes instead of stops, or a line gains a bend', () => {
const key = tourWaypointKey([A, B, C]);
expect(tourWaypointKey(withShaping([A, B, C], 'b', true))).not.toBe(key);
const two = {
kind: 'free' as const,
geometry: [
[49, 12],
[49.01, 12.01],
] as [number, number][],
};
const three = {
kind: 'free' as const,
geometry: [
[49, 12],
[49.005, 12.0],
[49.01, 12.01],
] as [number, number][],
};
expect(tourWaypointKey([{ ...A, fixedLeg: two }, B])).not.toBe(tourWaypointKey([{ ...A, fixedLeg: three }, B]));
});
it('FE-TOUR-WAYPOINTS-005: a point the router set is part of the snapshot, and roles follow the order', () => {
const auto = { from: { id: 'a', lat: 49, lng: 12 }, to: { id: 'c', lat: 49.02, lng: 12.02 } };
expect(sameWaypointSnapshot([A, B, C], [A, { ...B, auto }, C])).toBe(false);
expect(sameWaypointSnapshot([A, B, C], [A, B, C])).toBe(true);
expect(normalizePlannerWaypoints([C, A, B]).map((point) => point.role)).toEqual(['start', 'via', 'end']);
});
});
@@ -0,0 +1,119 @@
import type { PaddleLock, TourFixedLeg, TourWaypoint, TourWaypointRole } from '@trek/shared';
import type { AutoBase } from './paddleRouting';
import { keepJoinedFixedLegs } from './tourFixedLegs';
import { alignFreeLegs } from './tourRouteActions';
/** A control point of a planned tour, as the editor holds it. */
export interface TourPlannerWaypoint {
id: string;
lat: number;
lng: number;
role: TourWaypointRole;
/** The leg to the next waypoint as a fixed line (a via ferrata on the tour), not routed. */
fixedLeg?: TourFixedLeg | null;
/** PAD-07: a lock at this point of a paddle tour, with the times expected there. */
lock?: PaddleLock | null;
/** P2A-03: a shaping point, there only to steer the route; no stop. */
shaping?: boolean;
/** PAD-11: set where the router found a portage or a lock; gone once the paddler touches the point. */
auto?: AutoBase;
/** PAD-03: at the last point, the boat is carried on to the next point once it is set; never saved. */
carryNext?: boolean;
}
/** A saved tour's waypoints as the editor holds them, each under a fresh id. */
export function plannerWaypointsOf(saved: readonly TourWaypoint[], newId: () => string): TourPlannerWaypoint[] {
return saved.map((point) => ({
id: newId(),
lat: point.lat,
lng: point.lng,
role: point.role,
...(point.fixed_leg ? { fixedLeg: point.fixed_leg } : {}),
...(point.lock ? { lock: point.lock } : {}),
...(point.shaping ? { shaping: true } : {}),
}));
}
/**
* The editor's waypoints as they are saved, in their order: what the server
* keeps and nothing of the editor's own (ids, automatic marks, a portage
* waiting for its next point).
*/
export function savedWaypointsOf(points: readonly TourPlannerWaypoint[]): TourWaypoint[] {
return points.map((point, sequence) => ({
lat: point.lat,
lng: point.lng,
role: point.role,
sequence,
...(point.fixedLeg ? { fixed_leg: point.fixedLeg } : {}),
...(point.lock ? { lock: point.lock } : {}),
...(point.shaping ? { shaping: true } : {}),
}));
}
/** Roles from the order; free legs follow their points, and a paddle tour keeps its portages and locks. */
export function normalizePlannerWaypoints(points: TourPlannerWaypoint[], paddle = false): TourPlannerWaypoint[] {
return keepJoinedFixedLegs(alignFreeLegs(points, paddle)).map((point, index) => ({
...point,
role: index === 0 ? 'start' : index === points.length - 1 ? 'end' : 'via',
}));
}
function fixedLegKey(leg: TourFixedLeg | null | undefined): string {
if (!leg) return '';
return leg.kind === 'ferrata' ? `:${leg.ref}` : `:${leg.kind}:${leg.geometry.length}`;
}
/** What the route depends on: every point, where it is, the fixed line after it and whether it only shapes. */
export function tourWaypointKey(points: TourPlannerWaypoint[]): string {
return points
.map(
(point) =>
`${point.id}:${point.lat.toFixed(7)}:${point.lng.toFixed(7)}${fixedLegKey(point.fixedLeg)}${point.shaping ? ':shape' : ''}`
)
.join('|');
}
/** The line, and what a paddler planned along it that draws no line: a portage's time, a lock, a point the router set. */
export function sameWaypointSnapshot(a: TourPlannerWaypoint[], b: TourPlannerWaypoint[]): boolean {
const extras = (points: TourPlannerWaypoint[]) =>
JSON.stringify(
points.map((point) => [
point.fixedLeg?.kind === 'portage' ? (point.fixedLeg.extra_minutes ?? null) : null,
point.lock ?? null,
!!point.auto,
!!point.carryNext,
])
);
return tourWaypointKey(a) === tourWaypointKey(b) && extras(a) === extras(b);
}
/** P2A-03: the points with a shaping point set into the leg after `afterId`; unchanged when there is no such leg. */
export function withShapingPoint(
points: TourPlannerWaypoint[],
afterId: string,
shape: Pick<TourPlannerWaypoint, 'id' | 'lat' | 'lng'>
): TourPlannerWaypoint[] {
const index = points.findIndex((point) => point.id === afterId);
if (index < 0 || index >= points.length - 1) return points;
return [...points.slice(0, index + 1), { ...shape, role: 'via', shaping: true }, ...points.slice(index + 1)];
}
/** P2A-03: a stop made a shaping point, or a shaping point a stop. The ends of a tour are always stops. */
export function withShaping(points: TourPlannerWaypoint[], id: string, shaping: boolean): TourPlannerWaypoint[] {
return points.map((point, index) => {
if (point.id !== id || index === 0 || index === points.length - 1) return point;
if (shaping) return { ...point, shaping: true };
const { shaping: _dropped, ...stop } = point;
return stop;
});
}
/** PAD-11: every leg drawn by hand handed back to the router. */
export function withDrawnLegsRouted(points: TourPlannerWaypoint[]): TourPlannerWaypoint[] {
return points.map((point) => {
if (point.fixedLeg?.kind !== 'free') return point;
const { fixedLeg: _drawn, ...routed } = point;
return routed;
});
}
@@ -108,10 +108,25 @@ describe('free legs (P2A-04)', () => {
expect(aligned.map((point) => point.fixedLeg)).toEqual([undefined, undefined, undefined]);
});
it('draws every leg by hand for a paddle tour', () => {
it('routes a paddle tour on the water: a via ferrata goes back to the router, a leg drawn by hand follows its points', () => {
const aligned = alignFreeLegs([A, { ...B, fixedLeg: FERRATA }, C], true);
expect(aligned.map((point) => point.fixedLeg?.kind)).toEqual(['free', 'free', undefined]);
expect(aligned[1].fixedLeg).toEqual(freeLegBetween(B, C));
expect(aligned.map((point) => point.fixedLeg?.kind)).toEqual([undefined, undefined, undefined]);
const drawn = alignFreeLegs([{ ...A, fixedLeg: freeLegBetween(A, C) }, B, C], true);
expect(drawn[0].fixedLeg).toEqual(freeLegBetween(A, B));
});
it('keeps the shape of a drawn paddle leg while its ends still meet their points, and redraws it once one moves', () => {
const shaped = {
kind: 'free' as const,
geometry: [
[A.lat, A.lng],
[A.lat + 0.001, A.lng + 0.002],
[B.lat, B.lng],
] as [number, number][],
};
expect(alignFreeLegs([{ ...A, fixedLeg: shaped }, B], true)[0].fixedLeg).toEqual(shaped);
const moved = { ...B, lat: B.lat + 0.01 };
expect(alignFreeLegs([{ ...A, fixedLeg: shaped }, moved, C], true)[0].fixedLeg).toEqual(freeLegBetween(A, moved));
});
});
@@ -122,7 +137,31 @@ describe('portages and locks (PAD-03, PAD-07)', () => {
const carried = togglePortageLeg(alignFreeLegs([A, B, C], true), 'a');
expect(carried[0].fixedLeg).toEqual(portageLegBetween(A, B));
expect(togglePortageLeg(carried, 'a')[0].fixedLeg).toEqual(freeLegBetween(A, B));
expect(togglePortageLeg(carried, 'c')).toEqual(carried);
});
it('asks for a portage at the last point and draws it to the point set next', () => {
const asked = togglePortageLeg(alignFreeLegs([A, B], true), 'b');
expect(asked[1]).toMatchObject({ carryNext: true });
// Redrawn with no point after it, the ask waits.
expect(alignFreeLegs(asked, true)[1]).toMatchObject({ carryNext: true });
const placed = alignFreeLegs([...asked, C], true);
expect(placed[1].fixedLeg).toEqual(portageLegBetween(B, C));
expect(placed[1]).not.toHaveProperty('carryNext');
// A second press takes the ask back, and a hike forgets it.
expect(togglePortageLeg(asked, 'b')[1]).not.toHaveProperty('carryNext');
expect(alignFreeLegs([...asked, C])[1]).not.toHaveProperty('carryNext');
});
it('keeps a portage that follows a way while its ends stay, and draws it straight once one moves', () => {
const geometry: [number, number][] = [
[A.lat, A.lng],
[47.004, 11.006],
[B.lat, B.lng],
];
const points: RoutePoint[] = [{ ...A, fixedLeg: { ...portageLegBetween(A, B), geometry } }, B, C];
expect(alignFreeLegs(points, true)[0].fixedLeg).toEqual(points[0].fixedLeg);
const moved = alignFreeLegs([points[0], { ...B, lat: 47.012 }, C], true);
expect(moved[0].fixedLeg).toEqual(portageLegBetween(A, { lat: 47.012, lng: B.lng }));
});
it('keeps a portage and its time when a paddle tour is redrawn, and moves the time to the leg that leads it', () => {
@@ -14,6 +14,12 @@ export interface RoutePoint {
lng: number;
fixedLeg?: TourFixedLeg | null;
lock?: PaddleLock | null;
/**
* PAD-03: the boat is carried on from this point, the last of the tour so
* far; the portage is drawn to the next point once it is set. The planner's
* own, never saved.
*/
carryNext?: boolean;
}
/** Closer than this, in degrees, two waypoints stand on the same spot (about a centimetre). */
@@ -114,25 +120,46 @@ function extrasOnFirstLeg<T extends RoutePoint>(points: T[]): T[] {
return points;
}
/** A line still joins its points when its ends lie this close to them, in degrees (about two metres). */
const JOINS_DEG = 2e-5;
function stillJoins(leg: TourFixedLeg, from: { lat: number; lng: number }, to: { lat: number; lng: number }): boolean {
const first = leg.geometry[0];
const last = leg.geometry[leg.geometry.length - 1];
const near = (end: readonly unknown[] | undefined, point: { lat: number; lng: number }) =>
!!end && Math.abs(Number(end[0]) - point.lat) < JOINS_DEG && Math.abs(Number(end[1]) - point.lng) < JOINS_DEG;
return near(first, from) && near(last, to);
}
/**
* Every hand-drawn leg, and every portage, redrawn straight to the waypoint
* that now follows it, so moving a point drags them along instead of tearing
* them off. A leg on the last point leads nowhere and goes, and so does a lock
* nobody paddles to on a tour that is no paddle tour. With `allFree` every
* leg that is not a portage becomes hand-drawn, the way a paddle tour is planned.
* Every hand-drawn leg redrawn straight to the waypoint that now follows it,
* so moving a point drags it along instead of tearing it off; a leg on the
* last point leads nowhere and goes. On a hike a portage and a lock are a
* paddler's and go. On a paddle tour (`paddle`) a via ferrata is a hiker's
* and goes back to the router; a portage and a lock stay, a portage is
* dragged along like a drawn leg, and a portage or drawn leg whose line has
* a shape of its own (a portage way the router followed) keeps it while its
* ends still meet their points. A leg without a line stays routed. A portage
* asked for at the last point of a paddle tour becomes one once a point follows.
*/
export function alignFreeLegs<T extends RoutePoint>(points: readonly T[], allFree = false): T[] {
const aligned = points.map((point, index) => {
export function alignFreeLegs<T extends RoutePoint>(points: readonly T[], paddle = false): T[] {
const aligned = points.map((current, index) => {
const next = points[index + 1];
const leg = point.fixedLeg;
const kept = allFree ? point : dropPaddleOnly(point);
const free = allFree || leg?.kind === 'free';
if (!free && !(allFree && isPortage(leg))) return kept;
const { carryNext, ...own } = current;
if (carryNext && paddle) {
if (!next) return current;
return { ...own, fixedLeg: portageLegBetween(current, next) } as T;
}
const point = (carryNext ? own : current) as T;
const kept = paddle ? dropHikeOnly(point) : dropPaddleOnly(point);
const leg = kept.fixedLeg;
const follows = leg?.kind === 'free' || (paddle && isPortage(leg));
if (!follows || !leg) return kept;
if (!next) {
if (!kept.fixedLeg) return kept;
const { fixedLeg: _dropped, ...rest } = kept;
return rest as T;
}
if (paddle && leg.geometry.length > 2 && stillJoins(leg, point, next)) return kept;
return {
...kept,
fixedLeg: isPortage(leg)
@@ -140,7 +167,14 @@ export function alignFreeLegs<T extends RoutePoint>(points: readonly T[], allFre
: freeLegBetween(point, next),
};
});
return allFree ? extrasOnFirstLeg(aligned) : aligned;
return paddle ? extrasOnFirstLeg(aligned) : aligned;
}
/** A boat climbs no via ferrata: its leg goes back to the router, on the water. */
function dropHikeOnly<T extends RoutePoint>(point: T): T {
if (point.fixedLeg?.kind !== 'ferrata') return point;
const { fixedLeg: _ferrata, ...routed } = point;
return routed as T;
}
/** A hike carries no boat: a portage turns back into a routed leg and a lock goes. */
@@ -151,13 +185,21 @@ function dropPaddleOnly<T extends RoutePoint>(point: T): T {
return plain as T;
}
/** PAD-03: the leg after this point carried as a portage, or paddled again. */
/**
* PAD-03: the leg after this point carried as a portage, or paddled again. At
* the last point there is no leg yet: the portage waits for the next point.
*/
export function togglePortageLeg<T extends RoutePoint>(points: readonly T[], id: string): T[] {
const index = points.findIndex((point) => point.id === id);
const point = points[index];
const next = points[index + 1];
if (!point || !next) return [...points];
if (!point) return [...points];
const copy = [...points];
if (!next) {
const { carryNext, ...own } = point;
copy[index] = (carryNext ? own : { ...point, carryNext: true }) as T;
return copy;
}
copy[index] = {
...point,
fixedLeg: isPortage(point.fixedLeg) ? freeLegBetween(point, next) : portageLegBetween(point, next),
@@ -189,14 +231,15 @@ export function setWaypointLock<T extends RoutePoint>(points: readonly T[], id:
}
/**
* The leg after this waypoint drawn by hand, or routed again. A via ferrata
* keeps its line; the last point has no leg to change.
* The leg after this waypoint drawn by hand, or routed again (on a paddle
* tour: on the water). A via ferrata and a portage keep their line; the last
* point has no leg to change.
*/
export function toggleFreeLeg<T extends RoutePoint>(points: readonly T[], id: string): T[] {
const index = points.findIndex((point) => point.id === id);
const point = points[index];
const next = points[index + 1];
if (!point || !next || point.fixedLeg?.kind === 'ferrata') return [...points];
if (!point || !next || point.fixedLeg?.kind === 'ferrata' || isPortage(point.fixedLeg)) return [...points];
const copy = [...points];
if (point.fixedLeg?.kind === 'free') {
const { fixedLeg: _dropped, ...rest } = point;
@@ -0,0 +1,47 @@
// FE-TOUR-ROUTE-STYLE-001 to FE-TOUR-ROUTE-STYLE-003: how the planner map draws the parts of a tour (PAD-03, PAD-11).
import { describe, expect, it } from 'vitest';
import { tourRouteStyle } from './tourRouteStyle';
import type { TourRoutePart } from './tourRouting';
const PAINT = { portage: 'brown', rapids: 'amber', gap: 'red', casing: 'white' };
const line: [number, number][] = [
[49, 12],
[49.01, 12.01],
];
const part = (extra: Partial<TourRoutePart> = {}): TourRoutePart => ({ coordinates: line, free: false, ...extra });
describe('tourRouteStyle', () => {
it('FE-TOUR-ROUTE-STYLE-001: a routed tour is one plain line, and no parts draw nothing', () => {
expect(tourRouteStyle([part(), part()], true, PAINT)).toEqual({ walking: null, colors: null });
expect(tourRouteStyle(null, true, PAINT)).toEqual({ walking: null, colors: null });
});
it('FE-TOUR-ROUTE-STYLE-002: a paddle tour dots and colours what no router planned and what the paddler should see', () => {
const style = tourRouteStyle(
[
part(),
part({ land: true }),
part({ mark: 'rapids' }),
part({ mark: 'gap' }),
part({ mark: 'unrouted' }),
part({ free: true }),
],
true,
PAINT
);
expect(style.walking).toEqual([false, true, false, true, true, true]);
expect(style.colors).toEqual([
undefined,
{ line: 'brown', casing: 'white' },
{ line: 'amber', casing: 'white' },
{ line: 'red', casing: 'white' },
{ line: 'red', casing: 'white' },
undefined,
]);
});
it('FE-TOUR-ROUTE-STYLE-003: a hike dots its hand-drawn stretches and keeps its own colour', () => {
const style = tourRouteStyle([part(), part({ free: true })], false, PAINT);
expect(style).toEqual({ walking: [false, true], colors: null });
});
});
@@ -1,36 +1,47 @@
import type { TourRoutePart } from './tourRouting';
/**
* PAD-03: a portage on the map, in an earth brown over a rim in the map's own
* white, dotted the way the map draws a walk: the boat is carried there, not
* paddled. The colours come resolved from the paddle tokens (`usePaddlePaint`).
* PAD-03, PAD-11: the paddle paints of the planner map, resolved from the
* paddle tokens (`usePaddlePaint`): a portage in earth brown, whitewater and
* boat passes in amber, a gap in the data or a leg no route was found for in
* red, each over a rim in the map's own white.
*/
export interface PortagePaint {
line: string;
export interface RoutePaint {
portage: string;
rapids: string;
gap: string;
casing: string;
}
export interface TourRouteStyle {
/** Per line: dotted (a hand-drawn stretch of a hike, a portage) or solid. */
/** Per line: dotted (a stretch nobody routed: drawn by hand, carried, or a gap) or solid. */
walking: boolean[] | null;
/** Per line: the portage brown, or the route's own colour where undefined. */
/** Per line: a paddle paint, or the route's own colour where undefined. */
colors: ({ line: string; casing: string } | undefined)[] | null;
}
function paddleColor(part: TourRoutePart, paint: RoutePaint): { line: string; casing: string } | undefined {
if (part.land) return { line: paint.portage, casing: paint.casing };
if (part.mark === 'rapids') return { line: paint.rapids, casing: paint.casing };
if (part.mark === 'gap' || part.mark === 'unrouted') return { line: paint.gap, casing: paint.casing };
return undefined;
}
/**
* How the planner map draws the parts of a tour being edited. A hike draws
* what no router planned dotted, so a routed path and a hand-drawn one never
* look alike. A paddle tour is drawn by hand throughout, so its water is the
* plain line and only its portages stand out, dotted and brown.
* How the planner map draws the parts of a tour being edited. What no router
* planned is dotted, so a routed path and a hand-drawn one never look alike:
* a hike's hand-drawn stretches, a paddle tour's portages, gaps, unrouted legs
* and stretches drawn by hand. A paddle tour also colours what the paddler
* should look at.
*/
export function tourRouteStyle(
parts: readonly TourRoutePart[] | null,
isPaddle: boolean,
portage: PortagePaint
paint: RoutePaint
): TourRouteStyle {
if (!parts?.length) return { walking: null, colors: null };
const walking = parts.map((part) => (isPaddle ? !!part.land : part.free));
const colors = parts.map((part) => (part.land ? { line: portage.line, casing: portage.casing } : undefined));
const walking = parts.map((part) => part.free || !!part.land || part.mark === 'gap' || part.mark === 'unrouted');
const colors = parts.map((part) => (isPaddle ? paddleColor(part, paint) : undefined));
return {
walking: walking.some(Boolean) ? walking : null,
colors: colors.some(Boolean) ? colors : null,
@@ -9,6 +9,12 @@ export interface TourRoutePart {
free: boolean
/** PAD-03: carried over land, a portage of a paddle tour; absent on water and on a hike. */
land?: boolean
/**
* PAD-11: on a routed paddle tour, a stretch the paddler should look at:
* whitewater or a boat pass, a gap in the data the router bridged, or a leg
* it could not plan (drawn straight, and nothing checked it).
*/
mark?: 'rapids' | 'gap' | 'unrouted'
}
export interface TourRouteResult {
@@ -1,6 +1,7 @@
import {
recommendedPaddleSpeedKmh,
type PaddleBoatType,
type PaddleLakeStyle,
type PaddleWaterContext,
type TourListItem,
} from '@trek/shared';
@@ -13,6 +14,8 @@ export interface PaddleFieldValues {
speedKmh: number | null;
/** PAD-07: the carrying speed the paddler chose, km/h; null while the starting value applies. Absent in an older draft. */
portageSpeedKmh?: number | null;
/** PAD-11: how lakes are routed; null (or absent, in an older draft) is straight over. */
lakeStyle?: PaddleLakeStyle | null;
}
export const NO_PADDLE_FIELDS: PaddleFieldValues = {
@@ -20,17 +23,22 @@ export const NO_PADDLE_FIELDS: PaddleFieldValues = {
waterContext: null,
speedKmh: null,
portageSpeedKmh: null,
lakeStyle: null,
};
/** The paddle fields of a saved tour, or none for a hike or a list cached before they existed. */
export function paddleFieldsOf(
tour: Pick<TourListItem, 'boat_type' | 'water_context' | 'paddle_speed_kmh' | 'portage_speed_kmh'>
tour: Pick<
TourListItem,
'boat_type' | 'water_context' | 'paddle_speed_kmh' | 'portage_speed_kmh' | 'paddle_lake_style'
>
): PaddleFieldValues {
return {
boatType: tour.boat_type ?? null,
waterContext: tour.water_context ?? null,
speedKmh: tour.paddle_speed_kmh ?? null,
portageSpeedKmh: tour.portage_speed_kmh ?? null,
lakeStyle: tour.paddle_lake_style ?? null,
};
}
@@ -51,7 +59,8 @@ export function usePaddleFields(initial: PaddleFieldValues, onEdit: () => boolea
merged.boatType === values.boatType &&
merged.waterContext === values.waterContext &&
Object.is(merged.speedKmh, values.speedKmh) &&
Object.is(merged.portageSpeedKmh ?? null, values.portageSpeedKmh ?? null);
Object.is(merged.portageSpeedKmh ?? null, values.portageSpeedKmh ?? null) &&
(merged.lakeStyle ?? null) === (values.lakeStyle ?? null);
if (!same && onEdit()) setValues(merged);
},
[onEdit, values]
@@ -61,6 +70,7 @@ export function usePaddleFields(initial: PaddleFieldValues, onEdit: () => boolea
return {
...values,
portageSpeedKmh: values.portageSpeedKmh ?? null,
lakeStyle: values.lakeStyle ?? 'direct',
recommendedSpeedKmh: recommended,
/** The speed the time is worked out with: the chosen one, else the boat's suggestion. */
effectiveSpeedKmh: values.speedKmh ?? recommended,
@@ -69,6 +79,8 @@ export function usePaddleFields(initial: PaddleFieldValues, onEdit: () => boolea
setSpeedKmh: useCallback((speedKmh: number | null) => edit({ speedKmh }), [edit]),
/** PAD-07: the carrying speed, or back to the starting value with null. */
setPortageSpeedKmh: useCallback((portageSpeedKmh: number | null) => edit({ portageSpeedKmh }), [edit]),
/** PAD-11: straight over the lakes, or along their shores. */
setLakeStyle: useCallback((lakeStyle: PaddleLakeStyle) => edit({ lakeStyle }), [edit]),
/** Back to the boat's suggestion, by choice. */
adoptRecommendedSpeed: useCallback(() => edit({ speedKmh: null }), [edit]),
/** Loaded from a tour or a draft, or cleared; not an edit. */
@@ -0,0 +1,71 @@
import { useCallback, type RefObject } from 'react';
import { randomId } from '../../../utils/randomId';
import { withDrawnLegsRouted, withShaping, withShapingPoint, type TourPlannerWaypoint } from './tourPlannerWaypoints';
type Commit = (change: (current: TourPlannerWaypoint[]) => TourPlannerWaypoint[]) => void;
/**
* P2A-03, P2A-05 and PAD-11: the editor's tools for the line between the
* stops. A shaping point steers the route without being a stop, a routed leg
* can be planned afresh, and a paddle tour's legs drawn by hand go back to the
* router in one step. Each change is one step of the history, through the
* planner's own commit; nothing here plans a route itself.
*/
export function useRouteShaping({
commit,
waypointsRef,
mayEdit,
isPaddle,
retry,
forgetLeg,
}: {
commit: Commit;
waypointsRef: RefObject<TourPlannerWaypoint[]>;
/** Whether the route may change now: the permission held and no save under way. */
mayEdit: () => boolean;
isPaddle: () => boolean;
/** Plans the route again as it stands. */
retry: () => void;
/** Drops the answer kept for a paddle leg, so the router is asked again. */
forgetLeg: (from: TourPlannerWaypoint, to: TourPlannerWaypoint) => void;
}) {
/** A shaping point into the leg after `afterId`; its id, or null when there is no such leg. */
const insertShapingPoint = useCallback(
(afterId: string, lat: number, lng: number) => {
if (!mayEdit() || !Number.isFinite(lat) || !Number.isFinite(lng)) return null;
const points = waypointsRef.current;
const shape = { id: randomId(), lat, lng };
if (withShapingPoint(points, afterId, shape) === points) return null;
commit((current) => withShapingPoint(current, afterId, shape));
return shape.id;
},
[commit, mayEdit, waypointsRef]
);
const setWaypointShaping = useCallback(
(id: string, shaping: boolean) => {
if (mayEdit()) commit((current) => withShaping(current, id, shaping));
},
[commit, mayEdit]
);
const routeDrawnLegsOnWater = useCallback(() => {
if (mayEdit() && isPaddle()) commit(withDrawnLegsRouted);
}, [commit, isPaddle, mayEdit]);
/** The routed leg after this waypoint planned afresh, past any answer kept from before. */
const recomputeLeg = useCallback(
(id: string) => {
const points = waypointsRef.current;
const index = points.findIndex((point) => point.id === id);
const point = points[index];
const next = points[index + 1];
if (!point || !next || point.fixedLeg) return;
if (isPaddle()) forgetLeg(point, next);
retry();
},
[forgetLeg, isPaddle, retry, waypointsRef]
);
return { insertShapingPoint, setWaypointShaping, routeDrawnLegsOnWater, recomputeLeg };
}
@@ -0,0 +1,26 @@
import { useCallback } from 'react';
import { legStartAt } from './routeLegAt';
import type { TourPlannerController } from './useTourPlanner';
/**
* P2A-03: a click on the route being edited sets a shaping point where it
* landed, in the leg that runs there, and selects it, ready to be dragged
* where the route should go. Undefined while the points cannot be moved, or
* while a click on the line picks a spot for something else.
*/
export function useShapingClick(
planner: Pick<TourPlannerController, 'waypoints' | 'route' | 'insertShapingPoint' | 'setSelectedWaypointId'>,
{ editable, picking }: { editable: boolean; picking: boolean }
): ((lat: number, lng: number) => void) | undefined {
const { waypoints, route, insertShapingPoint, setSelectedWaypointId } = planner;
const shapeAt = useCallback(
(lat: number, lng: number) => {
const after = legStartAt(waypoints, route, lat, lng);
if (!after) return;
const id = insertShapingPoint(after, lat, lng);
if (id) setSelectedWaypointId(id);
},
[insertShapingPoint, route, setSelectedWaypointId, waypoints]
);
return editable && !picking ? shapeAt : undefined;
}
@@ -1,16 +1,20 @@
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const { routeWalkingTour, enrichTourElevations, createTour, detailTour, updateTour } = vi.hoisted(() => ({
routeWalkingTour: vi.fn(),
enrichTourElevations: vi.fn(),
createTour: vi.fn(),
detailTour: vi.fn(),
updateTour: vi.fn(),
}));
const { routeWalkingTour, enrichTourElevations, createTour, detailTour, updateTour, paddlePlan, paddleForget } =
vi.hoisted(() => ({
routeWalkingTour: vi.fn(),
enrichTourElevations: vi.fn(),
createTour: vi.fn(),
detailTour: vi.fn(),
updateTour: vi.fn(),
paddlePlan: vi.fn(),
paddleForget: vi.fn(),
}));
vi.mock('./tourRouting', () => ({ routeWalkingTour, enrichTourElevations }));
vi.mock('../../../repo/tourRepo', () => ({ tourRepo: { create: createTour, detail: detailTour, update: updateTour } }));
vi.mock('../../../repo/paddleRouteRepo', () => ({ paddleRouteRepo: { plan: paddlePlan, forget: paddleForget } }));
vi.mock('../useTourPermissions', () => ({
useTourPermissions: ({ canEdit = true, canAssign = true }: { canEdit?: boolean; canAssign?: boolean }) => ({
canEdit,
@@ -64,6 +68,20 @@ function plannerWith(points: Array<[number, number]>) {
return hook;
}
type LegAsked = { from: { lat: number; lng: number }; to: { lat: number; lng: number } };
/** The water router's answer for every leg asked: a straight stretch on the water, 1.2 km long. */
const onWater = (legs: LegAsked[]) =>
legs.map(({ from, to }) => ({
status: 'ok' as const,
geometry: [
[from.lat, from.lng],
[to.lat, to.lng],
],
segments: [{ kind: 'water' as const, from: 0, to: 1 }],
distance_m: 1200,
snapped_m: { from: 0, to: 0 },
}));
const coordinatesOf = (points: Array<{ lat: number; lng: number }>) => points.map((point) => [point.lat, point.lng]);
describe('useTourPlanner route tools', () => {
@@ -71,6 +89,8 @@ describe('useTourPlanner route tools', () => {
vi.useFakeTimers();
localStorage.clear();
routeWalkingTour.mockReset().mockResolvedValue(routed);
paddlePlan.mockReset().mockImplementation(async (_trip: number, legs: LegAsked[]) => onWater(legs));
paddleForget.mockReset();
enrichTourElevations.mockReset().mockResolvedValue(enriched);
createTour.mockReset();
detailTour.mockReset();
@@ -221,7 +241,7 @@ describe('useTourPlanner route tools', () => {
});
describe('paddle tours (PAD-01)', () => {
it('draws every leg by hand once paddle is chosen, and one undo takes the type and the legs back', () => {
it('plans every leg on the water once paddle is chosen, and one undo takes the type back', async () => {
const { result } = plannerWith([
[48, 11],
[48.01, 11.02],
@@ -229,9 +249,22 @@ describe('useTourPlanner route tools', () => {
]);
act(() => result.current.setTourType('kayak'));
expect(result.current.isPaddle).toBe(true);
expect(result.current.waypoints.map((point) => point.fixedLeg?.kind)).toEqual(['free', 'free', undefined]);
expect(result.current.waypoints.map((point) => point.fixedLeg)).toEqual([undefined, undefined, undefined]);
routeWalkingTour.mockClear();
await act(async () => {
await vi.advanceTimersByTimeAsync(450);
});
expect(routeWalkingTour).not.toHaveBeenCalled();
expect(paddlePlan).toHaveBeenLastCalledWith(
31,
expect.any(Array),
{ boat: 'kayak', lakeStyle: 'direct' },
expect.any(AbortSignal)
);
expect(result.current.status).toBe('ready');
expect(result.current.paddleRoute?.legLengths).toEqual([1200, 1200]);
act(() => result.current.addWaypoint(48.03, 11.01));
expect(result.current.waypoints[2].fixedLeg?.kind).toBe('free');
expect(result.current.waypoints[2].fixedLeg).toBeUndefined();
act(() => result.current.undo());
act(() => result.current.undo());
expect(result.current.tourType).toBe('hike');
@@ -240,7 +273,6 @@ describe('useTourPlanner route tools', () => {
it('holds Save back until a boat and the water are chosen, then saves them without a hiking limit', async () => {
createTour.mockResolvedValue({ tour: { ...savedTour, tour_type: 'kayak' }, waypoints: [] });
routeWalkingTour.mockResolvedValue({ ...routed, parts: [{ ...routed.parts[0], free: true }] });
const { result } = plannerWith([
[48, 11],
[48.01, 11.02],
@@ -264,11 +296,14 @@ describe('useTourPlanner route tools', () => {
boat_type: 'canoe',
water_context: 'lake',
paddle_speed_kmh: null,
paddle_lake_style: 'direct',
max_hiking_difficulty: null,
});
// A paddle tour carries no heights to look up.
expect(enrichTourElevations).not.toHaveBeenCalled();
});
it('times the water at the boat speed, keeps a chosen speed when the boat changes, and takes the suggestion only on purpose', async () => {
it('times the water by the routed length at the boat speed, keeps a chosen speed when the boat changes, and takes the suggestion only on purpose', async () => {
const { result } = plannerWith([
[48, 11],
[48.01, 11.02],
@@ -278,13 +313,13 @@ describe('useTourPlanner route tools', () => {
await act(async () => {
await vi.advanceTimersByTimeAsync(450);
});
const distanceKm = result.current.routeAnalysis?.distanceKm ?? 0;
expect(result.current.walkingDurationMinutes).toBe(Math.round((distanceKm / 4) * 60));
// 1.2 km on the water the router found, at 4 km/h.
expect(result.current.walkingDurationMinutes).toBe(18);
act(() => result.current.paddle.setSpeedKmh(6));
act(() => result.current.paddle.setBoatType('other'));
expect(result.current.paddle.speedKmh).toBe(6);
expect(result.current.walkingDurationMinutes).toBe(Math.round((distanceKm / 6) * 60));
expect(result.current.walkingDurationMinutes).toBe(12);
act(() => result.current.paddle.adoptRecommendedSpeed());
expect(result.current.paddle.recommendedSpeedKmh).toBeNull();
@@ -343,4 +378,135 @@ describe('useTourPlanner route tools', () => {
expect(old.result.current.name).toBe('Old');
});
});
describe('shaping and water routing (P2A-03, P2A-05, PAD-11)', () => {
const settle = () =>
act(async () => {
await vi.advanceTimersByTimeAsync(450);
});
it('sets a shaping point into a leg, makes it a stop and back, and never past the end', async () => {
const { result } = plannerWith([
[48, 11],
[48.02, 11.02],
]);
const [start, end] = result.current.waypoints;
let id: string | null = null;
act(() => {
id = result.current.insertShapingPoint(start!.id, 48.01, 11.005);
});
expect(result.current.waypoints.map((point) => !!point.shaping)).toEqual([false, true, false]);
expect(result.current.waypoints[1]?.id).toBe(id);
act(() => {
expect(result.current.insertShapingPoint(end!.id, 48.03, 11.03)).toBeNull();
expect(result.current.insertShapingPoint(start!.id, Number.NaN, 11)).toBeNull();
});
act(() => result.current.setWaypointShaping(id!, false));
expect(result.current.waypoints[1]).not.toHaveProperty('shaping');
act(() => result.current.setWaypointShaping(start!.id, true));
expect(result.current.waypoints[0]).not.toHaveProperty('shaping');
// One undo takes back one change.
act(() => result.current.undo());
expect(result.current.waypoints[1]?.shaping).toBe(true);
await settle();
expect(routeWalkingTour).toHaveBeenLastCalledWith(
expect.arrayContaining([expect.objectContaining({ shaping: true })]),
expect.any(AbortSignal),
2
);
});
it('plans a leg afresh: a paddle leg is forgotten and asked again, a fixed leg is left alone', async () => {
const { result } = plannerWith([
[48, 11],
[48.01, 11.02],
]);
act(() => result.current.setTourType('kayak'));
await settle();
expect(paddlePlan).toHaveBeenCalledTimes(1);
const [start, end] = result.current.waypoints;
act(() => result.current.recomputeLeg(start!.id));
expect(paddleForget).toHaveBeenCalledWith(31, start, end, { boat: 'kayak', lakeStyle: 'direct' });
await settle();
expect(paddlePlan).toHaveBeenCalledTimes(2);
act(() => result.current.recomputeLeg(end!.id));
expect(paddleForget).toHaveBeenCalledTimes(1);
});
it('sends every leg drawn by hand back to the water router in one step', async () => {
const { result } = plannerWith([
[48, 11],
[48.01, 11.02],
[48.02, 11],
]);
act(() => result.current.setTourType('kayak'));
for (const point of result.current.waypoints.slice(0, 2))
act(() => result.current.toggleWaypointFreeLeg(point.id));
expect(result.current.waypoints.map((point) => point.fixedLeg?.kind)).toEqual(['free', 'free', undefined]);
act(() => result.current.routeDrawnLegsOnWater());
expect(result.current.waypoints.map((point) => point.fixedLeg)).toEqual([undefined, undefined, undefined]);
act(() => result.current.undo());
expect(result.current.waypoints[0]?.fixedLeg?.kind).toBe('free');
});
it('keeps a tour with an unplanned leg from being saved, and says it per leg', async () => {
paddlePlan.mockImplementation(async (_trip: number, legs: LegAsked[]) =>
legs.map(() => ({ status: 'failed', code: 'not_on_water', at: { lat: 48.01, lng: 11.02 } }))
);
const { result } = plannerWith([
[48, 11],
[48.01, 11.02],
]);
act(() => result.current.setName('Off the water'));
act(() => result.current.setTourType('kayak'));
act(() => result.current.paddle.setBoatType('kayak'));
act(() => result.current.paddle.setWaterContext('river'));
await settle();
expect(result.current.status).toBe('routing-failed');
expect(result.current.error).toBe('paddle-route');
expect(result.current.paddleRoute?.failures).toEqual([
{ index: 0, code: 'not_on_water', at: { lat: 48.01, lng: 11.02 } },
]);
expect(result.current.routeCurrent).toBe(true);
expect(result.current.canSave).toBe(false);
});
it('sets the portage and the lock the router found as points of their own, and they go when their leg changes', async () => {
paddlePlan.mockImplementation(async (_trip: number, legs: LegAsked[]) =>
legs.map(({ from, to }) => {
const mid = (a: number, b: number, t: number) => a + (b - a) * t;
const at = (t: number): [number, number] => [mid(from.lat, to.lat, t), mid(from.lng, to.lng, t)];
const geometry = [at(0), at(0.3), at(0.4), at(1)];
const segments = [
{ kind: 'water', from: 0, to: 1 },
{ kind: 'portage', from: 1, to: 2, source: 'tagged' },
{ kind: 'water', from: 2, to: 3 },
].map((segment) => ({ name: null, source: null, osm_ref: null, grade: null, ...segment }));
return { status: 'ok', geometry, segments, distance_m: 3000, snapped_m: { from: 0, to: 0 } };
})
);
const { result } = plannerWith([
[48, 11],
[48.1, 11],
]);
act(() => result.current.setTourType('kayak'));
await settle();
await settle();
expect(result.current.waypoints).toHaveLength(4);
expect(result.current.waypoints[1]).toMatchObject({ fixedLeg: { kind: 'portage' } });
expect(result.current.waypoints.filter((point) => point.auto)).toHaveLength(2);
// Found by the router, not done by the paddler: no step of the history of its own.
act(() => result.current.undo());
expect(result.current.tourType).toBe('hike');
act(() => result.current.redo());
await settle();
await settle();
const end = result.current.waypoints[result.current.waypoints.length - 1];
act(() => result.current.setWaypointPosition(end.id, 48.2, 11));
await settle();
expect(result.current.waypoints.filter((point) => point.auto).every((point) => point.auto?.to.lat === 48.2)).toBe(
true
);
});
});
});
@@ -1596,7 +1596,7 @@ describe('useTourPlanner', () => {
expect(result.current.mode).toEqual({ type: 'new-draft' })
expect(JSON.parse(localStorage.getItem('tour-draft-23') || 'null')).toMatchObject({
version: 8,
version: 9,
tourType: 'hike',
name: '',
waypoints: [],
@@ -1,29 +1,21 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { MAX_PLANNED_TOUR_DURATION_MINUTES, paddleSpeedKmhSchema, tourWebsiteSchema, type PlannableTourType, type TourCreateResponse, type TourFixedLeg, type TourListItem, type TourWaypointRole, type TourMaxHikingDifficulty, type PaddleLock } from '@trek/shared'
import { MAX_PLANNED_TOUR_DURATION_MINUTES, paddleSpeedKmhSchema, tourWebsiteSchema, 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 { keepJoinedFixedLegs } from './tourFixedLegs'
import { alignFreeLegs, closeLoop, isClosedLoop, reverseRoute, toggleFreeLeg } from './tourRouteActions'
import { closeLoop, isClosedLoop, reverseRoute, toggleFreeLeg } from './tourRouteActions'
import { normalizePlannerWaypoints, plannerWaypointsOf, sameWaypointSnapshot, savedWaypointsOf, tourWaypointKey, type TourPlannerWaypoint } from './tourPlannerWaypoints'
import { useRouteShaping } from './useRouteShaping'
import { useTourMapView } from './useTourMapView'
import { validDraft, type DraftPayload } from './tourPlannerDraft'
import { paddleEstimateOf } from './paddlePlanOf'
import { adoptChangedPoints, planPaddleStep, type PaddleTourRoute } from './paddleRouting'
import { NO_PADDLE_FIELDS, paddleFieldsOf, usePaddleFields, type PaddleFieldValues } from './usePaddleFields'
import { hikingTimeMinutes } from '../hikingTime'
import { useTourPermissions, type TourPermissionProps } from '../useTourPermissions'
export interface TourPlannerWaypoint {
id: string
lat: number
lng: number
role: TourWaypointRole
/** The leg to the next waypoint as a fixed line (a via ferrata on the tour), not routed. */
fixedLeg?: TourFixedLeg | null
/** PAD-07: a lock at this point of a paddle tour, with the times expected there. */
lock?: PaddleLock | null
}
/** What a tour planned from an import starts with. */
export interface DerivedTourDraft {
name: string
@@ -69,29 +61,6 @@ function hasCompleteElevation(points: TourElevationPoint[] | null): points is [n
return !!points && points.every(point => point.length === 3 && Number.isFinite(point[2]))
}
/** Roles from the order; free legs follow their points, and a paddle tour draws every leg by hand. */
export function normalizePlannerWaypoints(points: TourPlannerWaypoint[], allFree = false): TourPlannerWaypoint[] {
return keepJoinedFixedLegs(alignFreeLegs(points, allFree)).map((point, index) => ({
...point,
role: index === 0 ? 'start' : index === points.length - 1 ? 'end' : 'via',
}))
}
export function tourWaypointKey(points: TourPlannerWaypoint[]): string {
return points.map(point => `${point.id}:${point.lat.toFixed(7)}:${point.lng.toFixed(7)}${fixedLegKey(point.fixedLeg)}`).join('|')
}
function fixedLegKey(leg: TourFixedLeg | null | undefined): string {
if (!leg) return ''
return leg.kind === 'ferrata' ? `:${leg.ref}` : `:${leg.kind}`
}
/** The line, and what a paddler planned along it that draws no line: a portage's time, a lock. */
function sameWaypointSnapshot(a: TourPlannerWaypoint[], b: TourPlannerWaypoint[]): boolean {
const extras = (points: TourPlannerWaypoint[]) => JSON.stringify(points.map(point => [point.fixedLeg?.kind === 'portage' ? point.fixedLeg.extra_minutes ?? null : null, point.lock ?? null]))
return tourWaypointKey(a) === tourWaypointKey(b) && extras(a) === extras(b)
}
/** Where a new tour was planned from; an edit leaves it as it was saved. */
function derivedFromField(placeId: number | null, derivedFrom: number | null): { derived_from_place_id?: number } {
return placeId === null && derivedFrom !== null ? { derived_from_place_id: derivedFrom } : {}
@@ -157,6 +126,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
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)
@@ -241,7 +211,10 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
const commitWaypoints = useCallback((nextValue: TourPlannerWaypoint[] | ((current: TourPlannerWaypoint[]) => TourPlannerWaypoint[])) => {
if (!editPermissionRef.current) return
const current = waypointsRef.current
const next = normalizePlannerWaypoints(typeof nextValue === 'function' ? nextValue(current) : nextValue, tourTypeRef.current === 'kayak')
const changed = typeof nextValue === 'function' ? nextValue(current) : nextValue
const paddle = tourTypeRef.current === 'kayak'
// A point the router set that the paddler moves or edits is theirs from then on.
const next = normalizePlannerWaypoints(paddle ? adoptChangedPoints(current, changed) : changed, paddle)
if (sameWaypointSnapshot(current, next)) return
invalidateDetailRequest()
interruptRouting()
@@ -256,6 +229,19 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
setError(null)
}, [invalidateDetailRequest, interruptRouting, snapshot])
// Detail laid in after the step that asked for it (a portage's way on land), with no step of its own.
const amendWaypoints = useCallback((change: (current: TourPlannerWaypoint[]) => TourPlannerWaypoint[]) => {
if (!editPermissionRef.current || saveInFlightRef.current) return
const changed = change(waypointsRef.current)
if (changed === waypointsRef.current) return
interruptRouting()
draftRevisionRef.current += 1
waypointsRef.current = normalizePlannerWaypoints(changed, tourTypeRef.current === 'kayak')
setWaypoints(waypointsRef.current)
setHasUnsavedChanges(true)
setStatus('dirty')
}, [interruptRouting])
const setMaxHikingDifficulty = useCallback((value: TourMaxHikingDifficulty) => {
if (!editPermissionRef.current) return
if (value === difficultyRef.current) return
@@ -333,9 +319,9 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
commitWaypoints(change)
}, [commitWaypoints])
/** P2A-04: the leg after this waypoint drawn by hand, or routed again. */
/** P2A-04: the leg after this waypoint drawn by hand, or routed again (a paddle tour's on the water). */
const toggleWaypointFreeLeg = useCallback((id: string) => {
if (!editPermissionRef.current || saveInFlightRef.current || tourTypeRef.current === 'kayak') return
if (!editPermissionRef.current || saveInFlightRef.current) return
commitWaypoints(current => toggleFreeLeg(current, id))
}, [commitWaypoints])
@@ -449,6 +435,8 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
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,
@@ -487,8 +475,10 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
const paddleIncomplete = isPaddle && (paddle.boatType === null || paddle.waterContext === null)
// A paddle tour is timed on the water at its speed; a hike by the signposts' rule once the heights are in.
const { effectiveSpeedKmh, portageSpeedKmh } = paddle
const paddleEstimate = useMemo(() => isPaddle ? paddleEstimateOf(waypoints, { effectiveSpeedKmh, portageSpeedKmh }, paddleSpeedInvalid) : null,
[effectiveSpeedKmh, isPaddle, paddleSpeedInvalid, portageSpeedKmh, waypoints])
// 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 paddleEstimate = useMemo(() => isPaddle ? paddleEstimateOf(waypoints, { effectiveSpeedKmh, portageSpeedKmh }, paddleSpeedInvalid, routedLegLengths) : null,
[effectiveSpeedKmh, isPaddle, paddleSpeedInvalid, portageSpeedKmh, routedLegLengths, waypoints])
const walkingDurationMinutes = paddleEstimate
? paddleEstimate.waterMinutes === null ? null : paddleEstimate.estimateMinutes
: routeAnalysis?.gain != null && routeAnalysis.loss != null
@@ -501,11 +491,11 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
&& (!Number.isInteger(breakAdditionalMinutes) || breakAdditionalMinutes < 0 || breakAdditionalMinutes > MAX_PLANNED_TOUR_DURATION_MINUTES)
const plannedTotalMinutes = plannedDurationMinutes ?? automaticPlannedTotalMinutes
// What the type adds to a save: a hike its routing limit, a paddle tour its boat, water and speed.
const { boatType, waterContext, speedKmh } = paddle
const { boatType, waterContext, speedKmh, lakeStyle } = paddle
const typeFields = useMemo(() => tourType === 'kayak'
? { tour_type: tourType, max_hiking_difficulty: null, boat_type: boatType, water_context: waterContext, paddle_speed_kmh: speedKmh, portage_speed_kmh: portageSpeedKmh }
: { tour_type: tourType, max_hiking_difficulty: maxHikingDifficulty, boat_type: null, water_context: null, paddle_speed_kmh: null, portage_speed_kmh: null },
[boatType, maxHikingDifficulty, portageSpeedKmh, speedKmh, tourType, waterContext])
? { tour_type: tourType, max_hiking_difficulty: null, boat_type: boatType, water_context: waterContext, paddle_speed_kmh: speedKmh, portage_speed_kmh: portageSpeedKmh, paddle_lake_style: lakeStyle }
: { tour_type: tourType, max_hiking_difficulty: maxHikingDifficulty, boat_type: null, water_context: null, paddle_speed_kmh: null, portage_speed_kmh: null, paddle_lake_style: null },
[boatType, lakeStyle, maxHikingDifficulty, portageSpeedKmh, speedKmh, tourType, waterContext])
// The router's own time stands in for a hike without heights; a paddle tour has only its speed.
const savedDurationSeconds = walkingDurationMinutes === null ? (isPaddle ? null : durationSeconds) : walkingDurationMinutes * 60
const plannedTotalInvalid = plannedDurationMinutes === null
@@ -537,6 +527,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
setStatus('empty')
setRoute(null)
setRouteParts(null)
setPaddleRoute(null)
setEnrichedGeometry(null)
setRouteForKey(null)
setDistanceMeters(null)
@@ -676,14 +667,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
interruptRouting()
const openedType: PlannableTourType = result.tour.tour_type === 'kayak' ? 'kayak' : 'hike'
const nextWaypoints = normalizePlannerWaypoints(result.waypoints.map(point => ({
id: randomId(),
lat: point.lat,
lng: point.lng,
role: point.role,
...(point.fixed_leg ? { fixedLeg: point.fixed_leg } : {}),
...(point.lock ? { lock: point.lock } : {}),
})), openedType === 'kayak')
const nextWaypoints = normalizePlannerWaypoints(plannerWaypointsOf(result.waypoints, randomId), openedType === 'kayak')
localStorage.removeItem(storageKey)
contextGenerationRef.current += 1
draftRevisionRef.current += 1
@@ -704,6 +688,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
setStatus('dirty')
setRoute(null)
setRouteParts(null)
setPaddleRoute(null)
setEnrichedGeometry(null)
setRouteForKey(null)
setDistanceMeters(null)
@@ -736,6 +721,15 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
setRetryToken(value => value + 1)
}, [interruptRouting])
// P2A-03/P2A-05/PAD-11: shaping points, a leg planned afresh, drawn legs handed back to the router.
const shaping = useRouteShaping({
commit: commitWaypoints, waypointsRef, retry,
mayEdit: useCallback(() => editPermissionRef.current && !saveInFlightRef.current, []),
isPaddle: useCallback(() => tourTypeRef.current === 'kayak', []),
forgetLeg: useCallback((from: TourPlannerWaypoint, to: TourPlannerWaypoint) =>
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),
@@ -764,10 +758,40 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
const controller = new AbortController()
abortRef.current?.abort()
abortRef.current = controller
const timer = window.setTimeout(async () => {
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)
if (controller.signal.aborted || generation !== generationRef.current) return
if (stale()) return
if (!routed) {
setStatus('routing-failed')
setError('routing')
@@ -776,6 +800,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
setRoute(routed.coordinates)
setRouteParts(routed.parts)
setPaddleRoute(null)
setDistanceMeters(routed.distanceMeters)
setDurationSeconds(routed.durationSeconds)
setRouteForKey(waypointKey)
@@ -783,7 +808,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
setStatus('enriching-elevation')
const enriched = await enrichTourElevations(routed.coordinates, controller.signal)
if (controller.signal.aborted || generation !== generationRef.current) return
if (stale()) return
if (!enriched) {
setStatus('elevation-failed')
setError('elevation')
@@ -797,24 +822,33 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
}
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()
}
}, [interruptRouting, maxHikingDifficulty, retryToken, waypointKey, waypoints])
}, [interruptRouting, isPaddle, maxHikingDifficulty, paddleBoat, paddleLakeStyle, retryToken, tripId, waypointKey, waypoints])
useEffect(() => {
if (!hasUnsavedChanges) return
const draft: DraftPayload = { version: 8, name, description, website, plannedDurationMinutes, breakAdditionalMinutes, waypoints, maxHikingDifficulty, editingPlaceId,
const draft: DraftPayload = { version: 9, name, description, website, plannedDurationMinutes, breakAdditionalMinutes, waypoints, maxHikingDifficulty, editingPlaceId,
derivedFromPlaceId, tourType,
paddle: { boatType: paddle.boatType, waterContext: paddle.waterContext, speedKmh: paddle.speedKmh, portageSpeedKmh: paddle.portageSpeedKmh },
paddle: { boatType: paddle.boatType, waterContext: paddle.waterContext, speedKmh: paddle.speedKmh, portageSpeedKmh: paddle.portageSpeedKmh, lakeStyle: paddle.lakeStyle },
}
localStorage.setItem(storageKey, JSON.stringify(draft))
}, [breakAdditionalMinutes,
derivedFromPlaceId, description, editingPlaceId, hasUnsavedChanges, maxHikingDifficulty, name, plannedDurationMinutes, storageKey, waypoints, website,
tourType, paddle.boatType, paddle.waterContext, paddle.speedKmh, paddle.portageSpeedKmh])
tourType, paddle.boatType, paddle.waterContext, paddle.speedKmh, paddle.portageSpeedKmh, paddle.lakeStyle])
useEffect(() => {
if (!hasUnsavedChanges) return
@@ -844,14 +878,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
website: parsedWebsiteOrNull(website),
...typeFields,
route_geometry: enrichedGeometry.map(point => [point[0], point[1], point[2]]),
waypoints: waypoints.map((point, sequence) => ({
lat: point.lat,
lng: point.lng,
role: point.role,
sequence,
...(point.fixedLeg ? { fixed_leg: point.fixedLeg } : {}),
...(point.lock ? { lock: point.lock } : {}),
})),
waypoints: savedWaypointsOf(waypoints),
duration_seconds: savedDurationSeconds,
planned_duration_minutes: plannedDurationMinutes,
break_additional_minutes: breakAdditionalMinutes,
@@ -909,7 +936,8 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
walkingDurationMinutes, plannedTotalMinutes, plannedTotalInvalid,
waypoints, selectedWaypointId, setSelectedWaypointId,
addWaypoint, appendFixedLeg, setWaypointPosition, removeWaypoint, moveWaypoint, reorderWaypoint,
reverse, returnToStart, isLoop: isClosedLoop(waypoints), toggleWaypointFreeLeg, editPaddlePoints, paddleEstimate,
reverse, returnToStart, isLoop: isClosedLoop(waypoints), toggleWaypointFreeLeg, editPaddlePoints, amendWaypoints, paddleEstimate,
...shaping, paddleRoute, routeCurrent: routeForKey === waypointKey,
undo, redo, canUndo: history.past.length > 0, canRedo: history.future.length > 0,
status, error, retry, isSaving,
route, routeParts, enrichedGeometry, routeAnalysis, distanceMeters, durationSeconds,