feat(tours): import a ski track from GPX and keep it as recorded

SKI-02. Ski joins the types a GPX file can be imported as, offered in the
import preview's type field only: TREK routes no ski track, so the planner
never offers it. The preview asks for the discipline on purpose (alpine,
snowboard, cross-country or ski touring, none chosen at first) and, for
cross-country, the technique (classic, skating or unknown); Import waits
until both are named, and the technique stays in sight but dimmed for the
other disciplines. The track is stored exactly as recorded, with its file
name as provenance, its distance and heights from the file and no time:
no ski time is worked out and no hiking estimate stands in for one.

Opened in the planner, a ski track gets a rail card with its discipline on
a tinted tile, a cross-country technique as a badge beside it, the ski time
said as not worked out, and an info dot on what TREK does not say (snow,
avalanches, open runs, and that the 3D gradient colours are no difficulty
or avalanche rating). Change opens a dialog to classify the track again;
only the classification changes, through the offline core, with the
revision it was made at. Planning over the import is not offered for ski.
The existing 3D terrain view, the elevation profile and its focus work on
the track as for any import, with the standard map, topo and satellite and
no via ferratas. Lists, the day plan and the detail show the discipline as
a frosted corner badge on the tile and as a pill with the technique inside;
day assignment, copies and take-overs work as for any tour. The corner
badge is now one component that the winter label shares.

