feat(tours): link the track a tour was actually done with, and show its own values (ACT-01)

A planned tour can now be given the track it was actually done with. In the
tour's detail, "Add actual track" opens a dialog that asks for the day the
tour was done on (or none) and a recording of the trip: an import nobody
planned over, or a new one through the existing GPX import, its preview
preset to the tour's type. What the choice measures is shown before anything
is written, and only "Link" writes. The linked track keeps its own name and
source; the detail shows its distance, heights, profile and, only where the
file carried time stamps, the time it took, marked as actual values next to
the untouched plan. A track can be changed or unlinked again.

Server: a tour_activities table points a tour's execution (a day assignment,
or none) at a recording of the same trip, and the tours GPX import keeps the
first and last time of a track whose every point carries one. The values are
read from the recording's own line on every read, so a changed recording
updates them while the plan's line, measures and revision stay as they were.
Every check runs inside the write: the recording must be an import of this
trip not planned over, documenting no other tour; the day must be one of this
tour; a refusal names its reason and changes nothing. PUT and DELETE
/api/trips/:tripId/tours/:placeId/activities answer the detail, which now
carries the actual tracks; the list names them per tour and per recording.
MCP: assign_tour_track and unassign_tour_track over the same service and
checks, get_tour_plan reads the values without the line.

