fix(tours): read and write a run's pace in the user's distance unit

The pace was always min/km and the run's time sum forced kilometres, so
with distances in miles the run card disagreed with every other figure in
the planner. The pace is still kept per km, but is typed, shown and
checked per mile when distances are in miles, and the time sum reads in
that unit too.
This commit is contained in:
Maurice
2026-10-20 16:51:34 +02:00
parent 2a40b884a1
commit a249c861e6
36 changed files with 206 additions and 78 deletions
@@ -204,7 +204,7 @@ 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, t);
const pace = runPaceText(tour, t, unit);
const timeParts = [
walking ? `${movingTimeLabel(tour, t('tours.planner.inspector.duration'), t)}: ${walking}` : null,
// RUN-01: the pace the running time is planned at.
@@ -275,7 +275,7 @@ export default function TourDayRowFacts({
movingTimeLabel(tour, t('tours.planner.inspector.duration'), t),
'trip-plan-tour-walking-time'
);
const pace = runPaceText(tour, t);
const pace = runPaceText(tour, t, unit);
if (pace) add(Gauge, pace, t('tours.run.pace'), 'plan-tour-run-pace');
if (times.breakMinutes != null && times.breakMinutes > 0)
add(
@@ -1,6 +1,7 @@
import type { CollectionTourItem } from '@trek/shared';
import { AlertTriangle, CopyPlus, Gauge, Moon, Route, Trash2, Waypoints, WifiOff } from 'lucide-react';
import { useTranslation } from '../../../i18n';
import { useSettingsStore } from '../../../store/settingsStore';
import { WhiteBadge } from '../../Planner/planParts';
import ConfirmDialog from '../../shared/ConfirmDialog';
import { fs } from '../../shared/DialogShell';
@@ -24,7 +25,8 @@ function sourceText(tour: CollectionTourItem, t: (key: string, params?: Record<s
*/
function KeptTourTypeBadges({ tour }: { tour: CollectionTourItem }) {
const { t } = useTranslation();
const pace = runPaceText(tour, t);
const unit = useSettingsStore((state) => state.settings.distance_unit) ?? 'metric';
const pace = runPaceText(tour, t, unit);
const stages = tour.stage_count ? t('tours.stages.count', { count: tour.stage_count }) : null;
const icon = 'flex-none text-content-faint';
return (
@@ -1,10 +1,12 @@
import { fireEvent, render, screen } from '@testing-library/react';
import { useState, type ComponentProps } from 'react';
import { describe, expect, it, vi } from 'vitest';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { resetAllStores, seedStore } from '../../../../tests/helpers/store';
import { useSettingsStore } from '../../../store/settingsStore';
import { RunFields, RunProfileField } from './RunFields';
import { runPaceInvalid } from './runPace';
// FE-TOUR-RUN-FIELDS-001 to FE-TOUR-RUN-FIELDS-008
// FE-TOUR-RUN-FIELDS-001 to FE-TOUR-RUN-FIELDS-009
type Planner = ComponentProps<typeof RunFields>['planner'];
@@ -42,6 +44,8 @@ function Stateful({
const paceField = () => screen.getByRole('textbox');
afterEach(() => resetAllStores());
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();
@@ -142,10 +146,31 @@ describe('RunFields (RUN-01)', () => {
it('FE-TOUR-RUN-FIELDS-008: a trail run is timed as any run, distance times pace, nothing added for the terrain (RUN-02)', () => {
render(<Stateful initial={450} profile="trail" />);
const sum = screen.getByTestId('tour-run-time-sum');
expect(sum).toHaveTextContent('7:30 /km');
expect(sum).toHaveTextContent('7:30 tours.run.paceUnit');
expect(sum).toHaveTextContent('1 h');
expect(screen.getByRole('button', { name: 'tours.run.paceInfoLabel' })).toHaveAccessibleDescription(
'tours.run.paceInfo'
);
});
it('FE-TOUR-RUN-FIELDS-009: with distances in miles the pace is typed and read per mile, kept per km, and the sum in miles', () => {
seedStore(useSettingsStore, { settings: { distance_unit: 'imperial' } });
render(<Stateful />);
expect(screen.getByText('tours.run.paceUnitMi')).toBeInTheDocument();
fireEvent.focus(paceField());
// 9:39 a mile is 6:00 a kilometre, the way it is kept.
fireEvent.change(paceField(), { target: { value: '9:39' } });
expect(screen.getByTestId('pace')).toHaveTextContent('360');
fireEvent.blur(paceField());
expect(paceField()).toHaveValue('9:39');
const sum = screen.getByTestId('tour-run-time-sum');
expect(sum).toHaveTextContent('5 mi');
expect(sum).not.toHaveTextContent('km');
expect(sum).toHaveTextContent('9:39 tours.run.paceUnitMi');
expect(sum).toHaveTextContent('48 min');
fireEvent.focus(paceField());
fireEvent.change(paceField(), { target: { value: '1:30' } });
fireEvent.blur(paceField());
expect(screen.getByRole('alert')).toHaveTextContent('tours.run.paceInvalidMi');
});
});
+29 -19
View File
@@ -7,6 +7,8 @@ import {
import { Clock, Gauge, Info, Ruler } from 'lucide-react';
import { useState } from 'react';
import { useTranslation } from '../../../i18n';
import { useSettingsStore } from '../../../store/settingsStore';
import type { DistanceUnit } from '../../../types';
import { formatDistance } from '../../../utils/units';
import { INPUT, LABEL, Segmented } from '../../shared/dialogParts';
import { fs } from '../../shared/DialogShell';
@@ -14,7 +16,7 @@ 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, runPaceInvalid } from './runPace';
import { formatRunPace, parseRunPace, RUN_PACE_INPUT_MAX_LENGTH, runPaceInvalid, runPaceUnitText } from './runPace';
import { RUN_PROFILE_ICON } from './runProfileIcon';
/**
@@ -53,8 +55,14 @@ type RunPlanner = Pick<
'runProfile' | 'setRunProfile' | 'runPace' | 'runPaceMissing' | 'runPaceInvalid' | 'routeAnalysis'
> & { walkingDurationMinutes: number | null };
/** The distance unit the user reads distances in, which a pace is typed and read in too. */
function useDistanceUnit(): DistanceUnit {
return useSettingsStore((state) => state.settings.distance_unit) ?? 'metric';
}
/**
* The pace as min:s per km. A pace a run can be saved with reaches the planner
* The pace as min:s per km, or per mile with distances in miles; it is kept
* per km whatever the unit. A pace a run can be saved with reaches the planner
* while it is typed. Anything else waits for leaving the field (or Enter), so
* the first digit of "12:30" flashes no error: then a pace out of bounds
* reaches the planner as it is and text that is no pace as NaN, the planner
@@ -63,11 +71,12 @@ type RunPlanner = Pick<
*/
function RunPaceInput({ planner, locked }: { planner: RunPlanner; locked: boolean }) {
const { t } = useTranslation();
const unit = useDistanceUnit();
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 shown = pace === null || unreadable ? '' : formatRunPace(pace, unit);
const showDraft = draft !== null && (focused || unreadable);
return (
<div className="relative">
@@ -87,13 +96,13 @@ function RunPaceInput({ planner, locked }: { planner: RunPlanner; locked: boolea
}}
onChange={(event) => {
setDraft(event.target.value);
const parsed = parseRunPace(event.target.value);
const parsed = parseRunPace(event.target.value, unit);
if (!runPaceInvalid(parsed)) setPace(parsed);
}}
onBlur={() => {
setFocused(false);
if (draft === null) return;
const parsed = parseRunPace(draft);
const parsed = parseRunPace(draft, unit);
setPace(parsed);
if (!Number.isNaN(parsed)) setDraft(null);
}}
@@ -109,42 +118,41 @@ function RunPaceInput({ planner, locked }: { planner: RunPlanner; locked: boolea
className="pointer-events-none absolute inset-y-0 end-3 flex items-center text-content-faint"
style={fs(12, 'body')}
>
{t('tours.run.paceUnit')}
{runPaceUnitText(unit, t)}
</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
* The sum the running time is, laid out as badges: the distance, times the
* pace, is the time, both in the unit the user reads distances in. 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 unit = useDistanceUnit();
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');
// The pace reads per km or per mile as the distances do, so the sum reads in that unit too.
const distance = formatDistance(distanceKm, unit);
const paceText = `${formatRunPace(pace, unit)} ${runPaceUnitText(unit, t)}`;
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 })}
aria-label={t('tours.run.timeSum', { distance, pace: paceText, 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)} ${t('tours.run.paceUnit')}`}
/>
<FigureBadge icon={<Gauge size={11} strokeWidth={2} aria-hidden="true" />} value={paceText} />
<span aria-hidden="true" className={operator} style={fs(12)}>
=
</span>
@@ -161,6 +169,11 @@ function RunTimeSum({ planner }: { planner: RunPlanner }) {
*/
export function RunFields({ planner, locked }: { planner: RunPlanner; locked: boolean }) {
const { t } = useTranslation();
const unit = useDistanceUnit();
const bounds = {
fastest: formatRunPace(MIN_RUN_PACE_SECONDS_PER_KM, unit),
slowest: formatRunPace(MAX_RUN_PACE_SECONDS_PER_KM, unit),
};
return (
<div data-testid="tour-planner-run-fields" className="flex min-w-0 flex-col gap-3">
<RunProfileField value={planner.runProfile} onChange={planner.setRunProfile} />
@@ -174,10 +187,7 @@ export function RunFields({ planner, locked }: { planner: RunPlanner; locked: bo
<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),
})}
{t(unit === 'imperial' ? 'tours.run.paceInvalidMi' : 'tours.run.paceInvalid', bounds)}
</span>
) : (
<RunTimeSum planner={planner} />
@@ -1,6 +1,7 @@
import type { TourListItem } from '@trek/shared';
import { Gauge } from 'lucide-react';
import { useTranslation } from '../../../i18n';
import { useSettingsStore } from '../../../store/settingsStore';
import { fs } from '../../shared/DialogShell';
import { Tooltip } from '../../shared/Tooltip';
import { runPaceText } from './runPaceText';
@@ -19,8 +20,9 @@ export function RunHeadPills({
className: string;
}) {
const { t } = useTranslation();
const unit = useSettingsStore((state) => state.settings.distance_unit) ?? 'metric';
if (tour.tour_type !== 'run') return null;
const pace = runPaceText(tour, t);
const pace = runPaceText(tour, t, unit);
const ProfileIcon = RUN_PROFILE_ICON[tour.run_profile ?? 'running'];
return (
<>
@@ -1,7 +1,8 @@
import { describe, expect, it } from 'vitest';
import { formatRunPace, parseRunPace, runPaceInvalid } from './runPace';
import { formatRunPace, parseRunPace, runPaceInvalid, runPaceUnitText } from './runPace';
import { runPaceText } from './runPaceText';
// FE-TOUR-RUN-PACE-001 to FE-TOUR-RUN-PACE-003
// FE-TOUR-RUN-PACE-001 to FE-TOUR-RUN-PACE-004
describe('run pace (RUN-01)', () => {
it('FE-TOUR-RUN-PACE-001: reads min:s, whole minutes, minutes and a tenth, two digits after a point as seconds, and nothing as no pace', () => {
@@ -32,4 +33,20 @@ describe('run pace (RUN-01)', () => {
expect(runPaceInvalid(360)).toBe(false);
expect([Number.NaN, 0, 119, 1201].map(runPaceInvalid)).toEqual([true, true, true, true]);
});
it('FE-TOUR-RUN-PACE-004: with distances in miles a pace is read and written per mile and kept per km', () => {
expect(parseRunPace('9:39', 'imperial')).toBe(360);
expect(parseRunPace('8', 'imperial')).toBe(298);
expect(parseRunPace('', 'imperial')).toBeNull();
expect(parseRunPace('9:75', 'imperial')).toBeNaN();
expect(formatRunPace(360, 'imperial')).toBe('9:39');
expect(formatRunPace(parseRunPace('9:39', 'imperial') ?? 0, 'imperial')).toBe('9:39');
expect(formatRunPace(360, 'metric')).toBe('6:00');
const t = (key: string) => key;
expect(runPaceUnitText('imperial', t)).toBe('tours.run.paceUnitMi');
expect(runPaceUnitText('metric', t)).toBe('tours.run.paceUnit');
const run = { tour_type: 'run' as const, run_pace_seconds_per_km: 360 };
expect(runPaceText(run, t, 'imperial')).toBe('9:39 tours.run.paceUnitMi');
expect(runPaceText(run, t)).toBe('6:00 tours.run.paceUnit');
});
});
+32 -16
View File
@@ -1,4 +1,5 @@
import { runPaceSecondsPerKmSchema } from '@trek/shared';
import type { DistanceUnit } from '../../../types';
/** The longest text the pace field takes: "12:30" and a little room. */
export const RUN_PACE_INPUT_MAX_LENGTH = 6;
@@ -9,22 +10,14 @@ function clockSeconds(minutes: string, seconds: string): number {
return secondsNumber < 60 ? Number(minutes) * 60 + secondsNumber : Number.NaN;
}
/** A statute mile in kilometres: a pace per mile is this many times a pace per kilometre. */
const KM_PER_MILE = 1.609344;
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
* tenth. Two digits after the point or comma are seconds, the way "5.30" or
* "5,30" is written for 5:30 in much of Europe, not hundredths of a minute.
* 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;
/** A pace as typed, whole seconds per the unit it is typed in. */
function typedSeconds(value: string): number {
const clock = CLOCK.exec(value);
if (clock) return clockSeconds(clock[1], clock[2]);
const minutes = MINUTES.exec(value);
@@ -34,12 +27,35 @@ export function parseRunPace(text: string): number | null {
return Math.round(Number(`${whole}.${part}`) * 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);
/**
* RUN-01: a pace as typed, read as whole seconds per kilometre, the way it is
* stored. The runner types it per kilometre or, with distances in miles, per
* mile. "5:30" is minutes and seconds, "6" whole minutes and "5,5" or "5.5"
* minutes and a tenth. Two digits after the point or comma are seconds, the
* way "5.30" or "5,30" is written for 5:30 in much of Europe, not hundredths
* of a minute. 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, unit: DistanceUnit = 'metric'): number | null {
const value = text.trim();
if (value === '') return null;
const seconds = typedSeconds(value);
return unit === 'imperial' && !Number.isNaN(seconds) ? Math.round(seconds / KM_PER_MILE) : seconds;
}
/** A pace as the runner reads it, minutes and seconds per kilometre or per mile: 360 s/km is "6:00" or "9:39". */
export function formatRunPace(secondsPerKm: number, unit: DistanceUnit = 'metric'): string {
const whole = Math.round(unit === 'imperial' ? secondsPerKm * KM_PER_MILE : secondsPerKm);
return `${Math.floor(whole / 60)}:${String(whole % 60).padStart(2, '0')}`;
}
/** The unit a pace reads in, in the user's language: minutes per kilometre, or per mile with distances in miles. */
export function runPaceUnitText(unit: DistanceUnit, t: (key: string) => string): string {
return t(unit === 'imperial' ? 'tours.run.paceUnitMi' : 'tours.run.paceUnit');
}
/** 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;
@@ -1,16 +1,18 @@
import type { TourListItem } from '@trek/shared';
import { formatRunPace, runPaceInvalid } from './runPace';
import type { DistanceUnit } from '../../../types';
import { formatRunPace, runPaceInvalid, runPaceUnitText } from './runPace';
/**
* RUN-01: a saved run's pace as its facts say it, "6:00 min/km" with the unit
* in the user's language, 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.
* in the user's language, or "9:39 min/mi" with distances in miles; 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'>>,
t: (key: string) => string
t: (key: string) => string,
unit: DistanceUnit = 'metric'
): string | null {
const pace = tour.tour_type === 'run' ? (tour.run_pace_seconds_per_km ?? null) : null;
return pace === null || runPaceInvalid(pace) ? null : `${formatRunPace(pace)} ${t('tours.run.paceUnit')}`;
return pace === null || runPaceInvalid(pace) ? null : `${formatRunPace(pace, unit)} ${runPaceUnitText(unit, t)}`;
}