The server keeps tours.ski_discipline and tours.ski_technique (CHECK lists,
NULL on every other type), switches the ski type on without a routing
profile, refuses a ski import without its discipline, a technique outside
cross-country and ski fields on any other type, and takes a planned save's
classification off. PUT /api/trips/:tripId/tours/:placeId/ski classifies a
ski track again (place_edit, 409 on a stale revision, 400 for a tour that
is no ski track) and broadcasts tours:changed. GPX export names the
discipline (alpine_skiing, snowboarding, cross_country_skiing,
backcountry_skiing), and list_tours describes both fields with what a ski
track does not say. Ski is labelled plainly as Ski in every language, so
it no longer reads as ski touring.
This commit is contained in:
Maurice
2026-10-20 13:45:56 +02:00
parent 68907ec811
commit 0169be3d79
93 changed files with 2853 additions and 183 deletions
@@ -0,0 +1,54 @@
import { fireEvent, render, screen } from '@testing-library/react';
import { useState } from 'react';
import { describe, expect, it } from 'vitest';
import { SkiClassificationFields } from './SkiClassificationFields';
import { NO_SKI_CHOICE, type SkiChoice } from './skiChoice';
// FE-TOUR-SKI-FIELDS-001 to FE-TOUR-SKI-FIELDS-003
const option = (name: string) => screen.getByRole('button', { name });
/** The fields over a form that keeps what it is given, as the import and the dialog do. */
function Stateful({ initial = NO_SKI_CHOICE }: { initial?: SkiChoice }) {
const [choice, setChoice] = useState<SkiChoice>(initial);
return (
<>
<SkiClassificationFields choice={choice} onChange={setChoice} />
<output data-testid="choice">{`${choice.discipline ?? 'none'}/${choice.technique ?? 'none'}`}</output>
</>
);
}
describe('SkiClassificationFields (SKI-02)', () => {
it('FE-TOUR-SKI-FIELDS-001: offers the four disciplines with none chosen, and asks for one', () => {
render(<Stateful />);
for (const discipline of ['alpine', 'snowboard', 'cross_country', 'touring']) {
expect(option(`tours.ski.discipline.${discipline}`)).toHaveAttribute('aria-pressed', 'false');
}
expect(screen.getByRole('status')).toHaveTextContent('tours.ski.chooseDiscipline');
expect(screen.getByRole('button', { name: 'tours.ski.infoLabel' })).toHaveAccessibleDescription('tours.ski.info');
fireEvent.click(option('tours.ski.discipline.touring'));
expect(screen.getByTestId('choice')).toHaveTextContent('touring/none');
expect(screen.queryByRole('status')).toBeNull();
});
it('FE-TOUR-SKI-FIELDS-002: the technique stays dimmed and out of reach until cross-country is chosen', () => {
render(<Stateful initial={{ discipline: 'alpine', technique: null }} />);
expect(screen.getByTestId('tour-ski-technique')).toHaveClass('opacity-50');
expect(option('tours.ski.technique.classic')).toBeDisabled();
fireEvent.click(option('tours.ski.discipline.cross_country'));
expect(screen.getByTestId('tour-ski-technique')).not.toHaveClass('opacity-50');
expect(screen.getByRole('status')).toHaveTextContent('tours.ski.chooseTechnique');
fireEvent.click(option('tours.ski.technique.unknown'));
expect(screen.getByTestId('choice')).toHaveTextContent('cross_country/unknown');
expect(option('tours.ski.technique.unknown')).toHaveAttribute('aria-pressed', 'true');
expect(screen.queryByRole('status')).toBeNull();
});
it('FE-TOUR-SKI-FIELDS-003: a technique left from cross-country shows as none chosen on another discipline', () => {
render(<Stateful initial={{ discipline: 'snowboard', technique: 'skating' }} />);
expect(option('tours.ski.technique.skating')).toHaveAttribute('aria-pressed', 'false');
fireEvent.click(option('tours.ski.discipline.cross_country'));
expect(option('tours.ski.technique.skating')).toHaveAttribute('aria-pressed', 'true');
});
});
@@ -0,0 +1,72 @@
import { SKI_DISCIPLINES, SKI_TECHNIQUES, type SkiDiscipline, type SkiTechnique } from '@trek/shared';
import { Info } from 'lucide-react';
import { useTranslation } from '../../../i18n';
import { LABEL, Segmented } from '../../shared/dialogParts';
import { InfoDot, TourNotice } from '../tourParts';
import { skiChoiceMissing, type SkiChoice } from './skiChoice';
import { SKI_DISCIPLINE_ICON } from './skiMarks';
/**
* SKI-02: what a ski track is, chosen on purpose: the discipline, none until
* one is picked, and for cross-country the technique, Unknown among its
* answers. The technique stays in sight but dimmed while another discipline
* is chosen. The info dot says what TREK does with the track. The GPX import
* and the classification dialog share it.
*/
export function SkiClassificationFields({
choice,
onChange,
}: {
choice: SkiChoice;
onChange: (choice: SkiChoice) => void;
}) {
const { t } = useTranslation();
const crossCountry = choice.discipline === 'cross_country';
const missing = skiChoiceMissing(choice);
return (
<div data-testid="tour-ski-fields" className="flex min-w-0 flex-col gap-3">
<div className="min-w-0">
<div className="mb-[5px] flex min-h-5 min-w-0 items-center gap-1">
<span className={`${LABEL} !mb-0 min-w-0 truncate leading-5`}>{t('tours.ski.discipline')}</span>
<InfoDot label={t('tours.ski.infoLabel')} description={t('tours.ski.info')} />
</div>
<Segmented<SkiDiscipline>
value={(choice.discipline ?? '') as SkiDiscipline}
onChange={(discipline) => onChange({ ...choice, discipline })}
label={t('tours.ski.discipline')}
fill
options={SKI_DISCIPLINES.map((discipline) => {
const Icon = SKI_DISCIPLINE_ICON[discipline];
return {
value: discipline,
label: t(`tours.ski.discipline.${discipline}`),
icon: <Icon size={13} strokeWidth={2} aria-hidden="true" />,
};
})}
/>
</div>
<fieldset
data-testid="tour-ski-technique"
disabled={!crossCountry}
className={`m-0 min-w-0 border-0 p-0 transition-opacity ${crossCountry ? '' : 'opacity-50'}`}
>
<span className={LABEL}>{t('tours.ski.technique')}</span>
<Segmented<SkiTechnique>
value={(crossCountry ? (choice.technique ?? '') : '') as SkiTechnique}
onChange={(technique) => onChange({ ...choice, technique })}
label={t('tours.ski.technique')}
fill
options={SKI_TECHNIQUES.map((technique) => ({
value: technique,
label: t(`tours.ski.technique.${technique}`),
}))}
/>
</fieldset>
{missing && (
<TourNotice role="status" icon={<Info size={13} strokeWidth={2} />}>
{t(missing === 'discipline' ? 'tours.ski.chooseDiscipline' : 'tours.ski.chooseTechnique')}
</TourNotice>
)}
</div>
);
}
@@ -0,0 +1,66 @@
import { MountainSnow } from 'lucide-react';
import { useId } from 'react';
import { useTranslation } from '../../../i18n';
import {
DialogButton,
DialogFooter,
DialogHeader,
DialogShell,
DialogTile,
FooterSpacer,
NEUTRAL_TINT,
} from '../../shared/DialogShell';
import { SkiClassificationFields } from './SkiClassificationFields';
import type { SkiClassification } from './useSkiClassification';
/**
* SKI-02: the ski track classified again, in a dialog: the same fields as the
* import, starting from what the track has. Save stays off until the choice
* is complete and differs; Cancel and the backdrop change nothing.
*/
export function SkiClassifyDialog({ ski }: { ski: SkiClassification }) {
const { t } = useTranslation();
const labelId = useId();
const { tour, draft } = ski;
if (!tour || !draft) return null;
return (
<DialogShell
onClose={ski.close}
labelledBy={labelId}
width="detail"
blocked={ski.saving}
header={
<DialogHeader
tile={
<DialogTile>
<MountainSnow size={20} strokeWidth={2} className="text-content" />
</DialogTile>
}
tint={NEUTRAL_TINT}
labelId={labelId}
onClose={ski.close}
eyebrow={t('tours.ski.classifyTitle')}
title={tour.name}
/>
}
footer={
<DialogFooter>
<FooterSpacer />
<DialogButton onClick={ski.close} disabled={ski.saving}>
{t('common.cancel')}
</DialogButton>
<DialogButton
variant="primary"
data-testid="ski-classify-save"
disabled={!ski.canSave || ski.saving}
onClick={() => void ski.save()}
>
{t('common.save')}
</DialogButton>
</DialogFooter>
}
>
<SkiClassificationFields choice={draft} onChange={ski.setDraft} />
</DialogShell>
);
}
@@ -0,0 +1,77 @@
import { fireEvent, render, screen } from '@testing-library/react';
import type { TourListItem } from '@trek/shared';
import { describe, expect, it, vi } from 'vitest';
import { SkiTrackCard } from './SkiTrackCard';
import type { SkiClassification } from './useSkiClassification';
// FE-TOUR-SKI-CARD-001 to FE-TOUR-SKI-CARD-004
const tour = {
place_id: 21,
name: 'Up to the hut',
tour_type: 'ski',
ski_discipline: 'cross_country',
ski_technique: 'skating',
} as TourListItem;
function classification(overrides: Partial<SkiClassification> = {}): SkiClassification {
return {
tour,
canEdit: true,
saving: false,
draft: null,
setDraft: vi.fn(),
canSave: false,
open: vi.fn(),
close: vi.fn(),
save: vi.fn(),
...overrides,
};
}
describe('SkiTrackCard (SKI-02)', () => {
it('FE-TOUR-SKI-CARD-001: names the discipline, the technique as a badge, and the ski time as not worked out', () => {
render(<SkiTrackCard ski={classification()} />);
expect(screen.getByTestId('ski-track-discipline')).toHaveTextContent('tours.ski.discipline.cross_country');
expect(screen.getByTestId('ski-track-technique')).toHaveTextContent('tours.ski.technique.skating');
expect(screen.getByText('tours.ski.time')).toBeInTheDocument();
expect(screen.getByText('tours.ski.timeUnknown')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'tours.ski.infoLabel' })).toHaveAccessibleDescription('tours.ski.info');
expect(screen.queryByRole('dialog')).toBeNull();
});
it('FE-TOUR-SKI-CARD-002: Change opens the dialog, and is dimmed for someone who may not edit', () => {
const ski = classification();
const { rerender } = render(<SkiTrackCard ski={ski} />);
fireEvent.click(screen.getByRole('button', { name: 'common.change' }));
expect(ski.open).toHaveBeenCalledOnce();
rerender(<SkiTrackCard ski={classification({ canEdit: false })} />);
expect(screen.getByRole('button', { name: 'common.change' })).toBeDisabled();
});
it('FE-TOUR-SKI-CARD-003: the dialog saves only a complete change, and Cancel closes it', () => {
const ski = classification({ draft: { discipline: 'cross_country', technique: 'skating' } });
const { rerender } = render(<SkiTrackCard ski={ski} />);
expect(screen.getByRole('dialog')).toBeInTheDocument();
expect(screen.getByText('tours.ski.classifyTitle')).toBeInTheDocument();
expect(screen.getByTestId('ski-classify-save')).toBeDisabled();
fireEvent.click(screen.getByRole('button', { name: 'tours.ski.discipline.touring' }));
expect(ski.setDraft).toHaveBeenCalledWith({ discipline: 'touring', technique: 'skating' });
fireEvent.click(screen.getByRole('button', { name: 'common.cancel' }));
expect(ski.close).toHaveBeenCalled();
const ready = classification({ draft: { discipline: 'touring', technique: null }, canSave: true });
rerender(<SkiTrackCard ski={ready} />);
fireEvent.click(screen.getByTestId('ski-classify-save'));
expect(ready.save).toHaveBeenCalledOnce();
});
it('FE-TOUR-SKI-CARD-004: shows nothing while no ski track is in view, and asks for a discipline a track lacks', () => {
const { container, rerender } = render(<SkiTrackCard ski={classification({ tour: null })} />);
expect(container).toBeEmptyDOMElement();
const unclassified = { ...tour, ski_discipline: null, ski_technique: null };
rerender(<SkiTrackCard ski={classification({ tour: unclassified })} />);
expect(screen.getByTestId('ski-track-discipline')).toHaveTextContent('tours.ski.chooseDiscipline');
expect(screen.queryByTestId('ski-track-technique')).toBeNull();
});
});
@@ -0,0 +1,65 @@
import { MountainSnow, Pencil } from 'lucide-react';
import { useTranslation } from '../../../i18n';
import { fs } from '../../shared/DialogShell';
import { FigureBadge } from '../paddle/FigureBadge';
import { CardAction, InfoDot, RailCard, RailFacts } from '../tourParts';
import { SkiClassifyDialog } from './SkiClassifyDialog';
import { SKI_DISCIPLINE_ICON, skiDisciplineOf, skiTechniqueOf } from './skiMarks';
import type { SkiClassification } from './useSkiClassification';
/**
* SKI-02: a ski track in the planner's rail: its discipline on a tinted tile,
* a cross-country technique as a badge beside it, and the ski time said as
* not worked out rather than left blank or filled with a hike's estimate. The
* classification changes in a dialog; a viewer who may not edit sees the
* action dimmed. Distance and heights are the inspector's below, as recorded.
*/
export function SkiTrackCard({ ski }: { ski: SkiClassification }) {
const { t } = useTranslation();
const { tour } = ski;
if (!tour) return null;
const discipline = skiDisciplineOf(tour);
const technique = skiTechniqueOf(tour);
const Icon = discipline ? SKI_DISCIPLINE_ICON[discipline] : MountainSnow;
return (
<>
<RailCard
icon={<MountainSnow size={14} strokeWidth={2} />}
title={t('tours.ski.title')}
aside={<InfoDot label={t('tours.ski.infoLabel')} description={t('tours.ski.info')} />}
>
<div data-testid="ski-track-card" className="flex flex-col gap-3">
<div className="flex min-w-0 items-center gap-2.5">
<span
aria-hidden="true"
className="grid h-8 w-8 flex-none place-items-center rounded-full bg-info-soft text-info ring-1 ring-inset ring-edge-faint"
>
<Icon size={15} strokeWidth={2} />
</span>
<span className="flex min-w-0 flex-1 flex-col items-start gap-1">
<span
data-testid="ski-track-discipline"
className={`block max-w-full truncate font-semibold ${discipline ? 'text-content' : 'text-content-muted'}`}
style={fs(13, 'body')}
>
{discipline ? t(`tours.ski.discipline.${discipline}`) : t('tours.ski.chooseDiscipline')}
</span>
{technique && (
<FigureBadge
label={t('tours.ski.technique')}
value={t(`tours.ski.technique.${technique}`)}
testId="ski-track-technique"
/>
)}
</span>
<CardAction icon={<Pencil size={12} strokeWidth={2.2} />} onClick={ski.open} disabled={!ski.canEdit}>
{t('common.change')}
</CardAction>
</div>
<RailFacts facts={[{ label: t('tours.ski.time'), value: t('tours.ski.timeUnknown') }]} />
</div>
</RailCard>
<SkiClassifyDialog ski={ski} />
</>
);
}
@@ -0,0 +1,35 @@
import { describe, expect, it } from 'vitest';
import { NO_SKI_CHOICE, skiChoiceChanged, skiChoiceMissing, skiChoiceOf, skiFieldsOf } from './skiChoice';
// FE-TOUR-SKI-CHOICE-001 to FE-TOUR-SKI-CHOICE-003
describe('ski choice (SKI-02)', () => {
it('FE-TOUR-SKI-CHOICE-001: asks for a discipline first, then for a cross-country technique, Unknown counting as one', () => {
expect(skiChoiceMissing(NO_SKI_CHOICE)).toBe('discipline');
expect(skiChoiceMissing({ discipline: 'cross_country', technique: null })).toBe('technique');
expect(skiChoiceMissing({ discipline: 'cross_country', technique: 'unknown' })).toBeNull();
expect(skiChoiceMissing({ discipline: 'alpine', technique: null })).toBeNull();
});
it('FE-TOUR-SKI-CHOICE-002: sends a technique for cross-country only, and nothing while incomplete', () => {
expect(skiFieldsOf(NO_SKI_CHOICE)).toBeNull();
expect(skiFieldsOf({ discipline: 'cross_country', technique: null })).toBeNull();
expect(skiFieldsOf({ discipline: 'cross_country', technique: 'classic' })).toEqual({
ski_discipline: 'cross_country',
ski_technique: 'classic',
});
// A technique tried on cross-country and left behind stays out of an alpine track.
expect(skiFieldsOf({ discipline: 'alpine', technique: 'classic' })).toEqual({ ski_discipline: 'alpine' });
});
it('FE-TOUR-SKI-CHOICE-003: opens from the saved track, and counts the technique as a change for cross-country only', () => {
const saved = skiChoiceOf({ ski_discipline: 'cross_country', ski_technique: 'skating' });
expect(saved).toEqual({ discipline: 'cross_country', technique: 'skating' });
expect(skiChoiceOf({})).toEqual(NO_SKI_CHOICE);
expect(skiChoiceChanged(saved, saved)).toBe(false);
expect(skiChoiceChanged({ ...saved, technique: 'classic' }, saved)).toBe(true);
expect(skiChoiceChanged({ discipline: 'touring', technique: 'skating' }, saved)).toBe(true);
const alpine = { discipline: 'alpine' as const, technique: null };
expect(skiChoiceChanged({ discipline: 'alpine', technique: 'classic' }, alpine)).toBe(false);
});
});
@@ -0,0 +1,40 @@
import type { SkiDiscipline, SkiTechnique, TourListItem, TourSkiClassificationRequest } from '@trek/shared';
/**
* SKI-02: a ski classification as a form holds it: nothing chosen until the
* skier picks, and a technique remembered while another discipline is tried,
* though only cross-country sends one.
*/
export interface SkiChoice {
discipline: SkiDiscipline | null;
technique: SkiTechnique | null;
}
export const NO_SKI_CHOICE: SkiChoice = { discipline: null, technique: null };
/** What a choice still lacks before it can be sent: the discipline, or a cross-country technique. */
export function skiChoiceMissing(choice: SkiChoice): 'discipline' | 'technique' | null {
if (choice.discipline === null) return 'discipline';
return choice.discipline === 'cross_country' && choice.technique === null ? 'technique' : null;
}
/** The fields a complete choice is sent as; null while something is missing. */
export function skiFieldsOf(
choice: SkiChoice,
): Pick<TourSkiClassificationRequest, 'ski_discipline' | 'ski_technique'> | null {
if (choice.discipline === null || skiChoiceMissing(choice)) return null;
return choice.discipline === 'cross_country'
? { ski_discipline: choice.discipline, ski_technique: choice.technique }
: { ski_discipline: choice.discipline };
}
/** The choice a saved ski track opens with. */
export function skiChoiceOf(tour: Partial<Pick<TourListItem, 'ski_discipline' | 'ski_technique'>>): SkiChoice {
return { discipline: tour.ski_discipline ?? null, technique: tour.ski_technique ?? null };
}
/** Whether a choice says something else than the saved track does; the technique counts for cross-country only. */
export function skiChoiceChanged(choice: SkiChoice, saved: SkiChoice): boolean {
if (choice.discipline !== saved.discipline) return true;
return choice.discipline === 'cross_country' && choice.technique !== saved.technique;
}
@@ -0,0 +1,71 @@
import { render, screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { TourDayRowAvatar } from '../TourDayRowFacts';
import { TourGradeTile } from '../tourParts';
import { SkiCornerMark, SkiHeadPill, skiClassificationText, skiDisciplineOf, skiTechniqueOf } from './skiMarks';
// FE-TOUR-SKI-MARK-001 to FE-TOUR-SKI-MARK-005
const t = (key: string) => key;
const skiTrack = {
tour_type: 'ski' as const,
max_hiking_difficulty: null,
wanderer_ref: null,
has_waypoints: false,
ski_discipline: 'cross_country' as const,
ski_technique: 'skating' as const,
};
describe('ski marks (SKI-02)', () => {
it('FE-TOUR-SKI-MARK-001: reads the discipline of a ski track only, and the technique of cross-country only', () => {
expect(skiDisciplineOf(skiTrack)).toBe('cross_country');
expect(skiTechniqueOf(skiTrack)).toBe('skating');
expect(skiTechniqueOf({ ...skiTrack, ski_discipline: 'alpine' })).toBeNull();
expect(skiDisciplineOf({ tour_type: 'hike', ski_discipline: 'alpine' })).toBeNull();
expect(skiDisciplineOf({ tour_type: 'ski' })).toBeNull();
expect(skiClassificationText(skiTrack, t)).toBe(
'tours.ski.discipline.cross_country, tours.ski.technique: tours.ski.technique.skating'
);
expect(skiClassificationText({ tour_type: 'ski', ski_discipline: 'touring' }, t)).toBe(
'tours.ski.discipline.touring'
);
expect(skiClassificationText({ tour_type: 'run' }, t)).toBeNull();
});
it('FE-TOUR-SKI-MARK-002: the corner mark names the classification, and any other tour shows none', () => {
const { container, rerender } = render(<SkiCornerMark tour={{ tour_type: 'hike' }} />);
expect(container).toBeEmptyDOMElement();
rerender(<SkiCornerMark tour={{ tour_type: 'ski', ski_discipline: 'snowboard' }} size={20} />);
const mark = screen.getByRole('img', { name: 'tours.ski.discipline.snowboard' });
expect(mark).toHaveAttribute('data-testid', 'tour-ski-mark');
expect(mark).toHaveStyle({ width: '20px', height: '20px' });
});
it('FE-TOUR-SKI-MARK-003: the head pill names the discipline with a cross-country technique inside it', () => {
const { container, rerender } = render(<SkiHeadPill tour={{ tour_type: 'bike' }} className="head-pill" />);
expect(container).toBeEmptyDOMElement();
rerender(<SkiHeadPill tour={skiTrack} className="head-pill" />);
const pill = screen.getByTestId('tour-detail-ski');
expect(pill).toHaveClass('head-pill');
expect(pill).toHaveTextContent('tours.ski.discipline.cross_country');
expect(screen.getByTestId('tour-detail-ski-technique')).toHaveTextContent('tours.ski.technique.skating');
rerender(<SkiHeadPill tour={{ ...skiTrack, ski_discipline: 'alpine' }} className="head-pill" />);
expect(screen.queryByTestId('tour-detail-ski-technique')).toBeNull();
});
it('FE-TOUR-SKI-MARK-004: a tour list tile shows the ski icon with the discipline at its corner', () => {
render(<TourGradeTile tour={skiTrack} />);
expect(screen.getByLabelText('tourTypes.ski')).toBeInTheDocument();
expect(screen.getByTestId('tour-ski-mark')).toBeInTheDocument();
});
it('FE-TOUR-SKI-MARK-005: the day plan tile names the type and carries the mark, a ski track without one stays plain', () => {
const { container, rerender } = render(
<TourDayRowAvatar tour={{ ...skiTrack, ski_discipline: null, ski_technique: null }} size={32} />
);
expect(container.firstElementChild).toHaveAttribute('data-testid', 'plan-tour-icon');
expect(screen.getByRole('img', { name: 'tourTypes.ski' })).toBeInTheDocument();
rerender(<TourDayRowAvatar tour={skiTrack} size={50} />);
expect(screen.getByTestId('tour-ski-mark')).toHaveStyle({ width: '22px' });
});
});
@@ -0,0 +1,82 @@
import type { SkiDiscipline, SkiTechnique, TourListItem } from '@trek/shared';
import { CableCar, Snowflake, Spline, TrendingUp, type LucideIcon } from 'lucide-react';
import { useTranslation } from '../../../i18n';
import { fs } from '../../shared/DialogShell';
import { Tooltip } from '../../shared/Tooltip';
import { TourCornerMark } from '../TourCornerMark';
/**
* SKI-02: the icon each discipline goes by: a lift for alpine skiing, a
* snowflake for the board, a winding trail for cross-country and the climb on
* skins for ski touring.
*/
export const SKI_DISCIPLINE_ICON: Record<SkiDiscipline, LucideIcon> = {
alpine: CableCar,
snowboard: Snowflake,
cross_country: Spline,
touring: TrendingUp,
};
type SkiTour = Partial<Pick<TourListItem, 'tour_type' | 'ski_discipline' | 'ski_technique'>>;
/** The discipline of a ski track, or null for any other tour and a ski track listed before it had one. */
export function skiDisciplineOf(tour: SkiTour): SkiDiscipline | null {
return tour.tour_type === 'ski' ? (tour.ski_discipline ?? null) : null;
}
/** A cross-country track's technique; null for every other discipline and type. */
export function skiTechniqueOf(tour: SkiTour): SkiTechnique | null {
return skiDisciplineOf(tour) === 'cross_country' ? (tour.ski_technique ?? null) : null;
}
/** The classification in words, the discipline and a cross-country technique, as one tooltip reads it. */
export function skiClassificationText(tour: SkiTour, t: (key: string) => string): string | null {
const discipline = skiDisciplineOf(tour);
if (!discipline) return null;
const technique = skiTechniqueOf(tour);
const name = t(`tours.ski.discipline.${discipline}`);
return technique ? `${name}, ${t('tours.ski.technique')}: ${t(`tours.ski.technique.${technique}`)}` : name;
}
/**
* SKI-02: a ski track's discipline on the corner of its round tile, a frosted
* badge carrying the discipline's icon, the way a hike carries its winter
* label there. Its tooltip names the discipline and a cross-country technique.
*/
export function SkiCornerMark({ tour, size = 15 }: { tour: SkiTour; size?: number }) {
const { t } = useTranslation();
const discipline = skiDisciplineOf(tour);
const label = skiClassificationText(tour, t);
if (!discipline || !label) return null;
return <TourCornerMark icon={SKI_DISCIPLINE_ICON[discipline]} label={label} size={size} testId="tour-ski-mark" />;
}
/**
* SKI-02: a ski track's discipline as a pill of a tour's head, beside its
* type, a cross-country technique as a badge inside it. The tooltip says what
* TREK does with the track and what it does not say.
*/
export function SkiHeadPill({ tour, className }: { tour: SkiTour; className: string }) {
const { t } = useTranslation();
const discipline = skiDisciplineOf(tour);
if (!discipline) return null;
const technique = skiTechniqueOf(tour);
const Icon = SKI_DISCIPLINE_ICON[discipline];
return (
<Tooltip label={t('tours.ski.info')}>
<span data-testid="tour-detail-ski" className={className} style={fs(10.5)}>
<Icon size={11} strokeWidth={2} className="flex-none text-info" aria-hidden="true" />
{t(`tours.ski.discipline.${discipline}`)}
{technique && (
<span
data-testid="tour-detail-ski-technique"
className="ms-0.5 inline-flex h-[16px] items-center rounded-full bg-surface-secondary px-1.5 text-content"
>
<span className="sr-only">{t('tours.ski.technique')}:</span>
{t(`tours.ski.technique.${technique}`)}
</span>
)}
</span>
</Tooltip>
);
}
@@ -0,0 +1,141 @@
import { act, renderHook } from '@testing-library/react';
import { TOUR_REVISION_CONFLICT, type TourListItem } from '@trek/shared';
import { AxiosError, AxiosHeaders } from 'axios';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { tourRepo } from '../../../repo/tourRepo';
import type { TourPlannerController } from '../planner/useTourPlanner';
import { useSkiClassification } from './useSkiClassification';
// FE-TOUR-SKI-HOOK-001 to FE-TOUR-SKI-HOOK-005
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }));
vi.mock('../../shared/Toast', () => ({ useToast: () => toast }));
vi.mock('../../../repo/tourRepo', () => ({ tourRepo: { classifySki: vi.fn() } }));
const ski: TourListItem = {
place_id: 21,
name: 'Up to the hut',
tour_type: 'ski',
distance: 12,
elevation_gain: 980,
elevation_loss: 980,
duration: null,
difficulty: null,
wanderer_ref: null,
match_confidence: 1,
max_hiking_difficulty: null,
planned: true,
caution: false,
has_waypoints: false,
revision: 3,
ski_discipline: 'cross_country',
ski_technique: 'unknown',
};
const viewing = (tour: TourListItem) =>
({ mode: { type: 'view-gpx', placeId: tour.place_id, tour } }) as Pick<TourPlannerController, 'mode'>;
function setup(overrides: { tour?: TourListItem; tours?: TourListItem[]; canEdit?: boolean } = {}) {
const onSaved = vi.fn();
const tour = overrides.tour ?? ski;
const hook = renderHook(() =>
useSkiClassification({
tripId: 5,
planner: viewing(tour),
tours: overrides.tours ?? [tour],
canEdit: overrides.canEdit ?? true,
onSaved,
})
);
return { ...hook, onSaved };
}
beforeEach(() => {
vi.clearAllMocks();
});
describe('useSkiClassification (SKI-02)', () => {
it('FE-TOUR-SKI-HOOK-001: knows the ski track in view, as the trip list has it now, and nothing for another tour', () => {
const newer = { ...ski, ski_technique: 'skating' as const, revision: 4 };
expect(setup({ tours: [newer] }).result.current.tour).toBe(newer);
expect(setup({ tour: { ...ski, tour_type: 'hike' } }).result.current.tour).toBeNull();
const planned = renderHook(() =>
useSkiClassification({
tripId: 5,
planner: { mode: { type: 'edit-saved', placeId: 21 } } as Pick<TourPlannerController, 'mode'>,
tours: [ski],
canEdit: true,
onSaved: vi.fn(),
})
);
expect(planned.result.current.tour).toBeNull();
});
it('FE-TOUR-SKI-HOOK-002: the dialog opens with the saved choice, saves only a complete change, and closes without one', () => {
const { result } = setup();
act(() => result.current.open());
expect(result.current.draft).toEqual({ discipline: 'cross_country', technique: 'unknown' });
expect(result.current.canSave).toBe(false);
act(() => result.current.setDraft({ discipline: 'cross_country', technique: null }));
expect(result.current.canSave).toBe(false);
act(() => result.current.setDraft({ discipline: 'touring', technique: null }));
expect(result.current.canSave).toBe(true);
act(() => result.current.close());
expect(result.current.draft).toBeNull();
expect(tourRepo.classifySki).not.toHaveBeenCalled();
});
it('FE-TOUR-SKI-HOOK-003: saves the classification with the revision it was made at, hands the tour on and closes', async () => {
const saved = { ...ski, ski_technique: 'classic' as const, revision: 4 };
vi.mocked(tourRepo.classifySki).mockResolvedValue({ tour: saved, waypoints: [] });
const { result, onSaved } = setup();
act(() => result.current.open());
act(() => result.current.setDraft({ discipline: 'cross_country', technique: 'classic' }));
await act(async () => {
await result.current.save();
});
expect(tourRepo.classifySki).toHaveBeenCalledWith(5, 21, {
ski_discipline: 'cross_country',
ski_technique: 'classic',
expected_revision: 3,
});
expect(onSaved).toHaveBeenCalledWith(saved);
expect(result.current.draft).toBeNull();
expect(toast.success).toHaveBeenCalledWith('tours.ski.saved');
});
it('FE-TOUR-SKI-HOOK-004: a refused save keeps the dialog and says why, a tour saved elsewhere as such', async () => {
const conflict = new AxiosError('conflict', '409', undefined, undefined, {
status: 409,
statusText: 'Conflict',
headers: {},
config: { headers: new AxiosHeaders() },
data: { error: 'changed', code: TOUR_REVISION_CONFLICT, revision: 5 },
});
vi.mocked(tourRepo.classifySki).mockRejectedValueOnce(conflict).mockRejectedValueOnce(new Error('offline'));
const { result, onSaved } = setup();
act(() => result.current.open());
act(() => result.current.setDraft({ discipline: 'alpine', technique: null }));
await act(async () => {
await result.current.save();
});
expect(toast.error).toHaveBeenLastCalledWith('tours.revision.conflictTitle');
await act(async () => {
await result.current.save();
});
expect(toast.error).toHaveBeenLastCalledWith('tours.ski.saveFailed');
expect(onSaved).not.toHaveBeenCalled();
expect(result.current.draft).toEqual({ discipline: 'alpine', technique: null });
expect(result.current.saving).toBe(false);
});
it('FE-TOUR-SKI-HOOK-005: someone who may not edit opens nothing and saves nothing', async () => {
const { result } = setup({ canEdit: false });
act(() => result.current.open());
expect(result.current.draft).toBeNull();
await act(async () => {
await result.current.save();
});
expect(tourRepo.classifySki).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,80 @@
import type { TourListItem } from '@trek/shared';
import { useCallback, useMemo, useState } from 'react';
import { useTranslation } from '../../../i18n';
import { tourRepo } from '../../../repo/tourRepo';
import { useToast } from '../../shared/Toast';
import type { TourPlannerController } from '../planner/useTourPlanner';
import { revisionConflictOf } from '../planner/useTourRevisionGuard';
import { NO_SKI_CHOICE, skiChoiceChanged, skiChoiceOf, skiFieldsOf, type SkiChoice } from './skiChoice';
interface SkiClassificationOptions {
tripId: number;
planner: Pick<TourPlannerController, 'mode'>;
/** The trip's tours, which follow every save, so the card shows the classification as it stands. */
tours: readonly TourListItem[];
canEdit: boolean;
/** The tour as it stands after the save, for the lists and the map to take it in. */
onSaved: (tour: TourListItem) => Promise<void> | void;
}
/**
* SKI-02: the ski track open in the planner and its classification, changed
* on purpose in a dialog: the discipline, and for cross-country the
* technique. Saving goes through the offline core and changes nothing of the
* track; closing the dialog changes nothing at all.
*/
export function useSkiClassification({ tripId, planner, tours, canEdit, onSaved }: SkiClassificationOptions) {
const { t } = useTranslation();
const toast = useToast();
const [draft, setDraft] = useState<SkiChoice | null>(null);
const [saving, setSaving] = useState(false);
const viewed = planner.mode.type === 'view-gpx' ? planner.mode.tour : null;
const tour =
viewed?.tour_type === 'ski' ? (tours.find((item) => item.place_id === viewed.place_id) ?? viewed) : null;
const saved = useMemo(() => (tour ? skiChoiceOf(tour) : NO_SKI_CHOICE), [tour]);
const open = useCallback(() => {
if (tour && canEdit) setDraft(saved);
}, [canEdit, saved, tour]);
const close = useCallback(() => {
if (!saving) setDraft(null);
}, [saving]);
const save = useCallback(async () => {
const fields = draft ? skiFieldsOf(draft) : null;
if (!tour || !fields || saving || !canEdit) return;
setSaving(true);
try {
const result = await tourRepo.classifySki(tripId, tour.place_id, {
...fields,
expected_revision: tour.revision ?? null,
});
await onSaved(result.tour);
setDraft(null);
toast.success(t('tours.ski.saved'));
} catch (error: unknown) {
// Saved elsewhere meanwhile: the list brings the newer classification, the dialog stays to choose again.
toast.error(t(revisionConflictOf(error) === null ? 'tours.ski.saveFailed' : 'tours.revision.conflictTitle'));
} finally {
setSaving(false);
}
}, [canEdit, draft, onSaved, saving, t, toast, tour, tripId]);
return {
/** The ski track in view, or null while none is. */
tour,
canEdit,
saving,
/** The choice in the open dialog; null while it is closed. */
draft,
setDraft,
/** The dialog's choice is complete and says something else than the saved one. */
canSave: draft !== null && skiFieldsOf(draft) !== null && skiChoiceChanged(draft, saved),
open,
close,
save,
};
}
export type SkiClassification = ReturnType<typeof useSkiClassification>;