A recording linked as a tour's actual track is no longer counted as a tour of
its own in the trip's tour summary, and the GPX preview imports a city walk
as one instead of as a hike.
This commit is contained in:
Maurice
2026-10-20 12:42:33 +02:00
parent f016972a4e
commit d0cc6fc2f4
101 changed files with 5031 additions and 50 deletions
@@ -316,6 +316,13 @@ describe('TourDetailDialog', () => {
expect(screen.getAllByText('T2').length).toBeGreaterThan(0)
})
it('ACT-01: a recording that is the actual track of a tour names that tour in its head', () => {
seedStore(useTripStore, { places: [buildPlace({ id: 7, name: 'Lake loop' }), place] })
render(<TourDetailDialog {...defaultProps} tour={{ ...tour, has_waypoints: false, origin: 'gpx', activity_of: 7 }} />)
expect(screen.getByTestId('tour-detail-track-of')).toHaveTextContent('Actual track of Lake loop')
})
it('shows the grade on the tile and no second difficulty scale', () => {
render(<TourDetailDialog {...defaultProps} tour={{ ...tour, difficulty: 'easy', max_hiking_difficulty: 1 }} />)
@@ -13,6 +13,7 @@ import {
FileDown,
FileImage,
FileText,
Footprints,
Loader2,
Minus,
Navigation,
@@ -48,6 +49,7 @@ import TrackColorPicker from '../shared/TrackColorPicker';
import { markdownLinkComponents } from '../shared/markdownLink';
import { TourDayRowAvatar } from './TourDayRowFacts';
import { TourGpxExportButton } from './TourGpxExportButton';
import TourActivitySection from './activity/TourActivitySection';
import { PaddleCheckSection } from './paddle/PaddleCheckSection';
import { PaddleWindSection } from './paddle/PaddleWindCard';
import { TourProvenanceBlock } from './provenance/TourProvenanceSection';
@@ -88,6 +90,8 @@ interface TourDetailDialogProps extends TourPermissionProps {
onSourceReimported?: (tour: TourListItem) => Promise<void> | void;
/** P2C-07: save this tour again as a new, independent one. */
onSaveAsNew?: (tour: TourListItem) => Promise<void> | void;
/** ACT-01: a recorded track was assigned, taken off or imported; the lists take in these tours. */
onToursChanged?: (placeIds: number[]) => Promise<void> | void;
onAssignToDay?: (placeId: number, dayId?: number) => void;
onRemoveAssignment?: (dayId: number, assignmentId: number) => void;
onDelete?: () => void;
@@ -243,6 +247,10 @@ function TourHeadPills({
? null
: (state.places.find((p) => p.id === tour.derived_from_place_id)?.name ?? null)
);
// ACT-01: the tour this one is the recorded track of.
const documentsName = useTripStore((state) =>
tour.activity_of == null ? null : (state.places.find((p) => p.id === tour.activity_of)?.name ?? null)
);
return (
<div className="mt-2 flex flex-wrap items-center gap-1.5">
<span className={HEAD_PILL} style={fs(10.5)}>
@@ -285,6 +293,14 @@ function TourHeadPills({
</span>
</Tooltip>
)}
{documentsName && (
<Tooltip label={t('tours.activity.isTrackHint')}>
<span data-testid="tour-detail-track-of" className={`${HEAD_PILL} max-w-[220px]`} style={fs(10.5)}>
<Footprints size={11} strokeWidth={2} className="flex-none text-success" />
<span className="min-w-0 truncate">{t('tours.activity.ofTour', { name: documentsName })}</span>
</span>
</Tooltip>
)}
{shownTime != null && (
<Tooltip label={timeTooltip}>
<span aria-label={timeTooltip} className={HEAD_PILL} style={fs(10.5)}>
@@ -483,6 +499,7 @@ export default function TourDetailDialog({
onFileUpload,
onSourceReimported,
onSaveAsNew,
onToursChanged,
onAssignToDay,
onRemoveAssignment,
onDelete,
@@ -709,6 +726,17 @@ export default function TourDetailDialog({
)}
{tour.tour_type === 'kayak' && <PaddleCheckSection tour={tour} />}
{tour.tour_type === 'kayak' && <PaddleWindSection placeId={place.id} start={placeStart(place)} />}
{/* A tour written here offline has no server copy to assign a recording to until it syncs. */}
{place.id > 0 && (
<TourActivitySection
tripId={place.trip_id}
tour={tour}
days={days}
assignments={assignments}
canEdit={canEdit}
onToursChanged={onToursChanged}
/>
)}
{description && (
<DialogSection className="flex-none" label={t('places.formDescription')}>
@@ -0,0 +1,74 @@
// FE-GPX-PREVIEW-001 to FE-GPX-PREVIEW-003
// The GPX preview as ACT-01 uses it: preset to the tour's type, a city walk
// imported as one, and when a track was recorded shown where it carried times.
import { fireEvent, render, screen } from '@testing-library/react';
import type { TourGpxPreviewTrack } from '@trek/shared';
import { describe, expect, it, vi } from 'vitest';
import TourGpxPreviewDialog from './TourGpxPreviewDialog';
import type { TourGpxImport } from './useTourGpxImport';
vi.mock('../Map/MapViewAuto', () => ({ MapViewAuto: () => <div data-testid="gpx-preview-map-stub" /> }));
function track(overrides: Partial<TourGpxPreviewTrack> = {}): TourGpxPreviewTrack {
return {
name: 'Morning',
geometry: [
[47, 11],
[47.01, 11],
],
point_count: 2,
distance_km: 1.1,
elevation_gain_m: null,
elevation_loss_m: null,
started_at: '2026-07-02T06:10:00.000Z',
ended_at: '2026-07-02T07:00:00.000Z',
duplicate: false,
...overrides,
};
}
function gpxImport(tracks: TourGpxPreviewTrack[]): TourGpxImport {
return {
importing: false,
preview: [{ file: new File(['<gpx/>'], 'morning.gpx'), tracks }],
confirm: vi.fn(),
cancel: vi.fn(),
pick: vi.fn(),
importFiles: vi.fn(),
} as unknown as TourGpxImport;
}
describe('TourGpxPreviewDialog (ACT-01)', () => {
it('FE-GPX-PREVIEW-001: shows when a track was recorded and how long it took, and nothing for one without times', () => {
const tracks = [track(), track({ name: 'Drawn', started_at: null, ended_at: null })];
render(<TourGpxPreviewDialog gpxImport={gpxImport(tracks)} />);
const recorded = screen.getAllByTestId('gpx-preview-recorded');
expect(recorded).toHaveLength(1);
expect(recorded[0]).toHaveTextContent('50 min');
});
it('FE-GPX-PREVIEW-002: imports as the preset type, a paddle tour with its boat and water', () => {
const current = gpxImport([track()]);
render(
<TourGpxPreviewDialog
gpxImport={current}
initial={{ tour_type: 'kayak', boat_type: 'sup', water_context: 'lake' }}
/>
);
fireEvent.click(screen.getByTestId('gpx-preview-import'));
expect(current.confirm).toHaveBeenCalledWith({ tour_type: 'kayak', boat_type: 'sup', water_context: 'lake' });
});
it('FE-GPX-PREVIEW-003: a city walk is imported as a city walk, and without a preset as a hike', () => {
const walk = gpxImport([track()]);
const { unmount } = render(<TourGpxPreviewDialog gpxImport={walk} initial={{ tour_type: 'walk' }} />);
fireEvent.click(screen.getByTestId('gpx-preview-import'));
expect(walk.confirm).toHaveBeenCalledWith({ tour_type: 'walk' });
unmount();
const hike = gpxImport([track()]);
render(<TourGpxPreviewDialog gpxImport={hike} />);
fireEvent.click(screen.getByTestId('gpx-preview-import'));
expect(hike.confirm).toHaveBeenCalledWith({ tour_type: 'hike' });
});
});
@@ -1,9 +1,11 @@
import { AlertTriangle, FileDown } from 'lucide-react';
import type { TourGpxImportFields } from '@trek/shared';
import { AlertTriangle, Clock, FileDown } from 'lucide-react';
import { useId, useMemo } from 'react';
import { OFM_POSITRON } from '../../constants/mapDefaults';
import { useTileUrl } from '../../hooks/useTileUrl';
import { useTranslation } from '../../i18n';
import { useSettingsStore } from '../../store/settingsStore';
import { formatDate } from '../../utils/formatters';
import { formatDistance, formatElevation } from '../../utils/units';
import { MapViewAuto } from '../Map/MapViewAuto';
import { SoftPill } from '../Planner/planParts';
@@ -18,14 +20,30 @@ import {
fs,
NEUTRAL_TINT,
} from '../shared/DialogShell';
import { recordedMinutes } from './activity/tourActivityModel';
import { importFields, importMissing, useGpxImportChoices } from './gpxImportChoices';
import { GpxImportTypeSection } from './GpxImportTypeSection';
import { TourNotice } from './tourParts';
import { formatPlannedTourDuration } from './tourPresentation';
import type { GpxPreviewFile, TourGpxImport } from './useTourGpxImport';
const BADGE =
'inline-flex flex-none items-center rounded-full bg-surface-secondary px-2 font-geist tabular-nums leading-[20px] text-content-secondary';
/** ACT-01: when a track was recorded and how long it took, where every point carried a time. */
function RecordedBadge({ track }: { track: GpxPreviewFile['tracks'][number] }) {
const { locale } = useTranslation();
const minutes = recordedMinutes(track.started_at, track.ended_at);
if (minutes === null || !track.started_at) return null;
return (
<span className={`${BADGE} gap-1`} data-testid="gpx-preview-recorded">
<Clock size={10} strokeWidth={2.2} className="flex-none text-content-faint" />
{formatDate(track.started_at.slice(0, 10), locale)}
<span className="text-content-faint">{formatPlannedTourDuration(minutes)}</span>
</span>
);
}
/** One track of the file as a row: its name, and what it measures as badges; a track the trip holds says so. */
function PreviewTrackRow({ name, track }: { name: string; track: GpxPreviewFile['tracks'][number] }) {
const { t } = useTranslation();
@@ -54,6 +72,7 @@ function PreviewTrackRow({ name, track }: { name: string; track: GpxPreviewFile[
<span className={BADGE}>{t('tours.import.previewNoHeights')}</span>
)}
<span className={BADGE}>{t('tours.import.previewPoints', { count: track.point_count })}</span>
<RecordedBadge track={track} />
</div>
</li>
);
@@ -66,19 +85,36 @@ function PreviewTrackRow({ name, track }: { name: string; track: GpxPreviewFile[
* and water, as a planned paddle tour does, a ski import its discipline
* (SKI-02); a ride (HOR-02) says before anything is stored that its line stays
* as recorded, gets no riding time and is not checked for access. Closing it
* stores nothing.
* stores nothing. `initial` presets the type, as a recording imported for a
* tour takes that tour's (ACT-01); left out, it is a hike.
*/
export default function TourGpxPreviewDialog({ gpxImport }: { gpxImport: TourGpxImport }) {
export default function TourGpxPreviewDialog({
gpxImport,
initial,
}: {
gpxImport: TourGpxImport;
initial?: TourGpxImportFields;
}) {
const { preview } = gpxImport;
if (!preview) return null;
return <PreviewDialog gpxImport={gpxImport} files={preview} />;
return <PreviewDialog gpxImport={gpxImport} files={preview} initial={initial ?? HIKE} />;
}
function PreviewDialog({ gpxImport, files }: { gpxImport: TourGpxImport; files: GpxPreviewFile[] }) {
const HIKE: TourGpxImportFields = { tour_type: 'hike' };
function PreviewDialog({
gpxImport,
files,
initial,
}: {
gpxImport: TourGpxImport;
files: GpxPreviewFile[];
initial: TourGpxImportFields;
}) {
const { t } = useTranslation();
const labelId = useId();
const tileUrl = useTileUrl(OFM_POSITRON);
const choices = useGpxImportChoices();
const choices = useGpxImportChoices(initial);
const tracks = files.flatMap((file) => file.tracks.map((track) => ({ file: file.file, track })));
const fresh = tracks.filter(({ track }) => !track.duplicate).length;
+2 -1
View File
@@ -3,7 +3,7 @@ import { useId, type ReactNode } from 'react'
import { Eye, EyeOff } from 'lucide-react'
import type { TourListItem } from '@trek/shared'
import { fs } from '../shared/DialogShell'
import { TourCautionBadge, TourDaysBadge, TourGradeTile } from './tourParts'
import { TourActivityBadge, TourCautionBadge, TourDaysBadge, TourGradeTile } from './tourParts'
import type { Day } from '../../types'
import { endPlaceDrag, startPlaceDrag } from '../Map/markerDrag'
import { TourDayRowPills } from './TourDayRowFacts'
@@ -76,6 +76,7 @@ function TourRowBody({ tour, nameId, tourDays, dimmed }: {
className="-mx-0.5 mt-0.5 flex h-6 min-w-0 flex-wrap content-start gap-x-1.5 gap-y-2 overflow-hidden px-0.5 pt-0.5"
>
<TourCautionBadge tour={tour} />
<TourActivityBadge tour={tour} />
<TourDayRowPills tour={tour} compact />
<TourDaysBadge tourDays={tourDays} />
</div>
@@ -0,0 +1,23 @@
// FE-ACT-BADGE-001
// ACT-01 on a tour's row: a tour with an actual track and a recording that is
// the actual track of a tour each say so with an icon, the tooltip naming which.
import { render, screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { TourActivityBadge } from '../tourParts';
describe('TourActivityBadge (ACT-01)', () => {
it('FE-ACT-BADGE-001: marks a tour with an actual track and a recording that is one, nothing else', () => {
const { rerender } = render(
<TourActivityBadge tour={{ activity_tracks: [{ id: 1, track_place_id: 9, assignment_id: null }] }} />
);
expect(screen.getByTestId('tour-activity-badge')).toHaveAttribute('aria-label', 'tours.activity.badgeHint');
rerender(<TourActivityBadge tour={{ activity_tracks: [], activity_of: 4 }} />);
expect(screen.getByTestId('tour-activity-badge')).toHaveAttribute('aria-label', 'tours.activity.isTrackHint');
rerender(<TourActivityBadge tour={{ activity_tracks: [], activity_of: null }} />);
expect(screen.queryByTestId('tour-activity-badge')).toBeNull();
rerender(<TourActivityBadge tour={{}} />);
expect(screen.queryByTestId('tour-activity-badge')).toBeNull();
});
});
@@ -0,0 +1,119 @@
// FE-ACT-DIALOG-001 to FE-ACT-DIALOG-004
// ACT-01, the link dialog: the day, the recordings with one taken by another
// tour dimmed, what the choice measures, the GPX import as the second way in,
// and only "Link" writing, once a free recording is chosen.
import { fireEvent, render, screen } from '@testing-library/react';
import type { TourListItem } from '@trek/shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import TourActivityDialog from './TourActivityDialog';
import type { TourActivities } from './useTourActivities';
import type { TrackAssignment } from './useTrackAssignment';
const hook = vi.hoisted(() => ({ assignment: null as unknown }));
vi.mock('./useTrackAssignment', () => ({ useTrackAssignment: () => hook.assignment }));
vi.mock('../TourGpxPreviewDialog', () => ({ default: () => null }));
const tour = { place_id: 7, name: 'Ridge', tour_type: 'hike' } as TourListItem;
const recording = (placeId: number, name: string) =>
({
place_id: placeId,
name,
tour_type: 'hike',
origin: 'gpx',
has_waypoints: false,
distance: 12.4,
track_started_at: '2026-07-02T06:10:00Z',
track_ended_at: '2026-07-02T09:25:00Z',
}) as TourListItem;
function assignment(overrides: Partial<TrackAssignment> = {}): TrackAssignment {
const watch = { tour: recording(20, 'Watch export'), takenBy: null };
return {
executions: [{ assignmentId: 11, day: { id: 1, date: '2026-07-02', title: null }, index: 0 }],
assignmentId: 11,
execution: { assignmentId: 11, day: null, index: 0 },
chooseExecution: vi.fn(),
candidates: [watch, { tour: recording(21, 'Phone export'), takenBy: 'Lake loop' }],
selected: 20,
choose: vi.fn(),
choice: watch,
replaces: null,
gpxImport: {
importing: false,
preview: null,
pick: vi.fn(),
confirm: vi.fn(),
cancel: vi.fn(),
importFiles: vi.fn(),
},
importFields: { tour_type: 'hike' },
ready: true,
...overrides,
} as unknown as TrackAssignment;
}
const state = (overrides: Partial<TourActivities> = {}) =>
({
busy: false,
canEdit: true,
assigning: {},
assign: vi.fn(),
closeAssign: vi.fn(),
...overrides,
}) as unknown as TourActivities;
const show = (current: TourActivities = state()) =>
render(<TourActivityDialog tripId={1} tour={tour} executions={[]} state={current} activities={[]} />);
beforeEach(() => {
hook.assignment = assignment();
});
describe('TourActivityDialog (ACT-01)', () => {
it('FE-ACT-DIALOG-001: offers the recordings, the taken one dimmed with its tour, and what the choice measures', () => {
show();
expect(screen.getByText('tours.activity.dialogEyebrow')).toBeInTheDocument();
expect(screen.getByText('tours.activity.dialogHint')).toBeInTheDocument();
const [watch, phone] = screen.getAllByTestId('tour-activity-candidate');
expect(watch).toHaveAttribute('aria-checked', 'true');
expect(phone).toBeDisabled();
expect(phone).toHaveTextContent('tours.activity.ofTour');
expect(watch).toHaveTextContent('3 h 15 min');
expect(screen.getByText('tours.activity.time')).toBeInTheDocument();
});
it('FE-ACT-DIALOG-002: only Link writes, with the chosen recording and day', () => {
const current = state();
show(current);
fireEvent.click(screen.getAllByTestId('tour-activity-candidate')[0] as HTMLElement);
expect((hook.assignment as TrackAssignment).choose).toHaveBeenCalledWith(20);
expect(current.assign).not.toHaveBeenCalled();
fireEvent.click(screen.getByTestId('tour-activity-confirm'));
expect(current.assign).toHaveBeenCalledWith(20, 11);
});
it('FE-ACT-DIALOG-003: nothing to link until a free recording is chosen; what it replaces is said', () => {
hook.assignment = assignment({ ready: false, choice: null, selected: null, replaces: 'Old export' });
const current = state();
show(current);
expect(screen.getByTestId('tour-activity-confirm')).toBeDisabled();
fireEvent.click(screen.getByTestId('tour-activity-confirm'));
expect(current.assign).not.toHaveBeenCalled();
expect(screen.getByText('tours.activity.replaces')).toBeInTheDocument();
expect(screen.queryByText('tours.activity.time')).toBeNull();
});
it('FE-ACT-DIALOG-004: the GPX import is the way in when the trip has none; a list still loading waits', () => {
const empty = assignment({ candidates: [], choice: null, selected: null, ready: false });
hook.assignment = empty;
const { unmount } = show();
expect(screen.getByText('tours.activity.noCandidates')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /tours.activity.importGpx/ }));
expect(empty.gpxImport.pick).toHaveBeenCalled();
unmount();
hook.assignment = assignment({ candidates: null, choice: null, selected: null, ready: false });
show();
expect(screen.getByLabelText('common.loading')).toBeInTheDocument();
});
});
@@ -0,0 +1,284 @@
import type { TourActivity, TourListItem } from '@trek/shared';
import { AlertTriangle, Check, Clock, FileDown, Footprints, Link2, Loader2, Ruler, Upload } from 'lucide-react';
import { useId, useMemo } from 'react';
import { useTranslation } from '../../../i18n';
import { useSettingsStore } from '../../../store/settingsStore';
import { useTripStore } from '../../../store/tripStore';
import { formatDate } from '../../../utils/formatters';
import { analyzeRouteGeometry } from '../../../utils/routeGeometry';
import { formatDistance } from '../../../utils/units';
import { SoftPill } from '../../Planner/planParts';
import {
DialogButton,
DialogFooter,
DialogHeader,
DialogSection,
DialogShell,
DialogTile,
FooterSpacer,
fs,
NEUTRAL_TINT,
} from '../../shared/DialogShell';
import { PillSelect } from '../../shared/dialogParts';
import TourGpxPreviewDialog from '../TourGpxPreviewDialog';
import { CardAction, TourMetricFields, TourNotice } from '../tourParts';
import { formatPlannedTourDuration, hikeSourceBadgeLabel } from '../tourPresentation';
import { recordedMinutes, type TourExecution, type TrackCandidate } from './tourActivityModel';
import type { TourActivities } from './useTourActivities';
import { useTrackAssignment, type TrackAssignment } from './useTrackAssignment';
/** The value of the execution picker for "no day". */
const NO_DAY = 'none';
/** One recording of the trip to choose: its name and what it is as badges; one taken by another tour is dimmed. */
function CandidateRow({
candidate,
selected,
onChoose,
}: {
candidate: TrackCandidate;
selected: boolean;
onChoose: () => void;
}) {
const { t, locale } = useTranslation();
const unit = useSettingsStore((store) => store.settings.distance_unit) ?? 'metric';
const { tour, takenBy } = candidate;
const minutes = recordedMinutes(tour.track_started_at, tour.track_ended_at);
const recordedOn = tour.track_started_at ? formatDate(tour.track_started_at.slice(0, 10), locale) : null;
return (
<button
type="button"
role="radio"
aria-checked={selected}
disabled={takenBy !== null}
onClick={onChoose}
data-testid="tour-activity-candidate"
className={`flex w-full items-center gap-2.5 rounded-[12px] border px-3 py-2.5 text-start transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent disabled:cursor-default disabled:opacity-55 ${selected ? 'border-accent bg-surface-card shadow-sm' : 'border-edge-faint bg-surface-card enabled:hover:bg-surface-hover'}`}
>
<span
aria-hidden="true"
className={`grid h-5 w-5 flex-none place-items-center rounded-full ring-1 ring-inset ${selected ? 'bg-accent text-accent-text ring-accent' : 'ring-edge'}`}
>
{selected && <Check size={12} strokeWidth={2.6} />}
</span>
<span className="min-w-0 flex-1">
<span className="block truncate font-semibold text-content" style={fs(13, 'body')}>
{tour.name}
</span>
<span className="mt-1 flex flex-wrap items-center gap-1">
<SoftPill icon={<FileDown size={10} strokeWidth={2.2} className="flex-none text-content-faint" />}>
{hikeSourceBadgeLabel(tour, t)}
</SoftPill>
{tour.distance != null && (
<SoftPill icon={<Ruler size={10} strokeWidth={2.2} className="flex-none text-content-faint" />}>
{formatDistance(tour.distance, unit)}
</SoftPill>
)}
{recordedOn && (
<SoftPill icon={<Clock size={10} strokeWidth={2.2} className="flex-none text-content-faint" />}>
{minutes === null ? recordedOn : `${recordedOn} ${formatPlannedTourDuration(minutes)}`}
</SoftPill>
)}
{takenBy !== null && <SoftPill tone="warning">{t('tours.activity.ofTour', { name: takenBy })}</SoftPill>}
</span>
</span>
</button>
);
}
/** The recordings to choose from, or what to do while there is none. */
function CandidateList({ assignment }: { assignment: TrackAssignment }) {
const { t } = useTranslation();
const { candidates } = assignment;
if (candidates === null) {
return (
<div className="flex justify-center py-3 text-content-faint">
<Loader2 size={16} className="animate-spin" aria-label={t('common.loading')} />
</div>
);
}
if (candidates.length === 0) {
return (
<TourNotice role="status" icon={<Footprints size={13} strokeWidth={2} />}>
{t('tours.activity.noCandidates')}
</TourNotice>
);
}
return (
<div role="radiogroup" aria-label={t('tours.activity.track')} className="flex flex-col gap-1.5">
{candidates.map((candidate) => (
<CandidateRow
key={candidate.tour.place_id}
candidate={candidate}
selected={candidate.tour.place_id === assignment.selected}
onChoose={() => assignment.choose(candidate.tour.place_id)}
/>
))}
</div>
);
}
/** What the chosen recording measures, read the way the detail will show it, before anything is written. */
function ChoicePreview({ choice }: { choice: TourListItem }) {
const { t } = useTranslation();
const unit = useSettingsStore((store) => store.settings.distance_unit) ?? 'metric';
const line = useTripStore((store) => store.places.find((place) => place.id === choice.place_id)?.route_geometry);
const analysis = useMemo(() => analyzeRouteGeometry(line), [line]);
const minutes = recordedMinutes(choice.track_started_at, choice.track_ended_at);
return (
<DialogSection label={t('tours.activity.badge')}>
<TourMetricFields
analysis={analysis}
unit={unit}
extra={[
{
label: t('tours.activity.time'),
value: minutes === null ? t('tours.activity.noTime') : formatPlannedTourDuration(minutes),
},
]}
/>
</DialogSection>
);
}
/** The day picker: every day the tour is on, and no day at all. */
function ExecutionPicker({ assignment }: { assignment: TrackAssignment }) {
const { t, locale } = useTranslation();
const options = [
...assignment.executions.map((execution: TourExecution) => ({
value: String(execution.assignmentId),
label: t('dayplan.dayN', { n: execution.index + 1 }),
hint: (execution.day && formatDate(execution.day.date, locale)) || undefined,
})),
{ value: NO_DAY, label: t('tours.activity.noDay') },
];
return (
<PillSelect
quiet
value={assignment.assignmentId === null ? NO_DAY : String(assignment.assignmentId)}
options={options}
onChange={(value) => assignment.chooseExecution(value === NO_DAY ? null : Number(value))}
label={t('tours.activity.execution')}
/>
);
}
interface TourActivityDialogProps {
tripId: number;
tour: TourListItem;
executions: readonly TourExecution[];
state: TourActivities;
activities: readonly TourActivity[];
onToursChanged?: (placeIds: number[]) => Promise<void> | void;
}
/**
* ACT-01: assigning a recorded track, on purpose and confirmed. The user picks
* the day it was done on and a recording of the trip, or imports one through
* the GPX import as always, sees what it measures, and only "Assign" writes.
* The plan is not touched, and the head says so.
*/
export default function TourActivityDialog({
tripId,
tour,
executions,
state,
activities,
onToursChanged,
}: TourActivityDialogProps) {
const { t } = useTranslation();
const labelId = useId();
const assignment = useTrackAssignment({
tripId,
tour,
executions,
activities,
target: state.assigning ?? {},
canEdit: state.canEdit,
onToursChanged,
});
const { gpxImport, choice, selected } = assignment;
const importing = gpxImport.importing || gpxImport.preview !== null;
const confirm = () => {
if (selected !== null && assignment.ready) void state.assign(selected, assignment.assignmentId);
};
return (
<>
<DialogShell
onClose={state.closeAssign}
labelledBy={labelId}
width="detail"
align="top"
blocked={state.busy || importing}
header={
<DialogHeader
tile={
<DialogTile>
<Footprints size={20} strokeWidth={2} className="text-content" />
</DialogTile>
}
tint={NEUTRAL_TINT}
labelId={labelId}
onClose={state.closeAssign}
eyebrow={t('tours.activity.dialogEyebrow')}
title={tour.name}
sub={t('tours.activity.dialogHint')}
subWraps
/>
}
footer={
<DialogFooter>
<FooterSpacer />
<DialogButton onClick={state.closeAssign} disabled={state.busy}>
{t('common.cancel')}
</DialogButton>
<DialogButton
variant="primary"
data-testid="tour-activity-confirm"
disabled={!assignment.ready || state.busy || importing}
icon={
state.busy ? <Loader2 size={14} className="animate-spin" /> : <Link2 size={14} strokeWidth={2} />
}
onClick={confirm}
>
{t('tours.activity.confirm')}
</DialogButton>
</DialogFooter>
}
>
<DialogSection label={t('tours.activity.execution')}>
<ExecutionPicker assignment={assignment} />
</DialogSection>
<DialogSection
label={t('tours.activity.track')}
action={
<CardAction
icon={
gpxImport.importing ? (
<Loader2 size={12} className="animate-spin" />
) : (
<Upload size={12} strokeWidth={2.2} />
)
}
onClick={gpxImport.pick}
disabled={importing}
>
{t('tours.activity.importGpx')}
</CardAction>
}
>
<div className="flex flex-col gap-2">
<CandidateList assignment={assignment} />
{assignment.replaces && (
<TourNotice tone="warning" icon={<AlertTriangle size={13} strokeWidth={2} />}>
{t('tours.activity.replaces', { name: assignment.replaces })}
</TourNotice>
)}
</div>
</DialogSection>
{choice && choice.takenBy === null && <ChoicePreview choice={choice.tour} />}
</DialogShell>
<TourGpxPreviewDialog gpxImport={gpxImport} initial={assignment.importFields} />
</>
);
}
@@ -0,0 +1,135 @@
// FE-ACT-SECTION-001 to FE-ACT-SECTION-005
// ACT-01 in the tour's detail, rendered without the translation provider so
// every text reads as its key: the actual tracks with their own values marked
// as such, a time only where the track measured one, and the actions only for
// someone who may change the tour.
import { fireEvent, render, screen } from '@testing-library/react';
import type { TourActivity, TourListItem } from '@trek/shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { Day } from '../../../types';
import TourActivitySection from './TourActivitySection';
import type { TourActivities } from './useTourActivities';
const hook = vi.hoisted(() => ({ state: null as unknown }));
vi.mock('./useTourActivities', () => ({ useTourActivities: () => hook.state }));
vi.mock('./TourActivityDialog', () => ({ default: () => <div data-testid="tour-activity-dialog" /> }));
const tour = { place_id: 7, name: 'Ridge', tour_type: 'hike' } as TourListItem;
const days = [{ id: 1, date: '2026-07-02', title: null }] as unknown as Day[];
const assignments = { '1': [{ id: 11, place_id: 7 }] } as never;
function activity(overrides: Partial<TourActivity['metrics']> = {}, assignmentId: number | null = 11): TourActivity {
return {
id: 4,
assignment_id: assignmentId,
day_id: 1,
assigned_at: null,
track: { place_id: 20, name: 'Watch export', origin: 'gpx', file_name: 'morning.gpx', imported_at: null },
metrics: {
distance_km: 0.1,
elevation_gain_m: 100,
elevation_loss_m: 0,
started_at: '2026-07-02T06:10:00Z',
ended_at: '2026-07-02T09:25:00Z',
elapsed_minutes: 195,
point_count: 2,
...overrides,
},
geometry: [
[47, 11, 600],
[47.001, 11, 700],
],
};
}
function state(overrides: Partial<TourActivities> = {}): TourActivities {
return {
activities: [activity()],
canEdit: true,
busy: false,
assigning: null,
openAssign: vi.fn(),
closeAssign: vi.fn(),
assign: vi.fn(),
removing: null,
askRemove: vi.fn(),
cancelRemove: vi.fn(),
remove: vi.fn(),
...overrides,
} as TourActivities;
}
const show = (canEdit = true, item: TourListItem = tour) =>
render(<TourActivitySection tripId={1} tour={item} days={days} assignments={assignments} canEdit={canEdit} />);
beforeEach(() => {
hook.state = state();
});
describe('TourActivitySection (ACT-01)', () => {
it('FE-ACT-SECTION-001: shows an actual track with its day, its file, its own values and its profile', () => {
show();
expect(screen.getByText('tours.activity.label')).toBeInTheDocument();
expect(screen.getByText('Watch export')).toBeInTheDocument();
expect(screen.getByTestId('tour-activity-day')).toHaveTextContent('dayplan.dayN');
expect(screen.getByText('morning.gpx')).toBeInTheDocument();
expect(screen.getByText('tours.activity.badge')).toBeInTheDocument();
expect(screen.getByText('tours.activity.time')).toBeInTheDocument();
expect(screen.getByText('3 h 15 min')).toBeInTheDocument();
expect(screen.getByText('tours.detail.ascent')).toBeInTheDocument();
});
it('FE-ACT-SECTION-002: a track without times measures no time, and a track without a day says so', () => {
hook.state = state({ activities: [activity({ elapsed_minutes: null, started_at: null, ended_at: null }, null)] });
show();
expect(screen.getByText('tours.activity.noTime')).toBeInTheDocument();
expect(screen.getByTestId('tour-activity-day')).toHaveTextContent('tours.activity.noDay');
expect(screen.queryByText('tours.activity.recordedOn')).toBeNull();
});
it('FE-ACT-SECTION-003: someone who may change the tour links, changes and unlinks; the dialog opens when asked', () => {
const current = state();
hook.state = current;
const { rerender } = show();
fireEvent.click(screen.getByRole('button', { name: /tours.activity.assign$/ }));
expect(current.openAssign).toHaveBeenCalledWith();
fireEvent.click(screen.getByRole('button', { name: /tours.activity.change/ }));
expect(current.openAssign).toHaveBeenCalledWith({ assignmentId: 11 });
fireEvent.click(screen.getByRole('button', { name: /tours.activity.remove/ }));
expect(current.askRemove).toHaveBeenCalledWith(current.activities?.[0]);
hook.state = state({ assigning: {}, removing: activity() });
rerender(<TourActivitySection tripId={1} tour={tour} days={days} assignments={assignments} canEdit />);
expect(screen.getByTestId('tour-activity-dialog')).toBeInTheDocument();
expect(screen.getByText('tours.activity.removeTitle')).toBeInTheDocument();
});
it('FE-ACT-SECTION-004: without the right to change it, the values show and no action does', () => {
hook.state = state({ canEdit: false });
show(false);
expect(screen.getByText('Watch export')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: /tours.activity.assign$/ })).toBeNull();
expect(screen.queryByRole('button', { name: /tours.activity.remove/ })).toBeNull();
});
it('FE-ACT-SECTION-005: an empty place for one when it may be linked; nothing while loading, when it cannot, or for a track of another tour', () => {
hook.state = state({ activities: [] });
const { unmount } = show();
expect(screen.getByTestId('tour-activity-empty')).toHaveTextContent('tours.activity.empty');
unmount();
hook.state = state({ activities: [], canEdit: false });
const readOnly = show(false);
expect(readOnly.container).toBeEmptyDOMElement();
readOnly.unmount();
hook.state = state({ activities: null });
const loading = show();
expect(loading.container).toBeEmptyDOMElement();
loading.unmount();
hook.state = state();
const track = show(true, { ...tour, activity_of: 3 });
expect(track.container).toBeEmptyDOMElement();
});
});
@@ -0,0 +1,243 @@
import type { TourActivity, TourListItem } from '@trek/shared';
import { CalendarDays, Clock, FileDown, Footprints, Plus, RefreshCw, Unlink } from 'lucide-react';
import { useMemo } from 'react';
import { useTranslation } from '../../../i18n';
import { useSettingsStore } from '../../../store/settingsStore';
import type { AssignmentsMap, Day } from '../../../types';
import { formatDate } from '../../../utils/formatters';
import { BOX } from '../../Planner/bookings/bookingParts';
import { SoftPill } from '../../Planner/planParts';
import ConfirmDialog from '../../shared/ConfirmDialog';
import { DialogSection, fs } from '../../shared/DialogShell';
import ElevationProfile from '../../shared/ElevationProfile';
import { Tooltip } from '../../shared/Tooltip';
import { dayMenuLabel } from '../tourDays';
import { CardAction, TourMetricFields, type TourMetricField } from '../tourParts';
import { formatPlannedTourDuration } from '../tourPresentation';
import TourActivityDialog from './TourActivityDialog';
import { analysisOfLine, executionOf, executionsOf, type TourExecution } from './tourActivityModel';
import { useTourActivities, type TourActivities } from './useTourActivities';
type Translate = (key: string, params?: Record<string, unknown>) => string;
/** The line and the profile of what was recorded take the colour of done, apart from the plan's track colour. */
const RECORDED_COLOR = 'var(--success)';
/** The recorded time as a field: measured from the track's times, or said to be missing, never estimated. */
function timeField(activity: TourActivity, t: Translate): TourMetricField {
const minutes = activity.metrics.elapsed_minutes;
const label = t('tours.activity.time');
return minutes === null
? { label, value: t('tours.activity.noTime'), info: { label, description: t('tours.activity.noTimeHint') } }
: { label, value: formatPlannedTourDuration(minutes), info: { label, description: t('tours.activity.timeHint') } };
}
/** The tile of a recording: footprints, with a small dot at its foot that says it was recorded. */
function RecordedTile() {
return (
<span className="relative grid h-9 w-9 flex-none place-items-center rounded-full bg-surface-secondary text-content-secondary">
<Footprints size={15} strokeWidth={2} aria-hidden="true" />
<span
aria-hidden="true"
className="absolute -bottom-0.5 -end-0.5 h-3 w-3 rounded-full bg-success ring-2 ring-surface-card"
/>
</span>
);
}
/** Where and when: the execution, the file it came from, the day it was recorded, each a badge of its own. */
function ActivityBadges({ activity, execution }: { activity: TourActivity; execution: TourExecution }) {
const { t, locale } = useTranslation();
const dayLabel = execution.day ? t('dayplan.dayN', { n: execution.index + 1 }) : t('tours.activity.noDay');
const dayTitle = execution.day ? dayMenuLabel(execution.day, execution.index, t, locale) : dayLabel;
const recordedOn = activity.metrics.started_at ? formatDate(activity.metrics.started_at.slice(0, 10), locale) : null;
const source =
activity.track.file_name ?? t(activity.track.origin === 'wanderer' ? 'tours.badge.wanderer' : 'tours.badge.gpx');
return (
<div className="mt-1 flex flex-wrap items-center gap-1">
<Tooltip label={dayTitle}>
<span className="inline-flex" data-testid="tour-activity-day">
<SoftPill icon={<CalendarDays size={10} strokeWidth={2.2} className="flex-none text-content-faint" />}>
{dayLabel}
</SoftPill>
</span>
</Tooltip>
<SoftPill
className="max-w-[180px]"
icon={<FileDown size={10} strokeWidth={2.2} className="flex-none text-content-faint" />}
>
<span className="min-w-0 truncate">{source}</span>
</SoftPill>
{recordedOn && (
<SoftPill icon={<Clock size={10} strokeWidth={2.2} className="flex-none text-content-faint" />}>
{t('tours.activity.recordedOn', { date: recordedOn })}
</SoftPill>
)}
</div>
);
}
/** One recording: who it is, its values marked as recorded, its profile, and what the user can do with it. */
function ActivityCard({
activity,
execution,
state,
}: {
activity: TourActivity;
execution: TourExecution;
state: TourActivities;
}) {
const { t } = useTranslation();
const unit = useSettingsStore((store) => store.settings.distance_unit) ?? 'metric';
const analysis = useMemo(() => analysisOfLine(activity.geometry), [activity.geometry]);
return (
<article data-testid="tour-activity" className={`${BOX} overflow-hidden`}>
<header className="flex items-start gap-2.5 px-3 py-2.5">
<RecordedTile />
<div className="min-w-0 flex-1">
<div className="truncate font-semibold text-content" style={fs(13, 'body')}>
{activity.track.name}
</div>
<ActivityBadges activity={activity} execution={execution} />
</div>
<Tooltip label={t('tours.activity.badgeHint')}>
<span className="inline-flex">
<SoftPill tone="success" caps>
{t('tours.activity.badge')}
</SoftPill>
</span>
</Tooltip>
</header>
<div className="flex flex-col gap-2 border-t border-edge-faint p-2.5">
<TourMetricFields analysis={analysis} unit={unit} extra={[timeField(activity, t)]} />
{analysis && analysis.distanceIndexedProfileSamples.length >= 2 && (
<ElevationProfile
samples={analysis.distanceIndexedProfileSamples}
color={RECORDED_COLOR}
gradientId={`tour-activity-${activity.id}`}
/>
)}
</div>
{state.canEdit && (
<footer className="flex flex-wrap gap-1.5 border-t border-edge-faint px-2.5 py-2">
<CardAction
icon={<RefreshCw size={12} strokeWidth={2.2} />}
onClick={() => state.openAssign({ assignmentId: activity.assignment_id })}
disabled={state.busy}
>
{t('tours.activity.change')}
</CardAction>
<CardAction
icon={<Unlink size={12} strokeWidth={2.2} />}
onClick={() => state.askRemove(activity)}
disabled={state.busy}
>
{t('tours.activity.remove')}
</CardAction>
</footer>
)}
</article>
);
}
/** No recording yet: a quiet line, dimmed rather than hidden, so the place for one is known. */
function NoActivity() {
const { t } = useTranslation();
return (
<div
data-testid="tour-activity-empty"
className={`${BOX} flex items-center gap-2.5 px-3 py-2.5 text-content-faint`}
style={fs(12, 'body')}
>
<span className="grid h-7 w-7 flex-none place-items-center rounded-full border border-dashed border-edge">
<Footprints size={13} strokeWidth={2} aria-hidden="true" />
</span>
{t('tours.activity.empty')}
</div>
);
}
interface TourActivitySectionProps {
tripId: number;
tour: TourListItem;
days: Day[];
assignments: AssignmentsMap;
canEdit: boolean;
onToursChanged?: (placeIds: number[]) => Promise<void> | void;
}
/**
* ACT-01 in the tour's detail: the tracks the tour was actually done with,
* each with the values its own recording measures and its profile, apart from
* the planned values above; and for someone who may change the tour, the way
* to assign one, change it or take it off. A tour that is itself the recording
* of another shows none: it says so in its head instead.
*/
export default function TourActivitySection({
tripId,
tour,
days,
assignments,
canEdit,
onToursChanged,
}: TourActivitySectionProps) {
const { t } = useTranslation();
const executions = useMemo(() => executionsOf(tour.place_id, days, assignments), [assignments, days, tour.place_id]);
const state = useTourActivities({ tripId, tour, executions, canEdit, onToursChanged });
const { activities } = state;
if (activities === null || tour.activity_of != null || (activities.length === 0 && !canEdit)) return null;
return (
<DialogSection
className="flex-none"
label={t('tours.activity.label')}
action={
canEdit && (
<Tooltip label={t('tours.activity.assignHint')}>
<span className="inline-flex">
<CardAction
icon={<Plus size={12} strokeWidth={2.2} />}
onClick={() => state.openAssign()}
disabled={state.busy}
>
{t('tours.activity.assign')}
</CardAction>
</span>
</Tooltip>
)
}
>
{activities.length === 0 ? (
<NoActivity />
) : (
<div className="flex flex-col gap-2">
{activities.map((activity) => (
<ActivityCard
key={activity.id}
activity={activity}
execution={executionOf(executions, activity.assignment_id)}
state={state}
/>
))}
</div>
)}
{state.assigning && (
<TourActivityDialog
tripId={tripId}
tour={tour}
executions={executions}
state={state}
activities={activities}
onToursChanged={onToursChanged}
/>
)}
<ConfirmDialog
isOpen={state.removing !== null}
onClose={state.cancelRemove}
onConfirm={() => void state.remove()}
title={t('tours.activity.removeTitle')}
message={t('tours.activity.removeBody')}
confirmLabel={t('tours.activity.remove')}
/>
</DialogSection>
);
}
@@ -0,0 +1,147 @@
// FE-ACT-MODEL-001 to FE-ACT-MODEL-008
// ACT-01, the pure half of a tour's actual tracks: its executions, the
// recordings that can be linked, the GPX preset, the time and the refusals.
import type { TourActivity, TourListItem } from '@trek/shared';
import { describe, expect, it } from 'vitest';
import type { Assignment, AssignmentsMap, Day } from '../../../types';
import {
analysisOfLine,
executionOf,
executionsOf,
importFieldsFor,
inDayOrder,
isRecording,
recordedMinutes,
refusalOf,
trackCandidates,
} from './tourActivityModel';
const day = (id: number, date: string | null = null) => ({ id, date, title: null }) as unknown as Day;
const days = [day(1, '2026-07-01'), day(2, '2026-07-02'), day(3, '2026-07-03')];
const assignments: AssignmentsMap = {
'1': [{ id: 11, place_id: 7 } as Assignment, { id: 12, place_id: 8 } as Assignment],
'3': [{ id: 31, place_id: 7 } as Assignment],
};
function tour(overrides: Partial<TourListItem> = {}): TourListItem {
return {
place_id: 7,
name: 'Ridge',
tour_type: 'hike',
distance: 8,
elevation_gain: 600,
elevation_loss: 600,
duration: 180,
difficulty: null,
wanderer_ref: null,
match_confidence: 1,
max_hiking_difficulty: 2,
planned: true,
caution: false,
has_waypoints: true,
origin: 'trek',
...overrides,
};
}
const activity = (id: number, assignmentId: number | null) =>
({ id, assignment_id: assignmentId }) as unknown as TourActivity;
describe('executions', () => {
it('FE-ACT-MODEL-001: lists the days the tour is on with their assignment, in trip order', () => {
const executions = executionsOf(7, days, assignments);
expect(executions.map((execution) => [execution.assignmentId, execution.day?.id, execution.index])).toEqual([
[11, 1, 0],
[31, 3, 2],
]);
expect(executionOf(executions, 31).index).toBe(2);
expect(executionOf(executions, null)).toEqual({ assignmentId: null, day: null, index: -1 });
expect(executionOf(executions, 99).day).toBeNull();
});
it('FE-ACT-MODEL-002: orders the actual tracks by their days, the ones without a day last', () => {
const executions = executionsOf(7, days, assignments);
const ordered = inDayOrder([activity(1, null), activity(2, 31), activity(3, 11), activity(4, null)], executions);
expect(ordered.map((item) => item.id)).toEqual([3, 2, 1, 4]);
});
});
describe('candidates', () => {
it('FE-ACT-MODEL-003: a recording is an import nobody planned over', () => {
expect(isRecording(tour({ origin: 'gpx', has_waypoints: false }))).toBe(true);
expect(isRecording(tour({ origin: 'wanderer', has_waypoints: false }))).toBe(true);
expect(isRecording(tour({ origin: 'gpx', has_waypoints: true }))).toBe(false);
expect(isRecording(tour({ origin: 'trek', has_waypoints: false }))).toBe(false);
expect(isRecording(tour({ origin: undefined, has_waypoints: false }))).toBe(false);
});
it('FE-ACT-MODEL-004: offers the recordings, dims one taken by another tour and leaves out the rest', () => {
const tours = [
tour(),
tour({ place_id: 20, name: 'Watch', origin: 'gpx', has_waypoints: false }),
tour({ place_id: 21, name: 'Phone', origin: 'gpx', has_waypoints: false, activity_of: 30 }),
tour({ place_id: 22, name: 'Mine', origin: 'gpx', has_waypoints: false, activity_of: 7 }),
tour({
place_id: 23,
name: 'Plan',
origin: 'gpx',
has_waypoints: false,
activity_tracks: [{ id: 1, track_place_id: 24, assignment_id: null }],
}),
tour({ place_id: 30, name: 'Lake' }),
];
expect(trackCandidates(tours, 7).map(({ tour: item, takenBy }) => [item.place_id, takenBy])).toEqual([
[20, null],
[21, 'Lake'],
[22, null],
]);
});
});
describe('the GPX preset', () => {
it('FE-ACT-MODEL-005: imports a recording as the tour’s own type', () => {
expect(importFieldsFor(tour({ tour_type: 'bike', bike_profile: 'gravel' }))).toEqual({
tour_type: 'bike',
bike_profile: 'gravel',
});
expect(importFieldsFor(tour({ tour_type: 'bike', bike_profile: null }))).toEqual({
tour_type: 'bike',
bike_profile: 'touring',
});
expect(importFieldsFor(tour({ tour_type: 'kayak', boat_type: 'sup', water_context: 'lake' }))).toEqual({
tour_type: 'kayak',
boat_type: 'sup',
water_context: 'lake',
});
expect(importFieldsFor(tour({ tour_type: 'kayak', boat_type: null, water_context: null }))).toEqual({
tour_type: 'kayak',
});
expect(importFieldsFor(tour({ tour_type: 'walk' }))).toEqual({ tour_type: 'walk' });
expect(importFieldsFor(tour({ tour_type: 'ski' }))).toEqual({ tour_type: 'hike' });
});
});
describe('measures', () => {
it('FE-ACT-MODEL-006: the time is only what the track’s times say', () => {
expect(recordedMinutes('2026-07-02T06:10:00Z', '2026-07-02T09:25:00Z')).toBe(195);
expect(recordedMinutes(null, '2026-07-02T09:25:00Z')).toBeNull();
expect(recordedMinutes('2026-07-02T09:25:00Z', '2026-07-02T06:10:00Z')).toBeNull();
expect(recordedMinutes('nonsense', undefined)).toBeNull();
});
it('FE-ACT-MODEL-007: analyses a line like the plan’s, and nothing of fewer than two points', () => {
const analysis = analysisOfLine([
[47, 11, 600],
[47.01, 11, 700],
]);
expect(analysis?.gain).toBe(100);
expect(analysisOfLine([[47, 11]])).toBeNull();
});
it('FE-ACT-MODEL-008: reads the server’s reason for a refusal, and none from anything else', () => {
expect(refusalOf({ response: { data: { code: 'activity_track_in_use' } } })).toBe('activity_track_in_use');
expect(refusalOf({ response: { data: { code: 'tour_revision_conflict' } } })).toBeNull();
expect(refusalOf(new Error('offline'))).toBeNull();
expect(refusalOf(null)).toBeNull();
});
});
@@ -0,0 +1,126 @@
import {
TOUR_ACTIVITY_REFUSALS,
type TourActivity,
type TourActivityRefusal,
type TourGpxImportFields,
type TourListItem,
} from '@trek/shared';
import type { AssignmentsMap, Day } from '../../../types';
import { analyzeRouteGeometry, type RouteGeometryAnalysis } from '../../../utils/routeGeometry';
/**
* ACT-01, the pure half of a tour's recorded tracks: the executions a
* recording can belong to (the days the tour is on, or none), the recordings
* of the trip that can be assigned, and what one of them measures.
*/
/** One execution of a tour: a day it is on, through its day assignment; `null` assignment for none. */
export interface TourExecution {
assignmentId: number | null;
day: Day | null;
/** The day's position in the trip, so `index + 1` is the number the plan shows; -1 without a day. */
index: number;
}
/** Every day the tour is on, in the order of the trip, each with its assignment. */
export function executionsOf(placeId: number, days: readonly Day[], assignments: AssignmentsMap): TourExecution[] {
return days.flatMap((day, index) => {
const assignment = (assignments[String(day.id)] ?? []).find((item) => item.place_id === placeId);
return assignment ? [{ assignmentId: assignment.id, day, index }] : [];
});
}
/** The execution an assignment stands for; one whose day is gone reads as none. */
export function executionOf(executions: readonly TourExecution[], assignmentId: number | null): TourExecution {
return (
executions.find((execution) => execution.assignmentId === assignmentId) ?? {
assignmentId: null,
day: null,
index: -1,
}
);
}
/** The recordings in the order of the days they belong to, the ones without a day last. */
export function inDayOrder(activities: readonly TourActivity[], executions: readonly TourExecution[]): TourActivity[] {
const position = (activity: TourActivity) => {
const index = executionOf(executions, activity.assignment_id).index;
return index < 0 ? Number.MAX_SAFE_INTEGER : index;
};
return [...activities].sort((a, b) => position(a) - position(b) || a.id - b.id);
}
/** A tour of the trip that still is the line it was recorded with: an import nobody planned over. */
export function isRecording(tour: Pick<TourListItem, 'origin' | 'has_waypoints'>): boolean {
return tour.origin !== undefined && tour.origin !== 'trek' && !tour.has_waypoints;
}
/**
* What can be offered for this tour: every recording of the trip but the tour
* itself and the ones with recordings of their own. One that documents another
* tour stays in the list, dimmed, with that tour's name, so the user sees why
* it cannot be picked rather than missing it.
*/
export interface TrackCandidate {
tour: TourListItem;
/** The other tour this recording documents already; null while it is free or this tour's own. */
takenBy: string | null;
}
export function trackCandidates(tours: readonly TourListItem[], placeId: number): TrackCandidate[] {
const names = new Map(tours.map((tour) => [tour.place_id, tour.name]));
return tours
.filter((tour) => tour.place_id !== placeId && isRecording(tour) && !tour.activity_tracks?.length)
.map((tour) => {
const owner = tour.activity_of ?? null;
return { tour, takenBy: owner !== null && owner !== placeId ? (names.get(owner) ?? '') : null };
});
}
/**
* The type a recording of this tour is imported as, preset in the GPX
* preview: the tour's own, with its bike or run profile or its boat and water where
* it has them. A type the import does not offer starts as a hike, as the
* preview always did.
*/
export function importFieldsFor(
tour: Pick<TourListItem, 'tour_type' | 'bike_profile' | 'boat_type' | 'water_context'> &
Partial<Pick<TourListItem, 'run_profile'>>
): TourGpxImportFields {
switch (tour.tour_type) {
case 'bike':
return { tour_type: 'bike', bike_profile: tour.bike_profile ?? 'touring' };
case 'run':
return { tour_type: 'run', run_profile: tour.run_profile ?? 'running' };
case 'horse':
return { tour_type: 'horse' };
case 'kayak':
return {
tour_type: 'kayak',
...(tour.boat_type ? { boat_type: tour.boat_type } : {}),
...(tour.water_context ? { water_context: tour.water_context } : {}),
};
case 'walk':
return { tour_type: 'walk' };
default:
return { tour_type: 'hike' };
}
}
/** A recording's line analysed the way the plan's is, so both read alike. */
export function analysisOfLine(geometry: TourActivity['geometry']): RouteGeometryAnalysis | null {
return geometry.length >= 2 ? analyzeRouteGeometry(JSON.stringify(geometry)) : null;
}
/** Minutes from a track's first to its last time, pauses included; null unless both are there and in order. */
export function recordedMinutes(startedAt?: string | null, endedAt?: string | null): number | null {
const start = startedAt ? Date.parse(startedAt) : Number.NaN;
const end = endedAt ? Date.parse(endedAt) : Number.NaN;
return Number.isFinite(start) && Number.isFinite(end) && end > start ? Math.round((end - start) / 60_000) : null;
}
/** Why the server refused an assignment, when it named a reason this build knows; null for anything else. */
export function refusalOf(error: unknown): TourActivityRefusal | null {
const code = (error as { response?: { data?: { code?: unknown } } } | null)?.response?.data?.code;
return TOUR_ACTIVITY_REFUSALS.find((known) => known === code) ?? null;
}
@@ -0,0 +1,133 @@
// FE-ACT-HOOK-001 to FE-ACT-HOOK-005
// ACT-01: the actual tracks read with the tour's detail, linked from the
// dialog and unlinked after confirming, each write telling the lists and the
// user, and a refusal named in the user's words without changing anything.
import { act, renderHook, waitFor } from '@testing-library/react';
import type { TourActivity, TourListItem } from '@trek/shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { TourExecution } from './tourActivityModel';
import { useTourActivities } from './useTourActivities';
const repo = vi.hoisted(() => ({ detail: vi.fn(), assignActivity: vi.fn(), unassignActivity: vi.fn() }));
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }));
vi.mock('../../../repo/tourRepo', () => ({ tourRepo: repo }));
vi.mock('../../shared/Toast', () => ({ useToast: () => toast }));
const tour = { place_id: 7, name: 'Ridge', activity_tracks: [] } as unknown as TourListItem;
const executions: TourExecution[] = [{ assignmentId: 11, day: null, index: 0 }];
function activity(id: number, assignmentId: number | null, trackPlaceId = 20): TourActivity {
return {
id,
assignment_id: assignmentId,
day_id: null,
assigned_at: null,
track: { place_id: trackPlaceId, name: 'Watch', origin: 'gpx', file_name: null, imported_at: null },
metrics: {
distance_km: 3,
elevation_gain_m: null,
elevation_loss_m: null,
started_at: null,
ended_at: null,
elapsed_minutes: null,
point_count: 2,
},
geometry: [],
};
}
beforeEach(() => {
vi.clearAllMocks();
repo.detail.mockResolvedValue({ tour, waypoints: [], activities: [activity(1, null), activity(2, 11, 21)] });
});
function render(canEdit = true, onToursChanged = vi.fn()) {
return renderHook(
({ current }) => useTourActivities({ tripId: 1, tour: current, executions, canEdit, onToursChanged }),
{ initialProps: { current: tour } }
);
}
describe('useTourActivities', () => {
it('FE-ACT-HOOK-001: reads the actual tracks with the detail, in day order, and again when the list says they changed', async () => {
const { result, rerender } = render();
expect(result.current.activities).toBeNull();
await waitFor(() => expect(result.current.activities?.map((item) => item.id)).toEqual([2, 1]));
expect(repo.detail).toHaveBeenCalledWith(1, 7, expect.any(AbortSignal));
rerender({ current: { ...tour, activity_tracks: [{ id: 3, track_place_id: 22, assignment_id: null }] } });
await waitFor(() => expect(repo.detail).toHaveBeenCalledTimes(2));
});
it('FE-ACT-HOOK-002: a detail that cannot be had shows none', async () => {
repo.detail.mockRejectedValueOnce(new Error('offline'));
const { result } = render();
await waitFor(() => expect(result.current.activities).toEqual([]));
});
it('FE-ACT-HOOK-003: links the confirmed track, takes the answer in, tells the lists and closes the dialog', async () => {
const onToursChanged = vi.fn();
repo.assignActivity.mockResolvedValue({ tour, waypoints: [], activities: [activity(5, 11, 30)] });
const { result } = render(true, onToursChanged);
await waitFor(() => expect(result.current.activities).not.toBeNull());
act(() => result.current.openAssign({ assignmentId: 11 }));
expect(result.current.assigning).toEqual({ assignmentId: 11 });
await act(async () => result.current.assign(30, 11));
expect(repo.assignActivity).toHaveBeenCalledWith(1, 7, { track_place_id: 30, assignment_id: 11 });
expect(result.current.activities?.map((item) => item.id)).toEqual([5]);
expect(onToursChanged).toHaveBeenCalledWith([7, 30]);
expect(toast.success).toHaveBeenCalledWith('tours.activity.assigned');
expect(result.current.assigning).toBeNull();
});
it('FE-ACT-HOOK-004: a refusal names its reason, keeps the dialog open and changes nothing', async () => {
repo.assignActivity.mockRejectedValue({ response: { status: 409, data: { code: 'activity_track_in_use' } } });
const { result } = render();
await waitFor(() => expect(result.current.activities).not.toBeNull());
act(() => result.current.openAssign());
await act(async () => result.current.assign(30, null));
expect(toast.error).toHaveBeenCalledWith('tours.activity.refused.activity_track_in_use');
expect(result.current.assigning).toEqual({});
expect(result.current.activities?.map((item) => item.id)).toEqual([2, 1]);
repo.assignActivity.mockRejectedValue(new Error('offline'));
await act(async () => result.current.assign(30, null));
expect(toast.error).toHaveBeenLastCalledWith('tours.activity.failed');
act(() => result.current.closeAssign());
expect(result.current.assigning).toBeNull();
});
it('FE-ACT-HOOK-005: unlinks only after the question, and nothing for someone who may not change the tour', async () => {
const onToursChanged = vi.fn();
repo.unassignActivity.mockResolvedValue({ tour, waypoints: [], activities: [] });
const { result } = render(true, onToursChanged);
await waitFor(() => expect(result.current.activities).not.toBeNull());
const target = result.current.activities?.[0] as TourActivity;
act(() => result.current.askRemove(target));
expect(result.current.removing).toBe(target);
act(() => result.current.cancelRemove());
await act(async () => result.current.remove());
expect(repo.unassignActivity).not.toHaveBeenCalled();
act(() => result.current.askRemove(target));
await act(async () => result.current.remove());
expect(repo.unassignActivity).toHaveBeenCalledWith(1, 7, 2);
expect(onToursChanged).toHaveBeenCalledWith([7, 21]);
expect(toast.success).toHaveBeenCalledWith('tours.activity.removed');
expect(result.current.activities).toEqual([]);
const readOnly = render(false);
await waitFor(() => expect(readOnly.result.current.activities).not.toBeNull());
act(() => {
readOnly.result.current.openAssign();
readOnly.result.current.askRemove(target);
});
expect(readOnly.result.current.assigning).toBeNull();
expect(readOnly.result.current.removing).toBeNull();
await act(async () => readOnly.result.current.assign(30, null));
expect(repo.assignActivity).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,133 @@
import type { TourActivity, TourDetailResponse, TourListItem } from '@trek/shared';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from '../../../i18n';
import { tourRepo } from '../../../repo/tourRepo';
import { useToast } from '../../shared/Toast';
import { inDayOrder, refusalOf, type TourExecution } from './tourActivityModel';
interface TourActivitiesOptions {
tripId: number;
tour: TourListItem;
/** The days the tour is on, each an execution a recording can belong to. */
executions: readonly TourExecution[];
canEdit: boolean;
/** Lets the trip's lists take in a change: the tour lists its recordings, a recording the tour it documents. */
onToursChanged?: (placeIds: number[]) => Promise<void> | void;
}
/** Which execution the assignment dialog is open for: `undefined` lets it pick the first free one. */
export interface AssignTarget {
assignmentId?: number | null;
}
/** The refs a list item names, so the detail is read again when another client changed them. */
function refsKey(tour: TourListItem): string {
return (tour.activity_tracks ?? []).map((ref) => `${ref.id}:${ref.track_place_id}:${ref.assignment_id}`).join(',');
}
/**
* ACT-01: the recorded tracks of a tour in its detail, read with the detail
* (online from the server, offline from the copy the last detail left), and
* the two changes the user can make: open the assignment for an execution,
* and take a recording off after confirming it. Both writes are online only,
* as the GPX import a recording comes through is; a refused one says why and
* changes nothing.
*/
export function useTourActivities({ tripId, tour, executions, canEdit, onToursChanged }: TourActivitiesOptions) {
const { t } = useTranslation();
const toast = useToast();
const placeId = tour.place_id;
const refs = refsKey(tour);
const [loaded, setLoaded] = useState<{ placeId: number; activities: TourActivity[] } | null>(null);
const [assigning, setAssigning] = useState<AssignTarget | null>(null);
const [removing, setRemoving] = useState<TourActivity | null>(null);
const [busy, setBusy] = useState(false);
useEffect(() => {
const controller = new AbortController();
tourRepo.detail(tripId, placeId, controller.signal).then(
(detail) => {
if (!controller.signal.aborted) setLoaded({ placeId, activities: detail.activities ?? [] });
},
() => {
if (!controller.signal.aborted) setLoaded({ placeId, activities: [] });
}
);
return () => controller.abort();
// `refs` is the list's word that the recordings changed elsewhere.
}, [tripId, placeId, refs]);
const activities = useMemo(
() => (loaded?.placeId === placeId ? inDayOrder(loaded.activities, executions) : null),
[executions, loaded, placeId]
);
/** One write, its answer taken in, the lists told and the user too; false when it was refused. */
const apply = useCallback(
async (write: () => Promise<TourDetailResponse>, success: string, changed: number[]): Promise<boolean> => {
setBusy(true);
try {
const detail = await write();
setLoaded({ placeId, activities: detail.activities ?? [] });
await onToursChanged?.(changed);
toast.success(t(success));
return true;
} catch (error: unknown) {
const refusal = refusalOf(error);
toast.error(t(refusal ? `tours.activity.refused.${refusal}` : 'tours.activity.failed'));
return false;
} finally {
setBusy(false);
}
},
[onToursChanged, placeId, t, toast]
);
/** The confirmed assignment from the dialog; the dialog closes once it is written. */
const assign = useCallback(
async (trackPlaceId: number, assignmentId: number | null) => {
if (!canEdit || busy) return;
const done = await apply(
() => tourRepo.assignActivity(tripId, placeId, { track_place_id: trackPlaceId, assignment_id: assignmentId }),
'tours.activity.assigned',
[placeId, trackPlaceId]
);
if (done) setAssigning(null);
},
[apply, busy, canEdit, placeId, tripId]
);
/** The recording asked about, taken off once the user confirmed it. */
const remove = useCallback(async () => {
const target = removing;
if (!canEdit || !target || busy) return;
setRemoving(null);
await apply(() => tourRepo.unassignActivity(tripId, placeId, target.id), 'tours.activity.removed', [
placeId,
target.track.place_id,
]);
}, [apply, busy, canEdit, placeId, removing, tripId]);
return {
/** Null while the detail loads. */
activities,
canEdit,
busy,
assigning,
openAssign: (target: AssignTarget = {}) => {
if (canEdit) setAssigning(target);
},
closeAssign: () => {
if (!busy) setAssigning(null);
},
assign,
removing,
askRemove: (activity: TourActivity) => {
if (canEdit) setRemoving(activity);
},
cancelRemove: () => setRemoving(null),
remove,
};
}
export type TourActivities = ReturnType<typeof useTourActivities>;
@@ -0,0 +1,105 @@
// FE-ACT-ASSIGN-001 to FE-ACT-ASSIGN-004
// ACT-01, the link dialog's state: the day it starts on, the recordings of the
// trip to choose from, what a choice replaces, and a recording imported here
// chosen for the user but never linked by itself.
import { act, renderHook, waitFor } from '@testing-library/react';
import type { TourActivity, TourListItem } from '@trek/shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { TourExecution } from './tourActivityModel';
import { useTrackAssignment } from './useTrackAssignment';
const repo = vi.hoisted(() => ({ list: vi.fn() }));
interface ImportOptions {
onImported?: (tours: TourListItem[]) => void;
onToursChanged?: (ids?: number[]) => unknown;
}
const gpx = vi.hoisted(() => ({ options: null as null | ImportOptions }));
vi.mock('../../../repo/tourRepo', () => ({ tourRepo: repo }));
vi.mock('../useTourGpxImport', () => ({
useTourGpxImport: (options: ImportOptions) => {
gpx.options = options;
return { importing: false, preview: null, pick: vi.fn(), confirm: vi.fn(), cancel: vi.fn(), importFiles: vi.fn() };
},
}));
const tour = { place_id: 7, name: 'Ridge', tour_type: 'hike', origin: 'trek', has_waypoints: true } as TourListItem;
const recording = (placeId: number, name: string, extra: Partial<TourListItem> = {}) =>
({ place_id: placeId, name, tour_type: 'hike', origin: 'gpx', has_waypoints: false, ...extra }) as TourListItem;
const executions: TourExecution[] = [
{ assignmentId: 11, day: null, index: 0 },
{ assignmentId: 31, day: null, index: 2 },
];
const linked = (assignmentId: number | null, trackPlaceId: number, name: string) =>
({
id: trackPlaceId,
assignment_id: assignmentId,
track: { place_id: trackPlaceId, name },
}) as unknown as TourActivity;
beforeEach(() => {
vi.clearAllMocks();
repo.list.mockResolvedValue({ tours: [tour, recording(20, 'Watch'), recording(21, 'Phone', { activity_of: 99 })] });
});
function render(activities: TourActivity[], target: { assignmentId?: number | null } = {}, onToursChanged = vi.fn()) {
return renderHook(() =>
useTrackAssignment({ tripId: 1, tour, executions, activities, target, canEdit: true, onToursChanged })
);
}
describe('useTrackAssignment', () => {
it('FE-ACT-ASSIGN-001: starts on the first day without an actual track, or on the day asked for', async () => {
expect(render([]).result.current.assignmentId).toBe(11);
expect(render([linked(11, 20, 'Watch')]).result.current.assignmentId).toBe(31);
expect(render([linked(11, 20, 'Watch'), linked(31, 21, 'Phone')]).result.current.assignmentId).toBe(11);
const asked = render([linked(31, 21, 'Phone')], { assignmentId: 31 });
expect(asked.result.current.assignmentId).toBe(31);
// A change starts on the track the day has, which therefore replaces nothing.
expect(asked.result.current.selected).toBe(21);
expect(asked.result.current.replaces).toBeNull();
await waitFor(() => expect(asked.result.current.candidates).not.toBeNull());
});
it('FE-ACT-ASSIGN-002: lists the recordings of the trip, and only a free one can be linked', async () => {
const { result } = render([]);
expect(result.current.candidates).toBeNull();
expect(result.current.ready).toBe(false);
await waitFor(() => expect(result.current.candidates?.map((c) => c.tour.place_id)).toEqual([20, 21]));
expect(repo.list).toHaveBeenCalledWith(1);
act(() => result.current.choose(21));
expect(result.current.choice?.takenBy).toBe('');
expect(result.current.ready).toBe(false);
act(() => result.current.choose(20));
expect(result.current.ready).toBe(true);
expect(result.current.importFields).toEqual({ tour_type: 'hike' });
});
it('FE-ACT-ASSIGN-003: names the track a choice replaces on its day, and none on a day without one', async () => {
const { result } = render([linked(11, 21, 'Phone')], { assignmentId: 11 });
await waitFor(() => expect(result.current.candidates).not.toBeNull());
act(() => result.current.choose(20));
expect(result.current.replaces).toBe('Phone');
act(() => result.current.chooseExecution(null));
expect(result.current.execution.day).toBeNull();
expect(result.current.replaces).toBeNull();
});
it('FE-ACT-ASSIGN-004: a recording imported here is chosen and the list read again; the lists are told', async () => {
const onToursChanged = vi.fn();
const { result } = render([], {}, onToursChanged);
await waitFor(() => expect(result.current.candidates).not.toBeNull());
repo.list.mockResolvedValue({ tours: [tour, recording(20, 'Watch'), recording(40, 'Imported')] });
await act(async () => gpx.options?.onToursChanged?.([40]));
expect(onToursChanged).toHaveBeenCalledWith([40]);
await act(async () => gpx.options?.onToursChanged?.());
expect(onToursChanged).toHaveBeenLastCalledWith([]);
act(() => gpx.options?.onImported?.([recording(40, 'Imported')]));
expect(result.current.selected).toBe(40);
await waitFor(() => expect(result.current.choice?.tour.name).toBe('Imported'));
expect(repo.list).toHaveBeenCalledTimes(2);
act(() => gpx.options?.onImported?.([]));
expect(result.current.selected).toBe(40);
});
});
@@ -0,0 +1,104 @@
import type { TourActivity, TourListItem } from '@trek/shared';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { tourRepo } from '../../../repo/tourRepo';
import { useTourGpxImport } from '../useTourGpxImport';
import { executionOf, importFieldsFor, trackCandidates, type TourExecution } from './tourActivityModel';
import type { AssignTarget } from './useTourActivities';
interface TrackAssignmentOptions {
tripId: number;
tour: TourListItem;
executions: readonly TourExecution[];
/** The recordings the tour has now, to preset a change and to say what a choice replaces. */
activities: readonly TourActivity[];
target: AssignTarget;
canEdit: boolean;
onToursChanged?: (placeIds: number[]) => Promise<void> | void;
}
/** The execution the dialog starts on: the one asked for, else the first day without a recording, else none. */
function startingExecution(
executions: readonly TourExecution[],
activities: readonly TourActivity[],
target: AssignTarget
): number | null {
if (target.assignmentId !== undefined) return target.assignmentId;
const recorded = new Set(activities.map((activity) => activity.assignment_id));
return (executions.find((execution) => !recorded.has(execution.assignmentId)) ?? executions[0])?.assignmentId ?? null;
}
/**
* ACT-01, the dialog that assigns a recording: which execution it was, which
* recording of the trip, or a new one through the GPX import (its preview
* preset to the tour's type), and what the choice measures before anything is
* written. Nothing is stored until the user confirms; a recording imported
* here is chosen for them, never assigned.
*/
export function useTrackAssignment({
tripId,
tour,
executions,
activities,
target,
canEdit,
onToursChanged,
}: TrackAssignmentOptions) {
const [assignmentId, setAssignmentId] = useState<number | null>(() =>
startingExecution(executions, activities, target)
);
const current = activities.find((activity) => activity.assignment_id === assignmentId) ?? null;
const [selected, setSelected] = useState<number | null>(() => current?.track.place_id ?? null);
const [tours, setTours] = useState<TourListItem[] | null>(null);
const [reads, setReads] = useState(0);
useEffect(() => {
let cancelled = false;
tourRepo.list(tripId).then(
({ tours: listed }) => {
if (!cancelled) setTours(listed);
},
() => {
if (!cancelled) setTours([]);
}
);
return () => {
cancelled = true;
};
}, [tripId, reads]);
const onImported = useCallback((imported: TourListItem[]) => {
const first = imported[0];
if (first) setSelected(first.place_id);
setReads((count) => count + 1);
}, []);
const gpxImport = useTourGpxImport({
tripId,
canEdit,
onToursChanged: (placeIds) => onToursChanged?.(placeIds ?? []),
onImported,
});
const candidates = useMemo(() => (tours ? trackCandidates(tours, tour.place_id) : null), [tour.place_id, tours]);
const choice = candidates?.find((candidate) => candidate.tour.place_id === selected) ?? null;
// A recording the execution has now, other than the one chosen, gives way to it.
const replaces = current && current.track.place_id !== selected ? current.track.name : null;
return {
executions,
assignmentId,
execution: executionOf(executions, assignmentId),
chooseExecution: setAssignmentId,
/** Null while the trip's tours load. */
candidates,
selected,
choose: setSelected,
choice,
replaces,
gpxImport,
importFields: importFieldsFor(tour),
/** A free recording is chosen, so the assignment can be confirmed. */
ready: choice !== null && choice.takenBy === null,
};
}
export type TrackAssignment = ReturnType<typeof useTrackAssignment>;
+21 -11
View File
@@ -23,14 +23,22 @@ export interface GpxImportChoices {
ski: SkiChoice;
}
const START: GpxImportChoices = {
type: 'hike',
boat: null,
water: null,
bikeProfile: 'touring',
runProfile: 'running',
ski: NO_SKI_CHOICE,
};
const HIKE: TourGpxImportFields = { tour_type: 'hike' };
/** The choices a preview opens with: the fields it was preset to (ACT-01), the rest as a fresh preview has them. */
function choicesFrom(initial: TourGpxImportFields): GpxImportChoices {
return {
type: initial.tour_type,
boat: initial.boat_type ?? null,
water: initial.water_context ?? null,
bikeProfile: initial.bike_profile ?? 'touring',
runProfile: initial.run_profile ?? 'running',
ski:
initial.tour_type === 'ski'
? { discipline: initial.ski_discipline ?? null, technique: initial.ski_technique ?? null }
: NO_SKI_CHOICE,
};
}
/** What the chosen type still lacks before anything can be imported; null when nothing does. */
export function importMissing(chosen: GpxImportChoices): 'paddle' | 'ski' | null {
@@ -47,6 +55,8 @@ export function importFields(chosen: GpxImportChoices): TourGpxImportFields {
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 };
// ACT-01: a city walk comes in as one, not as a hike.
if (type === 'walk') return { tour_type: 'walk' };
// HOR-01: a recorded ride comes in as a ride, with nothing of another type.
if (type === 'horse') return { tour_type: 'horse' };
// SKI-02: a ski track comes in with its discipline and, for cross-country, its technique, and no time.
@@ -55,9 +65,9 @@ export function importFields(chosen: GpxImportChoices): TourGpxImportFields {
return { tour_type: 'hike' };
}
/** The preview's choices, each field set on its own; a fresh preview starts as a hike. */
export function useGpxImportChoices() {
const [chosen, setChosen] = useState<GpxImportChoices>(START);
/** The preview's choices, each field set on its own; a fresh preview starts as a hike, a preset one as preset. */
export function useGpxImportChoices(initial: TourGpxImportFields = HIKE) {
const [chosen, setChosen] = useState<GpxImportChoices>(() => choicesFrom(initial));
const set =
<K extends keyof GpxImportChoices>(key: K) =>
(value: GpxImportChoices[K]) =>
+21 -1
View File
@@ -1,6 +1,6 @@
import { useId, useLayoutEffect, useRef, useState, type ReactNode } from 'react'
import type { TourListItem } from '@trek/shared'
import { AlertTriangle, CalendarDays, ChevronDown, Info, Plus } from 'lucide-react'
import { AlertTriangle, CalendarDays, ChevronDown, Footprints, Info, Plus } from 'lucide-react'
import { createElement } from 'react'
import type { Day, DistanceUnit } from '../../types'
import type { RouteGeometryAnalysis } from '../../utils/routeGeometry'
@@ -122,6 +122,26 @@ export function TourCautionBadge({ tour }: { tour: Pick<TourListItem, 'caution'>
)
}
/**
* ACT-01 on a row, icon only like the caution: a tour that has a recorded
* track, or a recording that is the track of a tour. The tooltip says which.
*/
export function TourActivityBadge({ tour }: { tour: Pick<TourListItem, 'activity_tracks' | 'activity_of'> }) {
const { t } = useTranslation()
const isTrack = tour.activity_of != null
if (!isTrack && !tour.activity_tracks?.length) return null
const label = t(isTrack ? 'tours.activity.isTrackHint' : 'tours.activity.badgeHint')
return (
<Tooltip label={label}>
<span data-testid="tour-activity-badge" aria-label={label} className="inline-flex flex-none">
<WhiteBadge className="text-success" icon={<Footprints size={10} strokeWidth={2.2} className="flex-none" />}>
{null}
</WhiteBadge>
</span>
</Tooltip>
)
}
/**
* The days a tour is on as small pills, "Day 2" each, the date and title in the
* tooltip. A tour on many days names the first ones and folds the rest into "+n",
@@ -77,6 +77,13 @@ describe('tourScopeSummary (STA-01)', () => {
]);
});
it('ACT-01: leaves out a recording that is the actual track of a tour, so the tour is not counted twice', () => {
const track = { ...GPX_HIKE, place_id: 9, activity_of: HIKE_A.place_id };
const scope = tourScopeSummary([HIKE_A, track]);
expect(scope.count).toBe(1);
expect(scope.types[0].distanceKm).toEqual({ value: 10, known: 1, of: 1 });
});
it('sums what is known and says how much of the whole that is, never a zero for unknown', () => {
const [hike] = tourScopeSummary([HIKE_A, HIKE_B, GPX_HIKE]).types;
expect(hike.distanceKm).toEqual({ value: 23.5, known: 3, of: 3 });
+4 -1
View File
@@ -87,10 +87,13 @@ type OnDay = (tour: TourListItem) => boolean;
* however many days it is on; the list is the trip's tours, one row each, so
* a tour on three days is still one tour and one distance. `onDay` reads the
* day lists where the caller has them; the list's own flag is the fallback.
* A recording assigned to a tour as its recorded track (ACT-01) is that tour
* done, not a tour of its own, so it is not counted twice.
*/
export function tourScopeSummary(tours: readonly TourListItem[], onDay: OnDay = (tour) => tour.planned): TourScope {
const byType = new Map<TourTypeKey, TourListItem[]>();
for (const tour of new Map(tours.map((tour) => [tour.place_id, tour])).values()) {
const counted = tours.filter((tour) => tour.activity_of == null);
for (const tour of new Map(counted.map((tour) => [tour.place_id, tour])).values()) {
byType.set(tour.tour_type, [...(byType.get(tour.tour_type) ?? []), tour]);
}
const types = [...byType.entries()]