feat(tours): places along the tour picked on the map, stops that keep their kind, and calmer station rows

Along the tour (PLN-02, PLN-03): the list shows one line per place (its
icon, name and distance from the route) and scrolls past ten. A place
picked in the list or on the map opens its card over the map, where the
other cards of the planner sit, with what the source says and the way to
take it in as a stop. What taking it in did is one line in the list. The
intro, the theme line and the out-of-date note are gone: the themes say
what they look for on hover, and the search button says when to search
again.

A stop taken in from there keeps the kind of place it was found as
(migration 045400, poi_category, read back only where the contract knows
the kind) and its number carries that kind's icon at the corner, as a
via ferrata's end does.

City walks (CW-02, CW-03, CW-10): a stay nobody entered says nothing.
While no stay is entered at all the walk is planned as its walking time,
with no "unknown" and no "at least". A must-see rings its number, an
optional stop has a dashed ring, a protected one a shield at the corner;
only the stay stays under the name, below the coordinates.
This commit is contained in:
Maurice
2026-10-20 09:47:24 +02:00
parent 554d6f1b9f
commit 5d265c98de
55 changed files with 715 additions and 430 deletions
@@ -167,13 +167,14 @@ export function TourDayRowPills({ tour, compact = false }: { tour: TourListItem;
const times = tourPlannedTimes(tour);
const walking = times.walkingMinutes == null ? null : formatPlannedTourDuration(times.walkingMinutes);
const total = plannedTotalText(times, t);
const staysText = times.walk ? walkStaysText(times.walk, t) : null;
const timeParts = [
walking ? `${movingTimeLabel(tour, t('tours.planner.inspector.duration'), t)}: ${walking}` : null,
times.breakMinutes
? `${t('tours.planner.breaksAdditional')}: ${formatPlannedTourDuration(times.breakMinutes)}`
: null,
// CW-02: a city walk's stays, which its total adds to the walking time.
times.walk ? `${t('tours.walk.stays')}: ${walkStaysText(times.walk, t)}` : null,
staysText ? `${t('tours.walk.stays')}: ${staysText}` : null,
total
? `${t('tours.planner.plannedTotalDuration')}: ${total}${times.manuallyOverridden ? ` (${t('tours.planner.plannedTotalManual')})` : ''}`
: null,
@@ -1,7 +1,8 @@
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '../../../../tests/helpers/render';
import { StationDialog } from './StationDialog';
import { StationPills } from './stationParts';
import { stationMarkNote, stationRingClass } from './stationMarks';
import { StationPills, StationShield } from './stationParts';
import type { TourPlannerWaypoint } from './tourPlannerWaypoints';
const cathedral: TourPlannerWaypoint = {
@@ -126,32 +127,53 @@ describe('StationDialog (CW-02, CW-03, CW-10)', () => {
});
});
describe('StationPills (CW-02, CW-03, CW-10)', () => {
const pills = (point: Partial<TourPlannerWaypoint>) => {
describe('StationPills (CW-02)', () => {
const pills = (point: Partial<TourPlannerWaypoint>) =>
render(<StationPills point={{ id: 'p', lat: 0, lng: 0, role: 'via', ...point }} />);
return screen.getByTestId('station-pills');
};
it('says a stay nobody entered is unknown, and nothing of a normal, unprotected station', () => {
const row = pills({});
expect(row).toHaveTextContent('Stay unknown');
expect(row).not.toHaveTextContent('Must see');
expect(row).not.toHaveTextContent('Optional');
expect(screen.queryByLabelText('Protected')).not.toBeInTheDocument();
it('says nothing of a stay nobody entered', () => {
pills({ importance: 'must', protected: true });
expect(screen.queryByTestId('station-pills')).not.toBeInTheDocument();
});
it('names a point passed through', () => {
expect(pills({ stayMinutes: 0 })).toHaveTextContent('Passing through');
it('names a point passed through, and a stay entered as its time alone', () => {
pills({ stayMinutes: 0 });
expect(screen.getByTestId('station-pills')).toHaveTextContent('Passing through');
});
it('shows the stay, a must-see and a protection', () => {
const row = pills({ stayMinutes: 45, importance: 'must', protected: true });
it('shows the stay and nothing of the importance or the protection, which are on the number', () => {
pills({ stayMinutes: 45, importance: 'must', protected: true });
const row = screen.getByTestId('station-pills');
expect(row).toHaveTextContent('45');
expect(row).toHaveTextContent('Must see');
expect(screen.getByLabelText('Protected')).toBeInTheDocument();
});
it('shows an optional station as optional', () => {
expect(pills({ stayMinutes: 90, importance: 'optional' })).toHaveTextContent('Optional');
expect(row).not.toHaveTextContent('Must see');
expect(row).not.toHaveTextContent('Protected');
});
});
describe("a station's marks on its number (CW-03, CW-10)", () => {
const t = (key: string) =>
({
'tours.walk.importance.must': 'Must see',
'tours.walk.importance.optional': 'Optional',
'tours.walk.station.protected': 'Protected',
})[key] ?? key;
it('rings a must-see in full, an optional stop dashed, and a normal one not at all', () => {
expect(stationRingClass('must')).toContain('outline-warning');
expect(stationRingClass('optional')).toContain('outline-dashed');
expect(stationRingClass(null)).toBe('');
expect(stationRingClass(undefined)).toBe('');
});
it('names the importance and the protection for the label, and nothing for a plain station', () => {
expect(stationMarkNote({ importance: 'must', protected: true }, t)).toBe('Must see, Protected');
expect(stationMarkNote({ importance: 'optional' }, t)).toBe('Optional');
expect(stationMarkNote({ protected: true }, t)).toBe('Protected');
expect(stationMarkNote({}, t)).toBeNull();
});
it('draws a protection as a shield at the corner of the number', () => {
const { container } = render(<StationShield />);
expect(container.querySelector('[data-station-protected="true"]')).toBeInTheDocument();
});
});
@@ -192,8 +192,13 @@ describe('TourWaypointList', () => {
render(<TourWaypointList planner={controller} canEdit isSaving={false} />);
const rows = screen.getAllByTestId('tour-planner-waypoint-row');
expect(within(at(rows, 2)).getByTestId('tour-planner-waypoint-name')).toHaveTextContent('Cathedral');
expect(within(at(rows, 2)).getByTestId('station-pills')).toHaveTextContent('Must see');
expect(within(at(rows, 0)).getByTestId('station-pills')).toHaveTextContent('Stay unknown');
// The stay goes under the name; a must-see rings the number instead of a pill beside it.
expect(within(at(rows, 2)).getByTestId('station-pills')).toHaveTextContent('30 min');
expect(within(at(rows, 2)).getByTestId('station-pills')).not.toHaveTextContent('Must see');
const mustSee = within(at(rows, 2)).getByLabelText('Waypoint 2, Must see');
expect(mustSee.className).toContain('outline-warning');
// A stop without a stay entered says nothing of it, and a shaping point is no stop.
expect(within(at(rows, 0)).queryByTestId('station-pills')).not.toBeInTheDocument();
expect(within(at(rows, 1)).queryByTestId('station-pills')).not.toBeInTheDocument();
await userEvent.click(within(at(rows, 2)).getByRole('button', { name: 'More actions' }));
@@ -220,12 +225,23 @@ describe('TourWaypointList', () => {
expect(screen.queryByRole('button', { name: 'Edit stop' })).not.toBeInTheDocument();
});
it('FE-TOUR-WAYPOINT-LIST-009: a stop taken in along the tour carries its kind of place at the corner of its number (PLN-03)', () => {
const controller = planner({ waypoints: [START, { ...STOP, poiCategory: 'restaurant' as const }, END] });
render(<TourWaypointList planner={controller} canEdit isSaving={false} />);
const rows = screen.getAllByTestId('tour-planner-waypoint-row');
const number = within(at(rows, 1)).getByLabelText('Waypoint 2, Places to eat');
expect(number.querySelector('[data-waypoint-poi="restaurant"]')).toBeInTheDocument();
// A point set by hand has no kind to show.
expect(within(at(rows, 0)).queryByLabelText(/Places to eat/)).not.toBeInTheDocument();
expect(document.querySelectorAll('[data-waypoint-poi]')).toHaveLength(1);
});
it('FE-TOUR-WAYPOINT-LIST-008: the way back of a loop walk is no stop: no pills and no stop to edit', async () => {
const back = { ...START, id: 'back', role: 'end' as const };
const controller = planner({
tourType: 'walk',
isLoop: true,
waypoints: [START, STOP, back],
waypoints: [{ ...START, stayMinutes: 10 }, STOP, back],
selectedWaypointId: 'back',
});
render(<TourWaypointList planner={controller} canEdit isSaving={false} />);
@@ -1,4 +1,4 @@
import { paddleLayoutOfPoints, type PaddleRole } from '@trek/shared';
import { paddleLayoutOfPoints, type PaddleRole, type TourPoiCategory } from '@trek/shared';
import {
ArrowDown,
ArrowDownUp,
@@ -26,6 +26,7 @@ import {
} from '../../../store/tourFerrataCrossingStore';
import { toggleTourPlacing, useTourPlaceToolStore } from '../../../store/tourPlaceToolStore';
import { FerrataGlyph } from '../../Ferratas/FerrataGlyph';
import { TOUR_POI_LOOKS } from '../../Map/poiCategories';
import { SoftPill } from '../../Planner/planParts';
import { ContextMenu, useContextMenu } from '../../shared/ContextMenu';
import { fs } from '../../shared/DialogShell';
@@ -42,7 +43,8 @@ import { usePlannerWalkSchedule } from '../walk/useWalkSchedule';
import { WalkDayLine } from '../walk/WalkDayLine';
import { paddlePlanPoints, paddleRolesById } from './paddlePlanOf';
import { StationDialog } from './StationDialog';
import { StationPills } from './stationParts';
import { stationMarkNote, stationRingClass } from './stationMarks';
import { StationPills, StationShield } from './stationParts';
import { TripPlacePicker } from './TripPlacePicker';
import type { TourPlannerController } from './useTourPlanner';
import { useTripPlaceWaypoints } from './useTripPlaceWaypoints';
@@ -147,15 +149,57 @@ function WaypointEmptyState() {
);
}
/** PLN-03: the kind of place a point was found as, its icon at the number's corner in its colour on the map. */
function PoiCornerIcon({ category }: { category: TourPoiCategory }) {
const look = TOUR_POI_LOOKS[category];
return (
<span
aria-hidden="true"
data-waypoint-poi={category}
className="absolute -bottom-1 -start-1 grid h-4 w-4 place-items-center rounded-full ring-2 ring-[color:var(--bg-card)]"
style={{ background: `color-mix(in srgb, ${look.color} 22%, var(--bg-card))`, color: look.color }}
>
<look.Icon size={9} strokeWidth={2.6} />
</span>
);
}
/** A city walk station's own marks on its number (CW-03, CW-10); none on any other point. */
type StationMarks = Pick<WaypointPoint, 'importance' | 'protected'> | null;
/**
* What a waypoint's number says besides the number: the via ferrata it stands
* at an end of, or else the kind of place it was found as along the tour (a
* ferrata's end says more about the point, so it wins), and a station's
* importance and protection.
*/
function numberNote(
ferrata: TourWaypointFerrata | null,
poiCategory: TourPoiCategory | null,
station: StationMarks,
t: Translate
): { note: string | null; poi: TourPoiCategory | null } {
const marks = station ? stationMarkNote(station, t) : null;
const join = (first: string | null) => [first, marks].filter(Boolean).join(', ') || null;
if (ferrata) return { note: join(t('tours.ferrata.waypointAtEnd', { name: ferrata.name })), poi: null };
if (poiCategory) return { note: join(t(TOUR_POI_LOOKS[poiCategory].labelKey)), poi: poiCategory };
return { note: join(null), poi: null };
}
/**
* A waypoint's number, as the map pins show it. At the foot or the top of a via
* ferrata it takes a violet ring and the ferrata's ladder at its corner, named
* by the tooltip.
* by the tooltip. A point taken in from the places along the tour (PLN-03)
* carries that kind's icon at the same corner, in its colour on the map. A
* city walk's station shows how much it matters as a ring around the number
* and its protection as a shield at the top corner.
*/
function WaypointNumber({
stop,
selected,
ferrata,
poiCategory = null,
station = null,
loopEnd = false,
shaping = false,
}: {
@@ -163,6 +207,10 @@ function WaypointNumber({
stop: number;
selected: boolean;
ferrata: TourWaypointFerrata | null;
/** PLN-03: the kind of place the point was found as along the tour. */
poiCategory?: TourPoiCategory | null;
/** CW-03, CW-10: a station's importance and protection, drawn on the number; only a city walk's points carry them. */
station?: StationMarks;
/** The way back to the start of a loop: shown as the return, not as one more stop. */
loopEnd?: boolean;
/** P2A-03: a shaping point, a small dot as on the map. */
@@ -194,19 +242,22 @@ function WaypointNumber({
);
}
const label = t('tours.planner.waypointLabel', { n: stop });
const { note, poi } = numberNote(ferrata, poiCategory, station, t);
const number = (
<span
aria-label={ferrata ? `${label}, ${t('tours.ferrata.waypointAtEnd', { name: ferrata.name })}` : label}
aria-label={[label, note].filter(Boolean).join(', ')}
data-waypoint-number={stop}
data-ferrata-end={ferrata ? 'true' : undefined}
className={`relative grid h-7 w-7 flex-none place-items-center rounded-full font-geist font-semibold tabular-nums ${selected ? 'bg-accent text-accent-text' : 'bg-edge text-content'} ${ferrata ? 'ring-2 ring-inset ring-[color:var(--map-ferrata)]' : ''}`}
className={`relative grid h-7 w-7 flex-none place-items-center rounded-full font-geist font-semibold tabular-nums ${selected ? 'bg-accent text-accent-text' : 'bg-edge text-content'} ${ferrata ? 'ring-2 ring-inset ring-[color:var(--map-ferrata)]' : ''} ${stationRingClass(station?.importance)}`}
style={fs(11.5)}
>
{stop}
{ferrata && <FerrataGlyph size={22} className="absolute -bottom-2.5 -start-2.5" />}
{poi && <PoiCornerIcon category={poi} />}
{station?.protected && <StationShield />}
</span>
);
if (!ferrata) return number;
if (!ferrata) return note ? <Tooltip label={note}>{number}</Tooltip> : number;
const grade = ferrata.grade ? ` (${ferrata.grade})` : '';
return <Tooltip label={`${t('tours.ferrata.waypointAtEnd', { name: ferrata.name })}${grade}`}>{number}</Tooltip>;
}
@@ -231,7 +282,7 @@ function WaypointRowLabel({
paddleRole?: PaddleRole | null;
/** PR1-10: the point stands for this place of the trip, named after it. */
linked?: boolean;
/** CW-01: a city walk's station, which shows its stay, importance and protection. */
/** CW-01: a city walk's station, which shows its stay (its importance and protection are on its number). */
station?: boolean;
}) {
const { t } = useTranslation();
@@ -260,7 +311,6 @@ function WaypointRowLabel({
)}
{point.auto && <AutoPointPill />}
</span>
{station && !loopEnd && <StationPills point={point} />}
{linked && !loopEnd ? (
// A stop standing for a place of the trip says so where the coordinates would be (PR1-10).
<Tooltip label={t('tours.placePicker.linkedHint')}>
@@ -285,6 +335,8 @@ function WaypointRowLabel({
</span>
)
)}
{/* Under the coordinates: a station's stay, the one mark of it that is not on its number. */}
{station && !loopEnd && <StationPills point={point} />}
</>
);
}
@@ -727,6 +779,8 @@ export default function TourWaypointList({
stop={stop}
selected={selected}
ferrata={ferrataEnds[point.id] ?? null}
poiCategory={point.poiCategory ?? null}
station={point}
loopEnd={loopEnd}
shaping={!!point.shaping}
/>
@@ -0,0 +1,27 @@
import type { useTranslation } from '../../../i18n';
import type { TourPlannerWaypoint } from './tourPlannerWaypoints';
type Translate = ReturnType<typeof useTranslation>['t'];
/**
* CW-03: how much a station matters, as a ring around its number: a full ring
* in the warning colour for a must-see, a dashed muted one for an optional
* stop, none for a normal one.
*/
export function stationRingClass(importance: TourPlannerWaypoint['importance']): string {
if (importance === 'must') return 'outline outline-2 outline-offset-1 outline-warning';
if (importance === 'optional') return 'outline outline-2 outline-offset-1 outline-dashed outline-content-faint';
return '';
}
/** CW-03, CW-10: what the ring and the shield on a station's number say, for its label and tooltip. */
export function stationMarkNote(
point: Pick<TourPlannerWaypoint, 'importance' | 'protected'>,
t: Translate
): string | null {
const parts = [
point.importance ? t(`tours.walk.importance.${point.importance}`) : null,
point.protected ? t('tours.walk.station.protected') : null,
].filter((part): part is string => part !== null);
return parts.length ? parts.join(', ') : null;
}
@@ -2,10 +2,11 @@ import { walkStationsOf } from '@trek/shared';
import type { TourPlannerWaypoint } from './tourPlannerWaypoints';
/**
* CW-02: a city walk's time, walking and staying kept apart. A stay nobody
* entered is unknown, never nothing: the total then counts only what is
* known and says it is at least that much. A point passed through is a stay
* of 0, entered on purpose.
* CW-02: a city walk's time, walking and staying kept apart. While no stay is
* entered at all, the walk is planned as its walking time alone and nothing
* calls the stays unknown. Once some are entered, one left empty is unknown,
* never nothing: the total then counts only what is known and says it is at
* least that much. A point passed through is a stay of 0, entered on purpose.
*/
export interface WalkTimes {
walkingMinutes: number | null;
@@ -23,16 +24,21 @@ export interface WalkTimes {
/** The times of a walk from its parts: the walking time, the stays entered, how many are unknown and of how many. */
export function walkTimesOf(parts: Omit<WalkTimes, 'totalMinutes' | 'partial'>): WalkTimes {
const { walkingMinutes, stayMinutes, unknownStays } = parts;
const { walkingMinutes, stayMinutes, unknownStays, stations } = parts;
// Without a walking time the stays entered are still part of the whole: at least that much, never nothing.
const totalMinutes = walkingMinutes !== null ? walkingMinutes + stayMinutes : stayMinutes > 0 ? stayMinutes : null;
return {
...parts,
totalMinutes,
partial: totalMinutes !== null && (unknownStays > 0 || walkingMinutes === null),
partial: totalMinutes !== null && (someStaysUnknown({ unknownStays, stations }) || walkingMinutes === null),
};
}
/** Some stays entered and some not: none entered at all means none planned, not unknown. */
export function someStaysUnknown({ unknownStays, stations }: Pick<WalkTimes, 'unknownStays' | 'stations'>): boolean {
return unknownStays > 0 && unknownStays < stations;
}
export function walkTimes(points: readonly TourPlannerWaypoint[], walkingMinutes: number | null): WalkTimes {
// A shaping point is no station, and the way back of a loop is its start again: its stay counts once.
const stations = walkStationsOf(points);
@@ -1,38 +1,36 @@
import { Clock, ShieldCheck } from 'lucide-react';
import { useTranslation } from '../../../i18n';
import { SoftPill } from '../../Planner/planParts';
import { Tooltip } from '../../shared/Tooltip';
import { formatPlannedTourDuration } from '../tourPresentation';
import type { TourPlannerWaypoint } from './tourPlannerWaypoints';
/**
* CW-02, CW-03, CW-10: what a city walk's station row says besides its name:
* the stay (or that it is not known), an importance other than normal, and a
* protection, each a quiet pill.
* CW-02: a city walk station's stay, where one is entered, as a quiet pill
* under its name. A stay nobody entered says nothing. How much the station
* matters and whether it is protected are drawn on its number instead
* (`stationRingClass`, `StationShield`).
*/
export function StationPills({ point }: { point: TourPlannerWaypoint }) {
export function StationPills({ point }: { point: Pick<TourPlannerWaypoint, 'stayMinutes'> }) {
const { t } = useTranslation();
if (point.stayMinutes == null) return null;
return (
<span className="flex flex-wrap items-center gap-1" data-testid="station-pills">
<SoftPill icon={<Clock size={10} strokeWidth={2.2} aria-hidden="true" />}>
{point.stayMinutes == null
? t('tours.walk.station.stayUnknownShort')
: point.stayMinutes === 0
? t('tours.walk.station.passThrough')
: formatPlannedTourDuration(point.stayMinutes)}
{point.stayMinutes === 0 ? t('tours.walk.station.passThrough') : formatPlannedTourDuration(point.stayMinutes)}
</SoftPill>
{point.importance && (
<SoftPill tone={point.importance === 'must' ? 'warning' : undefined}>
{t(`tours.walk.importance.${point.importance}`)}
</SoftPill>
)}
{point.protected && (
<Tooltip label={t('tours.walk.station.protectedHint')}>
<span className="inline-flex" aria-label={t('tours.walk.station.protected')}>
<SoftPill icon={<ShieldCheck size={10} strokeWidth={2.2} aria-hidden="true" />} />
</span>
</Tooltip>
)}
</span>
);
}
/** CW-10: a protected station's shield, at the top corner of its number. */
export function StationShield() {
return (
<span
aria-hidden="true"
data-station-protected="true"
className="absolute -end-1.5 -top-1.5 grid h-3.5 w-3.5 place-items-center rounded-full bg-surface-card text-content-secondary shadow-sm"
>
<ShieldCheck size={9} strokeWidth={2.4} />
</span>
);
}
@@ -3,6 +3,7 @@ import type {
PlannableTourType,
StationImportance,
TourFixedLeg,
TourPoiCategory,
TourWaypoint,
TourWaypointRole,
} from '@trek/shared';
@@ -40,6 +41,8 @@ export interface TourPlannerWaypoint {
protected?: boolean;
/** CW-04: the station's opening hours as OpenStreetMap writes them. */
openingHours?: string | null;
/** PLN-03: the kind of place the point was taken in from along the tour, whose icon its row carries. */
poiCategory?: TourPoiCategory | null;
}
/** A saved tour's waypoints as the editor holds them, each under a fresh id. */
@@ -59,6 +62,7 @@ export function plannerWaypointsOf(saved: readonly TourWaypoint[], newId: () =>
...(point.importance ? { importance: point.importance } : {}),
...(point.protected ? { protected: true } : {}),
...(point.opening_hours ? { openingHours: point.opening_hours } : {}),
...(point.poi_category ? { poiCategory: point.poi_category } : {}),
}));
}
@@ -85,6 +89,7 @@ export function savedWaypointsOf(points: readonly TourPlannerWaypoint[], tourTyp
...(walk && point.importance ? { importance: point.importance } : {}),
...(walk && point.protected ? { protected: true } : {}),
...(point.openingHours ? { opening_hours: point.openingHours } : {}),
...(point.poiCategory ? { poi_category: point.poiCategory } : {}),
}));
}
@@ -144,8 +149,8 @@ export function routeExtrasKey(points: TourPlannerWaypoint[]): string {
/**
* CW-02: everything a route is planned from: every point with all it holds but
* a station's own fields (its name, stay, importance, protection and opening
* hours) and the key a save gave it. A change to those alone leaves the route
* a station's own fields (its name, stay, importance, protection, opening
* hours and the kind of place it was found as) and the key a save gave it. A change to those alone leaves the route
* as it is; any other change plans it again.
*/
export function routeInputsKey(points: readonly TourPlannerWaypoint[]): string {
@@ -157,6 +162,7 @@ export function routeInputsKey(points: readonly TourPlannerWaypoint[]): string {
importance: _importance,
protected: _protected,
openingHours: _hours,
poiCategory: _kind,
key: _key,
...routed
}) => routed
@@ -173,6 +179,7 @@ function stationFieldsKey(points: TourPlannerWaypoint[]): string {
point.importance ?? null,
!!point.protected,
point.openingHours ?? null,
point.poiCategory ?? null,
])
);
}
@@ -30,12 +30,13 @@ interface StationParts {
importance?: string | null;
protected?: boolean;
openingHours?: string | null;
poiCategory?: string | null;
}
/** A point split into what makes it a station and the rest of it; a part it does not have is left out. */
function stationSplit<T extends RoutePoint>(point: T & StationParts): { station: StationParts; rest: T } {
const { key, name, stayMinutes, importance, protected: kept, openingHours, ...rest } = point;
const parts: StationParts = { key, name, stayMinutes, importance, protected: kept, openingHours };
const { key, name, stayMinutes, importance, protected: kept, openingHours, poiCategory, ...rest } = point;
const parts: StationParts = { key, name, stayMinutes, importance, protected: kept, openingHours, poiCategory };
const station = Object.fromEntries(Object.entries(parts).filter(([, value]) => value !== undefined));
return { station, rest: rest as T };
}
@@ -0,0 +1,237 @@
import type { TourPoi, WalkTheme } from '@trek/shared';
import { WALK_THEMES } from '@trek/shared';
import { Clock, ExternalLink, MoveHorizontal, Plus, Route, X } from 'lucide-react';
import { useCallback, useRef } from 'react';
import { useTranslation } from '../../../i18n';
import { useSettingsStore } from '../../../store/settingsStore';
import { useTourPoiStore } from '../../../store/tourPoiStore';
import { formatDistance } from '../../../utils/units';
import { MAP_CARD_GLASS } from '../../Map/mapControlShadow';
import { TOUR_POI_LOOKS } from '../../Map/poiCategories';
import { useMapCardDismiss } from '../../Map/useMapCardDismiss';
import { WhiteBadge } from '../../Planner/planParts';
import { PillSelect } from '../../shared/dialogParts';
import { fs } from '../../shared/DialogShell';
import type { TourPlannerController } from '../planner/useTourPlanner';
import { useWaypointPlaceNames } from '../planner/useWaypointPlaceNames';
import { usePoiInsertion } from './usePoiInsertion';
import { useSelectedPoi } from './useTourPoiSearch';
type Unit = Parameters<typeof formatDistance>[1];
const km = (metres: number) => metres / 1000;
/** The point a place would follow, picked from the tour's points, with why one cannot take it. */
function AfterPicker({
planner,
poi,
insertion,
}: {
planner: TourPlannerController;
poi: TourPoi;
insertion: ReturnType<typeof usePoiInsertion>;
}) {
const { t } = useTranslation();
const names = useWaypointPlaceNames(planner.waypoints);
const afterId = insertion.afterIdFor(poi);
const options = planner.waypoints.map((point, index) => ({
value: point.id,
label: `${index + 1}. ${point.shaping ? t('tours.planner.shapingPoint') : (names[point.id] ?? `${point.lat.toFixed(4)}, ${point.lng.toFixed(4)}`)}`,
}));
const block = afterId ? insertion.blockOf(afterId) : 'none';
const locked = !planner.canEdit || planner.isSaving;
return (
<div className="mt-3 flex flex-col gap-2 border-t border-edge-faint pt-3" data-testid="tour-poi-insert">
<div className="flex min-w-0 items-center gap-2">
<span className="flex-none text-content-muted" style={fs(11.5, 'body')}>
{t('tours.poi.addAfter')}
</span>
<div className="min-w-0 flex-1">
<PillSelect
quiet
label={t('tours.poi.addAfter')}
value={afterId ?? ''}
options={options}
onChange={(value) => insertion.chooseAfter(poi, value)}
/>
</div>
</div>
{block && (
<p className="m-0 text-warning" style={fs(11, 'body')}>
{t(`tours.poi.blocked.${block}`)}
</p>
)}
<button
type="button"
disabled={!!block || locked}
onClick={() => insertion.insert(poi)}
data-testid="tour-poi-add"
title={t('tours.poi.notAPlace')}
className="inline-flex h-8 items-center justify-center gap-1.5 rounded-[10px] bg-accent px-3 font-semibold text-accent-text shadow-sm transition-opacity hover:opacity-90 disabled:cursor-default disabled:opacity-40"
style={fs(12, 'body')}
>
<Plus size={14} strokeWidth={2.2} />
{t('tours.poi.add')}
</button>
</div>
);
}
/** What the source says about the place: its address, its opening hours as written, and its website. */
function PoiFacts({ poi }: { poi: TourPoi }) {
const { t } = useTranslation();
if (!poi.address && !poi.opening_hours && !poi.website) return null;
return (
<div className="mt-2 flex flex-col gap-1.5">
{poi.address && (
<p className="m-0 break-words text-content-secondary" style={fs(11.5, 'body')}>
{poi.address}
</p>
)}
{poi.opening_hours && (
<p className="m-0 flex items-start gap-1.5 text-content-secondary" style={fs(11.5, 'body')}>
<Clock size={12} strokeWidth={2.2} className="mt-0.5 flex-none text-content-faint" />
<span className="min-w-0 break-words" title={t('tours.poi.hoursHint')}>
{poi.opening_hours}
</span>
</p>
)}
{poi.website && (
<a
href={poi.website}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 self-start text-content-secondary underline-offset-2 hover:underline"
style={fs(11.5, 'body')}
>
<ExternalLink size={12} strokeWidth={2.2} />
{t('tours.poi.website')}
</a>
)}
</div>
);
}
/**
* PLN-02/PLN-03: a place found along the tour, picked on the map or in the
* list, in the look of the other cards over the planner map: what it is, how
* far from the route and how far along it, why a city walk's theme suggested
* it, where the data comes from, and the way to take it in as a stop.
*/
function TourPoiCard({
poi,
theme,
planner,
insertion,
unit,
onClose,
width,
}: {
poi: TourPoi;
theme: WalkTheme | null;
planner: TourPlannerController;
insertion: ReturnType<typeof usePoiInsertion>;
unit: Unit;
onClose: () => void;
width?: number;
}) {
const { t } = useTranslation();
const look = TOUR_POI_LOOKS[poi.category];
const kind = t(look.labelKey);
const suggested = theme && (WALK_THEMES[theme] as readonly string[]).includes(poi.category) ? theme : null;
return (
<article
className={`max-h-[70vh] overflow-y-auto overscroll-contain rounded-2xl p-3 text-content ${width ? '' : 'w-[min(20rem,calc(100vw_-_2rem))]'}`}
style={{ ...MAP_CARD_GLASS, width }}
data-testid="tour-poi-card-map"
>
<div className="flex items-start gap-2">
{/* The category's own map colour, as its pin on the map has it: a light wash, the icon in full. */}
<span
className="grid h-7 w-7 flex-none place-items-center rounded-full"
style={{ background: `color-mix(in srgb, ${look.color} 16%, transparent)`, color: look.color }}
>
<look.Icon size={14} strokeWidth={2.2} />
</span>
<div className="min-w-0 flex-1">
<h3 className="line-clamp-2 break-words font-semibold" style={fs(14, 'body')} title={poi.name || kind}>
{poi.name || kind}
</h3>
{poi.name && <p className="truncate text-caption text-content-muted">{kind}</p>}
</div>
<button
type="button"
onClick={onClose}
aria-label={t('common.close')}
className="flex-none rounded-lg p-1 text-content-muted hover:bg-surface-hover hover:text-content"
>
<X size={14} aria-hidden="true" />
</button>
</div>
<div className="mt-2 flex flex-wrap gap-1.5">
<WhiteBadge icon={<MoveHorizontal size={10} strokeWidth={2.2} className="text-content-faint" />}>
{t('tours.poi.fromRoute', { distance: formatDistance(km(poi.distance_m), unit) })}
</WhiteBadge>
<WhiteBadge icon={<Route size={10} strokeWidth={2.2} className="text-content-faint" />}>
{t('tours.poi.along', { distance: formatDistance(km(poi.along_m), unit) })}
</WhiteBadge>
</div>
<PoiFacts poi={poi} />
<AfterPicker planner={planner} poi={poi} insertion={insertion} />
<p className="mt-2 flex flex-wrap gap-x-3 text-content-faint" style={fs(10.5, 'body')}>
{suggested && <span>{t('tours.walk.themeReason', { theme: t(`tours.walk.theme.${suggested}`) })}</span>}
<span>{t(poi.source === 'trek-places' ? 'tours.poi.source.trek' : 'tours.poi.source.osm')}</span>
</p>
</article>
);
}
/**
* The chosen place's card over the planner map, where a via ferrata's or a
* paddle object's card sits and closing as those do: on a press outside it
* and on Escape, the press handed on so the map leaves its click alone. The
* choice lives in the places store, so a pin on the map and a row in the list
* open the same card.
*/
export default function TourPoiOverlay({
planner,
onOutsidePress,
insetEnd,
bottom,
width,
}: {
planner: TourPlannerController;
onOutsidePress?: () => void;
insetEnd: number;
bottom: number;
width?: number;
}) {
const ref = useRef<HTMLDivElement>(null);
const unit = useSettingsStore((state) => state.settings.distance_unit) ?? 'metric';
const poi = useSelectedPoi();
const theme = useTourPoiStore((state) => state.theme);
const select = useTourPoiStore((state) => state.select);
const insertion = usePoiInsertion(planner);
const close = useCallback(() => select(null), [select]);
useMapCardDismiss(ref, !!poi, close, onOutsidePress);
if (!poi) return null;
return (
<div
ref={ref}
className="absolute z-[20] flex justify-end transition-[bottom] duration-200 ease-out"
style={{ insetInlineEnd: insetEnd, bottom, maxWidth: `calc(100% - ${insetEnd + 32}px)` }}
data-testid="tour-poi-overlay"
>
<TourPoiCard
poi={poi}
theme={theme}
planner={planner}
insertion={insertion}
unit={unit}
onClose={close}
width={width}
/>
</div>
);
}
@@ -1,21 +1,18 @@
import type { TourPoi, WalkTheme } from '@trek/shared';
import { TOUR_POI_CORRIDORS_M, WALK_THEMES } from '@trek/shared';
import { TOUR_POI_CORRIDORS_M } from '@trek/shared';
import {
AlertTriangle,
ChevronDown,
Clock,
Coffee,
ExternalLink,
Landmark,
Loader2,
MoveHorizontal,
Plus,
RefreshCw,
Route,
Search,
Shuffle,
Trees,
WifiOff,
X,
type LucideIcon,
} from 'lucide-react';
import { useEffect, useRef } from 'react';
@@ -26,11 +23,10 @@ import { formatDistance } from '../../../utils/units';
import { TOUR_POI_LOOKS } from '../../Map/poiCategories';
import { PopoverItem } from '../../Packing/PackingPopover';
import { WhiteBadge } from '../../Planner/planParts';
import { PillSelect, PopoverListPanel, Segmented } from '../../shared/dialogParts';
import { PopoverListPanel, Segmented } from '../../shared/dialogParts';
import { fs } from '../../shared/DialogShell';
import { usePopoverList } from '../../shared/usePopoverList';
import type { TourPlannerController } from '../planner/useTourPlanner';
import { useWaypointPlaceNames } from '../planner/useWaypointPlaceNames';
import { RailCard, TourNotice } from '../tourParts';
import { formatPlannedTourDuration } from '../tourPresentation';
import { usePoiInsertion, type InsertionOutcome } from './usePoiInsertion';
@@ -139,6 +135,7 @@ function ThemeGrid({
type="button"
onClick={() => onChoose(theme)}
aria-pressed={on}
title={t(`tours.walk.themeHint.${theme}`)}
data-testid={`tour-poi-theme-${theme}`}
className={`flex min-w-0 items-center gap-2 rounded-[10px] px-2.5 py-2 text-start font-medium leading-tight transition-colors ${on ? 'bg-surface-card text-content shadow-sm ring-1 ring-inset ring-edge-faint' : 'bg-surface-tertiary text-content-muted hover:text-content'}`}
style={fs(11.5, 'body')}
@@ -153,13 +150,14 @@ function ThemeGrid({
}
/**
* What the search answered beyond its places: out of date, offline, failed,
* kinds that could not be searched, partly searched, cut, or empty. Nothing
* What the search answered beyond its places: offline, failed, kinds that
* could not be searched, partly searched, cut, or empty. That the answer is
* out of date the search button says, as it is what to press then. Nothing
* found is said only when every kind was searched.
*/
function SearchNotices({ search, unit }: { search: TourPoiSearch; unit: Unit }) {
const { t } = useTranslation();
const { status, answer, outdated } = search;
const { status, answer } = search;
if (status === 'offline')
return <TourNotice icon={<WifiOff size={13} strokeWidth={2} />}>{t('tours.poi.offline')}</TourNotice>;
if (status === 'error')
@@ -169,7 +167,6 @@ function SearchNotices({ search, unit }: { search: TourPoiSearch; unit: Unit })
</TourNotice>
);
if (!answer) return null;
// Out of date is no fault, the route was just changed (often by adding a place from here): said plainly.
const unavailable = answer.unavailable.map((category) => t(TOUR_POI_LOOKS[category].labelKey)).join(', ');
const notes = [
unavailable && t('tours.poi.unavailable', { kinds: unavailable }),
@@ -179,7 +176,6 @@ function SearchNotices({ search, unit }: { search: TourPoiSearch; unit: Unit })
].filter((note): note is string => !!note);
return (
<>
{outdated && <TourNotice icon={<RefreshCw size={13} strokeWidth={2} />}>{t('tours.poi.outdated')}</TourNotice>}
{notes.map((note) => (
<TourNotice key={note} tone="warning" icon={<AlertTriangle size={13} strokeWidth={2} />}>
{note}
@@ -194,79 +190,12 @@ function SearchNotices({ search, unit }: { search: TourPoiSearch; unit: Unit })
);
}
/** The point a place would follow, picked from the tour's points, with why one cannot take it. */
function AfterPicker({
planner,
poi,
insertion,
}: {
planner: TourPlannerController;
poi: TourPoi;
insertion: ReturnType<typeof usePoiInsertion>;
}) {
const { t } = useTranslation();
const names = useWaypointPlaceNames(planner.waypoints);
const afterId = insertion.afterIdFor(poi);
const options = planner.waypoints.map((point, index) => ({
value: point.id,
label: `${index + 1}. ${point.shaping ? t('tours.planner.shapingPoint') : (names[point.id] ?? `${point.lat.toFixed(4)}, ${point.lng.toFixed(4)}`)}`,
}));
const block = afterId ? insertion.blockOf(afterId) : 'none';
const locked = !planner.canEdit || planner.isSaving;
return (
<div className="flex flex-col gap-2 rounded-[10px] bg-surface-secondary p-2.5" data-testid="tour-poi-insert">
<div className="flex flex-wrap items-center gap-2">
<span className="text-content-muted" style={fs(11.5, 'body')}>
{t('tours.poi.addAfter')}
</span>
<PillSelect
quiet
label={t('tours.poi.addAfter')}
value={afterId ?? ''}
options={options}
onChange={(value) => insertion.chooseAfter(poi, value)}
/>
</div>
{block && (
<p className="m-0 text-warning" style={fs(11, 'body')}>
{t(`tours.poi.blocked.${block}`)}
</p>
)}
<button
type="button"
disabled={!!block || locked}
onClick={() => insertion.insert(poi)}
data-testid="tour-poi-add"
className="inline-flex h-8 items-center justify-center gap-1.5 rounded-[10px] bg-accent px-3 font-semibold text-accent-text shadow-sm transition-opacity hover:opacity-90 disabled:cursor-default disabled:opacity-40"
style={fs(12, 'body')}
>
<Plus size={14} strokeWidth={2.2} />
{t('tours.poi.add')}
</button>
<p className="m-0 text-content-faint" style={fs(10.5, 'body')}>
{t('tours.poi.notAPlace')}
</p>
</div>
);
}
/** One place found: its kind, name and where it lies; opened, what the source says and the way to take it in. */
function PoiRow({
poi,
selected,
planner,
insertion,
unit,
theme = null,
}: {
poi: TourPoi;
selected: boolean;
planner: TourPlannerController;
insertion: ReturnType<typeof usePoiInsertion>;
unit: Unit;
/** CW-05: the theme the place was suggested for, said as its reason. */
theme?: WalkTheme | null;
}) {
/**
* One place found, in one line: its kind's icon in its map colour, its name,
* and how far it lies from the route. A click opens its card over the map,
* where the rest is said and the place is taken in as a stop.
*/
function PoiRow({ poi, selected, unit }: { poi: TourPoi; selected: boolean; unit: Unit }) {
const { t } = useTranslation();
const select = useTourPoiStore((state) => state.select);
const look = TOUR_POI_LOOKS[poi.category];
@@ -274,77 +203,33 @@ function PoiRow({
useEffect(() => {
if (selected) rowRef.current?.scrollIntoView?.({ block: 'nearest' });
}, [selected]);
const distance = formatDistance(km(poi.distance_m), unit);
return (
<li
ref={rowRef}
className={`rounded-[10px] ${selected ? 'bg-surface-selected' : ''}`}
data-testid={`tour-poi-${poi.id}`}
>
<li ref={rowRef} data-testid={`tour-poi-${poi.id}`}>
<button
type="button"
onClick={() => select(selected ? null : poi.id)}
aria-expanded={selected}
className="flex w-full min-w-0 items-start gap-2.5 rounded-[10px] px-2 py-2 text-start transition-colors hover:bg-surface-hover"
onClick={() => select(poi.id)}
aria-pressed={selected}
className={`flex w-full min-w-0 items-center gap-2 rounded-[8px] px-1.5 py-1 text-start transition-colors hover:bg-surface-hover ${selected ? 'bg-surface-selected' : ''}`}
>
{/* The category's own map colour, as its pin on the map has it: a light wash, the icon in full. */}
<span
className="grid h-7 w-7 flex-none place-items-center rounded-full"
className="grid h-6 w-6 flex-none place-items-center rounded-full"
style={{ background: `color-mix(in srgb, ${look.color} 16%, transparent)`, color: look.color }}
>
<look.Icon size={14} strokeWidth={2.2} />
<look.Icon size={12} strokeWidth={2.2} />
</span>
<span className="flex min-w-0 flex-1 flex-col gap-1">
<span className="min-w-0 truncate font-semibold text-content" style={fs(12.5, 'body')}>
{poi.name || t(look.labelKey)}
</span>
<span className="flex flex-wrap gap-1.5">
<WhiteBadge icon={<MoveHorizontal size={10} strokeWidth={2.2} className="text-content-faint" />}>
{t('tours.poi.fromRoute', { distance: formatDistance(km(poi.distance_m), unit) })}
</WhiteBadge>
<WhiteBadge icon={<Route size={10} strokeWidth={2.2} className="text-content-faint" />}>
{t('tours.poi.along', { distance: formatDistance(km(poi.along_m), unit) })}
</WhiteBadge>
</span>
<span className="min-w-0 flex-1 truncate font-medium text-content" style={fs(12, 'body')}>
{poi.name || t(look.labelKey)}
</span>
<span
className="flex-none tabular-nums text-content-faint"
style={fs(11, 'body')}
title={t('tours.poi.fromRoute', { distance })}
>
{distance}
</span>
</button>
{selected && (
<div className="flex flex-col gap-2 px-2 pb-2.5">
<p className="m-0 flex flex-wrap gap-x-3 text-content-faint" style={fs(10.5, 'body')}>
<span>{t(look.labelKey)}</span>
{theme && <span>{t('tours.walk.themeReason', { theme: t(`tours.walk.theme.${theme}`) })}</span>}
<span>{t(poi.source === 'trek-places' ? 'tours.poi.source.trek' : 'tours.poi.source.osm')}</span>
</p>
{poi.address && (
<p className="m-0 text-content-secondary" style={fs(11.5, 'body')}>
{poi.address}
</p>
)}
{poi.opening_hours && (
<p className="m-0 flex items-start gap-1.5 text-content-secondary" style={fs(11.5, 'body')}>
<Clock size={12} strokeWidth={2.2} className="mt-0.5 flex-none text-content-faint" />
<span>
{poi.opening_hours}
<span className="block text-content-faint" style={fs(10.5, 'body')}>
{t('tours.poi.hoursHint')}
</span>
</span>
</p>
)}
{poi.website && (
<a
href={poi.website}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 self-start text-content-secondary underline-offset-2 hover:underline"
style={fs(11.5, 'body')}
>
<ExternalLink size={12} strokeWidth={2.2} />
{t('tours.poi.website')}
</a>
)}
<AfterPicker planner={planner} poi={poi} insertion={insertion} />
</div>
)}
</li>
);
}
@@ -364,24 +249,30 @@ function OutcomeNotice({ outcome, onDismiss, unit }: { outcome: InsertionOutcome
)
}
>
<span className="flex flex-col gap-1.5">
<span>{t(`tours.poi.outcome.${outcome.kind}`, { name: outcome.name })}</span>
{outcome.kind === 'measured' && (
<span className="flex flex-wrap gap-1.5">
<WhiteBadge>{signed(formatDistance(km(Math.abs(outcome.extraM)), unit), outcome.extraM < 0)}</WhiteBadge>
{outcome.extraMinutes != null && (
<span className="flex items-start gap-2">
<span className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5">
<span>{t(`tours.poi.outcome.${outcome.kind}`, { name: outcome.name })}</span>
{outcome.kind === 'measured' && (
<>
<WhiteBadge>
{signed(formatPlannedTourDuration(Math.abs(outcome.extraMinutes)), outcome.extraMinutes < 0)}
{signed(formatDistance(km(Math.abs(outcome.extraM)), unit), outcome.extraM < 0)}
</WhiteBadge>
)}
</span>
)}
<span className="flex flex-wrap items-center gap-2 text-content-faint" style={fs(10.5, 'body')}>
{t('tours.poi.undoHint')}
<button type="button" onClick={onDismiss} className="font-semibold underline underline-offset-2">
{t('common.close')}
</button>
{outcome.extraMinutes != null && (
<WhiteBadge>
{signed(formatPlannedTourDuration(Math.abs(outcome.extraMinutes)), outcome.extraMinutes < 0)}
</WhiteBadge>
)}
</>
)}
</span>
<button
type="button"
onClick={onDismiss}
aria-label={t('common.close')}
className="flex-none rounded p-0.5 text-content-faint hover:text-content"
>
<X size={12} strokeWidth={2.4} aria-hidden="true" />
</button>
</span>
</TourNotice>
</div>
@@ -415,15 +306,9 @@ export function TourPoiSearchCard({ planner }: { planner: TourPlannerController
}
>
<div className="flex flex-col gap-3" data-testid="tour-poi-card">
<p className="m-0 text-content-faint" style={fs(11, 'body')}>
{t('tours.poi.intro')}
</p>
{search.themes.length > 0 && (
<div className="flex flex-col gap-1.5" data-testid="tour-poi-themes">
<div data-testid="tour-poi-themes">
<ThemeGrid themes={search.themes} active={search.theme} onChoose={search.chooseTheme} />
<span className="text-content-faint" style={fs(11, 'body')}>
{search.theme ? t(`tours.walk.themeHint.${search.theme}`) : t('tours.walk.themeHint.own')}
</span>
</div>
)}
<CategoryPicker search={search} />
@@ -446,8 +331,10 @@ export function TourPoiSearchCard({ planner }: { planner: TourPlannerController
type="button"
onClick={() => void search.search()}
disabled={!search.canSearch}
title={search.outdated ? t('tours.poi.outdated') : undefined}
data-testid="tour-poi-search"
className="inline-flex h-9 items-center justify-center gap-1.5 rounded-[10px] bg-surface-tertiary font-semibold text-content transition-colors hover:bg-surface-hover disabled:cursor-default disabled:opacity-50"
data-outdated={search.outdated || undefined}
className={`inline-flex h-9 items-center justify-center gap-1.5 rounded-[10px] font-semibold transition-colors disabled:cursor-default disabled:opacity-50 ${search.outdated ? 'bg-accent text-accent-text hover:opacity-90' : 'bg-surface-tertiary text-content hover:bg-surface-hover'}`}
style={fs(12.5, 'body')}
>
{search.status === 'loading' ? (
@@ -464,21 +351,12 @@ export function TourPoiSearchCard({ planner }: { planner: TourPlannerController
{insertion.outcome && <OutcomeNotice outcome={insertion.outcome} onDismiss={insertion.dismiss} unit={unit} />}
<SearchNotices search={search} unit={unit} />
{pois.length > 0 && (
<ul className={`m-0 flex list-none flex-col gap-0.5 p-0 ${search.status === 'loading' ? 'opacity-60' : ''}`}>
<ul
className={`m-0 flex max-h-[320px] list-none flex-col gap-px overflow-y-auto overscroll-contain p-0 ${search.status === 'loading' ? 'opacity-60' : ''}`}
data-testid="tour-poi-list"
>
{pois.map((poi) => (
<PoiRow
key={poi.id}
poi={poi}
selected={selected?.id === poi.id}
planner={planner}
insertion={insertion}
unit={unit}
theme={
search.theme && (WALK_THEMES[search.theme] as readonly string[]).includes(poi.category)
? search.theme
: null
}
/>
<PoiRow key={poi.id} poi={poi} selected={selected?.id === poi.id} unit={unit} />
))}
</ul>
)}
@@ -8,12 +8,13 @@ import { tourPoiSearchRepo } from '../../../repo/tourPoiSearchRepo';
import { useTourPoiStore } from '../../../store/tourPoiStore';
import type { TourPlannerWaypoint } from '../planner/tourPlannerWaypoints';
import type { TourPlannerController } from '../planner/useTourPlanner';
import TourPoiOverlay from './TourPoiCard';
import { TourPoiSearchCard } from './TourPoiSearchCard';
import { usePoiInsertion, type PoiInsertionPlanner } from './usePoiInsertion';
import { useTourPoiMarkers } from './useTourPoiMarkers';
import { useTourPoiSearch } from './useTourPoiSearch';
// FE-TOUR-POI-001 to FE-TOUR-POI-015
// FE-TOUR-POI-001 to FE-TOUR-POI-016
vi.mock('../planner/useWaypointPlaceNames', () => ({ useWaypointPlaceNames: () => ({}) }));
@@ -194,22 +195,63 @@ describe('usePoiInsertion (PLN-03)', () => {
});
});
/** The list in the side panel and the chosen place's card over the map, as the planner shows them. */
function renderAlong(planner: TourPlannerController) {
return render(
<>
<TourPoiSearchCard planner={planner} />
<TourPoiOverlay planner={planner} insetEnd={0} bottom={0} />
</>
);
}
describe('TourPoiSearchCard', () => {
it('FE-TOUR-POI-008: lists what was found with where it lies; opening a place offers to add it after a point', async () => {
it('FE-TOUR-POI-008: lists what was found in one line each; a place opens its card over the map, which adds it after a point', async () => {
const planner = {
...searchPlanner(),
...insertionPlanner(),
} as unknown as TourPlannerController;
render(<TourPoiSearchCard planner={planner} />);
renderAlong(planner);
fireEvent.click(screen.getByTestId('tour-poi-search'));
const row = await screen.findByTestId('tour-poi-node:1');
expect(row).toHaveTextContent('Spring');
expect(row).toHaveTextContent('80 m from the route');
expect(row).toHaveTextContent('80 m');
expect(within(row).queryByTestId('tour-poi-add')).not.toBeInTheDocument();
expect(screen.queryByTestId('tour-poi-overlay')).not.toBeInTheDocument();
fireEvent.click(within(row).getByRole('button', { name: /Spring/ }));
expect(within(row).getByText('Mo-Su 08:00-18:00')).toBeInTheDocument();
expect(within(row).getByText('As the source has them; check before you go.')).toBeInTheDocument();
fireEvent.click(within(row).getByTestId('tour-poi-add'));
const card = screen.getByTestId('tour-poi-overlay');
expect(within(row).getByRole('button', { name: /Spring/ })).toHaveAttribute('aria-pressed', 'true');
expect(card).toHaveTextContent('80 m from the route');
expect(within(card).getByText('Mo-Su 08:00-18:00')).toBeInTheDocument();
expect(within(card).getByText('Mo-Su 08:00-18:00')).toHaveAttribute(
'title',
'As the source has them; check before you go.'
);
fireEvent.click(within(card).getByTestId('tour-poi-add'));
await waitFor(() => expect(planner.editWaypoints).toHaveBeenCalledTimes(1));
// The card closes once the place is in, and the list says what it did.
expect(screen.queryByTestId('tour-poi-overlay')).not.toBeInTheDocument();
expect(screen.getByTestId('tour-poi-outcome')).toHaveTextContent('Spring');
});
it('FE-TOUR-POI-016: the card over the map closes on its button and on Escape, and a pin on the map opens it too', async () => {
const planner = { ...searchPlanner(), ...insertionPlanner() } as unknown as TourPlannerController;
renderAlong(planner);
fireEvent.click(screen.getByTestId('tour-poi-search'));
await screen.findByTestId('tour-poi-node:1');
const markers = renderHook(() => useTourPoiMarkers(), { wrapper: TranslationProvider });
// The one place found, picked as a click on its pin does.
for (const poi of markers.result.current.pois) act(() => markers.result.current.onPoiClick(poi));
expect(screen.getByTestId('tour-poi-overlay')).toHaveTextContent('Spring');
fireEvent.click(within(screen.getByTestId('tour-poi-overlay')).getByRole('button', { name: 'Close' }));
expect(screen.queryByTestId('tour-poi-overlay')).not.toBeInTheDocument();
fireEvent.click(within(screen.getByTestId('tour-poi-node:1')).getByRole('button', { name: /Spring/ }));
expect(screen.getByTestId('tour-poi-overlay')).toBeInTheDocument();
fireEvent.keyDown(document, { key: 'Escape' });
expect(screen.queryByTestId('tour-poi-overlay')).not.toBeInTheDocument();
});
it('FE-TOUR-POI-009: names the kinds that could not be searched, and does not claim nothing was found', async () => {
@@ -272,11 +314,11 @@ describe('a city walk along its places (CW-05)', () => {
// The walk starts with its first three categories, which no theme is.
for (const theme of ['culture', 'parks', 'food', 'mixed'])
expect(themeButton(theme)).toHaveAttribute('aria-pressed', 'false');
expect(themes).toHaveTextContent('Your own pick of categories below; a theme sets them for you.');
// What a theme looks for is said on the button, not in a line of its own.
expect(themeButton('food')).toHaveAttribute('title', 'Coffee shops, places to eat and markets along the route.');
fireEvent.click(themeButton('food'));
expect(themeButton('food')).toHaveAttribute('aria-pressed', 'true');
expect(themes).toHaveTextContent('Coffee shops, places to eat and markets along the route.');
expect(screen.getByTestId('tour-poi-categories')).toHaveTextContent('Coffee shops, Places to eat +1');
fireEvent.click(screen.getByTestId('tour-poi-search'));
await waitFor(() =>
@@ -290,7 +332,6 @@ describe('a city walk along its places (CW-05)', () => {
fireEvent.click(screen.getByTestId('tour-poi-categories'));
fireEvent.click(screen.getByRole('button', { name: 'Markets' }));
expect(themeButton('food')).toHaveAttribute('aria-pressed', 'false');
expect(themes).toHaveTextContent('Your own pick of categories below; a theme sets them for you.');
});
it('FE-TOUR-POI-012: the category field names two categories, counts the rest, and says when none is chosen', () => {
@@ -312,12 +353,14 @@ describe('a city walk along its places (CW-05)', () => {
it('FE-TOUR-POI-013: a place found for a theme says which theme suggested it', async () => {
search.mockResolvedValue({ ...ANSWER, pois: [CAFE, SPRING] });
render(<TourPoiSearchCard planner={walkPlanner()} />);
renderAlong(walkPlanner());
fireEvent.click(themeButton('food'));
fireEvent.click(screen.getByTestId('tour-poi-search'));
const cafe = await screen.findByTestId('tour-poi-node:3');
fireEvent.click(within(cafe).getByRole('button', { name: /Cafe Luitpold/ }));
expect(within(cafe).getByText('Suggested for Food and local life')).toBeInTheDocument();
expect(
within(screen.getByTestId('tour-poi-overlay')).getByText('Suggested for Food and local life')
).toBeInTheDocument();
fireEvent.click(within(screen.getByTestId('tour-poi-node:1')).getByRole('button', { name: /Spring/ }));
expect(screen.queryByText('Suggested for Food and local life')).not.toBeInTheDocument();
});
@@ -345,7 +388,13 @@ describe('a city walk along its places (CW-05)', () => {
(point) => !POINTS.includes(point)
) as TourPlannerWaypoint
);
expect(added[0]).toMatchObject({ name: 'Spring', openingHours: 'Mo-Su 08:00-18:00' });
expect(added[0]).toMatchObject({
name: 'Spring',
openingHours: 'Mo-Su 08:00-18:00',
poiCategory: 'drinking_water',
});
// PLN-03: the kind the place was found as goes with it, so its row carries the kind's icon.
expect(added[1]).toMatchObject({ poiCategory: 'cafe' });
expect(added[1]).not.toHaveProperty('name');
expect(added[1]).not.toHaveProperty('openingHours');
});
@@ -1,7 +1,7 @@
import type { TourPoi } from '@trek/shared';
import { useCallback, useState } from 'react';
import { useTranslation } from '../../../i18n';
import { useTourPoiStore } from '../../../store/tourPoiStore';
import { useTourPoiStore, type InsertedTourPoi } from '../../../store/tourPoiStore';
import { randomId } from '../../../utils/randomId';
import { TOUR_POI_LOOKS } from '../../Map/poiCategories';
import type { TourPlannerWaypoint } from '../planner/tourPlannerWaypoints';
@@ -16,15 +16,6 @@ interface Measures {
minutes: number | null;
}
/** A place taken in: which point it became, and the route's measures just before. */
interface Inserted {
pointId: string;
name: string;
before: Measures | null;
/** How many points the tour had once the place was in; another edit after it ends the comparison. */
pointCount: number;
}
export type InsertionOutcome =
| { kind: 'measuring'; name: string }
| { kind: 'measured'; name: string; extraM: number; extraMinutes: number | null }
@@ -62,7 +53,9 @@ export function usePoiInsertion(planner: PoiInsertionPlanner) {
const { t } = useTranslation();
const select = useTourPoiStore((state) => state.select);
const [afterChoice, setAfterChoice] = useState<{ poiId: string; afterId: string } | null>(null);
const [inserted, setInserted] = useState<Inserted | null>(null);
// Kept in the store: the place is taken in from its card over the map, and the list says what it did.
const inserted = useTourPoiStore((state) => state.inserted);
const setInserted = useTourPoiStore((state) => state.setInserted);
const afterIdFor = useCallback(
(poi: TourPoi) =>
@@ -85,6 +78,8 @@ export function usePoiInsertion(planner: PoiInsertionPlanner) {
role: 'via',
...(poi.name ? { name: poi.name } : {}),
...(poi.opening_hours ? { openingHours: poi.opening_hours } : {}),
// PLN-03: its row carries the kind's icon, as the map drew the place.
poiCategory: poi.category,
};
const next = withPointAfter(planner.waypoints, afterId, point);
if (!next) return false;
@@ -97,10 +92,10 @@ export function usePoiInsertion(planner: PoiInsertionPlanner) {
select(null);
return true;
},
[afterIdFor, planner, select, t]
[afterIdFor, planner, select, setInserted, t]
);
const dismiss = useCallback(() => setInserted(null), []);
const dismiss = useCallback(() => setInserted(null), [setInserted]);
return {
afterIdFor,
@@ -117,7 +112,7 @@ export function usePoiInsertion(planner: PoiInsertionPlanner) {
* now: nothing once the point is gone again (undone or removed) or the tour
* was edited further, so the figure never describes another route.
*/
function outcomeOf(inserted: Inserted | null, planner: PoiInsertionPlanner): InsertionOutcome | null {
function outcomeOf(inserted: InsertedTourPoi | null, planner: PoiInsertionPlanner): InsertionOutcome | null {
if (!inserted) return null;
const stillThere = planner.waypoints.some((point) => point.id === inserted.pointId);
if (!stillThere || planner.waypoints.length !== inserted.pointCount) return null;
@@ -112,7 +112,7 @@ export function useTourPoiSearch(planner: TourPoiPlanner) {
controller.signal
);
setAnswer({ key, status: 'ready', data });
publish(data.pois);
publish(data.pois, theme);
} catch (err: unknown) {
if (controller.signal.aborted) return;
setAnswer({ key, status: err instanceof OnlineOnlyError ? 'offline' : 'error' });
@@ -123,7 +123,7 @@ export function useTourPoiSearch(planner: TourPoiPlanner) {
setLoadingKey(null);
}
}
}, [categories, clear, corridorM, currentKey, locale, planner.tripId, publish, route, type]);
}, [categories, clear, corridorM, currentKey, locale, planner.tripId, publish, route, theme, type]);
// Leaving the planner, or a tour closed, takes the places off the map.
useEffect(
@@ -6,7 +6,8 @@ import type { Assignment, AssignmentsMap, Day } from '../../../types';
import { SoftPill } from '../../Planner/planParts';
import { DialogSection, fs } from '../../shared/DialogShell';
import { useToast } from '../../shared/Toast';
import { StationPills } from '../planner/stationParts';
import { stationMarkNote, stationRingClass } from '../planner/stationMarks';
import { StationPills, StationShield } from '../planner/stationParts';
import type { TourPlannerWaypoint } from '../planner/tourPlannerWaypoints';
import { TourDayRowPill } from '../TourDayRowFacts';
import { CardAction } from '../tourParts';
@@ -102,9 +103,11 @@ function StationRow({
data-testid="walk-station"
className={`flex items-start gap-2.5 rounded-[10px] px-1.5 py-1.5 ${status ? 'opacity-70' : ''}`}
>
{/* How much the station matters rings its number; a protection is a shield at its corner (CW-03, CW-10). */}
<span
className="grid h-6 w-6 flex-none place-items-center rounded-full bg-surface-tertiary font-geist tabular-nums text-content-secondary"
className={`relative grid h-6 w-6 flex-none place-items-center rounded-full bg-surface-tertiary font-geist tabular-nums text-content-secondary ${stationRingClass(station.importance)}`}
style={fs(11)}
title={stationMarkNote(station, t) ?? undefined}
>
{status === 'visited' ? (
<Check size={12} strokeWidth={2.4} />
@@ -113,6 +116,7 @@ function StationRow({
) : (
index + 1
)}
{station.protected && <StationShield />}
</span>
<span className="flex min-w-0 flex-1 flex-col gap-1">
<span
@@ -35,11 +35,10 @@ describe('walkTimeFields', () => {
['Stays', 'at least 1 h 30 min'],
['Planned', 'at least 2 h 15 min'],
]);
// No stay entered at all is not known, never nothing.
// No stay entered at all plans the walking time alone, with no stays field to call them unknown.
expect(fieldsOf(45, { stayMinutes: 0, unknownStays: 3, stations: 3 })).toEqual([
['Walking', '45 min'],
['Stays', 'Not known yet'],
['Planned', 'at least 45 min'],
['Planned', '45 min'],
]);
});
@@ -59,7 +58,6 @@ describe('walkTimeFields', () => {
]);
expect(fieldsOf(null, { stayMinutes: 0, unknownStays: 2, stations: 2 })).toEqual([
['Walking', 'Not calculated'],
['Stays', 'Not known yet'],
['Planned', 'Not calculated'],
]);
});
@@ -71,7 +69,7 @@ describe('walkTimeFields', () => {
['Planned (Manual override)', '4 h'],
['Computed', 'at least 2 h 15 min'],
]);
expect(fieldsOf(null, { stayMinutes: 0, unknownStays: 1, stations: 1 }, 60)[3]).toEqual([
expect(fieldsOf(null, { stayMinutes: 0, unknownStays: 1, stations: 1 }, 60)[2]).toEqual([
'Computed',
'Not calculated',
]);
@@ -104,7 +102,9 @@ describe('walkTimeFields', () => {
});
describe('walkStaysText', () => {
it('says a walk without stations has no stays to wait for', () => {
expect(walkStaysText({ stayMinutes: 0, unknownStays: 0, stations: 0 }, t)).toBe('0 min');
it('says nothing of the stays of a walk without stations, or with none entered', () => {
expect(walkStaysText({ stayMinutes: 0, unknownStays: 0, stations: 0 }, t)).toBeNull();
expect(walkStaysText({ stayMinutes: 0, unknownStays: 2, stations: 2 }, t)).toBeNull();
expect(walkStaysText({ stayMinutes: 30, unknownStays: 1, stations: 2 }, t)).toBe('at least 30 min');
});
});
@@ -1,4 +1,4 @@
import { walkTimesOf, type WalkTimes } from '../planner/stationModel';
import { someStaysUnknown, walkTimesOf, type WalkTimes } from '../planner/stationModel';
import type { TourMetricField } from '../tourParts';
import { formatPlannedTourDuration, plannedTotalText } from '../tourPresentation';
@@ -8,14 +8,16 @@ type Translate = (key: string, params?: Record<string, unknown>) => string;
type WalkStays = Pick<WalkTimes, 'stayMinutes' | 'unknownStays' | 'stations'>;
/**
* A city walk's stays as said: their sum, at least the sum while a stay is not
* entered yet, and not known while none is. A stop passed through counts as
* the 0 entered for it, so stays all entered as 0 read "0 min".
* A city walk's stays as said: their sum, and at least the sum while some
* stay is not entered yet. Nothing while no stay is entered at all: the walk
* is then planned as its walking time, and saying "unknown" at every turn
* would only be noise. A stop passed through counts as the 0 entered for it,
* so stays all entered as 0 read "0 min".
*/
export function walkStaysText(stays: WalkStays, t: Translate): string {
if (stays.stations > 0 && stays.unknownStays === stays.stations) return t('tours.walk.station.stayUnknown');
export function walkStaysText(stays: WalkStays, t: Translate): string | null {
if (stays.unknownStays >= stays.stations) return null;
const time = formatPlannedTourDuration(stays.stayMinutes);
return stays.unknownStays > 0 ? t('tours.walk.totalAtLeast', { time }) : time;
return someStaysUnknown(stays) ? t('tours.walk.totalAtLeast', { time }) : time;
}
export interface WalkTimeFieldsInput {
@@ -47,9 +49,10 @@ export function walkTimeFields({
const times = walkTimesOf({ walkingMinutes, stayMinutes, unknownStays, stations });
const computed =
plannedTotalText({ plannedTotalMinutes: times.totalMinutes, atLeast: times.partial }, t) ?? notCalculated;
const staysText = walkStaysText(stays, t);
const parts: TourMetricField[] = [
{ ...walking, value: walkingMinutes == null ? notCalculated : formatPlannedTourDuration(walkingMinutes) },
{ label: t('tours.walk.stays'), value: walkStaysText(stays, t) },
...(staysText ? [{ label: t('tours.walk.stays'), value: staysText }] : []),
];
const planned = t('tours.planner.plannedShort');
if (manualMinutes == null) return [...parts, { label: planned, value: computed }];