feat(tours): plan rides on horseback from signposted horse routes

A tour can now be a ride (HOR-01). The planner offers "Horse ride" as a
tour type with its own horseshoe, and a Horse routes card beside the
waypoints looks, when asked, for the route=horse relations OpenStreetMap
knows in the map view. A route opens in a dialog that shows it on a map in
the sections it is made of, split at forks, gaps and crossings, so nothing
is ever joined across a gap. The rider picks a section and its direction,
sees what the horse=* tags along it say (open, limited, closed, or unknown
where untagged) and whether it is signposted the other way, and takes it as
one undoable step. A section that does not start where the ride ends is
only joined by a straight manual stretch once the rider switched that on.

Nothing of a ride is routed: every leg follows a section or is drawn by
hand, and the waypoint list and the map say which (a section as a solid
line with its route, a manual stretch dashed and marked unchecked). A point
at a section stays where the route has it, a ride works out no riding time,
and distance, heights, day assignment, GPX import and export, the 3D view
and the reversed ride keep working with each leg's origin saved and opened
again. A failed lookup leaves the ride and the routes already found as they
were.

The server reads the routes through the shared Overpass client
(GET /api/trips/:tripId/tours/horse-routes, Tours addon, trip access),
keeps an answer twelve hours per grid-aligned view, and the tour contract
refuses a routed leg, a via ferrata or a riding time on a ride and a horse
route section on any other type. A migration enables the horse tour type.
This commit is contained in:
Maurice
2026-10-20 12:48:41 +02:00
parent dfe11e9c4c
commit 0331d9950f
103 changed files with 5470 additions and 82 deletions
@@ -82,6 +82,7 @@ export function TourNameField({ planner, locked }: TourFieldProps) {
kayak: t('tours.planner.namePlaceholder.kayak'),
walk: t('tours.planner.namePlaceholder.walk'),
run: t('tours.planner.namePlaceholder.run'),
horse: t('tours.planner.namePlaceholder.horse'),
}[planner.tourType]
}
className={INPUT}
@@ -51,6 +51,7 @@ import { useTourListFilters } from '../useTourListFilters'
import { TourPoiSearchCard } from '../poi/TourPoiSearchCard'
import { BikeWaysCard } from '../bike/BikeWaysCard'
import { RunWaysCard } from '../run/RunWaysCard'
import { HorseRoutesCard } from '../horse/HorseRoutesCard'
import { walkTimeFields } from '../walk/walkTimeFields'
const STATUS_KEY: Partial<Record<TourPlannerStatus, string>> = {
@@ -464,6 +465,8 @@ export function TourPlannerRail({ planner,
<RunWaysCard planner={planner} />
<HorseRoutesCard planner={planner} />
<TourPoiSearchCard planner={planner} />
<PaddleEditorCards planner={planner} locked={locked} checklist={paddleChecklist} />
@@ -622,20 +625,23 @@ interface TourPlannerToursRailProps extends TourPermissionProps {
onTakenOver?: (tour: TourListItem) => Promise<void>
}
/** The words of the time estimate: walking, riding (BIK-01), running (RUN-01) or paddling, each saying how it is reckoned. */
/** The words of the time estimate: walking, riding (BIK-01), running (RUN-01) or paddling, each saying how it is reckoned, and a ride none. */
const ESTIMATE_KEYS = {
hike: { labelKey: 'tours.planner.walkingEstimated', shortKey: 'tours.planner.walkingEstimatedShort', infoLabelKey: 'tours.planner.walkingEstimatedInfoLabel', infoKey: 'tours.planner.walkingEstimatedInfo' },
bike: { labelKey: 'tours.bike.timeEstimated', shortKey: 'tours.bike.timeEstimatedShort', infoLabelKey: 'tours.bike.timeEstimatedInfoLabel', infoKey: 'tours.bike.timeEstimatedInfo' },
kayak: { labelKey: 'tours.paddle.timeEstimated', shortKey: 'tours.paddle.timeEstimatedShort', infoLabelKey: 'tours.paddle.timeEstimatedInfoLabel', infoKey: 'tours.paddle.timeEstimatedInfo' },
walk: { labelKey: 'tours.walk.timeEstimated', shortKey: 'tours.walk.timeEstimatedShort', infoLabelKey: 'tours.walk.timeEstimatedInfoLabel', infoKey: 'tours.walk.timeEstimatedInfo' },
run: { labelKey: 'tours.run.timeEstimated', shortKey: 'tours.run.timeEstimatedShort', infoLabelKey: 'tours.run.timeEstimatedInfoLabel', infoKey: 'tours.run.timeEstimatedInfo' },
// HOR-01: a ride has no estimate; the field says why, and the planned total is the rider's own.
horse: { labelKey: 'tours.horse.time', shortKey: 'tours.horse.time', infoLabelKey: 'tours.horse.timeInfoLabel', infoKey: 'tours.horse.timeInfo' },
} as const
/** Which ways a point is out of reach of: paths for hikes and city walks, ways for bikes, runnable ways. */
/** Which ways a point is out of reach of: paths for hikes, city walks and rides, ways for bikes, runnable ways. */
const UNREACHABLE_WAYS: Record<PlannableTourType, 'hike' | 'bike' | 'run'> = {
hike: 'hike',
walk: 'hike',
kayak: 'hike',
horse: 'hike',
bike: 'bike',
run: 'run',
}
@@ -24,9 +24,10 @@ function TypeTile({ type, active = false }: { type: ImportableTourType; active?:
/**
* What the tour is, as one field that opens the types with what each one
* plans: a hike on footpaths within its limit, a bike tour on its profile, a
* paddle tour on the water. Room for the types still to come without the row
* of buttons it was growing too long for. The planner offers the types it
* plans; the GPX import offers ski as well (SKI-02), a track it only keeps.
* paddle tour on the water, a ride along horse routes. Room for the types
* still to come without the row of buttons it was growing too long for. The
* planner offers the types it plans; the GPX import offers ski as well
* (SKI-02), a track it only keeps.
*/
export function TourTypeSelect<T extends ImportableTourType = PlannableTourType>({
value,
@@ -355,7 +355,8 @@ 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).
* shaping point (P2A-03; never the first or the last). A ride (HOR-01) has
* none: no router plans any of its legs, so there is nothing to switch.
*/
function routeMenuItems(
planner: TourPlannerController,
@@ -364,6 +365,7 @@ function routeMenuItems(
lastIndex: number,
t: Translate
): MenuItems {
if (planner.isHorse) return [];
const hasLeg = index < lastIndex;
const free = point.fixedLeg?.kind === 'free';
const routed = hasLeg && !point.fixedLeg;
@@ -5,6 +5,7 @@ import { useSettingsStore } from '../../../store/settingsStore';
import type { TourFerrataCrossing } from '../../../store/tourFerrataCrossingStore';
import { formatDistance } from '../../../utils/units';
import { FerrataGlyph } from '../../Ferratas/FerrataGlyph';
import { HorseLegRow } from '../horse/HorseLegRow';
import { fs } from '../../shared/DialogShell';
import { Tooltip } from '../../shared/Tooltip';
import { PaddleLegFailureRow, PaddleLegNotes } from '../paddle/PaddleLegParts';
@@ -23,9 +24,10 @@ type WaypointPoint = TourPlannerController['waypoints'][number];
/**
* A leg drawn by hand, as a badge on that leg in the dashed look the map draws
* it in: no router planned it, and the badge says so. Its length is the line
* the user drew, the only measure it has.
* the user drew, the only measure it has. On a ride (HOR-01) it is the manual
* stretch between horse routes, said to be unchecked.
*/
function FreeLegRow({ leg }: { leg: TourFixedLeg }) {
function FreeLegRow({ leg, ride }: { leg: TourFixedLeg; ride: boolean }) {
const { t } = useTranslation();
const unit = useSettingsStore((state) => state.settings.distance_unit);
// Read as plain numbers: this workspace compiles without strict mode, where the schema's tuples are "maybe two".
@@ -33,11 +35,11 @@ function FreeLegRow({ leg }: { leg: TourFixedLeg }) {
const distance = formatDistance(lineLengthM(line) / 1000, unit ?? 'metric');
return (
<li data-testid="tour-planner-free-leg" className="flex min-w-0 py-0.5 ps-[34px]">
<Tooltip label={t('tours.planner.freeLegInfo')}>
<Tooltip label={t(ride ? 'tours.horse.leg.manualInfo' : 'tours.planner.freeLegInfo')}>
<span className="flex h-[26px] w-full min-w-0 items-center gap-1.5 rounded-full border border-dashed border-edge bg-surface-card pe-1 ps-2">
<Spline size={13} strokeWidth={2} className="flex-none text-content-muted" aria-hidden="true" />
<span className="min-w-0 flex-1 truncate font-semibold text-content" style={fs(11.5, 'body')}>
{t('tours.planner.freeLegBadge')}
{t(ride ? 'tours.horse.leg.manual' : 'tours.planner.freeLegBadge')}
</span>
<span
className="flex-none rounded-full bg-surface-secondary px-1.5 font-geist tabular-nums leading-[18px] text-content-secondary"
@@ -175,8 +177,9 @@ function LegFailure({
/**
* 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.
* crosses, a line drawn by hand, a ride's horse route section (HOR-01), 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.
*/
export function WaypointLegRows({
planner,
@@ -205,7 +208,8 @@ export function WaypointLegRows({
{crossings.map((crossing) => (
<FerrataLegRow key={`${crossing.id}-${crossing.fromM}`} crossing={crossing} />
))}
{point.fixedLeg?.kind === 'free' && <FreeLegRow leg={point.fixedLeg} />}
{point.fixedLeg?.kind === 'free' && <FreeLegRow leg={point.fixedLeg} ride={planner.isHorse} />}
{point.fixedLeg?.kind === 'horse_route' && <HorseLegRow leg={point.fixedLeg} />}
{routedLegs && <PaddleLegNotes leg={routedLegs.legs[index]} />}
{failure && (
<LegFailure
@@ -93,9 +93,11 @@ function runMinutes({ runPaceSecondsPerKm: pace, routeAnalysis }: TourPlannerFac
* pace, a bike tour by the router, which rides the profile at its speed and
* weighs the climbs, a hike by the signposts' rule over distance, climb and
* descent once the route has its heights, and by the router's own time before that.
* A ride (HOR-01) has none: its pace is the horse's and the rider's, so nothing is made up.
*/
function movingMinutes(input: TourPlannerFactsInput, routerMinutes: number | null): number | null {
const { paddleEstimate, routeAnalysis } = input;
if (input.tourType === 'horse') return null;
if (paddleEstimate) return paddleEstimate.waterMinutes === null ? null : paddleEstimate.estimateMinutes;
if (input.tourType === 'run') return runMinutes(input);
// A bike tour is timed by the router for its profile, a city walk by the router on foot.
@@ -192,9 +194,13 @@ export function tourPlannerFacts(input: TourPlannerFactsInput) {
automaticPlannedTotalMinutes > MAX_PLANNED_TOUR_DURATION_MINUTES,
// A city walk's stops are its stays: it saves no breaks, so a cafe never counts as a stay and a break at once.
savedBreakAdditionalMinutes: input.tourType === 'walk' ? null : breakAdditionalMinutes,
// The router's own time stands in for a hike without heights; a paddle tour has only its speed, a run its pace.
// The router's own time stands in for a hike without heights; a paddle tour has only its speed, a run its pace, a ride none.
savedDurationSeconds:
walkingDurationMinutes === null ? (isPaddle || isRun ? null : durationSeconds) : walkingDurationMinutes * 60,
walkingDurationMinutes === null
? isPaddle || isRun || input.tourType === 'horse'
? null
: durationSeconds
: walkingDurationMinutes * 60,
typeFields: typeFieldsOf(input),
};
}
@@ -7,6 +7,7 @@ import type {
TourWaypoint,
TourWaypointRole,
} from '@trek/shared';
import { rideLegs, withoutHorseRoutes } from '../horse/horseLegs';
import type { AutoBase } from './paddleRouting';
import { keepJoinedFixedLegs } from './tourFixedLegs';
import { alignFreeLegs } from './tourRouteActions';
@@ -100,7 +101,6 @@ export function unlinkedPoint<T extends TourPlannerWaypoint>(point: T): T {
return free as T;
}
/** Roles from the order; free legs follow their points, and a paddle tour keeps its portages and locks. */
/** BIK-01: a bike tour rides no via ferrata; a leg that followed one is planned by the router again. */
export function ridablePoints(points: TourPlannerWaypoint[]): TourPlannerWaypoint[] {
return points.some((point) => point.fixedLeg?.kind === 'ferrata')
@@ -108,8 +108,18 @@ export function ridablePoints(points: TourPlannerWaypoint[]): TourPlannerWaypoin
: points;
}
export function normalizePlannerWaypoints(points: TourPlannerWaypoint[], paddle = false): TourPlannerWaypoint[] {
return keepJoinedFixedLegs(alignFreeLegs(points, paddle)).map((point, index) => ({
/**
* Roles from the order; free legs follow their points, and a paddle tour keeps
* its portages and locks. A ride (HOR-01) has every leg on a horse route or
* drawn by hand; any other type gives a horse route section back to the router.
*/
export function normalizePlannerWaypoints(
points: TourPlannerWaypoint[],
tourType: PlannableTourType = 'hike'
): TourPlannerWaypoint[] {
const joined = keepJoinedFixedLegs(alignFreeLegs(points, tourType === 'kayak'));
const typed = tourType === 'horse' ? rideLegs(joined) : withoutHorseRoutes(joined);
return typed.map((point, index) => ({
...point,
role: index === 0 ? 'start' : index === points.length - 1 ? 'end' : 'via',
}));
@@ -117,7 +127,10 @@ export function normalizePlannerWaypoints(points: TourPlannerWaypoint[], paddle
function fixedLegKey(leg: TourFixedLeg | null | undefined): string {
if (!leg) return '';
return leg.kind === 'ferrata' ? `:${leg.ref}` : `:${leg.kind}:${leg.geometry.length}`;
if (leg.kind === 'ferrata') return `:${leg.ref}`;
// A section taken the other way round has the same ref and length: its first point tells them apart.
if (leg.kind === 'horse_route') return `:${leg.ref}:${leg.geometry.length}:${leg.geometry[0]?.join(',')}`;
return `:${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. */
@@ -1,4 +1,4 @@
import { isClosedLoop, type PaddleLock, type TourFixedLeg } from '@trek/shared';
import { isClosedLoop, turnedSignposted, type PaddleLock, type TourFixedLeg } from '@trek/shared';
/**
* The route tools of the tour planner as plain list operations: reversing the
@@ -67,12 +67,20 @@ export function closeLoop<T extends RoutePoint>(points: readonly T[], newId: str
return [...points, { ...start, id: newId } as T];
}
/** A fixed leg run the other way: its line turned round, and a horse route section's signposting with it. */
function turnedLeg(leg: TourFixedLeg): TourFixedLeg {
const geometry = [...leg.geometry].reverse();
if (leg.kind !== 'horse_route') return { ...leg, geometry };
return { ...leg, geometry, signposted: turnedSignposted(leg.signposted) };
}
/**
* The same tour the other way round: the last point starts it, the stops run
* backwards, and a fixed leg (a via ferrata, a hand-drawn stretch) stays on the
* stretch it covered, its line turned round with it. A loop stays a loop from
* the same spot, and its start stays the station there: the way back is no
* station, so the start's key, name and stay stay first (CW-02, CW-03).
* backwards, and a fixed leg (a via ferrata, a hand-drawn stretch, a section of
* a horse route) stays on the stretch it covered, its line turned round with
* it. A loop stays a loop from the same spot, and its start stays the station
* there: the way back is no station, so the start's key, name and stay stay
* first (CW-02, CW-03).
*/
export function reverseRoute<T extends RoutePoint>(points: readonly T[]): T[] {
const reversed = points.map((_, index) => {
@@ -82,7 +90,7 @@ export function reverseRoute<T extends RoutePoint>(points: readonly T[]): T[] {
const { fixedLeg: _old, ...rest } = point;
const leg = before?.fixedLeg;
if (!leg || index === points.length - 1) return rest as T;
return { ...rest, fixedLeg: { ...leg, geometry: [...leg.geometry].reverse() } } as T;
return { ...rest, fixedLeg: turnedLeg(leg) } as T;
});
if (!isClosedLoop(points)) return reversed;
const start = stationSplit(reversed[0]);
@@ -252,14 +260,15 @@ export function setWaypointLock<T extends RoutePoint>(points: readonly T[], id:
/**
* 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.
* tour: on the water). A via ferrata, a portage and a horse route section 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' || isPortage(point.fixedLeg)) return [...points];
const kind = point?.fixedLeg?.kind;
if (!point || !next || kind === 'ferrata' || kind === 'horse_route' || isPortage(point.fixedLeg)) return [...points];
const copy = [...points];
if (point.fixedLeg?.kind === 'free') {
const { fixedLeg: _dropped, ...rest } = point;
@@ -23,7 +23,8 @@ export interface TourRouteResult {
/** The same line cut where it changes between routed and hand-drawn, for the map to tell them apart. */
parts: TourRoutePart[]
distanceMeters: number
durationSeconds: number
/** Null where no time is worked out at all: a ride (HOR-01). */
durationSeconds: number | null
}
/**
@@ -167,6 +168,28 @@ export async function routeBikeTour(
return routeOnLand(waypoints, 'cycling', BIKE_COSTING[profile], signal)
}
/**
* HOR-01: a ride, put together from its legs as they are: a section of a horse
* route keeps its own line, a leg drawn by hand is sampled along its length so
* its heights follow the ground. No router is asked, nothing between the legs
* is filled in, and no riding time is worked out. Null while a leg has no line
* of its own, which a ride never keeps.
*/
export function rideTour(waypoints: LandWaypoint[]): TourRouteResult | null {
const lines: TourRoutePart[] = []
for (const point of waypoints.slice(0, -1)) {
const leg = point.fixedLeg
if (!leg) return null
const drawn = leg.geometry.map(([lat, lng]): [number, number] => [lat, lng])
const section = leg.kind === 'horse_route'
lines.push({ coordinates: section ? drawn : densifyLine(drawn), free: !section })
}
if (lines.length === 0) return null
const coordinates = lines.flatMap((line, index) => (index === 0 ? line.coordinates : line.coordinates.slice(1)))
const distanceMeters = lines.reduce((sum, line) => sum + lineLengthM(line.coordinates), 0)
return { coordinates, parts: mergeParts(lines), distanceMeters, durationSeconds: null }
}
async function routeOnLand(
waypoints: LandWaypoint[],
mode: 'walking' | 'cycling',
@@ -201,6 +224,8 @@ async function routeOnLand(
run.push(waypoints[i + 1])
continue
}
// A section of a horse route is a ride's (HOR-01), which no router plans and no clock times.
if (leg.kind === 'horse_route') return null
if (!(await routeRun(run, runStart))) return unreachable
const drawn = leg.geometry.map(([lat, lng]): [number, number] => [lat, lng])
// A hand-drawn leg is sampled along its length, so its heights follow the ground between its ends.
@@ -6,10 +6,13 @@ 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.
* while a click on the line picks a spot for something else, and on a ride
* (HOR-01): no router shapes it, and a point set into a horse route section
* would cut the section off its line.
*/
export function useShapingClick(
planner: Pick<TourPlannerController, 'waypoints' | 'route' | 'insertShapingPoint' | 'setSelectedWaypointId'>,
planner: Pick<TourPlannerController, 'waypoints' | 'route' | 'insertShapingPoint' | 'setSelectedWaypointId'> &
Partial<Pick<TourPlannerController, 'isHorse'>>,
{ editable, picking }: { editable: boolean; picking: boolean }
): ((lat: number, lng: number) => void) | undefined {
const { waypoints, route, insertShapingPoint, setSelectedWaypointId } = planner;
@@ -22,5 +25,5 @@ export function useShapingClick(
},
[insertShapingPoint, route, setSelectedWaypointId, waypoints]
);
return editable && !picking ? shapeAt : undefined;
return editable && !picking && !planner.isHorse ? shapeAt : undefined;
}
@@ -14,7 +14,7 @@ export function useTourDraftStorage(tripId: number | string) {
try {
const parsed = JSON.parse(localStorage.getItem(storageKey) || 'null') as unknown;
return validDraft(parsed)
? { ...parsed, waypoints: normalizePlannerWaypoints(parsed.waypoints, parsed.tourType === 'kayak') }
? { ...parsed, waypoints: normalizePlannerWaypoints(parsed.waypoints, parsed.tourType) }
: null;
} catch {
return null;
@@ -0,0 +1,179 @@
import { act, renderHook } from '@testing-library/react';
import type { HorseRoute } from '@trek/shared';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const { routeWalkingTour, routeBikeTour, enrichTourElevations, createTour, detailTour, updateTour } = vi.hoisted(
() => ({
routeWalkingTour: vi.fn(),
routeBikeTour: vi.fn(),
enrichTourElevations: vi.fn(),
createTour: vi.fn(),
detailTour: vi.fn(),
updateTour: vi.fn(),
})
);
// The ride is put together by the real rideTour; only a router asked by mistake and the heights are stand-ins.
vi.mock('./tourRouting', async (importOriginal) => ({
...(await importOriginal<typeof import('./tourRouting')>()),
routeWalkingTour,
routeBikeTour,
enrichTourElevations,
}));
vi.mock('../../../repo/tourRepo', () => ({ tourRepo: { create: createTour, detail: detailTour, update: updateTour } }));
vi.mock('../useTourPermissions', () => ({ useTourPermissions: () => ({ canEdit: true, canAssign: true }) }));
import { sectionLeg, withSectionAppended } from '../horse/horseSection';
import { useTourPlanner } from './useTourPlanner';
// FE-TOUR-HORSE-001 to FE-TOUR-HORSE-005
const route: HorseRoute = {
id: 'relation/42',
name: 'Reitweg Isartal',
ref: 'R1',
osmUrl: 'https://www.openstreetmap.org/relation/42',
continues: false,
sections: [
{
number: 1,
geometry: [
[48, 11],
[48.005, 11.005],
[48.01, 11.01],
],
length_m: 1360,
access: [{ value: 'designated', length_m: 1360 }],
signposted: 'with',
},
],
};
const section = sectionLeg(route, route.sections[0], false);
const heights = (line: [number, number][]) =>
line.map(([lat, lng], index): [number, number, number] => [lat, lng, 500 + index]);
async function settle() {
await act(async () => {
await vi.advanceTimersByTimeAsync(450);
});
}
function rideWithSection(tripId: number) {
const hook = renderHook(() => useTourPlanner({ tripId }));
let next = 0;
const newId = () => `section-point-${(next += 1)}`;
act(() => hook.result.current.setTourType('horse'));
act(() => hook.result.current.editWaypoints((points) => withSectionAppended(points, section, newId)));
return hook;
}
describe('useTourPlanner, rides on horseback (HOR-01)', () => {
beforeEach(() => {
vi.useFakeTimers();
localStorage.clear();
routeWalkingTour.mockReset();
routeBikeTour.mockReset();
enrichTourElevations.mockReset().mockImplementation(async (line: [number, number][]) => heights(line));
createTour.mockReset();
detailTour.mockReset();
updateTour.mockReset();
});
afterEach(() => vi.useRealTimers());
it('FE-TOUR-HORSE-001: a ride is its sections and manual legs as drawn, with heights and no riding time', async () => {
const { result } = rideWithSection(61);
act(() => result.current.addWaypoint(48.02, 11.02));
expect(result.current.isHorse).toBe(true);
expect(result.current.waypoints.map((point) => point.fixedLeg?.kind ?? null)).toEqual([
'horse_route',
'free',
null,
]);
await settle();
expect(routeWalkingTour).not.toHaveBeenCalled();
expect(result.current.status).toBe('ready');
expect(result.current.routeParts?.map((part) => part.free)).toEqual([false, true]);
expect(result.current.route?.[0]).toEqual([48, 11]);
expect(result.current.durationSeconds).toBeNull();
expect(result.current.walkingDurationMinutes).toBeNull();
expect(result.current.plannedTotalMinutes).toBeNull();
});
it('FE-TOUR-HORSE-002: saves the ride with the origin of each leg and no riding time worked out', async () => {
createTour.mockResolvedValue({ tour: { place_id: 9, tour_type: 'horse', revision: 1 }, waypoints: [] });
const { result } = rideWithSection(62);
act(() => result.current.addWaypoint(48.02, 11.02));
act(() => result.current.setName('Isar ride'));
await settle();
expect(result.current.canSave).toBe(true);
await act(async () => {
await result.current.save();
});
const body = createTour.mock.calls[0]?.[1];
expect(body).toMatchObject({
tour_type: 'horse',
duration_seconds: null,
max_hiking_difficulty: null,
bike_profile: null,
});
expect(body.waypoints.map((point: { fixed_leg?: { kind: string } }) => point.fixed_leg?.kind ?? null)).toEqual([
'horse_route',
'free',
null,
]);
expect(body.waypoints[0].fixed_leg).toMatchObject({ ref: 'relation/42', signposted: 'with' });
});
it('FE-TOUR-HORSE-003: a routed leg turns manual on a ride, a section goes back to the router on a hike', () => {
const { result } = renderHook(() => useTourPlanner({ tripId: 63 }));
act(() => {
result.current.addWaypoint(47.99, 10.99);
result.current.addWaypoint(48, 11);
});
expect(result.current.waypoints[0].fixedLeg).toBeUndefined();
act(() => result.current.setTourType('horse'));
expect(result.current.waypoints[0].fixedLeg?.kind).toBe('free');
// The hike ended where the section starts: the section goes on from that point.
act(() => result.current.editWaypoints((points) => withSectionAppended(points, section, () => 'section-end')));
expect(result.current.waypoints.map((point) => point.fixedLeg?.kind ?? null)).toEqual([
'free',
'horse_route',
null,
]);
act(() => result.current.setTourType('hike'));
expect(result.current.waypoints[1].fixedLeg ?? null).toBeNull();
act(() => result.current.undo());
expect(result.current.waypoints[1].fixedLeg?.kind).toBe('horse_route');
});
it('FE-TOUR-HORSE-004: a point at a section stays put, one between manual legs moves', () => {
const { result } = rideWithSection(64);
act(() => result.current.addWaypoint(48.02, 11.02));
const [start, end, last] = result.current.waypoints;
let moved = true;
act(() => {
moved = result.current.setWaypointPosition(end.id, 48.011, 11.011);
});
expect(moved).toBe(false);
expect(result.current.waypoints[1]).toMatchObject({ lat: 48.01, lng: 11.01 });
expect(result.current.setWaypointPosition(start.id, 47.9, 11)).toBe(false);
act(() => {
moved = result.current.setWaypointPosition(last.id, 48.03, 11.03);
});
expect(moved).toBe(true);
expect(result.current.waypoints[1].fixedLeg?.geometry).toEqual([
[48.01, 11.01],
[48.03, 11.03],
]);
});
it('FE-TOUR-HORSE-005: turning the ride round turns its section and its signposting round with it', () => {
const { result } = rideWithSection(65);
act(() => result.current.reverse());
const leg = result.current.waypoints[0].fixedLeg;
expect(leg?.kind).toBe('horse_route');
expect(leg?.geometry[0]).toEqual([48.01, 11.01]);
expect(leg?.kind === 'horse_route' ? leg.signposted : null).toBe('against');
});
});
@@ -5,6 +5,7 @@ import { tourRepo } from '../../../repo/tourRepo'
import { randomId } from '../../../utils/randomId'
import { analyzeRouteGeometry, type RouteProfileFocus } from '../../../utils/routeGeometry'
import { closeLoop, reverseRoute, toggleFreeLeg, withPointAppended } from './tourRouteActions'
import { holdsHorseSection } from '../horse/horseLegs'
import { walkTimes } from './stationModel'
import { hasCompleteElevation, useTourRoute } from './useTourRoute'
import { normalizePlannerWaypoints, plannerWaypointsOf, ridablePoints, routeInputsKey, sameWaypointSnapshot, savedWaypointsOf, unlinkedPoint, withSavedKeys, type TourPlannerWaypoint } from './tourPlannerWaypoints'
@@ -255,7 +256,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
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)
const next = normalizePlannerWaypoints(paddle ? adoptChangedPoints(current, changed) : changed, tourTypeRef.current)
if (sameWaypointSnapshot(current, next)) return
recordStep(snapshot())
waypointsRef.current = next
@@ -281,7 +282,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
if (changed === waypointsRef.current) return
interruptRouting()
draftRevisionRef.current += 1
waypointsRef.current = normalizePlannerWaypoints(changed, tourTypeRef.current === 'kayak')
waypointsRef.current = normalizePlannerWaypoints(changed, tourTypeRef.current)
setWaypoints(waypointsRef.current)
setHasUnsavedChanges(true)
setStatus('dirty')
@@ -355,6 +356,8 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
if (!current) return false
if (current.lat === lat && current.lng === lng) return true
const points = waypointsRef.current
// HOR-01: a ride's point at a horse route section stays where the route has it.
if (tourTypeRef.current === 'horse' && holdsHorseSection(points, id)) return false
// In a loop the start and the way back are one spot: moving either moves both.
const loopEnds = isClosedLoop(points) && (id === points[0].id || id === points[points.length - 1].id)
? new Set([points[0].id, points[points.length - 1].id])
@@ -492,9 +495,10 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
/**
* PAD-01, BIK-01, RUN-01: the type, as one step of the history with the
* route, since a paddle tour draws every leg by hand and neither a bike tour
* nor a run takes a via ferrata. Nothing is put on a day by the choice itself.
* PAD-01, BIK-01, RUN-01, HOR-01: the type, as one step of the history with
* the route, since a paddle tour draws every leg by hand, neither a bike tour
* nor a run takes a via ferrata and a ride takes every leg from a horse route
* or by hand. Nothing is put on a day by the choice itself.
*/
const setTourType = useCallback((value: PlannableTourType) => {
if (!editPermissionRef.current || saveInFlightRef.current || value === tourTypeRef.current) return
@@ -505,7 +509,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
tourTypeRef.current = value
setTourTypeState(value)
const noFerrata = value === 'bike' || value === 'run'
const next = normalizePlannerWaypoints(noFerrata ? ridablePoints(waypointsRef.current) : waypointsRef.current, value === 'kayak')
const next = normalizePlannerWaypoints(noFerrata ? ridablePoints(waypointsRef.current) : waypointsRef.current, value)
waypointsRef.current = next
setWaypoints(next)
setHasUnsavedChanges(true)
@@ -632,7 +636,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
draft.points.map(({ lat, lng, name }) => ({
id: randomId(), lat, lng, role: 'via' as const, ...(name ? { name } : {}),
})),
type === 'kayak',
type,
)
setDraftSource(draft.source ?? null)
tourTypeRef.current = type
@@ -725,7 +729,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
interruptRouting()
const opened = openedTourFields(result.tour)
const nextWaypoints = normalizePlannerWaypoints(plannerWaypointsOf(result.waypoints, randomId), opened.tourType === 'kayak')
const nextWaypoints = normalizePlannerWaypoints(plannerWaypointsOf(result.waypoints, randomId), opened.tourType)
forgetDraft()
contextGenerationRef.current += 1
draftRevisionRef.current += 1
@@ -916,7 +920,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
return {
tripId, canEdit, canAssign,
name, setName, maxHikingDifficulty, setMaxHikingDifficulty, hikingPreferences, setHikingPreferences,
bikeProfile, setBikeProfile, isBike: tourType === 'bike', winterActivity, setWinterActivity, winterActivityChoice,
bikeProfile, setBikeProfile, isBike: tourType === 'bike', isHorse: tourType === 'horse', winterActivity, setWinterActivity, winterActivityChoice,
runProfile, setRunProfile, isRun: tourType === 'run', runPace, runPaceMissing, runPaceInvalid,
tourType, setTourType, isPaddle, paddle, paddleSpeedInvalid, paddleIncomplete,
description, setDescription, website, setWebsite, websiteInvalid,
@@ -28,6 +28,7 @@ import {
import { isTourRoute, type TourRouteUnreachable } from './tourRouteOutcome';
import {
enrichTourElevations,
rideTour,
routeBikeTour,
routeCityWalk,
routeRun,
@@ -111,7 +112,7 @@ async function routePaddle({ inputs, plannedKey, runKey, signal, stale, setPlann
const profile = { boat: paddleBoat ?? 'kayak', lakeStyle: paddleLakeStyle } as const;
const step = await planPaddleStep(waypoints, tripId, profile, signal, randomId);
if (stale()) return;
if ('points' in step) return inputs.patchWaypoints(normalizePlannerWaypoints(step.points, true));
if ('points' in step) return inputs.patchWaypoints(normalizePlannerWaypoints(step.points, 'kayak'));
const planned = step.route;
setPlanned({
route: planned.coordinates,
@@ -130,17 +131,19 @@ async function routePaddle({ inputs, plannedKey, runKey, signal, stale, setPlann
/**
* A route on land for the type of the draft: a bike tour and a run for their
* profile, a city walk, a hike within its limit.
* profile, a city walk, a hike within its limit, and a ride (HOR-01) put
* together from its sections, never routed.
*/
function routeLand(inputs: RouteRun['inputs'], signal: AbortSignal) {
async function routeLand(inputs: RouteRun['inputs'], signal: AbortSignal) {
const { waypoints, tourType, bikeProfile, runProfile, maxHikingDifficulty, hikingPreferences } = inputs;
if (tourType === 'bike') return routeBikeTour(waypoints, bikeProfile, signal);
if (tourType === 'run') return routeRun(waypoints, runProfile, signal);
if (tourType === 'walk') return routeCityWalk(waypoints, signal);
return routeWalkingTour(waypoints, signal, maxHikingDifficulty, hikingPreferences);
if (tourType === 'horse') return rideTour(waypoints);
if (tourType === 'bike') return await routeBikeTour(waypoints, bikeProfile, signal);
if (tourType === 'run') return await routeRun(waypoints, runProfile, signal);
if (tourType === 'walk') return await routeCityWalk(waypoints, signal);
return await routeWalkingTour(waypoints, signal, maxHikingDifficulty, hikingPreferences);
}
// A hike, a run or a bike tour on land, then the heights along it.
// A hike, a run, a city walk, a bike tour or a ride on land, then the heights along it.
async function routeOnLand({ inputs, plannedKey, runKey, signal, stale, setPlanned, setUnreachable }: RouteRun) {
const { setStatus, setError } = inputs;
setStatus('routing');
@@ -181,8 +184,10 @@ async function routeOnLand({ inputs, plannedKey, runKey, signal, stale, setPlann
* The route of the planner's draft, planned again a moment after its points
* or its choices change: a hike on foot within its limit, a bike tour and a
* run for their profile (BIK-01, RUN-01), a paddle tour on the water by the
* server's router. A tour on land then gets its heights; a later change makes an answer
* still on its way stale, and a failure keeps the last route that was planned.
* server's router, a ride put together from its horse route sections and
* manual legs (HOR-01). Every tour on land then gets its heights; a later
* change makes an answer still on its way stale, and a failure keeps the last
* route that was planned.
*/
export function useTourRoute(inputs: TourRouteInputs) {
const {