mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-29 08:00:06 +00:00
feat(tours): plan a run at your own pace
RUN-01. Run joins the tour types in the planner, with Running as its first profile, chosen on purpose like a bike tour's. A run is routed on foot for runnable, mostly paved ways: tracks and ferries only where there is no other way (use_tracks 0, use_ferry 0, measured against the public Valhalla), no hiking limit and no via ferrata. The runner types a pace in min/km; the running time is the distance at that pace and nothing else, shown under the field as badges (8 km x 6:00 /km = 48 min). TREK suggests no pace: without one the time stays unknown and Save waits, text that is no pace or a pace outside 2:00 to 20:00 is marked. The info dot, the overview and the head say climbs, descents and difficulty are not in the time, and the time reads as planned everywhere, so it never passes for a recorded one; the heights are shown as for any tour on land. Type, profile, pace and route come back on opening, survive a draft reload, an undo of the type, a copy and a take-over; switching to another type drops profile and pace. Day assignment, the 3D terrain view (with topo and satellite, no ferratas) and a routing failure keeping the last route work as for every tour. A GPX file can be imported as a run with its profile and no pace, and planned over as a run. Runs export to GPX as running and get their own places along the way (water, toilets, parks, viewpoints). The server keeps tours.run_profile (CHECK list, already holding trail for RUN-02, since SQLite cannot widen a CHECK in place) and tours.run_pace_seconds_per_km (120 to 1200), switches the run type on, refuses a run without a profile and run fields on any other type, and list_tours names both with what the planned time does not include.
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import type { TourListItem } from '@trek/shared';
|
||||
import { ArrowUp, CheckCheck, Clock, Pause, Ruler, type LucideIcon } from 'lucide-react';
|
||||
import { plannableTourTypeSchema, type TourListItem } from '@trek/shared';
|
||||
import { ArrowUp, CheckCheck, Clock, Gauge, Pause, Ruler, type LucideIcon } from 'lucide-react';
|
||||
import { createElement, useId, useState } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
@@ -8,6 +8,7 @@ import { WhiteBadge } from '../Planner/planParts';
|
||||
import { fs } from '../shared/DialogShell';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
import { paddleCheckFact } from './paddle/paddleCheckModel';
|
||||
import { runPaceText } from './run/runPaceText';
|
||||
import { tourDayRowIcon } from './tourDayRowIcon';
|
||||
import { movingTimeLabel } from './tourFacts';
|
||||
import { formatPlannedTourDuration, plannedTotalText, tourPlannedTimes } from './tourPresentation';
|
||||
@@ -15,9 +16,19 @@ import { useWalkProgress } from './walk/walkProgress';
|
||||
import { walkStaysText } from './walk/walkTimeFields';
|
||||
import { WinterCornerMark } from './winter/winterMarks';
|
||||
|
||||
/** Whether the app names this type: one it plans, not a key only the catalogue holds. */
|
||||
function knownType(type: string): boolean {
|
||||
return plannableTourTypeSchema.safeParse(type).success;
|
||||
}
|
||||
|
||||
/** The icon the time on the move goes by: a ride, a run or a paddle by its type's own, any walk by footprints. */
|
||||
function movingIconType(type: string): string {
|
||||
return type === 'kayak' || type === 'bike' || type === 'run' ? type : 'walk';
|
||||
}
|
||||
|
||||
export function TourDayRowIcon({ type, size = 27 }: { type: string; size?: number }) {
|
||||
const { t } = useTranslation();
|
||||
const known = ['hike', 'bike', 'walk', 'kayak'].includes(type);
|
||||
const known = knownType(type);
|
||||
return (
|
||||
<span
|
||||
data-testid="plan-tour-icon"
|
||||
@@ -112,7 +123,7 @@ function TourGradeAvatar({
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const level = tour.max_hiking_difficulty;
|
||||
const known = ['hike', 'bike', 'walk', 'kayak'].includes(tour.tour_type);
|
||||
const known = knownType(tour.tour_type);
|
||||
const label =
|
||||
level != null
|
||||
? t(`tours.planner.difficulty.t${level}`)
|
||||
@@ -187,8 +198,11 @@ export function TourDayRowPills({ tour, compact = false }: { tour: TourListItem;
|
||||
const walking = times.walkingMinutes == null ? null : formatPlannedTourDuration(times.walkingMinutes);
|
||||
const total = plannedTotalText(times, t);
|
||||
const staysText = times.walk ? walkStaysText(times.walk, t) : null;
|
||||
const pace = runPaceText(tour);
|
||||
const timeParts = [
|
||||
walking ? `${movingTimeLabel(tour, t('tours.planner.inspector.duration'), t)}: ${walking}` : null,
|
||||
// RUN-01: the pace the running time is planned at.
|
||||
pace ? `${t('tours.run.pace')}: ${pace}` : null,
|
||||
times.breakMinutes
|
||||
? `${t('tours.planner.breaksAdditional')}: ${formatPlannedTourDuration(times.breakMinutes)}`
|
||||
: null,
|
||||
@@ -250,11 +264,13 @@ export default function TourDayRowFacts({
|
||||
add(ArrowUp, formatElevation(tour.elevation_gain, unit), t('tours.detail.ascent'), 'plan-tour-ascent');
|
||||
if (times.walkingMinutes != null)
|
||||
add(
|
||||
tourDayRowIcon(tour.tour_type === 'kayak' || tour.tour_type === 'bike' ? tour.tour_type : 'walk'),
|
||||
tourDayRowIcon(movingIconType(tour.tour_type)),
|
||||
formatPlannedTourDuration(times.walkingMinutes),
|
||||
movingTimeLabel(tour, t('tours.planner.inspector.duration'), t),
|
||||
'trip-plan-tour-walking-time'
|
||||
);
|
||||
const pace = runPaceText(tour);
|
||||
if (pace) add(Gauge, pace, t('tours.run.pace'), 'plan-tour-run-pace');
|
||||
if (times.breakMinutes != null && times.breakMinutes > 0)
|
||||
add(
|
||||
Pause,
|
||||
|
||||
@@ -51,6 +51,7 @@ import { TourGpxExportButton } from './TourGpxExportButton';
|
||||
import { PaddleCheckSection } from './paddle/PaddleCheckSection';
|
||||
import { PaddleWindSection } from './paddle/PaddleWindCard';
|
||||
import { TourProvenanceBlock } from './provenance/TourProvenanceSection';
|
||||
import { RunHeadPills } from './run/RunHeadPills';
|
||||
import { tourDayRowIcon } from './tourDayRowIcon';
|
||||
import { tourDaysOf } from './tourDays';
|
||||
import { heightsUnknown, movingTimeLabel, withoutHeights } from './tourFacts';
|
||||
@@ -209,7 +210,7 @@ function tourTimeFields(
|
||||
}
|
||||
|
||||
/**
|
||||
* The head's facts as pills: the type and a hike's winter label, where it came from, the time (its parts
|
||||
* The head's facts as pills: the type, a hike's winter label or a run's profile and pace, where it came from, the time (its parts
|
||||
* in the tooltip), distance, ascent, descent, and a caution.
|
||||
*/
|
||||
function TourHeadPills({
|
||||
@@ -253,6 +254,8 @@ function TourHeadPills({
|
||||
</span>
|
||||
{/* HIK-01: a hike's winter label, the travellers' own, beside its type. */}
|
||||
{tour.winter_activity && <WinterActivityPill activity={tour.winter_activity} className={HEAD_PILL} />}
|
||||
{/* RUN-01: a run's profile and the pace its time is planned at. */}
|
||||
<RunHeadPills tour={tour} className={HEAD_PILL} />
|
||||
{/* A paddle tour names its boat and its water, each a badge of its own. */}
|
||||
{tour.boat_type && (
|
||||
<span className={HEAD_PILL} style={fs(10.5)} data-testid="tour-detail-boat">
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
type PaddleBoatType,
|
||||
type PaddleWaterContext,
|
||||
type PlannableTourType,
|
||||
type RunProfile,
|
||||
type TourGpxImportFields,
|
||||
} from '@trek/shared';
|
||||
import { AlertTriangle, FileDown, Info } from 'lucide-react';
|
||||
@@ -28,6 +29,7 @@ import {
|
||||
NEUTRAL_TINT,
|
||||
} from '../shared/DialogShell';
|
||||
import { TourTypeSelect } from './planner/TourTypeSelect';
|
||||
import { RunProfileField } from './run/RunFields';
|
||||
import { TourNotice } from './tourParts';
|
||||
import type { GpxPreviewFile, TourGpxImport } from './useTourGpxImport';
|
||||
|
||||
@@ -69,6 +71,24 @@ function PreviewTrackRow({ name, track }: { name: string; track: GpxPreviewFile[
|
||||
);
|
||||
}
|
||||
|
||||
/** What the dialog has chosen besides the type: a paddle import's boat and water, a bike or run import's profile. */
|
||||
interface ImportChoices {
|
||||
boat: PaddleBoatType | null;
|
||||
water: PaddleWaterContext | null;
|
||||
bikeProfile: BikeProfile;
|
||||
runProfile: RunProfile;
|
||||
}
|
||||
|
||||
/** What the import is asked to store the tracks as: the type and the fields that type names. */
|
||||
function importFields(type: PlannableTourType, chosen: ImportChoices): TourGpxImportFields {
|
||||
if (type === 'kayak' && chosen.boat && chosen.water)
|
||||
return { tour_type: 'kayak', boat_type: chosen.boat, water_context: chosen.water };
|
||||
if (type === 'bike') return { tour_type: 'bike', bike_profile: chosen.bikeProfile };
|
||||
// RUN-01: a run comes in with its profile and no pace; its time stays unknown until one is planned from it.
|
||||
if (type === 'run') return { tour_type: 'run', run_profile: chosen.runProfile };
|
||||
return { tour_type: 'hike' };
|
||||
}
|
||||
|
||||
/**
|
||||
* PAD-02: a GPX file shown before anything is stored. The whole course on a
|
||||
* map, every track with its measures, the tracks the trip already holds named
|
||||
@@ -90,6 +110,7 @@ function PreviewDialog({ gpxImport, files }: { gpxImport: TourGpxImport; files:
|
||||
const [boat, setBoat] = useState<PaddleBoatType | null>(null);
|
||||
const [water, setWater] = useState<PaddleWaterContext | null>(null);
|
||||
const [bikeProfile, setBikeProfile] = useState<BikeProfile>('touring');
|
||||
const [runProfile, setRunProfile] = useState<RunProfile>('running');
|
||||
|
||||
const tracks = files.flatMap((file) => file.tracks.map((track) => ({ file: file.file, track })));
|
||||
const fresh = tracks.filter(({ track }) => !track.duplicate).length;
|
||||
@@ -103,12 +124,7 @@ function PreviewDialog({ gpxImport, files }: { gpxImport: TourGpxImport; files:
|
||||
const focusPoints = useMemo(() => lines.flat(), [lines]);
|
||||
const paddleIncomplete = type === 'kayak' && (boat === null || water === null);
|
||||
const canImport = fresh > 0 && !paddleIncomplete && !gpxImport.importing;
|
||||
const fields: TourGpxImportFields =
|
||||
type === 'kayak' && boat && water
|
||||
? { tour_type: 'kayak', boat_type: boat, water_context: water }
|
||||
: type === 'bike'
|
||||
? { tour_type: 'bike', bike_profile: bikeProfile }
|
||||
: { tour_type: 'hike' };
|
||||
const fields = importFields(type, { boat, water, bikeProfile, runProfile });
|
||||
const title = files.length === 1 ? files[0].file.name : t('tours.import.previewFiles', { count: files.length });
|
||||
|
||||
return (
|
||||
@@ -195,6 +211,7 @@ function PreviewDialog({ gpxImport, files }: { gpxImport: TourGpxImport; files:
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{type === 'run' && <RunProfileField value={runProfile} onChange={setRunProfile} />}
|
||||
{type === 'kayak' && (
|
||||
<div data-testid="gpx-preview-paddle" className="grid grid-cols-1 gap-3 sm:grid-cols-[3fr_2fr]">
|
||||
<div className="min-w-0">
|
||||
|
||||
@@ -363,6 +363,26 @@ describe('ToursSidebar', () => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('RUN-01: a run import names its profile, on purpose, and sends no pace', async () => {
|
||||
vi.spyOn(tourGpxApi, 'preview').mockResolvedValue({ tracks: [previewTrack()] })
|
||||
const importCall = vi.spyOn(tourGpxApi, 'import').mockResolvedValue({ tours: [tour], caution: false, skipped: 0 })
|
||||
seedStore(useTripStore, { refreshPlaces: vi.fn().mockResolvedValue(undefined) })
|
||||
render(
|
||||
<ToursSidebar tripId={1} days={[]} tours={[]} canEdit={true} onAssignToDay={vi.fn()} onSelectTour={vi.fn()} />
|
||||
)
|
||||
const file = new File(['<gpx/>'], 'laps.gpx', { type: 'application/gpx+xml' })
|
||||
pickFiles(screen.getByRole('button', { name: 'Import GPX' }), [file])
|
||||
await screen.findByRole('dialog')
|
||||
|
||||
fireEvent.click(screen.getByTestId('tour-type-select'))
|
||||
fireEvent.click(screen.getByTestId('tour-type-option-run'))
|
||||
expect(screen.getByRole('button', { name: 'Running' })).toHaveAttribute('aria-pressed', 'true')
|
||||
fireEvent.click(screen.getByTestId('gpx-preview-import'))
|
||||
|
||||
await waitFor(() => expect(importCall).toHaveBeenCalledWith(1, file, { tour_type: 'run', run_profile: 'running' }))
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('RC-04: refuses files that are not GPX before uploading anything', async () => {
|
||||
const importCall = vi.spyOn(tourGpxApi, 'import')
|
||||
render(
|
||||
|
||||
@@ -9,9 +9,9 @@ import type { TourPlannerController } from '../planner/useTourPlanner';
|
||||
import TourConversionSection from './TourConversionSection';
|
||||
import { useGpxConversion } from './useGpxConversion';
|
||||
|
||||
const routing = vi.hoisted(() => ({ route: vi.fn() }));
|
||||
const routing = vi.hoisted(() => ({ route: vi.fn(), run: vi.fn() }));
|
||||
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }));
|
||||
vi.mock('../planner/tourRouting', () => ({ routeWalkingTour: routing.route }));
|
||||
vi.mock('../planner/tourRouting', () => ({ routeWalkingTour: routing.route, routeRun: routing.run }));
|
||||
vi.mock('../../shared/Toast', () => ({ useToast: () => toast }));
|
||||
|
||||
const imported: TourListItem = {
|
||||
@@ -52,6 +52,7 @@ beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
seedStore(useSettingsStore, { settings: { distance_unit: 'metric' } });
|
||||
routing.route.mockResolvedValue({ coordinates: track, distanceMeters: 2000, durationSeconds: 1800 });
|
||||
routing.run.mockResolvedValue({ coordinates: track, distanceMeters: 2000, durationSeconds: 1800 });
|
||||
});
|
||||
|
||||
describe('useGpxConversion', () => {
|
||||
@@ -165,6 +166,31 @@ describe('useGpxConversion', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('RUN-01: a run import is routed for its profile and planned as a run, its pace left to the runner', async () => {
|
||||
const run = {
|
||||
...imported,
|
||||
tour_type: 'run' as const,
|
||||
run_profile: 'running' as const,
|
||||
max_hiking_difficulty: null,
|
||||
};
|
||||
const controller = planner({
|
||||
mode: { type: 'view-gpx', placeId: run.place_id, tour: run },
|
||||
readOnlyGpxTour: { tour: run, routeGeometry: null },
|
||||
} as Partial<TourPlannerController>);
|
||||
const { result } = renderHook(() => useGpxConversion(controller));
|
||||
await act(async () => {
|
||||
await result.current.analyze();
|
||||
});
|
||||
expect(routing.run).toHaveBeenCalledWith(result.current.points, 'running', expect.any(AbortSignal));
|
||||
expect(routing.route).not.toHaveBeenCalled();
|
||||
act(() => {
|
||||
result.current.adopt('new');
|
||||
});
|
||||
const draft = vi.mocked(controller.startDerivedTour).mock.calls[0]?.[0];
|
||||
expect(draft).toMatchObject({ tourType: 'run', runProfile: 'running' });
|
||||
expect(draft).not.toHaveProperty('paddle');
|
||||
});
|
||||
|
||||
it('PR1-05B: nothing is adopted before the suggestion is ready', () => {
|
||||
const controller = planner();
|
||||
const { result } = renderHook(() => useGpxConversion(controller));
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { TourMaxHikingDifficulty } from '@trek/shared';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { freeLegBetween } from '../planner/tourRouteActions';
|
||||
import { isTourRoute } from '../planner/tourRouteOutcome';
|
||||
import { routeBikeTour, routeWalkingTour } from '../planner/tourRouting';
|
||||
import { routeBikeTour, routeRun, routeWalkingTour } from '../planner/tourRouting';
|
||||
import { paddleFieldsOf } from '../planner/usePaddleFields';
|
||||
import type { TourPlannerController } from '../planner/useTourPlanner';
|
||||
import { compareRoutes, deriveControlPoints, type RouteComparison, type TrackPoint } from './gpxConversion';
|
||||
@@ -44,6 +44,8 @@ export function useGpxConversion(planner: TourPlannerController) {
|
||||
const paddle = tour?.tour_type === 'kayak';
|
||||
// BIK-01: a bike import is planned for its profile.
|
||||
const bikeProfile = tour?.tour_type === 'bike' ? (tour.bike_profile ?? 'touring') : null;
|
||||
// RUN-01: a run import is planned as a run for its profile; its pace is the runner's to enter.
|
||||
const runProfile = tour?.tour_type === 'run' ? (tour.run_profile ?? 'running') : null;
|
||||
|
||||
useEffect(() => () => abort.current?.abort(), []);
|
||||
|
||||
@@ -68,7 +70,9 @@ export function useGpxConversion(planner: TourPlannerController) {
|
||||
: points;
|
||||
const routed = bikeProfile
|
||||
? await routeBikeTour(legs, bikeProfile, controller.signal)
|
||||
: await routeWalkingTour(legs, controller.signal, difficulty);
|
||||
: runProfile
|
||||
? await routeRun(legs, runProfile, controller.signal)
|
||||
: await routeWalkingTour(legs, controller.signal, difficulty);
|
||||
if (controller.signal.aborted) return;
|
||||
if (!isTourRoute(routed)) {
|
||||
setState({ ...base, status: 'failed', error: 'routing' });
|
||||
@@ -81,7 +85,7 @@ export function useGpxConversion(planner: TourPlannerController) {
|
||||
line: routed.coordinates,
|
||||
comparison: compareRoutes(trackPoints, suggestion),
|
||||
});
|
||||
}, [bikeProfile, difficulty, paddle, tour, track]);
|
||||
}, [bikeProfile, difficulty, paddle, runProfile, tour, track]);
|
||||
|
||||
const cancel = useCallback(() => {
|
||||
abort.current?.abort();
|
||||
@@ -107,11 +111,12 @@ export function useGpxConversion(planner: TourPlannerController) {
|
||||
revision: tour.revision,
|
||||
...(paddle ? { tourType: 'kayak' as const, paddle: paddleFieldsOf(tour) } : {}),
|
||||
...(bikeProfile ? { tourType: 'bike' as const, bikeProfile } : {}),
|
||||
...(runProfile ? { tourType: 'run' as const, runProfile } : {}),
|
||||
});
|
||||
if (started) setState(IDLE);
|
||||
return started;
|
||||
},
|
||||
[bikeProfile, current.points, current.status, difficulty, paddle, startDerivedTour, tour]
|
||||
[bikeProfile, current.points, current.status, difficulty, paddle, runProfile, startDerivedTour, tour]
|
||||
);
|
||||
|
||||
return useMemo(
|
||||
|
||||
@@ -81,6 +81,7 @@ export function TourNameField({ planner, locked }: TourFieldProps) {
|
||||
bike: t('tours.planner.namePlaceholder.bike'),
|
||||
kayak: t('tours.planner.namePlaceholder.kayak'),
|
||||
walk: t('tours.planner.namePlaceholder.walk'),
|
||||
run: t('tours.planner.namePlaceholder.run'),
|
||||
}[planner.tourType]
|
||||
}
|
||||
className={INPUT}
|
||||
|
||||
@@ -993,3 +993,25 @@ describe('the paddle checklist in the rails (PAD-06)', () => {
|
||||
expect(safetyRow()).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('a run in the planner rails (RUN-01)', () => {
|
||||
const run = { mode: { type: 'new-draft' as const }, tourType: 'run' as const, isRun: true }
|
||||
|
||||
it('TOUR-PLANNER-RAIL-RUN-001: the overview names the time as planned and says climbs and difficulty stay out of it', () => {
|
||||
render(<TourPlannerToursRail planner={planner({ ...run, walkingDurationMinutes: 48, plannedTotalMinutes: 48 })} tours={[tour]} {...railProps} />)
|
||||
const facts = screen.getAllByRole('definition').map(value => [value.previousElementSibling?.textContent, value.textContent])
|
||||
expect(facts).toEqual(expect.arrayContaining([[expect.stringMatching(/^Running time \(planned\)/), '48 min']]))
|
||||
expect(screen.getByRole('button', { name: 'How the running time is planned' })).toHaveAccessibleDescription(
|
||||
'Distance × your pace and nothing else: climbs, descents and difficulty are not included. A plan, not a recorded time.'
|
||||
)
|
||||
})
|
||||
|
||||
it('TOUR-PLANNER-RAIL-RUN-002: the editor asks for the profile and pace, and a point off every runnable way says so', () => {
|
||||
const waypoints = [{ id: 'a', lat: 48, lng: 11, role: 'start' as const }, { id: 'b', lat: 48.01, lng: 11.02, role: 'end' as const }]
|
||||
render(<TourPlannerRail planner={planner({ ...run, runPaceMissing: true, waypoints, unreachable: { unreachable: 1, snappedMeters: 900 } })} />)
|
||||
expect(screen.getByTestId('tour-planner-run-fields')).toBeInTheDocument()
|
||||
expect(screen.getByText('Enter your pace to plan the running time and save this run.')).toBeInTheDocument()
|
||||
expect(screen.getByTestId('tour-planner-unreachable')).toHaveTextContent('No runnable way reaches point 2')
|
||||
expect(screen.getByTestId('tour-planner-unreachable')).toHaveTextContent('900 m')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react'
|
||||
import type { TourListItem } from '@trek/shared'
|
||||
import type { PlannableTourType, TourListItem } from '@trek/shared'
|
||||
import { AlertTriangle, ArrowLeft, Circle, History, Loader2, MapPin, Mountain, Plus, Redo2, RotateCcw, Route, Save, Trash2, Undo2 } from 'lucide-react'
|
||||
import type { Day } from '../../../types'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
@@ -612,14 +612,24 @@ interface TourPlannerToursRailProps extends TourPermissionProps {
|
||||
onTakenOver?: (tour: TourListItem) => Promise<void>
|
||||
}
|
||||
|
||||
/** The words of the time estimate: walking, riding (BIK-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. */
|
||||
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' },
|
||||
} as const
|
||||
|
||||
/** Which ways a point is out of reach of: paths for hikes and city walks, ways for bikes, runnable ways. */
|
||||
const UNREACHABLE_WAYS: Record<PlannableTourType, 'hike' | 'bike' | 'run'> = {
|
||||
hike: 'hike',
|
||||
walk: 'hike',
|
||||
kayak: 'hike',
|
||||
bike: 'bike',
|
||||
run: 'run',
|
||||
}
|
||||
|
||||
/**
|
||||
* A point no way of the tour's type reaches: the router would have bound it
|
||||
* that far off, so no route is drawn to a place the tour does not go. The
|
||||
@@ -635,7 +645,7 @@ function UnreachableNotice({ planner }: { planner: TourPlannerController }) {
|
||||
<TourNotice tone="warning" icon={<AlertTriangle size={13} strokeWidth={2} />}>
|
||||
<span className="flex flex-col items-start gap-1.5">
|
||||
<span data-testid="tour-planner-unreachable">
|
||||
{t(planner.isBike ? 'tours.planner.unreachable.bike' : 'tours.planner.unreachable.hike', {
|
||||
{t(`tours.planner.unreachable.${UNREACHABLE_WAYS[planner.tourType]}`, {
|
||||
point: point.unreachable + 1,
|
||||
distance: formatDistance(point.snappedMeters / 1000, distanceUnit),
|
||||
})}
|
||||
|
||||
@@ -13,6 +13,7 @@ import { INPUT, LABEL, Segmented } from '../../shared/dialogParts';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import { crossesLake } from '../paddle/lakeStyleAdvice';
|
||||
import { PaddleLakeStyleField } from '../paddle/PaddleLakeStyleField';
|
||||
import { RunFields } from '../run/RunFields';
|
||||
import { TourNotice } from '../tourParts';
|
||||
import { TourTypeSelect } from './TourTypeSelect';
|
||||
import type { TourPlannerController } from './useTourPlanner';
|
||||
@@ -104,10 +105,11 @@ function BikeProfileField({ planner }: { planner: TourPlannerController }) {
|
||||
}
|
||||
|
||||
/**
|
||||
* PAD-01, BIK-01: what the tour is. A hike keeps its fields where they were; a
|
||||
* bike tour names its profile; a paddle tour asks for exactly one boat and the
|
||||
* water it is on, and offers the boat's planning speed beside the paddler's
|
||||
* own. Nothing here puts the tour on a day.
|
||||
* PAD-01, BIK-01, RUN-01: what the tour is. A hike keeps its fields where they
|
||||
* were; a bike tour names its profile; a run its profile and the runner's pace;
|
||||
* a paddle tour asks for exactly one boat and the water it is on, and offers
|
||||
* the boat's planning speed beside the paddler's own. Nothing here puts the
|
||||
* tour on a day.
|
||||
*/
|
||||
export function TourTypeFields({ planner, locked }: TourTypeFieldsProps) {
|
||||
const { t } = useTranslation();
|
||||
@@ -130,6 +132,8 @@ export function TourTypeFields({ planner, locked }: TourTypeFieldsProps) {
|
||||
|
||||
{planner.isBike && <BikeProfileField planner={planner} />}
|
||||
|
||||
{planner.isRun && <RunFields planner={planner} locked={locked} />}
|
||||
|
||||
{planner.isPaddle && (
|
||||
<div data-testid="tour-planner-paddle-fields" className="flex min-w-0 flex-col gap-3">
|
||||
<div className="min-w-0">
|
||||
|
||||
@@ -41,7 +41,7 @@ export function TourTypeSelect({
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const valueId = useId();
|
||||
const list = usePopoverList(PLANNER_TOUR_TYPES.indexOf(value), { estimatedHeight: 220 });
|
||||
const list = usePopoverList(PLANNER_TOUR_TYPES.indexOf(value), { estimatedHeight: 270 });
|
||||
const { open, toggle, triggerRef, listId } = list;
|
||||
const label = t('tours.planner.tourType');
|
||||
const pick = (type: PlannableTourType) => {
|
||||
|
||||
@@ -4,10 +4,12 @@ import {
|
||||
MAX_PLANNED_TOUR_DURATION_MINUTES,
|
||||
paddleLockSchema,
|
||||
plannableTourTypeSchema,
|
||||
runProfileSchema,
|
||||
winterActivitySchema,
|
||||
type BikeProfile,
|
||||
type HikingPreferences,
|
||||
type PlannableTourType,
|
||||
type RunProfile,
|
||||
type TourMaxHikingDifficulty,
|
||||
type WinterActivity,
|
||||
} from '@trek/shared';
|
||||
@@ -47,6 +49,9 @@ export interface DraftPayload {
|
||||
bikeProfile?: BikeProfile;
|
||||
/** HIK-01: the hike's winter label; absent in a draft older than it. */
|
||||
winterActivity?: WinterActivity | null;
|
||||
/** RUN-01: the profile a run is routed for, and its pace in seconds per km; absent in a draft older than them. */
|
||||
runProfile?: RunProfile;
|
||||
runPaceSecondsPerKm?: number | null;
|
||||
}
|
||||
|
||||
const DRAFT_VERSIONS: ReadonlyArray<DraftPayload['version']> = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
|
||||
@@ -87,11 +92,21 @@ function validDraftWaypoint(point: TourPlannerWaypoint): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* RUN-01: a run's pace as a draft keeps it, whole seconds. Text that was no
|
||||
* pace yet (NaN in the planner) is written as JSON null and comes back as none.
|
||||
*/
|
||||
function optionalPace(value: number | null | undefined): boolean {
|
||||
return value == null || (Number.isInteger(value) && value > 0);
|
||||
}
|
||||
|
||||
/** The type of a draft, what its route is planned by and its winter label, each one absent in a draft older than it. */
|
||||
function validRouteChoices(draft: Partial<DraftPayload>): boolean {
|
||||
return (
|
||||
(draft.tourType === undefined || plannableTourTypeSchema.safeParse(draft.tourType).success) &&
|
||||
(draft.bikeProfile === undefined || bikeProfileSchema.safeParse(draft.bikeProfile).success) &&
|
||||
(draft.runProfile === undefined || runProfileSchema.safeParse(draft.runProfile).success) &&
|
||||
optionalPace(draft.runPaceSecondsPerKm) &&
|
||||
(draft.hikingPreferences == null || hikingPreferencesSchema.safeParse(draft.hikingPreferences).success) &&
|
||||
(draft.winterActivity == null || winterActivitySchema.safeParse(draft.winterActivity).success) &&
|
||||
optionalDifficulty(draft.maxHikingDifficulty)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
MAX_PLANNED_TOUR_DURATION_MINUTES,
|
||||
plannableTourTypeSchema,
|
||||
runMinutesAtPace,
|
||||
tourWebsiteSchema,
|
||||
type BikeProfile,
|
||||
type HikingPreferences,
|
||||
@@ -8,12 +9,14 @@ import {
|
||||
type PaddleLakeStyle,
|
||||
type PaddleWaterContext,
|
||||
type PlannableTourType,
|
||||
type RunProfile,
|
||||
type TourListItem,
|
||||
type TourMaxHikingDifficulty,
|
||||
type WinterActivity,
|
||||
} from '@trek/shared';
|
||||
import type { RouteGeometryAnalysis } from '../../../utils/routeGeometry';
|
||||
import { hikingTimeMinutes } from '../hikingTime';
|
||||
import { runPaceInvalid } from '../run/runPace';
|
||||
import { walkTimesOf, type WalkTimes } from './stationModel';
|
||||
|
||||
/** The editable fields of a saved tour as the planner opens them, each with its empty value. */
|
||||
@@ -30,6 +33,8 @@ export function openedTourFields(tour: TourListItem) {
|
||||
tourType: plannableTourTypeSchema.catch('hike').parse(tour.tour_type) as PlannableTourType,
|
||||
bikeProfile: (tour.bike_profile ?? 'touring') as BikeProfile,
|
||||
winterActivity: tour.winter_activity ?? null,
|
||||
runProfile: (tour.run_profile ?? 'running') as RunProfile,
|
||||
runPaceSecondsPerKm: tour.run_pace_seconds_per_km ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -43,6 +48,9 @@ export interface TourPlannerFactsInput {
|
||||
bikeProfile: BikeProfile;
|
||||
/** HIK-01: a hike's winter label, none by default; it changes nothing the planner works out. */
|
||||
winterActivity: WinterActivity | null;
|
||||
/** RUN-01: the profile a run is routed for, and the pace it is planned at (null while none is entered). */
|
||||
runProfile: RunProfile;
|
||||
runPaceSecondsPerKm: number | null;
|
||||
website: string;
|
||||
plannedDurationMinutes: number | null;
|
||||
breakAdditionalMinutes: number | null;
|
||||
@@ -71,14 +79,25 @@ function invalidMinutes(value: number | null): boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* The time on the move: a paddle tour on the water at its speed, a bike tour
|
||||
* by the router, which rides the profile at its speed and weighs the climbs, a
|
||||
* hike by the signposts' rule over distance, climb and descent once the route
|
||||
* has its heights, and by the router's own time before that.
|
||||
* RUN-01: a run's time is its distance at the runner's pace and nothing else:
|
||||
* no climb, no descent and no difficulty go in. Without a pace, or before the
|
||||
* route is in, it is unknown; the router's walking time never stands in.
|
||||
*/
|
||||
function runMinutes({ runPaceSecondsPerKm: pace, routeAnalysis }: TourPlannerFactsInput): number | null {
|
||||
if (pace === null || runPaceInvalid(pace) || !routeAnalysis) return null;
|
||||
return runMinutesAtPace(routeAnalysis.distanceKm, pace);
|
||||
}
|
||||
|
||||
/**
|
||||
* The time on the move: a paddle tour on the water at its speed, a run at its
|
||||
* 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.
|
||||
*/
|
||||
function movingMinutes(input: TourPlannerFactsInput, routerMinutes: number | null): number | null {
|
||||
const { paddleEstimate, routeAnalysis } = input;
|
||||
if (paddleEstimate) return paddleEstimate.waterMinutes === null ? null : paddleEstimate.estimateMinutes;
|
||||
if (input.tourType === 'run') return runMinutes(input);
|
||||
// A bike tour is timed by the router for its profile, a city walk by the router on foot.
|
||||
if (input.tourType === 'bike' || input.tourType === 'walk') return routerMinutes;
|
||||
return routeAnalysis?.gain != null && routeAnalysis.loss != null
|
||||
@@ -98,16 +117,20 @@ function walkTimesFor(input: TourPlannerFactsInput, walkingMinutes: number | nul
|
||||
|
||||
/**
|
||||
* What the type adds to a save: a hike its routing limit and its winter label,
|
||||
* a bike tour its profile, a paddle tour its boat, water and speed.
|
||||
* a bike tour its profile, a run its profile and pace, a paddle tour its boat,
|
||||
* water and speed.
|
||||
*/
|
||||
function typeFieldsOf(input: TourPlannerFactsInput) {
|
||||
const isBike = input.tourType === 'bike';
|
||||
const isRun = input.tourType === 'run';
|
||||
if (input.tourType === 'kayak') {
|
||||
const { boatType, waterContext, speedKmh, portageSpeedKmh, lakeStyle } = input.paddle;
|
||||
return {
|
||||
tour_type: input.tourType,
|
||||
max_hiking_difficulty: null,
|
||||
bike_profile: null,
|
||||
run_profile: null,
|
||||
run_pace_seconds_per_km: null,
|
||||
boat_type: boatType,
|
||||
water_context: waterContext,
|
||||
paddle_speed_kmh: speedKmh,
|
||||
@@ -122,6 +145,8 @@ function typeFieldsOf(input: TourPlannerFactsInput) {
|
||||
tour_type: input.tourType,
|
||||
max_hiking_difficulty: isHike ? input.maxHikingDifficulty : null,
|
||||
bike_profile: isBike ? input.bikeProfile : null,
|
||||
run_profile: isRun ? input.runProfile : null,
|
||||
run_pace_seconds_per_km: isRun ? input.runPaceSecondsPerKm : null,
|
||||
boat_type: null,
|
||||
water_context: null,
|
||||
paddle_speed_kmh: null,
|
||||
@@ -138,6 +163,7 @@ function typeFieldsOf(input: TourPlannerFactsInput) {
|
||||
*/
|
||||
export function tourPlannerFacts(input: TourPlannerFactsInput) {
|
||||
const isPaddle = input.tourType === 'kayak';
|
||||
const isRun = input.tourType === 'run';
|
||||
const { durationSeconds, breakAdditionalMinutes, plannedDurationMinutes } = input;
|
||||
const routerMinutes = durationSeconds === null ? null : Math.round(durationSeconds / 60);
|
||||
const walkingDurationMinutes = movingMinutes(input, routerMinutes);
|
||||
@@ -152,6 +178,9 @@ export function tourPlannerFacts(input: TourPlannerFactsInput) {
|
||||
// A city walk sends no breaks (CW-02), so one left from another type cannot hold its save up.
|
||||
breakAdditionalInvalid: input.tourType !== 'walk' && invalidMinutes(breakAdditionalMinutes),
|
||||
paddleIncomplete: isPaddle && (boatType === null || waterContext === null),
|
||||
/** RUN-01: a run is planned with a pace; without one Save waits, and a pace that is none is marked. */
|
||||
runPaceMissing: isRun && input.runPaceSecondsPerKm === null,
|
||||
runPaceInvalid: isRun && runPaceInvalid(input.runPaceSecondsPerKm),
|
||||
walkingDurationMinutes,
|
||||
/** CW-02: a city walk's walking time, stays and total; null for any other type. */
|
||||
stationStays: walk,
|
||||
@@ -163,9 +192,9 @@ 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.
|
||||
// The router's own time stands in for a hike without heights; a paddle tour has only its speed, a run its pace.
|
||||
savedDurationSeconds:
|
||||
walkingDurationMinutes === null ? (isPaddle ? null : durationSeconds) : walkingDurationMinutes * 60,
|
||||
walkingDurationMinutes === null ? (isPaddle || isRun ? null : durationSeconds) : walkingDurationMinutes * 60,
|
||||
typeFields: typeFieldsOf(input),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { tourPlannerFacts, type TourPlannerFactsInput } from './tourPlannerFacts';
|
||||
import { openedTourFields, tourPlannerFacts, type TourPlannerFactsInput } from './tourPlannerFacts';
|
||||
import { usePlannerHistory } from './usePlannerHistory';
|
||||
import { useTourDraftStorage } from './useTourDraftStorage';
|
||||
|
||||
@@ -10,6 +10,8 @@ const hike = (overrides: Partial<TourPlannerFactsInput> = {}): TourPlannerFactsI
|
||||
hikingPreferences: null,
|
||||
bikeProfile: 'touring',
|
||||
winterActivity: null,
|
||||
runProfile: 'running',
|
||||
runPaceSecondsPerKm: null,
|
||||
website: '',
|
||||
plannedDurationMinutes: null,
|
||||
breakAdditionalMinutes: null,
|
||||
@@ -77,6 +79,67 @@ describe('tourPlannerFacts', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('RUN-01: times a run as its distance at the pace, nothing else, and saves its profile and pace', () => {
|
||||
// 8 km with 600 m up and down at 6:00 min/km: 48 minutes, the climb left out.
|
||||
const analysis = { distanceKm: 8, gain: 600, loss: 600 } as TourPlannerFactsInput['routeAnalysis'];
|
||||
const facts = tourPlannerFacts(
|
||||
hike({ tourType: 'run', runPaceSecondsPerKm: 360, routeAnalysis: analysis, durationSeconds: 7200 })
|
||||
);
|
||||
expect(facts.walkingDurationMinutes).toBe(48);
|
||||
expect(facts.plannedTotalMinutes).toBe(48);
|
||||
expect(facts.savedDurationSeconds).toBe(48 * 60);
|
||||
expect(facts.runPaceMissing).toBe(false);
|
||||
expect(facts.runPaceInvalid).toBe(false);
|
||||
expect(facts.typeFields).toMatchObject({
|
||||
tour_type: 'run',
|
||||
run_profile: 'running',
|
||||
run_pace_seconds_per_km: 360,
|
||||
max_hiking_difficulty: null,
|
||||
hiking_preferences: null,
|
||||
winter_activity: null,
|
||||
bike_profile: null,
|
||||
});
|
||||
const withBreak = hike({
|
||||
tourType: 'run',
|
||||
runPaceSecondsPerKm: 360,
|
||||
routeAnalysis: analysis,
|
||||
breakAdditionalMinutes: 12,
|
||||
});
|
||||
expect(tourPlannerFacts(withBreak).plannedTotalMinutes).toBe(60);
|
||||
});
|
||||
|
||||
it('RUN-01: a run without a pace, or with one that is none, has no time and no save, never the router time', () => {
|
||||
const analysis = { distanceKm: 8, gain: 0, loss: 0 } as TourPlannerFactsInput['routeAnalysis'];
|
||||
const missing = tourPlannerFacts(hike({ tourType: 'run', routeAnalysis: analysis, durationSeconds: 7200 }));
|
||||
expect(missing.walkingDurationMinutes).toBeNull();
|
||||
expect(missing.savedDurationSeconds).toBeNull();
|
||||
expect(missing.runPaceMissing).toBe(true);
|
||||
for (const pace of [Number.NaN, 0, -360, 1201]) {
|
||||
const facts = tourPlannerFacts(hike({ tourType: 'run', runPaceSecondsPerKm: pace, routeAnalysis: analysis }));
|
||||
expect(facts.runPaceInvalid).toBe(true);
|
||||
expect(facts.walkingDurationMinutes).toBeNull();
|
||||
}
|
||||
// Before the route is in, the time waits for it.
|
||||
expect(tourPlannerFacts(hike({ tourType: 'run', runPaceSecondsPerKm: 360 })).walkingDurationMinutes).toBeNull();
|
||||
// Another type carries neither, and is never held back by a pace.
|
||||
const bike = tourPlannerFacts(hike({ tourType: 'bike', runPaceSecondsPerKm: 360 }));
|
||||
expect(bike.typeFields).toMatchObject({ run_profile: null, run_pace_seconds_per_km: null });
|
||||
expect([bike.runPaceMissing, bike.runPaceInvalid]).toEqual([false, false]);
|
||||
const paddle = tourPlannerFacts(hike({ tourType: 'kayak', runPaceSecondsPerKm: 360 }));
|
||||
expect(paddle.typeFields).toMatchObject({ run_profile: null, run_pace_seconds_per_km: null });
|
||||
});
|
||||
|
||||
it('RUN-01: opens a saved run with its profile and pace, and any tour cached before them with none', () => {
|
||||
const run = { name: 'River loop', tour_type: 'run', run_profile: 'running', run_pace_seconds_per_km: 330 };
|
||||
expect(openedTourFields(run as Parameters<typeof openedTourFields>[0])).toMatchObject({
|
||||
tourType: 'run',
|
||||
runProfile: 'running',
|
||||
runPaceSecondsPerKm: 330,
|
||||
});
|
||||
const hikeOpened = openedTourFields({ name: 'Ridge', tour_type: 'hike' } as Parameters<typeof openedTourFields>[0]);
|
||||
expect(hikeOpened).toMatchObject({ runProfile: 'running', runPaceSecondsPerKm: null });
|
||||
});
|
||||
|
||||
it('holds the fields to their bounds, and a total that runs past a day without an override', () => {
|
||||
const facts = tourPlannerFacts(
|
||||
hike({ website: 'http://plain.example', plannedDurationMinutes: 1.5, breakAdditionalMinutes: -1 })
|
||||
@@ -237,4 +300,23 @@ describe('useTourDraftStorage', () => {
|
||||
localStorage.setItem('tour-draft-6', JSON.stringify({ ...draft, winterActivity: 'ski_tour' }));
|
||||
expect(renderHook(() => useTourDraftStorage(6)).result.current.restored).toBeNull();
|
||||
});
|
||||
|
||||
it('RUN-01: gives back a draft with its run profile and pace, and drops one it cannot read', () => {
|
||||
localStorage.clear();
|
||||
const draft = { version: 10, name: 'River loop', waypoints: [{ id: 'a', lat: 48, lng: 11, role: 'start' }] };
|
||||
const run = { ...draft, tourType: 'run', runProfile: 'running', runPaceSecondsPerKm: 345 };
|
||||
localStorage.setItem('tour-draft-7', JSON.stringify(run));
|
||||
expect(renderHook(() => useTourDraftStorage(7)).result.current.restored).toMatchObject({
|
||||
tourType: 'run',
|
||||
runProfile: 'running',
|
||||
runPaceSecondsPerKm: 345,
|
||||
});
|
||||
localStorage.setItem('tour-draft-8', JSON.stringify({ ...draft, runPaceSecondsPerKm: null }));
|
||||
const unpaced = renderHook(() => useTourDraftStorage(8)).result.current.restored;
|
||||
expect(unpaced).toMatchObject({ runPaceSecondsPerKm: null });
|
||||
localStorage.setItem('tour-draft-9', JSON.stringify({ ...draft, runProfile: 'sprint' }));
|
||||
expect(renderHook(() => useTourDraftStorage(9)).result.current.restored).toBeNull();
|
||||
localStorage.setItem('tour-draft-10', JSON.stringify({ ...draft, runPaceSecondsPerKm: -5 }));
|
||||
expect(renderHook(() => useTourDraftStorage(10)).result.current.restored).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,7 +12,7 @@ vi.mock('../../Map/valhallaRoute', () => ({
|
||||
valhallaTurn,
|
||||
}))
|
||||
|
||||
import { enrichTourElevations, parseValhallaElevation, routeBikeTour, routeCityWalk, routeWalkingTour, type TourRouteResult } from './tourRouting'
|
||||
import { enrichTourElevations, parseValhallaElevation, routeBikeTour, routeCityWalk, routeRun, routeWalkingTour, type TourRouteResult } from './tourRouting'
|
||||
|
||||
/** A route as the planner reads it, for the cases that expect one. */
|
||||
const route = async (...args: Parameters<typeof routeWalkingTour>) => (await routeWalkingTour(...args)) as TourRouteResult | null
|
||||
@@ -235,4 +235,14 @@ describe('routing on land, bike profiles and unreachable points (BIK-01)', () =>
|
||||
expect(await routeCityWalk(waypoints)).toMatchObject({ distanceMeters: 1500, durationSeconds: 300 })
|
||||
expect(valhallaRun).toHaveBeenCalledWith(waypoints, 'walking', [], undefined, { use_ferry: 0 })
|
||||
})
|
||||
|
||||
it('TOUR-ROUTING-034: a run goes on foot, keeps off tracks and ferries where it can, with no hiking limit (RUN-01)', async () => {
|
||||
valhallaRun.mockResolvedValueOnce(run([3, 4]))
|
||||
const signal = new AbortController().signal
|
||||
expect(await routeRun(waypoints, 'running', signal)).toMatchObject({ distanceMeters: 1500 })
|
||||
expect(valhallaRun).toHaveBeenCalledWith(waypoints, 'walking', [], signal, { use_tracks: 0, use_ferry: 0 })
|
||||
// A point no runnable way reaches is named, as for any tour on land.
|
||||
valhallaRun.mockResolvedValueOnce(run([3, 900]))
|
||||
expect(await routeRun(waypoints, 'running')).toEqual({ unreachable: 1, snappedMeters: 900 })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { BikeProfile, HikingPreferences, TourFixedLeg } from '@trek/shared'
|
||||
import type { BikeProfile, HikingPreferences, RunProfile, TourFixedLeg } from '@trek/shared'
|
||||
import type { Waypoint } from '../../../types'
|
||||
import { valhallaBase, valhallaRun, valhallaTurn, type CostingOptions } from '../../Map/valhallaRoute'
|
||||
import { densifyLine, lineLengthM } from './tourFixedLegs'
|
||||
@@ -119,6 +119,33 @@ export async function routeCityWalk(
|
||||
|
||||
const CITY_WALK_COSTING: Readonly<CostingOptions> = { use_ferry: 0 }
|
||||
|
||||
/**
|
||||
* RUN-01: what each run profile asks Valhalla's pedestrian costing for.
|
||||
* Running keeps to runnable, mostly paved ways: farm and forest tracks are
|
||||
* taken only where there is no other way (`use_tracks` 0), and a run is run,
|
||||
* so a ferry only where no way on land exists (`use_ferry` 0). Checked with
|
||||
* trace_attributes against the public instance on 20.10.2026 (shares of the
|
||||
* length): Berlin S Grunewald into the forest went from 95 % tracks with 3 %
|
||||
* paved to 67 % smooth paved paths over 3.58 km instead of 3.50 km; Munich
|
||||
* Großhesseloher Brücke to Pullach from 79 % to 88 % smooth asphalt and no
|
||||
* track left; Marienplatz to the Englischer Garten stayed as it was. No hiking
|
||||
* limit is sent, so the router keeps to the ways it takes for walking anyway
|
||||
* (T1). The router's own time is a walker's and is never used: a run's time is
|
||||
* its distance at the runner's pace. Nothing here says a way can be run.
|
||||
*/
|
||||
const RUN_COSTING: Record<RunProfile, Readonly<CostingOptions>> = {
|
||||
running: { use_tracks: 0, use_ferry: 0 },
|
||||
}
|
||||
|
||||
/** RUN-01: a run, on foot for its profile; a leg drawn by hand is kept as drawn. */
|
||||
export async function routeRun(
|
||||
waypoints: LandWaypoint[],
|
||||
profile: RunProfile,
|
||||
signal?: AbortSignal,
|
||||
): Promise<TourRouteResult | TourRouteUnreachable | null> {
|
||||
return routeOnLand(waypoints, 'walking', RUN_COSTING[profile], signal)
|
||||
}
|
||||
|
||||
/** BIK-01: a bike tour, routed for its profile; a leg drawn by hand is kept as drawn. */
|
||||
export async function routeBikeTour(
|
||||
waypoints: LandWaypoint[],
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const { routeWalkingTour, routeRun, enrichTourElevations, createTour, detailTour, updateTour } = vi.hoisted(() => ({
|
||||
routeWalkingTour: vi.fn(),
|
||||
routeRun: vi.fn(),
|
||||
enrichTourElevations: vi.fn(),
|
||||
createTour: vi.fn(),
|
||||
detailTour: vi.fn(),
|
||||
updateTour: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('./tourRouting', () => ({ routeWalkingTour, routeRun, enrichTourElevations }));
|
||||
vi.mock('../../../repo/tourRepo', () => ({ tourRepo: { create: createTour, detail: detailTour, update: updateTour } }));
|
||||
vi.mock('../useTourPermissions', () => ({ useTourPermissions: () => ({ canEdit: true, canAssign: true }) }));
|
||||
|
||||
import { useTourPlanner } from './useTourPlanner';
|
||||
|
||||
// FE-TOUR-RUN-001 to FE-TOUR-RUN-007
|
||||
|
||||
const routed = {
|
||||
coordinates: [
|
||||
[48, 11],
|
||||
[48.01, 11.02],
|
||||
] as [number, number][],
|
||||
distanceMeters: 1860,
|
||||
// A walker's time: a run never takes it.
|
||||
durationSeconds: 1500,
|
||||
};
|
||||
const enriched = [
|
||||
[48, 11, 520],
|
||||
[48.01, 11.02, 560],
|
||||
] as [number, number, number][];
|
||||
const savedRun = {
|
||||
place_id: 91,
|
||||
name: 'River loop',
|
||||
tour_type: 'run' as const,
|
||||
run_profile: 'running' as const,
|
||||
run_pace_seconds_per_km: 330,
|
||||
distance: 1.86,
|
||||
elevation_gain: 40,
|
||||
elevation_loss: 0,
|
||||
duration: 10,
|
||||
difficulty: null,
|
||||
wanderer_ref: null,
|
||||
match_confidence: 1,
|
||||
max_hiking_difficulty: null,
|
||||
planned: true,
|
||||
caution: false,
|
||||
revision: 3,
|
||||
};
|
||||
const savedPoints = [
|
||||
{ lat: 48, lng: 11, role: 'start' as const, sequence: 0 },
|
||||
{ lat: 48.01, lng: 11.02, role: 'end' as const, sequence: 1 },
|
||||
];
|
||||
|
||||
async function settle() {
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(450);
|
||||
});
|
||||
}
|
||||
|
||||
async function plannedRun(tripId: number) {
|
||||
const hook = renderHook(() => useTourPlanner({ tripId }));
|
||||
act(() => {
|
||||
hook.result.current.setName('River loop');
|
||||
hook.result.current.setTourType('run');
|
||||
hook.result.current.addWaypoint(48, 11);
|
||||
hook.result.current.addWaypoint(48.01, 11.02);
|
||||
});
|
||||
await settle();
|
||||
return hook;
|
||||
}
|
||||
|
||||
describe("useTourPlanner, a run at the runner's own pace (RUN-01)", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
localStorage.clear();
|
||||
routeWalkingTour.mockReset().mockResolvedValue(routed);
|
||||
routeRun.mockReset().mockResolvedValue(routed);
|
||||
enrichTourElevations.mockReset().mockResolvedValue(enriched);
|
||||
createTour.mockReset();
|
||||
detailTour.mockReset();
|
||||
updateTour.mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it('FE-TOUR-RUN-001: a run is routed on foot for its profile, and has no time and no save until a pace is entered', async () => {
|
||||
const { result } = await plannedRun(71);
|
||||
expect(result.current.isRun).toBe(true);
|
||||
expect(result.current.runProfile).toBe('running');
|
||||
expect(routeRun).toHaveBeenCalledWith(expect.any(Array), 'running', expect.any(AbortSignal));
|
||||
expect(routeWalkingTour).not.toHaveBeenCalled();
|
||||
expect(result.current.status).toBe('ready');
|
||||
// No pace of TREK's own: the time stays unknown and the router's walking time never stands in.
|
||||
expect(result.current.runPace.paceSecondsPerKm).toBeNull();
|
||||
expect(result.current.walkingDurationMinutes).toBeNull();
|
||||
expect(result.current.runPaceMissing).toBe(true);
|
||||
expect(result.current.canSave).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-TOUR-RUN-002: the time is the distance at the pace, and a new pace plans nothing again', async () => {
|
||||
const { result } = await plannedRun(72);
|
||||
routeRun.mockClear();
|
||||
act(() => result.current.runPace.setPace(360));
|
||||
await settle();
|
||||
const distanceKm = result.current.routeAnalysis?.distanceKm ?? 0;
|
||||
expect(distanceKm).toBeGreaterThan(1);
|
||||
expect(result.current.walkingDurationMinutes).toBe(Math.round(distanceKm * 6));
|
||||
expect(result.current.plannedTotalMinutes).toBe(Math.round(distanceKm * 6));
|
||||
expect(routeRun).not.toHaveBeenCalled();
|
||||
expect(result.current.canSave).toBe(true);
|
||||
act(() => result.current.runPace.setPace(300));
|
||||
expect(result.current.walkingDurationMinutes).toBe(Math.round(distanceKm * 5));
|
||||
});
|
||||
|
||||
it('FE-TOUR-RUN-003: a pace that is no pace, or out of bounds, holds Save back', async () => {
|
||||
const { result } = await plannedRun(73);
|
||||
act(() => result.current.runPace.setPace(Number.NaN));
|
||||
expect(result.current.runPaceInvalid).toBe(true);
|
||||
expect(result.current.walkingDurationMinutes).toBeNull();
|
||||
expect(result.current.canSave).toBe(false);
|
||||
act(() => result.current.runPace.setPace(90));
|
||||
expect(result.current.runPaceInvalid).toBe(true);
|
||||
expect(result.current.canSave).toBe(false);
|
||||
act(() => result.current.runPace.setPace(420));
|
||||
expect(result.current.runPaceInvalid).toBe(false);
|
||||
expect(result.current.canSave).toBe(true);
|
||||
});
|
||||
|
||||
it('FE-TOUR-RUN-004: saves the type, profile, pace and planned time with the route', async () => {
|
||||
createTour.mockResolvedValue({ tour: savedRun, waypoints: savedPoints });
|
||||
const { result } = await plannedRun(74);
|
||||
act(() => result.current.runPace.setPace(330));
|
||||
await act(async () => {
|
||||
await result.current.save();
|
||||
});
|
||||
const minutes = result.current.walkingDurationMinutes ?? 0;
|
||||
expect(createTour).toHaveBeenCalledWith(
|
||||
74,
|
||||
expect.objectContaining({
|
||||
tour_type: 'run',
|
||||
run_profile: 'running',
|
||||
run_pace_seconds_per_km: 330,
|
||||
max_hiking_difficulty: null,
|
||||
bike_profile: null,
|
||||
winter_activity: null,
|
||||
duration_seconds: minutes * 60,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-TOUR-RUN-005: opens a saved run with its profile and pace, and another type saves neither', async () => {
|
||||
detailTour.mockResolvedValue({ tour: savedRun, waypoints: savedPoints });
|
||||
updateTour.mockResolvedValue({ tour: { ...savedRun, tour_type: 'hike', revision: 4 }, waypoints: savedPoints });
|
||||
const { result } = renderHook(() => useTourPlanner({ tripId: 75 }));
|
||||
await act(async () => {
|
||||
await result.current.openTour({ place_id: 91 });
|
||||
});
|
||||
expect(result.current.tourType).toBe('run');
|
||||
expect(result.current.runProfile).toBe('running');
|
||||
expect(result.current.runPace.paceSecondsPerKm).toBe(330);
|
||||
expect(result.current.hasUnsavedChanges).toBe(false);
|
||||
// The same pace again, or the same profile, is no edit.
|
||||
act(() => {
|
||||
result.current.runPace.setPace(330);
|
||||
result.current.setRunProfile('running');
|
||||
});
|
||||
expect(result.current.hasUnsavedChanges).toBe(false);
|
||||
act(() => result.current.setTourType('hike'));
|
||||
await settle();
|
||||
await act(async () => {
|
||||
await result.current.save();
|
||||
});
|
||||
expect(updateTour).toHaveBeenCalledWith(
|
||||
75,
|
||||
91,
|
||||
expect.objectContaining({ tour_type: 'hike', run_profile: null, run_pace_seconds_per_km: null })
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-TOUR-RUN-006: a draft comes back as a run with its pace, and a new tour starts as a hike without one', () => {
|
||||
const first = renderHook(() => useTourPlanner({ tripId: 76 }));
|
||||
act(() => {
|
||||
first.result.current.setTourType('run');
|
||||
first.result.current.runPace.setPace(345);
|
||||
});
|
||||
first.unmount();
|
||||
expect(JSON.parse(localStorage.getItem('tour-draft-76') || 'null')).toMatchObject({
|
||||
tourType: 'run',
|
||||
runProfile: 'running',
|
||||
runPaceSecondsPerKm: 345,
|
||||
});
|
||||
const again = renderHook(() => useTourPlanner({ tripId: 76 }));
|
||||
expect(again.result.current.tourType).toBe('run');
|
||||
expect(again.result.current.runPace.paceSecondsPerKm).toBe(345);
|
||||
act(() => again.result.current.startNewTour(true));
|
||||
expect(again.result.current.tourType).toBe('hike');
|
||||
expect(again.result.current.runPace.paceSecondsPerKm).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-TOUR-RUN-007: choosing run is one step of the history and the pace none of it', () => {
|
||||
const { result } = renderHook(() => useTourPlanner({ tripId: 77 }));
|
||||
act(() => result.current.setTourType('run'));
|
||||
act(() => result.current.runPace.setPace(360));
|
||||
act(() => result.current.undo());
|
||||
expect(result.current.tourType).toBe('hike');
|
||||
expect(result.current.runPace.paceSecondsPerKm).toBe(360);
|
||||
act(() => result.current.redo());
|
||||
expect(result.current.tourType).toBe('run');
|
||||
expect(result.current.runProfile).toBe('running');
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { hikingPreferencesOf, isClosedLoop, paddleSpeedKmhSchema, tourWebsiteSchema, type BikeProfile, type HikingPreferences, type PlannableTourType, type TourCreateResponse, type TourFixedLeg, type TourListItem, type TourMaxHikingDifficulty, type WinterActivity } from '@trek/shared'
|
||||
import { hikingPreferencesOf, isClosedLoop, paddleSpeedKmhSchema, tourWebsiteSchema, type BikeProfile, type HikingPreferences, type PlannableTourType, type RunProfile, type TourCreateResponse, type TourFixedLeg, type TourListItem, type TourMaxHikingDifficulty, type WinterActivity } from '@trek/shared'
|
||||
import { paddleRouteRepo } from '../../../repo/paddleRouteRepo'
|
||||
import { tourRepo } from '../../../repo/tourRepo'
|
||||
import { randomId } from '../../../utils/randomId'
|
||||
@@ -19,6 +19,7 @@ import { paddleEstimateOf } from './paddlePlanOf'
|
||||
import { adoptChangedPoints } from './paddleRouting'
|
||||
import { NO_PADDLE_FIELDS, paddleFieldsOf, usePaddleFields, type PaddleFieldValues } from './usePaddleFields'
|
||||
import { useTourPermissions, type TourPermissionProps } from '../useTourPermissions'
|
||||
import { useRunPace } from '../run/useRunPace'
|
||||
|
||||
/** What a tour planned from an import starts with. */
|
||||
export interface DerivedTourDraft {
|
||||
@@ -37,10 +38,11 @@ export interface DerivedTourDraft {
|
||||
inPlace: boolean
|
||||
/** P2C-03: the import's revision, which a save planned over in place names. */
|
||||
revision?: number
|
||||
/** A paddle import stays a paddle tour, with its boat and water, and a bike import a bike tour with its profile. */
|
||||
/** A paddle import stays a paddle tour, with its boat and water, and a bike or run import its type with its profile. */
|
||||
tourType?: PlannableTourType
|
||||
paddle?: PaddleFieldValues
|
||||
bikeProfile?: BikeProfile
|
||||
runProfile?: RunProfile
|
||||
/** CW-07: where the points came from, said in the planner until the draft is saved. */
|
||||
source?: DraftSource
|
||||
}
|
||||
@@ -59,7 +61,7 @@ export type TourPlannerStatus =
|
||||
/** One step of the history: the route, and what the route depends on. */
|
||||
interface HistoryEntry {
|
||||
waypoints: TourPlannerWaypoint[]; difficulty: TourMaxHikingDifficulty; preferences: HikingPreferences | null; bikeProfile: BikeProfile
|
||||
tourType: PlannableTourType
|
||||
runProfile: RunProfile; tourType: PlannableTourType
|
||||
}
|
||||
|
||||
/** CW-02: two steps plan the same route: their points alike but for a station's own fields, and the same choices. */
|
||||
@@ -124,6 +126,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
const [hikingPreferences, setHikingPreferencesState] = useState<HikingPreferences | null>(restored?.hikingPreferences ?? null)
|
||||
const [bikeProfile, setBikeProfileState] = useState<BikeProfile>(restored?.bikeProfile ?? 'touring')
|
||||
const [winterActivity, setWinterActivityState] = useState<WinterActivity | null>(restored?.winterActivity ?? null)
|
||||
const [runProfile, setRunProfileState] = useState<RunProfile>(restored?.runProfile ?? 'running')
|
||||
const [tourType, setTourTypeState] = useState<PlannableTourType>(restored?.tourType ?? 'hike')
|
||||
const [selectedWaypointId, setSelectedWaypointId] = useState<string | null>(restored?.waypoints[0]?.id ?? null)
|
||||
const history = usePlannerHistory<HistoryEntry>()
|
||||
@@ -171,12 +174,13 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
const difficultyRef = useRef(maxHikingDifficulty)
|
||||
const preferencesRef = useRef(hikingPreferences)
|
||||
const bikeProfileRef = useRef(bikeProfile)
|
||||
const runProfileRef = useRef(runProfile)
|
||||
const tourTypeRef = useRef(tourType)
|
||||
waypointsRef.current = waypoints
|
||||
difficultyRef.current = maxHikingDifficulty
|
||||
const snapshot = useCallback((): HistoryEntry => ({
|
||||
waypoints: waypointsRef.current, difficulty: difficultyRef.current, preferences: preferencesRef.current,
|
||||
bikeProfile: bikeProfileRef.current, tourType: tourTypeRef.current,
|
||||
bikeProfile: bikeProfileRef.current, runProfile: runProfileRef.current, tourType: tourTypeRef.current,
|
||||
}), [])
|
||||
|
||||
useEffect(() => {
|
||||
@@ -221,6 +225,8 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
}, [invalidateDetailRequest])
|
||||
|
||||
const paddle = usePaddleFields(restored?.paddle ?? NO_PADDLE_FIELDS, markEdited)
|
||||
const runPace = useRunPace(restored?.runPaceSecondsPerKm ?? null, markEdited)
|
||||
const loadRunPace = runPace.load
|
||||
const loadPaddle = paddle.load
|
||||
const paddleBoat = paddle.boatType
|
||||
// The router's own default where the tour names none, so a plan and its cache key agree.
|
||||
@@ -233,7 +239,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
}, [])
|
||||
const forgetFocus = useCallback(() => setRouteProfileFocus(null), [])
|
||||
const routing = useTourRoute({
|
||||
tripId, waypoints, tourType, maxHikingDifficulty, hikingPreferences, bikeProfile, paddleBoat, paddleLakeStyle, retryToken,
|
||||
tripId, waypoints, tourType, maxHikingDifficulty, hikingPreferences, bikeProfile, runProfile, paddleBoat, paddleLakeStyle, retryToken,
|
||||
error, setStatus, setError, onCleared: forgetFocus, patchWaypoints,
|
||||
})
|
||||
const { route, routeParts, paddleRoute, enrichedGeometry, routeCurrent, distanceMeters, durationSeconds,
|
||||
@@ -279,16 +285,17 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
|
||||
/**
|
||||
* The routing choices, as one step of the history: a hike's limit and its
|
||||
* preferences (MF-08), a bike tour's profile (BIK-01). The route is planned again.
|
||||
* preferences (MF-08), a bike tour's profile (BIK-01), a run's (RUN-01). The route is planned again.
|
||||
*/
|
||||
const setRoutingChoice = useCallback((change: {
|
||||
difficulty?: TourMaxHikingDifficulty; preferences?: HikingPreferences | null; bikeProfile?: BikeProfile
|
||||
difficulty?: TourMaxHikingDifficulty; preferences?: HikingPreferences | null; bikeProfile?: BikeProfile; runProfile?: RunProfile
|
||||
}) => {
|
||||
if (!editPermissionRef.current) return
|
||||
const difficulty = change.difficulty ?? difficultyRef.current
|
||||
const preferences = change.preferences === undefined ? preferencesRef.current : hikingPreferencesOf(change.preferences)
|
||||
const profile = change.bikeProfile ?? bikeProfileRef.current
|
||||
if (difficulty === difficultyRef.current && profile === bikeProfileRef.current
|
||||
const run = change.runProfile ?? runProfileRef.current
|
||||
if (difficulty === difficultyRef.current && profile === bikeProfileRef.current && run === runProfileRef.current
|
||||
&& JSON.stringify(preferences) === JSON.stringify(preferencesRef.current)) return
|
||||
invalidateDetailRequest()
|
||||
interruptRouting()
|
||||
@@ -297,9 +304,11 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
difficultyRef.current = difficulty
|
||||
preferencesRef.current = preferences
|
||||
bikeProfileRef.current = profile
|
||||
runProfileRef.current = run
|
||||
setMaxHikingDifficultyState(difficulty)
|
||||
setHikingPreferencesState(preferences)
|
||||
setBikeProfileState(profile)
|
||||
setRunProfileState(run)
|
||||
setHasUnsavedChanges(true)
|
||||
setSaveOutcome(null)
|
||||
setStatus('dirty')
|
||||
@@ -308,6 +317,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
const setMaxHikingDifficulty = useCallback((difficulty: TourMaxHikingDifficulty) => setRoutingChoice({ difficulty }), [setRoutingChoice])
|
||||
const setHikingPreferences = useCallback((preferences: HikingPreferences | null) => setRoutingChoice({ preferences }), [setRoutingChoice])
|
||||
const setBikeProfile = useCallback((profile: BikeProfile) => setRoutingChoice({ bikeProfile: profile }), [setRoutingChoice])
|
||||
const setRunProfile = useCallback((profile: RunProfile) => setRoutingChoice({ runProfile: profile }), [setRoutingChoice])
|
||||
|
||||
const addWaypoint = useCallback((lat: number, lng: number) => {
|
||||
if (!editPermissionRef.current) return
|
||||
@@ -420,11 +430,13 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
difficultyRef.current = entry.difficulty
|
||||
preferencesRef.current = entry.preferences
|
||||
bikeProfileRef.current = entry.bikeProfile
|
||||
runProfileRef.current = entry.runProfile
|
||||
tourTypeRef.current = entry.tourType
|
||||
setWaypoints(entry.waypoints)
|
||||
setMaxHikingDifficultyState(entry.difficulty)
|
||||
setHikingPreferencesState(entry.preferences)
|
||||
setBikeProfileState(entry.bikeProfile)
|
||||
setRunProfileState(entry.runProfile)
|
||||
setTourTypeState(entry.tourType)
|
||||
setSelectedWaypointId(id => entry.waypoints.some(point => point.id === id) ? id : entry.waypoints[0]?.id ?? null)
|
||||
setHasUnsavedChanges(true)
|
||||
@@ -474,9 +486,9 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
|
||||
|
||||
/**
|
||||
* PAD-01, BIK-01: hike, bike or paddle tour, as one step of the history with
|
||||
* the route, since a paddle tour draws every leg by hand and a bike tour
|
||||
* rides no via ferrata. Nothing is put on a day by the choice itself.
|
||||
* 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.
|
||||
*/
|
||||
const setTourType = useCallback((value: PlannableTourType) => {
|
||||
if (!editPermissionRef.current || saveInFlightRef.current || value === tourTypeRef.current) return
|
||||
@@ -486,7 +498,8 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
recordStep(snapshot())
|
||||
tourTypeRef.current = value
|
||||
setTourTypeState(value)
|
||||
const next = normalizePlannerWaypoints(value === 'bike' ? ridablePoints(waypointsRef.current) : waypointsRef.current, value === 'kayak')
|
||||
const noFerrata = value === 'bike' || value === 'run'
|
||||
const next = normalizePlannerWaypoints(noFerrata ? ridablePoints(waypointsRef.current) : waypointsRef.current, value === 'kayak')
|
||||
waypointsRef.current = next
|
||||
setWaypoints(next)
|
||||
setHasUnsavedChanges(true)
|
||||
@@ -508,15 +521,19 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
[effectiveSpeedKmh, isPaddle, paddleSpeedInvalid, portageSpeedKmh, routedLegLengths, waypoints])
|
||||
// CW-02: a city walk's stays, what of them is known.
|
||||
const stays = useMemo(() => (tourType === 'walk' ? walkTimes(waypoints, null) : null), [tourType, waypoints])
|
||||
const runPaceSecondsPerKm = runPace.paceSecondsPerKm
|
||||
const facts = useMemo(() => tourPlannerFacts({
|
||||
tourType, maxHikingDifficulty, hikingPreferences, bikeProfile, winterActivity, website, plannedDurationMinutes, breakAdditionalMinutes,
|
||||
tourType, maxHikingDifficulty, hikingPreferences, bikeProfile, winterActivity, runProfile, runPaceSecondsPerKm, website,
|
||||
plannedDurationMinutes, breakAdditionalMinutes,
|
||||
paddle: { boatType, waterContext, speedKmh, portageSpeedKmh, lakeStyle },
|
||||
paddleSpeedInvalid, paddleEstimate, routeAnalysis, durationSeconds, stays,
|
||||
}), [bikeProfile, boatType, breakAdditionalMinutes, durationSeconds, hikingPreferences, lakeStyle, maxHikingDifficulty, paddleEstimate, paddleSpeedInvalid,
|
||||
plannedDurationMinutes, portageSpeedKmh, routeAnalysis, speedKmh, stays, tourType, waterContext, website, winterActivity])
|
||||
plannedDurationMinutes, portageSpeedKmh, routeAnalysis, runPaceSecondsPerKm, runProfile, speedKmh, stays, tourType, waterContext, website,
|
||||
winterActivity])
|
||||
// CW-02: a city walk's times as the overview says them, from the same derivation as its planned total.
|
||||
const { websiteInvalid, plannedDurationInvalid, breakAdditionalInvalid, paddleIncomplete, walkingDurationMinutes,
|
||||
plannedTotalMinutes, plannedTotalInvalid, savedDurationSeconds, savedBreakAdditionalMinutes, typeFields, stationStays } = facts
|
||||
plannedTotalMinutes, plannedTotalInvalid, savedDurationSeconds, savedBreakAdditionalMinutes, typeFields, stationStays,
|
||||
runPaceMissing, runPaceInvalid } = facts
|
||||
|
||||
const returnToNeutral = useCallback(() => {
|
||||
if (saveInFlightRef.current) return
|
||||
@@ -541,6 +558,9 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
setHikingPreferencesState(null)
|
||||
bikeProfileRef.current = 'touring'
|
||||
setBikeProfileState('touring')
|
||||
runProfileRef.current = 'running'
|
||||
setRunProfileState('running')
|
||||
loadRunPace(null)
|
||||
setWinterActivityState(null)
|
||||
tourTypeRef.current = 'hike'
|
||||
setSelectedWaypointId(null)
|
||||
@@ -563,7 +583,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
setElevationProfileExpanded(true)
|
||||
setNewDraftGeneration(generation => generation + 1)
|
||||
setMapFocusKey(key => key + 1)
|
||||
}, [adoptRevision, clearHistory, clearRoute, invalidateDetailRequest, interruptRouting, loadPaddle, forgetDraft])
|
||||
}, [adoptRevision, clearHistory, clearRoute, invalidateDetailRequest, interruptRouting, loadPaddle, loadRunPace, forgetDraft])
|
||||
|
||||
const forgetDeletedTour = useCallback((placeId: number) => {
|
||||
deletedTourPlaceIdsRef.current.add(placeId)
|
||||
@@ -615,6 +635,10 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
bikeProfileRef.current = draft.bikeProfile
|
||||
setBikeProfileState(draft.bikeProfile)
|
||||
}
|
||||
if (draft.runProfile) {
|
||||
runProfileRef.current = draft.runProfile
|
||||
setRunProfileState(draft.runProfile)
|
||||
}
|
||||
setNameState(draft.name)
|
||||
setDescriptionState(draft.description ?? '')
|
||||
setWebsiteState(draft.website ?? '')
|
||||
@@ -712,6 +736,9 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
setHikingPreferencesState(opened.preferences)
|
||||
bikeProfileRef.current = opened.bikeProfile
|
||||
setBikeProfileState(opened.bikeProfile)
|
||||
runProfileRef.current = opened.runProfile
|
||||
setRunProfileState(opened.runProfile)
|
||||
loadRunPace(opened.runPaceSecondsPerKm)
|
||||
setWinterActivityState(opened.winterActivity)
|
||||
tourTypeRef.current = opened.tourType
|
||||
setSelectedWaypointId(nextWaypoints[0]?.id ?? null)
|
||||
@@ -741,7 +768,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
setOpeningTourId(null)
|
||||
}
|
||||
}
|
||||
}, [adoptRevision, clearHistory, clearRoute, interruptRouting, loadPaddle, forgetDraft, tripId])
|
||||
}, [adoptRevision, clearHistory, clearRoute, interruptRouting, loadPaddle, loadRunPace, forgetDraft, tripId])
|
||||
|
||||
const retry = useCallback(() => {
|
||||
if (waypointsRef.current.length < 2) return
|
||||
@@ -773,13 +800,14 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
if (!hasUnsavedChanges) return
|
||||
const draft: DraftPayload = { version: 10, name, description, website, plannedDurationMinutes, breakAdditionalMinutes, waypoints, maxHikingDifficulty, editingPlaceId,
|
||||
derivedFromPlaceId, draftSource, tourType, baseRevision: revision.base, hikingPreferences, bikeProfile, winterActivity,
|
||||
runProfile, runPaceSecondsPerKm,
|
||||
paddle: { boatType: paddle.boatType, waterContext: paddle.waterContext, speedKmh: paddle.speedKmh, portageSpeedKmh: paddle.portageSpeedKmh, lakeStyle: paddle.lakeStyle },
|
||||
}
|
||||
keepDraft(draft)
|
||||
}, [breakAdditionalMinutes,
|
||||
derivedFromPlaceId, draftSource, description, editingPlaceId, hasUnsavedChanges, maxHikingDifficulty, name, plannedDurationMinutes, keepDraft, waypoints, website,
|
||||
tourType, paddle.boatType, paddle.waterContext, paddle.speedKmh, paddle.portageSpeedKmh, paddle.lakeStyle, revision.base, hikingPreferences,
|
||||
bikeProfile, winterActivity])
|
||||
bikeProfile, winterActivity, runProfile, runPaceSecondsPerKm])
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasUnsavedChanges) return
|
||||
@@ -791,7 +819,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
const canSave = canEdit && !isSaving && hasUnsavedChanges && name.trim().length > 0 && status === 'ready'
|
||||
&& routeCurrent && hasCompleteElevation(enrichedGeometry)
|
||||
&& description.length <= 2000 && !websiteInvalid && !plannedDurationInvalid && !breakAdditionalInvalid && !plannedTotalInvalid
|
||||
&& !paddleIncomplete && !(isPaddle && paddleSpeedInvalid)
|
||||
&& !paddleIncomplete && !(isPaddle && paddleSpeedInvalid) && !runPaceMissing && !runPaceInvalid
|
||||
|
||||
/**
|
||||
* Saves the draft: over the tour it edits, naming the revision it was loaded
|
||||
@@ -880,6 +908,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
tripId, canEdit, canAssign,
|
||||
name, setName, maxHikingDifficulty, setMaxHikingDifficulty, hikingPreferences, setHikingPreferences,
|
||||
bikeProfile, setBikeProfile, isBike: tourType === 'bike', winterActivity, setWinterActivity,
|
||||
runProfile, setRunProfile, isRun: tourType === 'run', runPace, runPaceMissing, runPaceInvalid,
|
||||
tourType, setTourType, isPaddle, paddle, paddleSpeedInvalid, paddleIncomplete,
|
||||
description, setDescription, website, setWebsite, websiteInvalid,
|
||||
plannedDurationMinutes, setPlannedDurationMinutes, plannedDurationInvalid,
|
||||
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
PaddleBoatType,
|
||||
PaddleLakeStyle,
|
||||
PlannableTourType,
|
||||
RunProfile,
|
||||
TourMaxHikingDifficulty,
|
||||
} from '@trek/shared';
|
||||
import {
|
||||
@@ -29,6 +30,7 @@ import {
|
||||
enrichTourElevations,
|
||||
routeBikeTour,
|
||||
routeCityWalk,
|
||||
routeRun,
|
||||
routeWalkingTour,
|
||||
type TourElevationPoint,
|
||||
type TourRoutePart,
|
||||
@@ -45,6 +47,8 @@ export interface TourRouteInputs {
|
||||
maxHikingDifficulty: TourMaxHikingDifficulty;
|
||||
hikingPreferences: HikingPreferences | null;
|
||||
bikeProfile: BikeProfile;
|
||||
/** RUN-01: the profile a run is routed for. */
|
||||
runProfile: RunProfile;
|
||||
paddleBoat: PaddleBoatType | null;
|
||||
paddleLakeStyle: PaddleLakeStyle;
|
||||
/** Raised to plan the same points again. */
|
||||
@@ -124,16 +128,23 @@ async function routePaddle({ inputs, plannedKey, runKey, signal, stale, setPlann
|
||||
setError(failed ? 'paddle-route' : null);
|
||||
}
|
||||
|
||||
// A hike or a bike tour on land, then the heights along it.
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
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);
|
||||
}
|
||||
|
||||
// A hike, a run or a bike tour on land, then the heights along it.
|
||||
async function routeOnLand({ inputs, plannedKey, runKey, signal, stale, setPlanned, setUnreachable }: RouteRun) {
|
||||
const { waypoints, tourType, bikeProfile, maxHikingDifficulty, hikingPreferences, setStatus, setError } = inputs;
|
||||
const { setStatus, setError } = inputs;
|
||||
setStatus('routing');
|
||||
const routed =
|
||||
tourType === 'bike'
|
||||
? await routeBikeTour(waypoints, bikeProfile, signal)
|
||||
: tourType === 'walk'
|
||||
? await routeCityWalk(waypoints, signal)
|
||||
: await routeWalkingTour(waypoints, signal, maxHikingDifficulty, hikingPreferences);
|
||||
const routed = await routeLand(inputs, signal);
|
||||
if (stale()) return;
|
||||
if (!isTourRoute(routed)) {
|
||||
setUnreachable(routed);
|
||||
@@ -168,9 +179,9 @@ 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 for its
|
||||
* profile (BIK-01), a paddle tour on the water by the server's router. A hike
|
||||
* and a bike tour then get their heights; a later change makes an answer
|
||||
* 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.
|
||||
*/
|
||||
export function useTourRoute(inputs: TourRouteInputs) {
|
||||
@@ -181,6 +192,7 @@ export function useTourRoute(inputs: TourRouteInputs) {
|
||||
maxHikingDifficulty,
|
||||
hikingPreferences,
|
||||
bikeProfile,
|
||||
runProfile,
|
||||
paddleBoat,
|
||||
paddleLakeStyle,
|
||||
retryToken,
|
||||
@@ -208,7 +220,15 @@ export function useTourRoute(inputs: TourRouteInputs) {
|
||||
|
||||
const waypointKey = useMemo(() => tourWaypointKey(waypoints), [waypoints]);
|
||||
// What a route was planned for besides its points: a route of another type or profile is not this one's.
|
||||
const choices = [tourType, bikeProfile, maxHikingDifficulty, hikingPreferences, paddleBoat, paddleLakeStyle];
|
||||
const choices = [
|
||||
tourType,
|
||||
bikeProfile,
|
||||
runProfile,
|
||||
maxHikingDifficulty,
|
||||
hikingPreferences,
|
||||
paddleBoat,
|
||||
paddleLakeStyle,
|
||||
];
|
||||
const plannedKey = `${waypointKey}#${JSON.stringify(choices)}`;
|
||||
// CW-02, CW-03: a station's own fields and the keys a save answered are no part of what a route is planned from,
|
||||
// so a change to them alone plans nothing again.
|
||||
@@ -247,6 +267,7 @@ export function useTourRoute(inputs: TourRouteInputs) {
|
||||
maxHikingDifficulty,
|
||||
hikingPreferences,
|
||||
bikeProfile,
|
||||
runProfile,
|
||||
paddleBoat,
|
||||
paddleLakeStyle,
|
||||
setStatus,
|
||||
@@ -287,6 +308,7 @@ export function useTourRoute(inputs: TourRouteInputs) {
|
||||
retryToken,
|
||||
routeInputs,
|
||||
runKey,
|
||||
runProfile,
|
||||
setError,
|
||||
setStatus,
|
||||
tourType,
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { useState, type ComponentProps } from 'react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { RunFields, RunProfileField } from './RunFields';
|
||||
import { runPaceInvalid } from './runPace';
|
||||
|
||||
// FE-TOUR-RUN-FIELDS-001 to FE-TOUR-RUN-FIELDS-006
|
||||
|
||||
type Planner = ComponentProps<typeof RunFields>['planner'];
|
||||
|
||||
const analysis = { distanceKm: 8 } as Planner['routeAnalysis'];
|
||||
|
||||
/** The fields over a planner that keeps the pace it is given and times it as the real one does. */
|
||||
function Stateful({
|
||||
initial = null,
|
||||
distance = analysis,
|
||||
}: {
|
||||
initial?: number | null;
|
||||
distance?: Planner['routeAnalysis'];
|
||||
}) {
|
||||
const [pace, setPace] = useState<number | null>(initial);
|
||||
const invalid = runPaceInvalid(pace);
|
||||
const planner: Planner = {
|
||||
runProfile: 'running',
|
||||
setRunProfile: vi.fn(),
|
||||
runPace: { paceSecondsPerKm: pace, setPace, load: setPace },
|
||||
runPaceMissing: pace === null,
|
||||
runPaceInvalid: invalid,
|
||||
routeAnalysis: distance,
|
||||
walkingDurationMinutes:
|
||||
pace === null || invalid || !distance ? null : Math.round((distance.distanceKm * pace) / 60),
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<RunFields planner={planner} locked={false} />
|
||||
<output data-testid="pace">{pace === null ? 'none' : String(pace)}</output>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const paceField = () => screen.getByRole('textbox');
|
||||
|
||||
describe('RunFields (RUN-01)', () => {
|
||||
it('FE-TOUR-RUN-FIELDS-001: offers the profile on purpose, with what it asks the router for', () => {
|
||||
const onChange = vi.fn();
|
||||
render(<RunProfileField value="running" onChange={onChange} />);
|
||||
const running = screen.getByRole('button', { name: 'tours.run.profile.running' });
|
||||
expect(running).toHaveAttribute('aria-pressed', 'true');
|
||||
expect(screen.getByText('tours.run.profileHint.running')).toBeInTheDocument();
|
||||
fireEvent.click(running);
|
||||
expect(onChange).toHaveBeenCalledWith('running');
|
||||
});
|
||||
|
||||
it('FE-TOUR-RUN-FIELDS-002: asks for a pace without offering one, and says a run is saved with one', () => {
|
||||
render(<Stateful />);
|
||||
expect(paceField()).toHaveValue('');
|
||||
expect(paceField()).toHaveAttribute('placeholder', '0:00');
|
||||
expect(screen.getByText('min/km')).toBeInTheDocument();
|
||||
expect(screen.getByRole('status')).toHaveTextContent('tours.run.paceNeeded');
|
||||
expect(screen.queryByTestId('tour-run-time-sum')).toBeNull();
|
||||
expect(screen.getByRole('button', { name: 'tours.run.paceInfoLabel' })).toHaveAccessibleDescription(
|
||||
'tours.run.paceInfo'
|
||||
);
|
||||
});
|
||||
|
||||
it('FE-TOUR-RUN-FIELDS-003: a pace typed shows the sum the time is: 8 km at 6:00 min/km is 48 minutes', () => {
|
||||
render(<Stateful />);
|
||||
fireEvent.focus(paceField());
|
||||
fireEvent.change(paceField(), { target: { value: '6:00' } });
|
||||
expect(screen.getByTestId('pace')).toHaveTextContent('360');
|
||||
const sum = screen.getByTestId('tour-run-time-sum');
|
||||
expect(sum).toHaveTextContent('8 km');
|
||||
expect(sum).toHaveTextContent('6:00 /km');
|
||||
expect(sum).toHaveTextContent('48 min');
|
||||
expect(sum).toHaveAttribute('aria-label', 'tours.run.timeSum');
|
||||
expect(screen.queryByRole('status')).toBeNull();
|
||||
fireEvent.blur(paceField());
|
||||
expect(paceField()).toHaveValue('6:00');
|
||||
});
|
||||
|
||||
it('FE-TOUR-RUN-FIELDS-004: text that is no pace is kept and marked on leaving the field, and the sum goes', () => {
|
||||
render(<Stateful initial={360} />);
|
||||
fireEvent.focus(paceField());
|
||||
fireEvent.change(paceField(), { target: { value: '6:75' } });
|
||||
// While typing, the last readable pace stands.
|
||||
expect(screen.getByTestId('pace')).toHaveTextContent('360');
|
||||
fireEvent.blur(paceField());
|
||||
expect(screen.getByTestId('pace')).toHaveTextContent('NaN');
|
||||
expect(paceField()).toHaveValue('6:75');
|
||||
expect(paceField()).toHaveAttribute('aria-invalid', 'true');
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('tours.run.paceInvalid');
|
||||
expect(screen.queryByTestId('tour-run-time-sum')).toBeNull();
|
||||
// Back in the field, the text is there to fix, and a pace fixes it.
|
||||
fireEvent.focus(paceField());
|
||||
expect(paceField()).toHaveValue('6:75');
|
||||
fireEvent.change(paceField(), { target: { value: '6:15' } });
|
||||
fireEvent.blur(paceField());
|
||||
expect(screen.getByTestId('pace')).toHaveTextContent('375');
|
||||
expect(screen.queryByRole('alert')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-TOUR-RUN-FIELDS-005: a pace out of bounds is marked, and clearing the field leaves no pace', () => {
|
||||
render(<Stateful />);
|
||||
fireEvent.focus(paceField());
|
||||
fireEvent.change(paceField(), { target: { value: '1:30' } });
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('tours.run.paceInvalid');
|
||||
fireEvent.change(paceField(), { target: { value: '' } });
|
||||
fireEvent.keyDown(paceField(), { key: 'Enter' });
|
||||
expect(screen.getByTestId('pace')).toHaveTextContent('none');
|
||||
expect(screen.queryByRole('alert')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-TOUR-RUN-FIELDS-006: no sum before the route is in, whatever the pace', () => {
|
||||
render(<Stateful initial={300} distance={null} />);
|
||||
expect(paceField()).toHaveValue('5:00');
|
||||
expect(screen.queryByTestId('tour-run-time-sum')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,186 @@
|
||||
import {
|
||||
MAX_RUN_PACE_SECONDS_PER_KM,
|
||||
MIN_RUN_PACE_SECONDS_PER_KM,
|
||||
RUN_PROFILES,
|
||||
type RunProfile,
|
||||
} from '@trek/shared';
|
||||
import { Activity, Clock, Gauge, Info, Ruler, type LucideIcon } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { formatDistance } from '../../../utils/units';
|
||||
import { INPUT, LABEL, Segmented } from '../../shared/dialogParts';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import { FigureBadge } from '../paddle/FigureBadge';
|
||||
import type { TourPlannerController } from '../planner/useTourPlanner';
|
||||
import { InfoDot, TourNotice } from '../tourParts';
|
||||
import { formatPlannedTourDuration } from '../tourPresentation';
|
||||
import { formatRunPace, parseRunPace, RUN_PACE_INPUT_MAX_LENGTH } from './runPace';
|
||||
|
||||
const PROFILE_ICON: Record<RunProfile, LucideIcon> = { running: Activity };
|
||||
|
||||
/**
|
||||
* RUN-01: what a run is planned as, chosen on purpose like a bike tour's
|
||||
* profile, with a line on the ways it asks the router for. The planner and
|
||||
* the GPX import share it.
|
||||
*/
|
||||
export function RunProfileField({ value, onChange }: { value: RunProfile; onChange: (profile: RunProfile) => void }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div data-testid="tour-run-profile" className="min-w-0">
|
||||
<span className={LABEL}>{t('tours.run.profile')}</span>
|
||||
<Segmented<RunProfile>
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
label={t('tours.run.profile')}
|
||||
fill
|
||||
options={RUN_PROFILES.map((profile) => {
|
||||
const Icon = PROFILE_ICON[profile];
|
||||
return {
|
||||
value: profile,
|
||||
label: t(`tours.run.profile.${profile}`),
|
||||
icon: <Icon size={13} strokeWidth={2} aria-hidden="true" />,
|
||||
};
|
||||
})}
|
||||
/>
|
||||
<span className="mt-1.5 block text-content-faint" style={fs(11, 'body')}>
|
||||
{t(`tours.run.profileHint.${value}`)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type RunPlanner = Pick<
|
||||
TourPlannerController,
|
||||
'runProfile' | 'setRunProfile' | 'runPace' | 'runPaceMissing' | 'runPaceInvalid' | 'routeAnalysis'
|
||||
> & { walkingDurationMinutes: number | null };
|
||||
|
||||
/**
|
||||
* The pace as min:s per km. A readable pace reaches the planner while it is
|
||||
* typed; text that is no pace reaches it as NaN on leaving the field, so the
|
||||
* planner marks it and holds Save back, and the text stays for the runner to
|
||||
* fix. The field never offers a pace of its own: the placeholder is the format.
|
||||
*/
|
||||
function RunPaceInput({ planner, locked }: { planner: RunPlanner; locked: boolean }) {
|
||||
const [draft, setDraft] = useState<string | null>(null);
|
||||
const [focused, setFocused] = useState(false);
|
||||
const { paceSecondsPerKm: pace, setPace } = planner.runPace;
|
||||
const unreadable = pace !== null && Number.isNaN(pace);
|
||||
const shown = pace === null || unreadable ? '' : formatRunPace(pace);
|
||||
const showDraft = draft !== null && (focused || unreadable);
|
||||
return (
|
||||
<div className="relative">
|
||||
<input
|
||||
id="tour-planner-run-pace"
|
||||
type="text"
|
||||
inputMode="text"
|
||||
autoComplete="off"
|
||||
maxLength={RUN_PACE_INPUT_MAX_LENGTH}
|
||||
placeholder="0:00"
|
||||
disabled={locked}
|
||||
value={showDraft ? draft : shown}
|
||||
onFocus={() => {
|
||||
setFocused(true);
|
||||
// Text that is no pace yet stays to be fixed; otherwise editing starts from the pace as it reads.
|
||||
setDraft(unreadable ? (draft ?? '') : shown);
|
||||
}}
|
||||
onChange={(event) => {
|
||||
setDraft(event.target.value);
|
||||
const parsed = parseRunPace(event.target.value);
|
||||
if (parsed === null || !Number.isNaN(parsed)) setPace(parsed);
|
||||
}}
|
||||
onBlur={() => {
|
||||
setFocused(false);
|
||||
if (draft !== null && Number.isNaN(parseRunPace(draft))) setPace(Number.NaN);
|
||||
else setDraft(null);
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter') event.currentTarget.blur();
|
||||
}}
|
||||
aria-invalid={planner.runPaceInvalid || undefined}
|
||||
aria-describedby={planner.runPaceInvalid ? 'tour-planner-run-pace-error' : undefined}
|
||||
className={`${INPUT} pe-16 tabular-nums`}
|
||||
/>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none absolute inset-y-0 end-3 flex items-center text-content-faint"
|
||||
style={fs(12, 'body')}
|
||||
>
|
||||
min/km
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The sum the running time is, laid out as badges: the distance in km, times
|
||||
* the pace, is the time. Shown once all three are known, so the runner sees
|
||||
* where the time comes from and that nothing else goes into it.
|
||||
*/
|
||||
function RunTimeSum({ planner }: { planner: RunPlanner }) {
|
||||
const { t } = useTranslation();
|
||||
const distanceKm = planner.routeAnalysis?.distanceKm ?? null;
|
||||
const pace = planner.runPace.paceSecondsPerKm;
|
||||
const minutes = planner.walkingDurationMinutes;
|
||||
if (distanceKm === null || pace === null || planner.runPaceInvalid || minutes === null) return null;
|
||||
// The pace is per km, so the sum reads in km whatever unit the app shows distances in.
|
||||
const distance = formatDistance(distanceKm, 'metric');
|
||||
const time = formatPlannedTourDuration(minutes);
|
||||
const operator = 'font-geist font-semibold text-content-faint';
|
||||
return (
|
||||
<div
|
||||
data-testid="tour-run-time-sum"
|
||||
role="note"
|
||||
aria-label={t('tours.run.timeSum', { distance, pace: formatRunPace(pace), time })}
|
||||
className="mt-2 flex min-w-0 flex-wrap items-center gap-1.5"
|
||||
>
|
||||
<FigureBadge icon={<Ruler size={11} strokeWidth={2} aria-hidden="true" />} value={distance} />
|
||||
<span aria-hidden="true" className={operator} style={fs(12)}>
|
||||
×
|
||||
</span>
|
||||
<FigureBadge icon={<Gauge size={11} strokeWidth={2} aria-hidden="true" />} value={`${formatRunPace(pace)} /km`} />
|
||||
<span aria-hidden="true" className={operator} style={fs(12)}>
|
||||
=
|
||||
</span>
|
||||
<FigureBadge icon={<Clock size={11} strokeWidth={2} aria-hidden="true" />} value={time} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* RUN-01: a run's profile and the pace it is planned at. The time is the
|
||||
* distance at that pace; the info dot says climbs and difficulty stay out of
|
||||
* it, and the sum below the field shows it. Without a pace the run cannot be
|
||||
* saved, since its time would be unknown.
|
||||
*/
|
||||
export function RunFields({ planner, locked }: { planner: RunPlanner; locked: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div data-testid="tour-planner-run-fields" className="flex min-w-0 flex-col gap-3">
|
||||
<RunProfileField value={planner.runProfile} onChange={planner.setRunProfile} />
|
||||
<div className="min-w-0">
|
||||
<div className="mb-[5px] flex min-h-5 min-w-0 items-center gap-1">
|
||||
<label className={`${LABEL} !mb-0 min-w-0 truncate leading-5`} htmlFor="tour-planner-run-pace">
|
||||
{t('tours.run.pace')}
|
||||
</label>
|
||||
<InfoDot label={t('tours.run.paceInfoLabel')} description={t('tours.run.paceInfo')} />
|
||||
</div>
|
||||
<RunPaceInput planner={planner} locked={locked} />
|
||||
{planner.runPaceInvalid ? (
|
||||
<span id="tour-planner-run-pace-error" role="alert" className="mt-1 block text-danger" style={fs(11)}>
|
||||
{t('tours.run.paceInvalid', {
|
||||
fastest: formatRunPace(MIN_RUN_PACE_SECONDS_PER_KM),
|
||||
slowest: formatRunPace(MAX_RUN_PACE_SECONDS_PER_KM),
|
||||
})}
|
||||
</span>
|
||||
) : (
|
||||
<RunTimeSum planner={planner} />
|
||||
)}
|
||||
</div>
|
||||
{planner.runPaceMissing && (
|
||||
<TourNotice role="status" icon={<Info size={13} strokeWidth={2} />}>
|
||||
{t('tours.run.paceNeeded')}
|
||||
</TourNotice>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { TourListItem } from '@trek/shared';
|
||||
import { Activity, Gauge } from 'lucide-react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import { Tooltip } from '../../shared/Tooltip';
|
||||
import { runPaceText } from './runPaceText';
|
||||
|
||||
/**
|
||||
* RUN-01: a run's profile and planned pace as pills of a tour's head, beside
|
||||
* its type. The pace's tooltip says the running time is that pace over the
|
||||
* distance and nothing more; a run without a pace shows no pace pill.
|
||||
*/
|
||||
export function RunHeadPills({
|
||||
tour,
|
||||
className,
|
||||
}: {
|
||||
tour: Pick<TourListItem, 'tour_type' | 'run_profile' | 'run_pace_seconds_per_km'>;
|
||||
className: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
if (tour.tour_type !== 'run') return null;
|
||||
const pace = runPaceText(tour);
|
||||
return (
|
||||
<>
|
||||
{tour.run_profile && (
|
||||
<span data-testid="tour-detail-run-profile" className={className} style={fs(10.5)}>
|
||||
<Activity size={11} strokeWidth={2} className="flex-none text-content-faint" aria-hidden="true" />
|
||||
{t(`tours.run.profile.${tour.run_profile}`)}
|
||||
</span>
|
||||
)}
|
||||
{pace && (
|
||||
<Tooltip label={t('tours.run.paceInfo')}>
|
||||
<span data-testid="tour-detail-run-pace" className={className} style={fs(10.5)}>
|
||||
<Gauge size={11} strokeWidth={2} className="flex-none text-content-faint" aria-hidden="true" />
|
||||
<span className="sr-only">{t('tours.run.pace')}:</span>
|
||||
{pace}
|
||||
</span>
|
||||
</Tooltip>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import type { TourListItem } from '@trek/shared';
|
||||
import { Activity } from 'lucide-react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { render, screen } from '../../../../tests/helpers/render';
|
||||
import TourDayRowFacts, { TourDayRowPills } from '../TourDayRowFacts';
|
||||
import { tourDayRowIcon } from '../tourDayRowIcon';
|
||||
import { movingTimeLabel } from '../tourFacts';
|
||||
import { tourMapLayersFor } from '../tourMapLayers';
|
||||
import { TourGradeTile } from '../tourParts';
|
||||
import { RunHeadPills } from './RunHeadPills';
|
||||
import { runPaceText } from './runPaceText';
|
||||
|
||||
// FE-TOUR-RUN-MARK-001 to FE-TOUR-RUN-MARK-006
|
||||
|
||||
const run: TourListItem = {
|
||||
place_id: 7,
|
||||
name: 'River loop',
|
||||
tour_type: 'run',
|
||||
run_profile: 'running',
|
||||
run_pace_seconds_per_km: 360,
|
||||
distance: 8,
|
||||
elevation_gain: 40,
|
||||
elevation_loss: 40,
|
||||
duration: 48,
|
||||
break_additional_minutes: null,
|
||||
planned_duration_minutes: null,
|
||||
difficulty: null,
|
||||
wanderer_ref: null,
|
||||
match_confidence: 1,
|
||||
max_hiking_difficulty: null,
|
||||
planned: true,
|
||||
caution: false,
|
||||
has_waypoints: true,
|
||||
};
|
||||
|
||||
describe('a run wherever a tour shows (RUN-01)', () => {
|
||||
it('FE-TOUR-RUN-MARK-001: says a run pace as min:s per km, and nothing for a run without one or another type', () => {
|
||||
expect(runPaceText(run)).toBe('6:00 min/km');
|
||||
expect(runPaceText({ ...run, run_pace_seconds_per_km: null })).toBeNull();
|
||||
expect(runPaceText({ ...run, run_pace_seconds_per_km: 5 })).toBeNull();
|
||||
expect(runPaceText({ ...run, tour_type: 'hike' })).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-TOUR-RUN-MARK-002: the time is named as planned, and the run goes by its own icon and maps', () => {
|
||||
expect(movingTimeLabel(run, 'walking', (key) => key)).toBe('tours.run.timeEstimated');
|
||||
expect(tourDayRowIcon('run')).toBe(Activity);
|
||||
expect(tourMapLayersFor('run')).toEqual({
|
||||
bases: ['default', 'topo', 'satellite'],
|
||||
defaultBase: 'default',
|
||||
overlays: [],
|
||||
});
|
||||
});
|
||||
|
||||
it('FE-TOUR-RUN-MARK-003: the day plan shows the planned running time and the pace it is planned at', () => {
|
||||
render(<TourDayRowFacts tour={run} />);
|
||||
expect(screen.getByTestId('trip-plan-tour-walking-time')).toHaveAccessibleName('Running time (planned): 48 min');
|
||||
expect(screen.getByTestId('plan-tour-run-pace')).toHaveAccessibleName('Planned pace: 6:00 min/km');
|
||||
expect(screen.getByTestId('plan-tour-ascent')).toHaveTextContent('40');
|
||||
});
|
||||
|
||||
it('FE-TOUR-RUN-MARK-004: an imported run without a pace shows no time and no pace, rather than made-up ones', () => {
|
||||
render(<TourDayRowFacts tour={{ ...run, run_pace_seconds_per_km: null, duration: null, has_waypoints: false }} />);
|
||||
expect(screen.queryByTestId('trip-plan-tour-walking-time')).toBeNull();
|
||||
expect(screen.queryByTestId('plan-tour-run-pace')).toBeNull();
|
||||
expect(screen.getByTestId('plan-tour-distance')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-TOUR-RUN-MARK-005: the tour list names the pace in the time tooltip, and the tile the type', () => {
|
||||
render(<TourDayRowPills tour={run} compact />);
|
||||
expect(screen.getByTestId('trip-plan-tour-time')).toHaveAccessibleName(
|
||||
'Running time (planned): 48 min, Planned pace: 6:00 min/km, Planned total duration: 48 min'
|
||||
);
|
||||
render(<TourGradeTile tour={run} />);
|
||||
expect(screen.getByLabelText('Run')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-TOUR-RUN-MARK-006: the head names the profile and the pace, a run without a pace only its profile', () => {
|
||||
const { rerender } = render(<RunHeadPills tour={run} className="head-pill" />);
|
||||
expect(screen.getByTestId('tour-detail-run-profile')).toHaveTextContent('Running');
|
||||
const pace = screen.getByTestId('tour-detail-run-pace');
|
||||
expect(pace).toHaveTextContent('6:00 min/km');
|
||||
expect(pace).toHaveClass('head-pill');
|
||||
rerender(<RunHeadPills tour={{ ...run, run_pace_seconds_per_km: null }} className="head-pill" />);
|
||||
expect(screen.queryByTestId('tour-detail-run-pace')).toBeNull();
|
||||
rerender(<RunHeadPills tour={{ ...run, tour_type: 'hike', run_profile: null }} className="head-pill" />);
|
||||
expect(screen.queryByTestId('tour-detail-run-profile')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { formatRunPace, parseRunPace, runPaceInvalid } from './runPace';
|
||||
|
||||
// FE-TOUR-RUN-PACE-001 to FE-TOUR-RUN-PACE-003
|
||||
|
||||
describe('run pace (RUN-01)', () => {
|
||||
it('FE-TOUR-RUN-PACE-001: reads min:s, whole minutes and minutes with a part, and nothing as no pace', () => {
|
||||
expect(parseRunPace('6:00')).toBe(360);
|
||||
expect(parseRunPace(' 5:07 ')).toBe(307);
|
||||
expect(parseRunPace('6')).toBe(360);
|
||||
expect(parseRunPace('5,5')).toBe(330);
|
||||
expect(parseRunPace('5.25')).toBe(315);
|
||||
expect(parseRunPace('')).toBeNull();
|
||||
expect(parseRunPace(' ')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-TOUR-RUN-PACE-002: anything else is no pace, seconds of 60 or more included', () => {
|
||||
for (const text of ['5:60', '5:7', 'fast', '6 min', '-5', '5:30:00', '123']) {
|
||||
expect(parseRunPace(text)).toBeNaN();
|
||||
}
|
||||
});
|
||||
|
||||
it('FE-TOUR-RUN-PACE-003: writes a pace as min:s and holds it to the bounds a run is saved with', () => {
|
||||
expect(formatRunPace(360)).toBe('6:00');
|
||||
expect(formatRunPace(307)).toBe('5:07');
|
||||
expect(formatRunPace(1200)).toBe('20:00');
|
||||
expect(runPaceInvalid(null)).toBe(false);
|
||||
expect(runPaceInvalid(360)).toBe(false);
|
||||
expect([Number.NaN, 0, 119, 1201].map(runPaceInvalid)).toEqual([true, true, true, true]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { runPaceSecondsPerKmSchema } from '@trek/shared';
|
||||
|
||||
/** The longest text the pace field takes: "12:30" and a little room. */
|
||||
export const RUN_PACE_INPUT_MAX_LENGTH = 6;
|
||||
|
||||
const CLOCK = /^(\d{1,2}):(\d{2})$/;
|
||||
const MINUTES = /^(\d{1,2})(?:[.,](\d{1,2}))?$/;
|
||||
|
||||
/**
|
||||
* RUN-01: a pace as typed, read as whole seconds per kilometre. "5:30" is
|
||||
* minutes and seconds, "6" whole minutes and "5,5" or "5.5" minutes and a
|
||||
* part. An empty field is no pace (null); anything else, seconds of 60 or more
|
||||
* included, is NaN, so the planner marks it and holds Save back while the
|
||||
* text stays for the runner to fix. Whether the pace is in bounds is the
|
||||
* contract's to say, not this one's.
|
||||
*/
|
||||
export function parseRunPace(text: string): number | null {
|
||||
const value = text.trim();
|
||||
if (value === '') return null;
|
||||
const clock = CLOCK.exec(value);
|
||||
if (clock) {
|
||||
const seconds = Number(clock[2]);
|
||||
return seconds < 60 ? Number(clock[1]) * 60 + seconds : Number.NaN;
|
||||
}
|
||||
const minutes = MINUTES.exec(value);
|
||||
if (!minutes) return Number.NaN;
|
||||
return Math.round(Number(`${minutes[1]}.${minutes[2] ?? '0'}`) * 60);
|
||||
}
|
||||
|
||||
/** A pace as the runner reads it, minutes and seconds per kilometre: 360 is "6:00". */
|
||||
export function formatRunPace(secondsPerKm: number): string {
|
||||
const whole = Math.round(secondsPerKm);
|
||||
return `${Math.floor(whole / 60)}:${String(whole % 60).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/** Whether a pace held by the planner is one a run can be saved with: unset, or in the contract's bounds. */
|
||||
export function runPaceInvalid(secondsPerKm: number | null): boolean {
|
||||
return secondsPerKm !== null && !runPaceSecondsPerKmSchema.safeParse(secondsPerKm).success;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { TourListItem } from '@trek/shared';
|
||||
import { formatRunPace, runPaceInvalid } from './runPace';
|
||||
|
||||
/**
|
||||
* RUN-01: a saved run's pace as its facts say it, "6:00 min/km", or null for
|
||||
* another type and for a run without one (an import, a run whose runner has
|
||||
* not entered one yet): unknown stays unknown.
|
||||
*/
|
||||
export function runPaceText(
|
||||
tour: Pick<TourListItem, 'tour_type'> & Partial<Pick<TourListItem, 'run_pace_seconds_per_km'>>
|
||||
): string | null {
|
||||
const pace = tour.tour_type === 'run' ? (tour.run_pace_seconds_per_km ?? null) : null;
|
||||
return pace === null || runPaceInvalid(pace) ? null : `${formatRunPace(pace)} min/km`;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { useCallback, useState } from 'react';
|
||||
|
||||
/**
|
||||
* RUN-01: the pace a run is planned at, seconds per kilometre, a field of the
|
||||
* draft like its description: it plans no route again and is no step of the
|
||||
* history, it only changes the time. Null while the runner entered none; NaN
|
||||
* while the text typed is no pace. `onEdit` tells the planner the draft
|
||||
* changed, and says whether it may.
|
||||
*/
|
||||
export function useRunPace(initial: number | null, onEdit: () => boolean) {
|
||||
const [paceSecondsPerKm, setPaceState] = useState<number | null>(initial);
|
||||
const setPace = useCallback(
|
||||
(next: number | null) => {
|
||||
if (!Object.is(next, paceSecondsPerKm) && onEdit()) setPaceState(next);
|
||||
},
|
||||
[onEdit, paceSecondsPerKm]
|
||||
);
|
||||
return {
|
||||
paceSecondsPerKm,
|
||||
setPace,
|
||||
/** Loaded from a tour or a draft, or cleared; not an edit. */
|
||||
load: setPaceState,
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Bike, Footprints, Mountain, Route, Waves, type LucideIcon } from 'lucide-react';
|
||||
import { Activity, Bike, Footprints, Mountain, Route, Waves, type LucideIcon } from 'lucide-react';
|
||||
|
||||
export function tourDayRowIcon(type: string): LucideIcon {
|
||||
switch (type) {
|
||||
@@ -8,6 +8,8 @@ export function tourDayRowIcon(type: string): LucideIcon {
|
||||
return Bike;
|
||||
case 'walk':
|
||||
return Footprints;
|
||||
case 'run':
|
||||
return Activity;
|
||||
case 'kayak':
|
||||
return Waves;
|
||||
default:
|
||||
|
||||
@@ -47,7 +47,9 @@ export function withoutHeights<
|
||||
/**
|
||||
* What the time on the move is called: walking for a hike (in the wording the
|
||||
* place asks for) and for a city walk (CW-02), riding for a bike tour,
|
||||
* paddling for a paddle tour.
|
||||
* paddling for a paddle tour, and for a run (RUN-01) the running time it is
|
||||
* planned with, said as planned wherever it shows, so it never reads as a
|
||||
* time someone recorded.
|
||||
*/
|
||||
export function movingTimeLabel(
|
||||
tour: { tour_type?: string } | undefined,
|
||||
@@ -56,5 +58,6 @@ export function movingTimeLabel(
|
||||
): string {
|
||||
if (tour?.tour_type === 'kayak') return t('tours.paddle.timeEstimatedShort');
|
||||
if (tour?.tour_type === 'walk') return t('tours.walk.timeEstimatedShort');
|
||||
if (tour?.tour_type === 'run') return t('tours.run.timeEstimated');
|
||||
return tour?.tour_type === 'bike' ? t('tours.bike.timeEstimatedShort') : hikeLabel;
|
||||
}
|
||||
|
||||
@@ -16,6 +16,8 @@ import type { TourBaseLayer } from '../Map/MapLayerSwitcher';
|
||||
* allows it) and satellite beside it; via ferratas.
|
||||
* - Bike (BIK-01): the standard map, topo for the climbs, CyclOSM (BIK-06, while the admin
|
||||
* allows it) and satellite. No ferratas, a bike tour climbs none.
|
||||
* - Run (RUN-01): the standard map, topo for the climbs and satellite. No ferratas, a run
|
||||
* takes none.
|
||||
* - Paddle: the standard map, whose water reads clearly, and satellite. No topo and
|
||||
* no ferratas, those are hiking maps. Seamarks as an overlay.
|
||||
* - Any other type (switched off, or one this build does not plan): the standard map
|
||||
@@ -39,6 +41,7 @@ const HIKE: TourMapLayerSet = {
|
||||
const HIKE_WITH_HIKING_MAP: TourMapLayerSet = { ...HIKE, bases: ['default', 'topo', 'hiking', 'satellite'] };
|
||||
const BIKE: TourMapLayerSet = { bases: ['default', 'topo', 'satellite'], defaultBase: 'default', overlays: [] };
|
||||
const BIKE_WITH_CYCLE_MAP: TourMapLayerSet = { ...BIKE, bases: ['default', 'topo', 'cycle', 'satellite'] };
|
||||
const RUN: TourMapLayerSet = { bases: ['default', 'topo', 'satellite'], defaultBase: 'default', overlays: [] };
|
||||
const PADDLE: TourMapLayerSet = { bases: ['default', 'satellite'], defaultBase: 'default', overlays: ['seamarks'] };
|
||||
const OTHER: TourMapLayerSet = { bases: ['default', 'satellite'], defaultBase: 'default', overlays: [] };
|
||||
|
||||
@@ -49,6 +52,7 @@ export function tourMapLayersFor(
|
||||
): TourMapLayerSet {
|
||||
if (type === 'hike') return hikingMap ? HIKE_WITH_HIKING_MAP : HIKE;
|
||||
if (type === 'bike') return cycleMap ? BIKE_WITH_CYCLE_MAP : BIKE;
|
||||
if (type === 'run') return RUN;
|
||||
if (type === 'kayak') return PADDLE;
|
||||
return OTHER;
|
||||
}
|
||||
|
||||
@@ -28,8 +28,8 @@ export function TourGradeTile({ tour }: { tour: Pick<TourListItem, 'max_hiking_d
|
||||
const { t } = useTranslation()
|
||||
const level = tour.max_hiking_difficulty
|
||||
const source = tourSource(tour)
|
||||
// A tour without a grade (a paddle or a bike tour, an import) names its type instead; a hike keeps the mountain.
|
||||
const type = tour.tour_type === 'kayak' || tour.tour_type === 'bike' ? tour.tour_type : 'hike'
|
||||
// A tour without a grade (a paddle or a bike tour, a run, an import) names its type instead; a hike keeps the mountain.
|
||||
const type = tour.tour_type === 'kayak' || tour.tour_type === 'bike' || tour.tour_type === 'run' ? tour.tour_type : 'hike'
|
||||
const label = level != null ? t(`tours.planner.difficulty.t${level}`) : type !== 'hike' ? t(`tourTypes.${type}`) : null
|
||||
return (
|
||||
<span className="relative flex-none">
|
||||
|
||||
Reference in New Issue
Block a user