mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 00:20:07 +00:00
feat(tours): route choices for a hike, each checked against the router (MF-08)
A hike can ask the router for more than its difficulty limit: avoid steps, avoid ferries, prefer footpaths, shorter over faster. They sit under the limit in the planner's details as switches, each with what it really does, and the info dot says they weigh the way and give way where there is no other, and that none grades a path. Switching one plans the route again as one step of the history, and the choice is kept in the draft. Only preferences the public Valhalla was seen to honour are offered, with the measured cases beside hikingCostingOptions: step_penalty took Würzburg to the Festung from four flights to one, use_ferry 0 sent Kiel round the Förde and Hamburg through the Elbe tunnel, walkway_factor moved Garmisch to the Partnachklamm onto the paths, shortest cut the way to the Eckbauer. use_hills and use_tracks showed no effect on foot and are left out, as are marked, paved and rough ways, for which the router has no option. tours.hiking_preferences (migration 045000) holds them as JSON, NULL for none, so no tour saved before routes differently. Only a hike keeps them; a paddle tour naming one is refused. A copy carries them, and list_tours and get_tour_plan read them. The trip copy's waypoint links now follow the copied places inside TourWaypointsRepository.insertForPlace.
This commit is contained in:
@@ -191,7 +191,7 @@ export async function valhallaRun(
|
||||
profile: 'driving' | 'walking' | 'cycling',
|
||||
avoid: readonly AvoidClass[],
|
||||
signal?: AbortSignal,
|
||||
costingOptions: Readonly<Record<string, number>> = {},
|
||||
costingOptions: Readonly<Record<string, number | boolean>> = {},
|
||||
): Promise<ValhallaRun | null> {
|
||||
const base = valhallaBase()
|
||||
if (!base || notValhalla.has(base) || waypoints.length < 2) return null
|
||||
@@ -315,14 +315,14 @@ function routeBody(
|
||||
waypoints: Waypoint[],
|
||||
profile: 'driving' | 'walking' | 'cycling',
|
||||
avoid: readonly AvoidClass[],
|
||||
costingOptions: Readonly<Record<string, number>> = {},
|
||||
costingOptions: Readonly<Record<string, number | boolean>> = {},
|
||||
): Record<string, unknown> {
|
||||
const costing = COSTING[profile]
|
||||
// All of them in one request: the options are independent weightings, so asking to
|
||||
// leave out tolls and ferries together is one question rather than two routes to
|
||||
// reconcile. Measured Hamburg to Copenhagen: tolls, motorways and ferries weighted
|
||||
// away together answered 656.9 km against 339.2 km for the plain route.
|
||||
const options: Record<string, number> = { ...costingOptions }
|
||||
const options: Record<string, number | boolean> = { ...costingOptions }
|
||||
for (const cls of avoid) options[AVOID_OPTION[cls]] = 0
|
||||
return {
|
||||
locations: waypoints.map(w => ({ lat: w.lat, lon: w.lng, radius: SNAP_RADIUS_M })),
|
||||
@@ -366,7 +366,7 @@ async function requestRun(
|
||||
profile: 'driving' | 'walking' | 'cycling',
|
||||
avoid: readonly AvoidClass[],
|
||||
signal?: AbortSignal,
|
||||
costingOptions: Readonly<Record<string, number>> = {},
|
||||
costingOptions: Readonly<Record<string, number | boolean>> = {},
|
||||
): Promise<Omit<ValhallaRun, 'snapped'> | null> {
|
||||
const data = await postRoute(base, routeBody(waypoints, profile, avoid, costingOptions), signal)
|
||||
return data === null ? null : runFrom(data)
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { HIKING_PREFERENCE_KEYS, type HikingPreferenceKey } from '@trek/shared';
|
||||
import { ChartNoAxesColumnIncreasing, Footprints, Ruler, Ship } from 'lucide-react';
|
||||
import type { ComponentType } from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { BOX } from '../../Planner/bookings/bookingParts';
|
||||
import ToggleSwitch from '../../Settings/ToggleSwitch';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import { InfoDot } from '../tourParts';
|
||||
import type { TourPlannerController } from './useTourPlanner';
|
||||
|
||||
const ICON: Record<HikingPreferenceKey, ComponentType<{ size?: number; strokeWidth?: number; className?: string }>> = {
|
||||
avoid_steps: ChartNoAxesColumnIncreasing,
|
||||
avoid_ferries: Ship,
|
||||
prefer_paths: Footprints,
|
||||
shortest: Ruler,
|
||||
};
|
||||
|
||||
/**
|
||||
* MF-08: what a hike asks the router for besides its difficulty limit, as
|
||||
* switches under it. Only preferences the router was seen to honour are here
|
||||
* (hikingCostingOptions says which and how they were checked), each with what
|
||||
* it really does in a line of its own; the info dot says they weigh the way
|
||||
* and give way where there is none other, and that none of them grades a path.
|
||||
* Switching one plans the route again, as one step of the history.
|
||||
*/
|
||||
export function HikingPreferencesField({
|
||||
planner,
|
||||
locked,
|
||||
}: {
|
||||
planner: Pick<TourPlannerController, 'hikingPreferences' | 'setHikingPreferences'>;
|
||||
locked: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const current = planner.hikingPreferences;
|
||||
const toggle = (key: HikingPreferenceKey) => {
|
||||
if (!locked) planner.setHikingPreferences({ ...current, [key]: !current?.[key] });
|
||||
};
|
||||
return (
|
||||
<div className="min-w-0" data-testid="tour-hiking-preferences">
|
||||
<div className="mb-1.5 flex min-h-[18px] items-center gap-1.5">
|
||||
<span className="font-semibold uppercase tracking-[0.06em] text-content-muted" style={fs(10, 'caption')}>
|
||||
{t('tours.preferences.title')}
|
||||
</span>
|
||||
<InfoDot label={t('tours.preferences.infoLabel')} description={t('tours.preferences.info')} />
|
||||
</div>
|
||||
<ul className={`${BOX} m-0 flex list-none flex-col divide-y divide-edge-faint p-0`}>
|
||||
{HIKING_PREFERENCE_KEYS.map((key) => {
|
||||
const Icon = ICON[key];
|
||||
const hintId = `tour-preference-${key}-hint`;
|
||||
return (
|
||||
<li key={key} className="flex items-center gap-2.5 px-3 py-2">
|
||||
<Icon size={14} strokeWidth={2} className="flex-none text-content-faint" />
|
||||
<span className="flex min-w-0 flex-1 flex-col">
|
||||
<span className="font-semibold text-content" style={fs(12.5, 'body')}>
|
||||
{t(`tours.preferences.${key}`)}
|
||||
</span>
|
||||
<span id={hintId} className="leading-snug text-content-faint" style={fs(11, 'body')}>
|
||||
{t(`tours.preferences.${key}Hint`)}
|
||||
</span>
|
||||
</span>
|
||||
<span className={locked ? 'pointer-events-none opacity-50' : undefined}>
|
||||
<ToggleSwitch
|
||||
on={current?.[key] === true}
|
||||
onToggle={() => toggle(key)}
|
||||
label={t(`tours.preferences.${key}`)}
|
||||
describedBy={hintId}
|
||||
/>
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import CustomSelect from '../../shared/CustomSelect';
|
||||
import { INPUT, LABEL } from '../../shared/dialogParts';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import { FoldButton, InfoDot, TourNotice, TourSection } from '../tourParts';
|
||||
import { HikingPreferencesField } from './HikingPreferencesField';
|
||||
import { TOUR_DURATION_INPUT_MAX_LENGTH, formatTourDuration, parseTourDuration } from './tourDurationInput';
|
||||
import type { TourPlannerController } from './useTourPlanner';
|
||||
|
||||
@@ -350,7 +351,10 @@ export function TourDetailsSection({
|
||||
<TourWebsiteField planner={planner} locked={locked} />
|
||||
{/* A paddle tour is not graded on the hiking scale. */}
|
||||
{!planner.isPaddle && (
|
||||
<TourDifficultyField planner={planner} locked={locked} onDifficultyChange={onDifficultyChange} />
|
||||
<>
|
||||
<TourDifficultyField planner={planner} locked={locked} onDifficultyChange={onDifficultyChange} />
|
||||
<HikingPreferencesField planner={planner} locked={locked} />
|
||||
</>
|
||||
)}
|
||||
<TourTimeFields planner={planner} locked={locked} />
|
||||
</>
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { HikingPreferencesField } from './HikingPreferencesField';
|
||||
import { hikingCostingOptions } from './tourRouting';
|
||||
|
||||
describe('hikingCostingOptions (MF-08)', () => {
|
||||
it('asks the router only for what was switched on, in the options it was checked with', () => {
|
||||
expect(hikingCostingOptions(null)).toEqual({});
|
||||
expect(hikingCostingOptions({ avoid_steps: false })).toEqual({});
|
||||
expect(
|
||||
hikingCostingOptions({ avoid_steps: true, avoid_ferries: true, prefer_paths: true, shortest: true })
|
||||
).toEqual({ step_penalty: 600, use_ferry: 0, walkway_factor: 0.5, shortest: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe('HikingPreferencesField (MF-08)', () => {
|
||||
it('shows each checked preference with what it does, and switching one keeps the others', () => {
|
||||
const setHikingPreferences = vi.fn();
|
||||
render(
|
||||
<HikingPreferencesField
|
||||
planner={{ hikingPreferences: { prefer_paths: true }, setHikingPreferences }}
|
||||
locked={false}
|
||||
/>
|
||||
);
|
||||
const steps = screen.getByRole('button', { name: 'tours.preferences.avoid_steps' });
|
||||
expect(steps).toHaveAttribute('aria-pressed', 'false');
|
||||
expect(steps).toHaveAccessibleDescription('tours.preferences.avoid_stepsHint');
|
||||
expect(screen.getByRole('button', { name: 'tours.preferences.prefer_paths' })).toHaveAttribute(
|
||||
'aria-pressed',
|
||||
'true'
|
||||
);
|
||||
fireEvent.click(steps);
|
||||
expect(setHikingPreferences).toHaveBeenCalledWith({ prefer_paths: true, avoid_steps: true });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'tours.preferences.prefer_paths' }));
|
||||
expect(setHikingPreferences).toHaveBeenLastCalledWith({ prefer_paths: false });
|
||||
});
|
||||
|
||||
it('changes nothing while the tour is locked', () => {
|
||||
const setHikingPreferences = vi.fn();
|
||||
render(<HikingPreferencesField planner={{ hikingPreferences: null, setHikingPreferences }} locked />);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'tours.preferences.shortest' }));
|
||||
expect(setHikingPreferences).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,9 @@
|
||||
import {
|
||||
hikingPreferencesSchema,
|
||||
MAX_PLANNED_TOUR_DURATION_MINUTES,
|
||||
paddleLockSchema,
|
||||
plannableTourTypeSchema,
|
||||
type HikingPreferences,
|
||||
type PlannableTourType,
|
||||
type TourMaxHikingDifficulty,
|
||||
} from '@trek/shared';
|
||||
@@ -30,6 +32,8 @@ export interface DraftPayload {
|
||||
paddle?: PaddleFieldValues;
|
||||
/** P2C-03: the revision of the tour the draft edits, as it was loaded. */
|
||||
baseRevision?: number | null;
|
||||
/** MF-08: what the hike asks the router for besides its limit. */
|
||||
hikingPreferences?: HikingPreferences | null;
|
||||
}
|
||||
|
||||
const DRAFT_VERSIONS: ReadonlyArray<DraftPayload['version']> = [1, 2, 3, 4, 5, 6, 7, 8, 9];
|
||||
@@ -80,6 +84,7 @@ export function validDraft(value: unknown): value is DraftPayload {
|
||||
optionalPlaceId(draft.editingPlaceId) &&
|
||||
optionalPlaceId(draft.derivedFromPlaceId) &&
|
||||
optionalPlaceId(draft.baseRevision) &&
|
||||
(draft.hikingPreferences == null || hikingPreferencesSchema.safeParse(draft.hikingPreferences).success) &&
|
||||
optionalDifficulty(draft.maxHikingDifficulty) &&
|
||||
(draft.tourType === undefined || plannableTourTypeSchema.safeParse(draft.tourType).success) &&
|
||||
Array.isArray(draft.waypoints) &&
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
MAX_PLANNED_TOUR_DURATION_MINUTES,
|
||||
tourWebsiteSchema,
|
||||
type HikingPreferences,
|
||||
type PaddleBoatType,
|
||||
type PaddleLakeStyle,
|
||||
type PaddleWaterContext,
|
||||
@@ -14,6 +15,8 @@ import { hikingTimeMinutes } from '../hikingTime';
|
||||
export interface TourPlannerFactsInput {
|
||||
tourType: PlannableTourType;
|
||||
maxHikingDifficulty: TourMaxHikingDifficulty;
|
||||
/** MF-08: what the hike asks the router for besides its limit. */
|
||||
hikingPreferences: HikingPreferences | null;
|
||||
website: string;
|
||||
plannedDurationMinutes: number | null;
|
||||
breakAdditionalMinutes: number | null;
|
||||
@@ -84,6 +87,7 @@ export function tourPlannerFacts(input: TourPlannerFactsInput) {
|
||||
paddle_speed_kmh: speedKmh,
|
||||
portage_speed_kmh: portageSpeedKmh,
|
||||
paddle_lake_style: lakeStyle,
|
||||
hiking_preferences: null,
|
||||
}
|
||||
: {
|
||||
tour_type: input.tourType,
|
||||
@@ -93,6 +97,7 @@ export function tourPlannerFacts(input: TourPlannerFactsInput) {
|
||||
paddle_speed_kmh: null,
|
||||
portage_speed_kmh: null,
|
||||
paddle_lake_style: null,
|
||||
hiking_preferences: input.hikingPreferences,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { useTourDraftStorage } from './useTourDraftStorage';
|
||||
const hike = (overrides: Partial<TourPlannerFactsInput> = {}): TourPlannerFactsInput => ({
|
||||
tourType: 'hike',
|
||||
maxHikingDifficulty: 3,
|
||||
hikingPreferences: null,
|
||||
website: '',
|
||||
plannedDurationMinutes: null,
|
||||
breakAdditionalMinutes: null,
|
||||
|
||||
@@ -35,6 +35,16 @@ describe('routeWalkingTour', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('TOUR-ROUTING-030: asks the router for the preferences of a hike beside its limit (MF-08)', async () => {
|
||||
await routeWalkingTour(waypoints, undefined, 3, { avoid_steps: true, shortest: true })
|
||||
|
||||
expect(valhallaRun).toHaveBeenCalledWith(waypoints, 'walking', [], undefined, {
|
||||
max_hiking_difficulty: 3,
|
||||
step_penalty: 600,
|
||||
shortest: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('TOUR-ROUTING-020: takes a fixed leg as its own line and routes only the runs around it', async () => {
|
||||
const leg = {
|
||||
kind: 'ferrata' as const,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { TourFixedLeg } from '@trek/shared'
|
||||
import type { HikingPreferences, TourFixedLeg } from '@trek/shared'
|
||||
import type { Waypoint } from '../../../types'
|
||||
import { valhallaBase, valhallaRun, valhallaTurn } from '../../Map/valhallaRoute'
|
||||
import { densifyLine, lineLengthM } from './tourFixedLegs'
|
||||
@@ -34,6 +34,31 @@ const TOURS_MAX_HIKING_DIFFICULTY = 2
|
||||
/** How fast a fixed leg is reckoned until the heights are in: a via ferrata climbs slowly, a free leg is walked. */
|
||||
const FIXED_LEG_KM_PER_HOUR = { ferrata: 1.5, free: 4, portage: 2 } as const
|
||||
|
||||
/**
|
||||
* MF-08: a hike's preferences as Valhalla's pedestrian costing options. Each
|
||||
* one was checked against the public instance before it was offered, and is a
|
||||
* weighting that gives way where there is no other path:
|
||||
* - avoid_steps, `step_penalty` 600 s: Würzburg Altstadt to the Festung went
|
||||
* from four flights of steps over 1.49 km to one over 2.67 km.
|
||||
* - avoid_ferries, `use_ferry` 0: Kiel Reventlou to Dietrichsdorf went from the
|
||||
* Förde ferry (2.7 km) round the fjord on land (8.3 km); Hamburg
|
||||
* Landungsbrücken to Steinwerder through the old Elbe tunnel instead of the ferry.
|
||||
* - prefer_paths, `walkway_factor` 0.5: footpaths of their own weigh half of a
|
||||
* road, which moved Garmisch station to the Partnachklamm onto the paths.
|
||||
* - shortest, `shortest`: the way by its length, not its time (Garmisch to the
|
||||
* Eckbauer 5.09 km to 4.96 km); it still honours the penalties above.
|
||||
* Left out because the router showed no effect on foot: `use_hills` and
|
||||
* `use_tracks`; nor has it any option for marked, paved or rough ways.
|
||||
*/
|
||||
export function hikingCostingOptions(preferences: HikingPreferences | null | undefined): Record<string, number | boolean> {
|
||||
return {
|
||||
...(preferences?.avoid_steps ? { step_penalty: 600 } : {}),
|
||||
...(preferences?.avoid_ferries ? { use_ferry: 0 } : {}),
|
||||
...(preferences?.prefer_paths ? { walkway_factor: 0.5 } : {}),
|
||||
...(preferences?.shortest ? { shortest: true } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tours deliberately bypasses the OSRM-first RouteCalculator. A waypoint whose
|
||||
* leg is fixed (a via ferrata on the tour) hands its own line over for that
|
||||
@@ -43,6 +68,7 @@ export async function routeWalkingTour(
|
||||
waypoints: Array<Pick<Waypoint, 'lat' | 'lng'> & { fixedLeg?: TourFixedLeg | null }>,
|
||||
signal?: AbortSignal,
|
||||
maxHikingDifficulty = TOURS_MAX_HIKING_DIFFICULTY,
|
||||
preferences: HikingPreferences | null = null,
|
||||
): Promise<TourRouteResult | null> {
|
||||
const lines: TourRoutePart[] = []
|
||||
let distanceMeters = 0
|
||||
@@ -51,6 +77,7 @@ export async function routeWalkingTour(
|
||||
if (run.length < 2) return true
|
||||
const routed = await valhallaRun(run.map(({ lat, lng }) => ({ lat, lng })), 'walking', [], signal, {
|
||||
max_hiking_difficulty: maxHikingDifficulty,
|
||||
...hikingCostingOptions(preferences),
|
||||
})
|
||||
if (!routed) return false
|
||||
lines.push({ coordinates: routed.total.coordinates, free: false })
|
||||
|
||||
@@ -1018,7 +1018,7 @@ describe('useTourPlanner', () => {
|
||||
expect(result.current.waypoints.map(point => point.role)).toEqual(['start', 'end'])
|
||||
expect(result.current.hasUnsavedChanges).toBe(false)
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(450) })
|
||||
expect(routeWalkingTour).toHaveBeenCalledWith(result.current.waypoints, expect.any(AbortSignal), 2)
|
||||
expect(routeWalkingTour).toHaveBeenCalledWith(result.current.waypoints, expect.any(AbortSignal), 2, null)
|
||||
expect(result.current.status).toBe('ready')
|
||||
expect(result.current.route).toEqual(routed.coordinates)
|
||||
|
||||
@@ -1453,6 +1453,28 @@ describe('useTourPlanner', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-040: hiking preferences are a step of the history, kept in the draft and sent with the route (MF-08)', async () => {
|
||||
const { result } = renderHook(() => useTourPlanner({ tripId: 41 }))
|
||||
act(() => {
|
||||
result.current.addWaypoint(48, 11)
|
||||
result.current.addWaypoint(48.01, 11.02)
|
||||
})
|
||||
act(() => result.current.setHikingPreferences({ avoid_steps: true, shortest: false }))
|
||||
expect(result.current.hikingPreferences).toEqual({ avoid_steps: true })
|
||||
expect(JSON.parse(localStorage.getItem('tour-draft-41') || 'null')).toMatchObject({ hikingPreferences: { avoid_steps: true } })
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(450) })
|
||||
expect(routeWalkingTour).toHaveBeenLastCalledWith(expect.any(Array), expect.any(AbortSignal), 2, { avoid_steps: true })
|
||||
|
||||
// The same choice again is no step; an undo takes the preferences back with it.
|
||||
act(() => result.current.setHikingPreferences({ avoid_steps: true }))
|
||||
act(() => result.current.undo())
|
||||
expect(result.current.hikingPreferences).toBeNull()
|
||||
act(() => result.current.redo())
|
||||
expect(result.current.hikingPreferences).toEqual({ avoid_steps: true })
|
||||
act(() => result.current.startNewTour(true))
|
||||
expect(result.current.hikingPreferences).toBeNull()
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-010: starts a clean T2 draft and clears route, selection, history, and stored draft', async () => {
|
||||
const { result } = renderHook(() => useTourPlanner({ tripId: 16 }))
|
||||
act(() => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { paddleSpeedKmhSchema, tourWebsiteSchema, type PlannableTourType, type TourCreateResponse, type TourFixedLeg, type TourListItem, type TourMaxHikingDifficulty } from '@trek/shared'
|
||||
import { hikingPreferencesOf, paddleSpeedKmhSchema, tourWebsiteSchema, type HikingPreferences, type PlannableTourType, type TourCreateResponse, type TourFixedLeg, type TourListItem, type TourMaxHikingDifficulty } from '@trek/shared'
|
||||
import { paddleRouteRepo } from '../../../repo/paddleRouteRepo'
|
||||
import { tourRepo } from '../../../repo/tourRepo'
|
||||
import { randomId } from '../../../utils/randomId'
|
||||
@@ -52,7 +52,7 @@ export type TourPlannerStatus =
|
||||
| 'saved'
|
||||
|
||||
/** One step of the history: the route, and what the route depends on. */
|
||||
interface HistoryEntry { waypoints: TourPlannerWaypoint[]; difficulty: TourMaxHikingDifficulty; tourType: PlannableTourType }
|
||||
interface HistoryEntry { waypoints: TourPlannerWaypoint[]; difficulty: TourMaxHikingDifficulty; preferences: HikingPreferences | null; tourType: PlannableTourType }
|
||||
|
||||
const ROUTE_DEBOUNCE_MS = 450
|
||||
|
||||
@@ -112,6 +112,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
const [breakAdditionalMinutes, setBreakAdditionalMinutesState] = useState<number | null>(restored?.breakAdditionalMinutes ?? null)
|
||||
const [waypoints, setWaypoints] = useState<TourPlannerWaypoint[]>(restored?.waypoints ?? [])
|
||||
const [maxHikingDifficulty, setMaxHikingDifficultyState] = useState<TourMaxHikingDifficulty>(restored?.maxHikingDifficulty ?? 2)
|
||||
const [hikingPreferences, setHikingPreferencesState] = useState<HikingPreferences | null>(restored?.hikingPreferences ?? null)
|
||||
const [tourType, setTourTypeState] = useState<PlannableTourType>(restored?.tourType ?? 'hike')
|
||||
const [selectedWaypointId, setSelectedWaypointId] = useState<string | null>(restored?.waypoints[0]?.id ?? null)
|
||||
const history = usePlannerHistory<HistoryEntry>()
|
||||
@@ -163,10 +164,12 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
editingPlaceIdRef.current = editingPlaceId
|
||||
const waypointsRef = useRef(waypoints)
|
||||
const difficultyRef = useRef(maxHikingDifficulty)
|
||||
const preferencesRef = useRef(hikingPreferences)
|
||||
const tourTypeRef = useRef(tourType)
|
||||
waypointsRef.current = waypoints
|
||||
difficultyRef.current = maxHikingDifficulty
|
||||
const snapshot = useCallback((): HistoryEntry => ({ waypoints: waypointsRef.current, difficulty: difficultyRef.current, tourType: tourTypeRef.current }), [])
|
||||
preferencesRef.current = hikingPreferences
|
||||
const snapshot = useCallback((): HistoryEntry => ({ waypoints: waypointsRef.current, difficulty: difficultyRef.current, preferences: preferencesRef.current, tourType: tourTypeRef.current }), [])
|
||||
|
||||
useEffect(() => {
|
||||
mountedRef.current = true
|
||||
@@ -236,20 +239,27 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
setStatus('dirty')
|
||||
}, [interruptRouting])
|
||||
|
||||
const setMaxHikingDifficulty = useCallback((value: TourMaxHikingDifficulty) => {
|
||||
/** A hike's routing choices, its limit and its preferences (MF-08), as one step of the history; the route is planned again. */
|
||||
const setRoutingChoice = useCallback((change: { difficulty?: TourMaxHikingDifficulty; preferences?: HikingPreferences | null }) => {
|
||||
if (!editPermissionRef.current) return
|
||||
if (value === difficultyRef.current) return
|
||||
const difficulty = change.difficulty ?? difficultyRef.current
|
||||
const preferences = change.preferences === undefined ? preferencesRef.current : hikingPreferencesOf(change.preferences)
|
||||
if (difficulty === difficultyRef.current && JSON.stringify(preferences) === JSON.stringify(preferencesRef.current)) return
|
||||
invalidateDetailRequest()
|
||||
interruptRouting()
|
||||
draftRevisionRef.current += 1
|
||||
recordStep(snapshot())
|
||||
difficultyRef.current = value
|
||||
setMaxHikingDifficultyState(value)
|
||||
difficultyRef.current = difficulty
|
||||
preferencesRef.current = preferences
|
||||
setMaxHikingDifficultyState(difficulty)
|
||||
setHikingPreferencesState(preferences)
|
||||
setHasUnsavedChanges(true)
|
||||
setSaveOutcome(null)
|
||||
setStatus('dirty')
|
||||
setError(null)
|
||||
}, [recordStep, invalidateDetailRequest, interruptRouting, snapshot])
|
||||
const setMaxHikingDifficulty = useCallback((difficulty: TourMaxHikingDifficulty) => setRoutingChoice({ difficulty }), [setRoutingChoice])
|
||||
const setHikingPreferences = useCallback((preferences: HikingPreferences | null) => setRoutingChoice({ preferences }), [setRoutingChoice])
|
||||
|
||||
const addWaypoint = useCallback((lat: number, lng: number) => {
|
||||
if (!editPermissionRef.current) return
|
||||
@@ -358,9 +368,11 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
draftRevisionRef.current += 1
|
||||
waypointsRef.current = entry.waypoints
|
||||
difficultyRef.current = entry.difficulty
|
||||
preferencesRef.current = entry.preferences
|
||||
tourTypeRef.current = entry.tourType
|
||||
setWaypoints(entry.waypoints)
|
||||
setMaxHikingDifficultyState(entry.difficulty)
|
||||
setHikingPreferencesState(entry.preferences)
|
||||
setTourTypeState(entry.tourType)
|
||||
setSelectedWaypointId(id => entry.waypoints.some(point => point.id === id) ? id : entry.waypoints[0]?.id ?? null)
|
||||
setHasUnsavedChanges(true)
|
||||
@@ -451,10 +463,10 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
const paddleEstimate = useMemo(() => isPaddle ? paddleEstimateOf(waypoints, { effectiveSpeedKmh, portageSpeedKmh }, paddleSpeedInvalid, routedLegLengths) : null,
|
||||
[effectiveSpeedKmh, isPaddle, paddleSpeedInvalid, portageSpeedKmh, routedLegLengths, waypoints])
|
||||
const facts = useMemo(() => tourPlannerFacts({
|
||||
tourType, maxHikingDifficulty, website, plannedDurationMinutes, breakAdditionalMinutes,
|
||||
tourType, maxHikingDifficulty, hikingPreferences, website, plannedDurationMinutes, breakAdditionalMinutes,
|
||||
paddle: { boatType, waterContext, speedKmh, portageSpeedKmh, lakeStyle },
|
||||
paddleSpeedInvalid, paddleEstimate, routeAnalysis, durationSeconds,
|
||||
}), [boatType, breakAdditionalMinutes, durationSeconds, lakeStyle, maxHikingDifficulty, paddleEstimate, paddleSpeedInvalid,
|
||||
}), [boatType, breakAdditionalMinutes, durationSeconds, hikingPreferences, lakeStyle, maxHikingDifficulty, paddleEstimate, paddleSpeedInvalid,
|
||||
plannedDurationMinutes, portageSpeedKmh, routeAnalysis, speedKmh, tourType, waterContext, website])
|
||||
const { websiteInvalid, plannedDurationInvalid, breakAdditionalInvalid, paddleIncomplete, walkingDurationMinutes,
|
||||
plannedTotalMinutes, plannedTotalInvalid, savedDurationSeconds, typeFields } = facts
|
||||
@@ -478,6 +490,8 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
loadPaddle(NO_PADDLE_FIELDS)
|
||||
waypointsRef.current = []
|
||||
difficultyRef.current = 2
|
||||
preferencesRef.current = null
|
||||
setHikingPreferencesState(null)
|
||||
tourTypeRef.current = 'hike'
|
||||
setSelectedWaypointId(null)
|
||||
clearHistory()
|
||||
@@ -641,6 +655,8 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
loadPaddle(paddleFieldsOf(result.tour))
|
||||
waypointsRef.current = nextWaypoints
|
||||
difficultyRef.current = result.tour.max_hiking_difficulty ?? 2
|
||||
preferencesRef.current = result.tour.hiking_preferences ?? null
|
||||
setHikingPreferencesState(preferencesRef.current)
|
||||
tourTypeRef.current = openedType
|
||||
setSelectedWaypointId(nextWaypoints[0]?.id ?? null)
|
||||
clearHistory()
|
||||
@@ -750,7 +766,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
|
||||
const routeHike = async () => {
|
||||
setStatus('routing')
|
||||
const routed = await routeWalkingTour(waypoints, controller.signal, maxHikingDifficulty)
|
||||
const routed = await routeWalkingTour(waypoints, controller.signal, maxHikingDifficulty, hikingPreferences)
|
||||
if (stale()) return
|
||||
if (!routed) {
|
||||
setStatus('routing-failed')
|
||||
@@ -797,18 +813,18 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
window.clearTimeout(timer)
|
||||
controller.abort()
|
||||
}
|
||||
}, [interruptRouting, isPaddle, maxHikingDifficulty, paddleBoat, paddleLakeStyle, retryToken, tripId, waypointKey, waypoints])
|
||||
}, [hikingPreferences, interruptRouting, isPaddle, maxHikingDifficulty, paddleBoat, paddleLakeStyle, retryToken, tripId, waypointKey, waypoints])
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasUnsavedChanges) return
|
||||
const draft: DraftPayload = { version: 9, name, description, website, plannedDurationMinutes, breakAdditionalMinutes, waypoints, maxHikingDifficulty, editingPlaceId,
|
||||
derivedFromPlaceId, tourType, baseRevision: revision.base,
|
||||
derivedFromPlaceId, tourType, baseRevision: revision.base, hikingPreferences,
|
||||
paddle: { boatType: paddle.boatType, waterContext: paddle.waterContext, speedKmh: paddle.speedKmh, portageSpeedKmh: paddle.portageSpeedKmh, lakeStyle: paddle.lakeStyle },
|
||||
}
|
||||
keepDraft(draft)
|
||||
}, [breakAdditionalMinutes,
|
||||
derivedFromPlaceId, description, editingPlaceId, hasUnsavedChanges, maxHikingDifficulty, name, plannedDurationMinutes, keepDraft, waypoints, website,
|
||||
tourType, paddle.boatType, paddle.waterContext, paddle.speedKmh, paddle.portageSpeedKmh, paddle.lakeStyle, revision.base])
|
||||
tourType, paddle.boatType, paddle.waterContext, paddle.speedKmh, paddle.portageSpeedKmh, paddle.lakeStyle, revision.base, hikingPreferences])
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasUnsavedChanges) return
|
||||
@@ -899,7 +915,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
|
||||
return {
|
||||
tripId, canEdit, canAssign,
|
||||
name, setName, maxHikingDifficulty, setMaxHikingDifficulty,
|
||||
name, setName, maxHikingDifficulty, setMaxHikingDifficulty, hikingPreferences, setHikingPreferences,
|
||||
tourType, setTourType, isPaddle, paddle, paddleSpeedInvalid, paddleIncomplete,
|
||||
description, setDescription, website, setWebsite, websiteInvalid,
|
||||
plannedDurationMinutes, setPlannedDurationMinutes, plannedDurationInvalid,
|
||||
|
||||
Reference in New Issue
Block a user