mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 00:20:07 +00:00
feat(tours): route paddle tours on the water, shaping points and auto-loaded regions
Paddle tours are planned on the water by TREK's own router: a water network per paddle region, built from the same Geofabrik extract as the obstacles and searched in a worker thread of the server (no sidecar). Rivers, canals and lakes (direct or along the shore), portages round weirs, locks by policy, whitewater by boat, gaps marked. Found portages and locks become points of their own; an unplannable leg says why and offers a way out. - Shaping points: a click on the line sets a point that steers the route without being a stop (hikes and paddle tours); recompute a single leg. - Lake style direct/shore, suggested from the wind forecast. - Regions load by themselves where a paddler plans (admin setting: automatic, on request, off; size cap and a daily count), with requests for the admins, a notification, and the load followed on the leg. - Portage from the last point, portages follow footways via the walking router (or stay straight), "put in here" on slipways and put-ins. - MCP plan_paddle_route with the REST route's rules.
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
import type { PaddleLakeStyle } from '@trek/shared';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { LABEL, Segmented } from '../../shared/dialogParts';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
|
||||
const STYLES: readonly PaddleLakeStyle[] = ['direct', 'shore'];
|
||||
|
||||
/**
|
||||
* PAD-11: how the route crosses a lake. Straight over is the rule; along the
|
||||
* shore is for wind, when a capsize near the bank is a short swim. The wind
|
||||
* card suggests it on a windy day; here it is chosen.
|
||||
*/
|
||||
export function PaddleLakeStyleField({
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
value: PaddleLakeStyle;
|
||||
onChange: (style: PaddleLakeStyle) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div data-testid="tour-planner-lake-style" className="min-w-0">
|
||||
<span className={LABEL}>{t('tours.paddle.lakeStyle')}</span>
|
||||
<Segmented<PaddleLakeStyle>
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
label={t('tours.paddle.lakeStyle')}
|
||||
fill
|
||||
options={STYLES.map((style) => ({ value: style, label: t(`tours.paddle.lakeStyle.${style}`) }))}
|
||||
/>
|
||||
<span className="mt-1 block text-content-faint" style={fs(11, 'body')}>
|
||||
{t(`tours.paddle.lakeStyle.${value}Hint`)}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -33,6 +33,8 @@ const PAINT: PaddlePaint = {
|
||||
access: '#4338ca',
|
||||
landing: '#0f766e',
|
||||
portage: '#9a6233',
|
||||
rapids: '#d97706',
|
||||
gap: '#dc2626',
|
||||
disc: '#ffffff',
|
||||
shadow: 'rgba(15, 23, 42, 0.35)',
|
||||
};
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
import type { PaddleRouteLeg } from '@trek/shared';
|
||||
import { AlertTriangle, RotateCcw, Sparkles, Spline, Waves } from 'lucide-react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import type { PaddleLegAnswer } from '../../../repo/paddleRouteRepo';
|
||||
import { useSettingsStore } from '../../../store/settingsStore';
|
||||
import { formatDistance } from '../../../utils/units';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import { Tooltip } from '../../shared/Tooltip';
|
||||
import type { PaddleLegFailure } from '../planner/paddleRouting';
|
||||
import { lineLengthM } from '../planner/tourFixedLegs';
|
||||
|
||||
/**
|
||||
* PAD-11: what the waypoint list says about a leg the router planned or
|
||||
* could not plan, and about a point it set itself.
|
||||
*/
|
||||
|
||||
/** A point the route planner set at a portage or a lock it found; touched by the paddler, it becomes theirs. */
|
||||
export function AutoPointPill() {
|
||||
const { t } = useTranslation();
|
||||
// Only an icon: the row keeps its room for the place name, the tooltip says the rest.
|
||||
return (
|
||||
<Tooltip label={`${t('tours.paddle.auto')}: ${t('tours.paddle.autoHint')}`}>
|
||||
<span
|
||||
data-testid="tour-planner-auto-point"
|
||||
aria-label={t('tours.paddle.auto')}
|
||||
className="grid h-[18px] w-[18px] flex-none place-items-center rounded-full bg-surface-secondary text-content-muted"
|
||||
>
|
||||
<Sparkles size={10} strokeWidth={2.2} aria-hidden="true" />
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
type Note = { key: string; label: string; tone: 'rapids' | 'gap'; length: number };
|
||||
|
||||
/** The stretches of a routed leg worth a look: whitewater, a boat pass, a gap in the data. */
|
||||
function notesOf(
|
||||
leg: Extract<PaddleRouteLeg, { status: 'ok' }>,
|
||||
t: (key: string, params?: Record<string, string | number>) => string
|
||||
): Note[] {
|
||||
return leg.segments.flatMap((segment, index): Note[] => {
|
||||
const length = lineLengthM(leg.geometry.slice(segment.from, segment.to + 1) as [number, number][]);
|
||||
if (segment.kind === 'rapids' && segment.grade != null) {
|
||||
return [
|
||||
{ key: `r${index}`, label: t('tours.paddle.note.rapids', { grade: segment.grade }), tone: 'rapids', length },
|
||||
];
|
||||
}
|
||||
if (segment.kind === 'pass')
|
||||
return [{ key: `p${index}`, label: segment.name ?? t('tours.paddle.note.pass'), tone: 'rapids', length }];
|
||||
if (segment.kind === 'gap') return [{ key: `g${index}`, label: t('tours.paddle.note.gap'), tone: 'gap', length }];
|
||||
return [];
|
||||
});
|
||||
}
|
||||
|
||||
/** Chips under a routed leg for what the paddler should look at on it; nothing when the leg is plain water. */
|
||||
export function PaddleLegNotes({ leg }: { leg: PaddleLegAnswer | null | undefined }) {
|
||||
const { t } = useTranslation();
|
||||
const unit = useSettingsStore((state) => state.settings.distance_unit) ?? 'metric';
|
||||
if (!leg || leg.status !== 'ok') return null;
|
||||
const notes = notesOf(leg, t);
|
||||
if (notes.length === 0) return null;
|
||||
return (
|
||||
<li data-testid="tour-planner-leg-notes" className="flex min-w-0 flex-wrap gap-1 py-0.5 ps-[34px]">
|
||||
{notes.map((note) => (
|
||||
<Tooltip
|
||||
key={note.key}
|
||||
label={t(note.tone === 'gap' ? 'tours.paddle.note.gapHint' : 'tours.paddle.note.rapidsHint')}
|
||||
>
|
||||
<span
|
||||
className={`inline-flex h-[22px] min-w-0 items-center gap-1 rounded-full bg-surface-card pe-1 ps-1.5 font-semibold text-content shadow-sm ring-1 ring-inset ${note.tone === 'gap' ? 'ring-[color:var(--map-paddle-gap)]' : 'ring-[color:var(--map-paddle-rapids)]'}`}
|
||||
style={fs(11)}
|
||||
>
|
||||
{note.tone === 'gap' ? (
|
||||
<AlertTriangle
|
||||
size={11}
|
||||
strokeWidth={2.2}
|
||||
className="flex-none"
|
||||
style={{ color: 'var(--map-paddle-gap)' }}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
) : (
|
||||
<Waves
|
||||
size={11}
|
||||
strokeWidth={2.2}
|
||||
className="flex-none"
|
||||
style={{ color: 'var(--map-paddle-rapids)' }}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
)}
|
||||
<span className="min-w-0 truncate">{note.label}</span>
|
||||
<span
|
||||
className="flex-none rounded-full bg-surface-secondary px-1.5 font-geist font-normal tabular-nums leading-[16px] text-content-secondary"
|
||||
style={fs(10)}
|
||||
>
|
||||
{formatDistance(note.length / 1000, unit)}
|
||||
</span>
|
||||
</span>
|
||||
</Tooltip>
|
||||
))}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A leg the router could not plan: why, in plain words, and what to do about
|
||||
* it. The map draws it straight and red meanwhile, and the tour waits to be
|
||||
* saved until it is planned or drawn by hand on purpose. Where TREK could not
|
||||
* fetch the water data of the leg's region (PAD-11C), `message` says why and
|
||||
* `onLoadRetry` reads the region again.
|
||||
*/
|
||||
export function PaddleLegFailureRow({
|
||||
code,
|
||||
disabled,
|
||||
onDrawStraight,
|
||||
onRetry,
|
||||
message,
|
||||
onLoadRetry,
|
||||
}: {
|
||||
code: PaddleLegFailure;
|
||||
disabled: boolean;
|
||||
onDrawStraight: () => void;
|
||||
onRetry: () => void;
|
||||
message?: string | null;
|
||||
onLoadRetry?: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const retry = onLoadRetry ?? (code !== 'not_on_water' && code !== 'no_region' ? onRetry : null);
|
||||
const action =
|
||||
'inline-flex h-[22px] flex-none items-center gap-1 rounded-full bg-surface-card px-2 font-semibold text-content shadow-sm ring-1 ring-inset ring-edge-faint transition-colors hover:bg-surface-hover disabled:opacity-40';
|
||||
return (
|
||||
<li data-testid="tour-planner-leg-failure" className="flex min-w-0 py-0.5 ps-[34px]">
|
||||
<div role="alert" className="flex w-full min-w-0 flex-col gap-1.5 rounded-[10px] bg-danger-soft px-2 py-1.5">
|
||||
<span className="flex min-w-0 items-center gap-1.5 font-semibold text-danger" style={fs(11.5, 'body')}>
|
||||
<AlertTriangle size={12} strokeWidth={2.2} className="flex-none" aria-hidden="true" />
|
||||
<span className="min-w-0">{message ?? t(`tours.paddle.failed.${code}`)}</span>
|
||||
</span>
|
||||
<span className="flex flex-wrap gap-1">
|
||||
<button type="button" disabled={disabled} onClick={onDrawStraight} className={action} style={fs(10.5)}>
|
||||
<Spline size={11} strokeWidth={2.2} aria-hidden="true" />
|
||||
{t('tours.paddle.drawStraight')}
|
||||
</button>
|
||||
{retry && (
|
||||
<button type="button" disabled={disabled} onClick={retry} className={action} style={fs(10.5)}>
|
||||
<RotateCcw size={11} strokeWidth={2.2} aria-hidden="true" />
|
||||
{t('tours.paddle.retry')}
|
||||
</button>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
// FE-PADDLE-PLACE-001 to 004: a put-in, slipway or egress set as the next waypoint from its card (PAD-05B).
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen } from '../../../../tests/helpers/render';
|
||||
import { PaddleObstaclePlaceButton, placeOf } from './PaddleObstaclePlaceButton';
|
||||
|
||||
describe('placeOf', () => {
|
||||
it('FE-PADDLE-PLACE-001: takes a point as it is, the middle of a way and the middle of an outline', () => {
|
||||
expect(placeOf({ type: 'Point', coordinates: [12.9, 53.2] })).toEqual({ lat: 53.2, lng: 12.9 });
|
||||
expect(
|
||||
placeOf({
|
||||
type: 'LineString',
|
||||
coordinates: [
|
||||
[12.9, 53.2],
|
||||
[12.91, 53.21],
|
||||
[12.92, 53.22],
|
||||
],
|
||||
})
|
||||
).toEqual({ lat: 53.21, lng: 12.91 });
|
||||
const middle = placeOf({
|
||||
type: 'Polygon',
|
||||
coordinates: [
|
||||
[
|
||||
[12, 53],
|
||||
[12.02, 53],
|
||||
[12.02, 53.02],
|
||||
[12, 53.02],
|
||||
[12, 53],
|
||||
],
|
||||
],
|
||||
});
|
||||
expect(middle?.lat).toBeCloseTo(53.01, 9);
|
||||
expect(middle?.lng).toBeCloseTo(12.01, 9);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PaddleObstaclePlaceButton', () => {
|
||||
it('FE-PADDLE-PLACE-002: sets a slipway as a put-in at its spot', () => {
|
||||
const onPlace = vi.fn();
|
||||
render(
|
||||
<PaddleObstaclePlaceButton
|
||||
kind="slipway"
|
||||
geometry={{ type: 'Point', coordinates: [12.9, 53.2] }}
|
||||
onPlace={onPlace}
|
||||
/>
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('paddle-obstacle-place'));
|
||||
expect(onPlace).toHaveBeenCalledWith(53.2, 12.9);
|
||||
expect(screen.getByTestId('paddle-obstacle-place')).toHaveTextContent('Put in here');
|
||||
});
|
||||
|
||||
it('FE-PADDLE-PLACE-003: names an egress as the place to get out', () => {
|
||||
render(
|
||||
<PaddleObstaclePlaceButton
|
||||
kind="egress"
|
||||
geometry={{ type: 'Point', coordinates: [12.9, 53.2] }}
|
||||
onPlace={vi.fn()}
|
||||
/>
|
||||
);
|
||||
expect(screen.getByTestId('paddle-obstacle-place')).toHaveTextContent('Take out here');
|
||||
});
|
||||
|
||||
it('FE-PADDLE-PLACE-004: offers nothing on an obstacle', () => {
|
||||
render(
|
||||
<PaddleObstaclePlaceButton
|
||||
kind="weir"
|
||||
geometry={{ type: 'Point', coordinates: [12.9, 53.2] }}
|
||||
onPlace={vi.fn()}
|
||||
/>
|
||||
);
|
||||
expect(screen.queryByTestId('paddle-obstacle-place')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import type { PaddleGeometry, PaddleObstacleKind } from '@trek/shared';
|
||||
import { MapPinPlus } from 'lucide-react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
|
||||
/** Where a paddler gets in or out: these places can become a waypoint from their card. */
|
||||
const PLACEABLE: Partial<Record<PaddleObstacleKind, 'put_in' | 'egress'>> = {
|
||||
put_in: 'put_in',
|
||||
slipway: 'put_in',
|
||||
egress: 'egress',
|
||||
};
|
||||
|
||||
/**
|
||||
* The spot a waypoint goes to: the place itself, the middle of a way (a
|
||||
* slipway drawn as a ramp), or the middle of an area's outline.
|
||||
*/
|
||||
export function placeOf(geometry: PaddleGeometry): { lat: number; lng: number } | null {
|
||||
const line =
|
||||
geometry.type === 'Point'
|
||||
? [geometry.coordinates]
|
||||
: geometry.type === 'LineString'
|
||||
? geometry.coordinates
|
||||
: geometry.coordinates[0];
|
||||
if (!line?.length) return null;
|
||||
if (geometry.type === 'Polygon') {
|
||||
const ring = line.slice(0, -1);
|
||||
const lng = ring.reduce((sum, [x]) => sum + x, 0) / ring.length;
|
||||
const lat = ring.reduce((sum, [, y]) => sum + y, 0) / ring.length;
|
||||
return { lat, lng };
|
||||
}
|
||||
const [lng, lat] = line[Math.floor((line.length - 1) / 2)] ?? [];
|
||||
return lat === undefined || lng === undefined ? null : { lat, lng };
|
||||
}
|
||||
|
||||
/**
|
||||
* PAD-05B: a put-in, a slipway or an egress taken over as the tour's next
|
||||
* waypoint from its card on the map, so the point sits where the paddler
|
||||
* really gets in or out. Set after a portage asked for at the last point, it
|
||||
* is where the portage ends.
|
||||
*/
|
||||
export function PaddleObstaclePlaceButton({
|
||||
kind,
|
||||
geometry,
|
||||
onPlace,
|
||||
}: {
|
||||
kind: PaddleObstacleKind;
|
||||
geometry: PaddleGeometry;
|
||||
onPlace: (lat: number, lng: number) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const role = PLACEABLE[kind];
|
||||
const spot = role ? placeOf(geometry) : null;
|
||||
if (!role || !spot) return null;
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
data-testid="paddle-obstacle-place"
|
||||
onClick={() => onPlace(spot.lat, spot.lng)}
|
||||
className="mt-2 inline-flex h-8 w-full items-center justify-center gap-1.5 rounded-[10px] bg-accent px-3 font-semibold text-accent-text transition-opacity hover:opacity-90"
|
||||
style={fs(12, 'body')}
|
||||
>
|
||||
<MapPinPlus size={14} strokeWidth={2.2} aria-hidden="true" />
|
||||
{t(role === 'put_in' ? 'tours.paddle.placeHere.putIn' : 'tours.paddle.placeHere.egress')}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// FE-PADDLE-REGION-LOAD-ROW-001 to 004: what a leg waiting for its water data shows (PAD-11C).
|
||||
import type { PaddleRegionLoadState } from '@trek/shared';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen } from '../../../../tests/helpers/render';
|
||||
import { isRegionLoadPending, PaddleRegionLoadRow, regionLoadFailure } from './PaddleRegionLoadRow';
|
||||
|
||||
const REF = { id: 'oberpfalz', name: 'Oberpfalz' };
|
||||
const t = (key: string, params?: Record<string, unknown>) => `${key}${params ? JSON.stringify(params) : ''}`;
|
||||
|
||||
describe('PaddleRegionLoadRow', () => {
|
||||
it('FE-PADDLE-REGION-LOAD-ROW-001: says the data loads, how far, and that the leg follows on its own', () => {
|
||||
const onDrawStraight = vi.fn();
|
||||
render(
|
||||
<PaddleRegionLoadRow
|
||||
state={{ state: 'loading', region: REF, progress: { phase: 'download', fraction: 0.45 }, ahead: 0 }}
|
||||
disabled={false}
|
||||
onDrawStraight={onDrawStraight}
|
||||
/>
|
||||
);
|
||||
const row = screen.getByTestId('tour-planner-region-load');
|
||||
expect(row).toHaveTextContent('Loading the water data for Oberpfalz');
|
||||
expect(row).toHaveTextContent('Downloading 45%');
|
||||
fireEvent.click(screen.getByRole('button', { name: /Draw straight/ }));
|
||||
expect(onDrawStraight).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-PADDLE-REGION-LOAD-ROW-002: says a region waits for an admin, and why', () => {
|
||||
render(
|
||||
<PaddleRegionLoadRow
|
||||
state={{ state: 'requested', region: REF, reason: 'too_large' }}
|
||||
disabled={false}
|
||||
onDrawStraight={vi.fn()}
|
||||
/>
|
||||
);
|
||||
const row = screen.getByTestId('tour-planner-region-load');
|
||||
expect(row).toHaveTextContent('has been requested');
|
||||
expect(row).toHaveTextContent('larger than TREK loads by itself');
|
||||
});
|
||||
|
||||
it('FE-PADDLE-REGION-LOAD-ROW-003: shows the queue before the read starts, and no button once the data is there', () => {
|
||||
const { unmount } = render(
|
||||
<PaddleRegionLoadRow
|
||||
state={{ state: 'loading', region: REF, progress: null, ahead: 2 }}
|
||||
disabled={false}
|
||||
onDrawStraight={vi.fn()}
|
||||
/>
|
||||
);
|
||||
expect(screen.getByTestId('tour-planner-region-load')).toHaveTextContent('Waiting for other regions');
|
||||
unmount();
|
||||
render(<PaddleRegionLoadRow state={{ state: 'ready', region: REF }} disabled={false} onDrawStraight={vi.fn()} />);
|
||||
expect(screen.queryByRole('button')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('region load states', () => {
|
||||
it('FE-PADDLE-REGION-LOAD-ROW-004: waits on loading and requests, and names every way the data cannot come', () => {
|
||||
const pending: PaddleRegionLoadState[] = [
|
||||
{ state: 'ready', region: REF },
|
||||
{ state: 'requested', region: REF, reason: 'ask' },
|
||||
];
|
||||
for (const state of pending) expect(isRegionLoadPending(state)).toBe(true);
|
||||
expect(isRegionLoadPending(undefined)).toBe(false);
|
||||
expect(regionLoadFailure({ state: 'declined', region: REF }, t)).toBe(
|
||||
'tours.paddle.load.declined{"region":"Oberpfalz"}'
|
||||
);
|
||||
expect(regionLoadFailure({ state: 'failed', region: REF }, t)).toContain('tours.paddle.load.failed');
|
||||
expect(regionLoadFailure({ state: 'no_water', region: REF }, t)).toContain('tours.paddle.load.noWater');
|
||||
expect(regionLoadFailure({ state: 'unavailable', region: null, reason: 'no_extract' }, t)).toBe(
|
||||
'tours.paddle.load.noExtract'
|
||||
);
|
||||
expect(regionLoadFailure({ state: 'unavailable', region: null, reason: 'catalog_unavailable' }, t)).toBe(
|
||||
'tours.paddle.load.catalogUnavailable'
|
||||
);
|
||||
expect(regionLoadFailure({ state: 'unavailable', region: REF, reason: 'off' }, t)).toBeNull();
|
||||
expect(regionLoadFailure(undefined, t)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,130 @@
|
||||
import type { PaddleRegionLoadState } from '@trek/shared';
|
||||
import { CloudDownload, Hourglass, Loader2, Spline } from 'lucide-react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
|
||||
type Translate = ReturnType<typeof useTranslation>['t'];
|
||||
|
||||
/** The states in which the data is on its way: the leg waits rather than fails. */
|
||||
export function isRegionLoadPending(
|
||||
state: PaddleRegionLoadState | undefined
|
||||
): state is Extract<PaddleRegionLoadState, { state: 'loading' | 'ready' | 'requested' }> {
|
||||
return state?.state === 'loading' || state?.state === 'ready' || state?.state === 'requested';
|
||||
}
|
||||
|
||||
/**
|
||||
* Why a leg stays unplanned once the data cannot come: declined, failed, no
|
||||
* water near the place, nothing to load. Null where the leg's own reason says
|
||||
* it best (loading is off, or nothing was asked yet).
|
||||
*/
|
||||
export function regionLoadFailure(state: PaddleRegionLoadState | undefined, t: Translate): string | null {
|
||||
if (!state) return null;
|
||||
const region = state.region?.name ?? '';
|
||||
switch (state.state) {
|
||||
case 'declined':
|
||||
return t('tours.paddle.load.declined', { region });
|
||||
case 'failed':
|
||||
return t('tours.paddle.load.failed', { region });
|
||||
case 'no_water':
|
||||
return t('tours.paddle.load.noWater', { region });
|
||||
case 'unavailable':
|
||||
if (state.reason === 'no_extract') return t('tours.paddle.load.noExtract');
|
||||
if (state.reason === 'catalog_unavailable') return t('tours.paddle.load.catalogUnavailable');
|
||||
return null;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function headline(state: Extract<PaddleRegionLoadState, { state: 'loading' | 'ready' | 'requested' }>, t: Translate) {
|
||||
const region = state.region.name;
|
||||
if (state.state === 'ready') return t('tours.paddle.load.ready', { region });
|
||||
if (state.state === 'requested') return t('tours.paddle.load.requested', { region });
|
||||
return t('tours.paddle.load.loading', { region });
|
||||
}
|
||||
|
||||
/** The phase of a load in words, with its share where it is known. */
|
||||
function phaseText(state: Extract<PaddleRegionLoadState, { state: 'loading' }>, t: Translate, language: string) {
|
||||
if (!state.progress) return state.ahead > 0 ? t('tours.paddle.load.waiting') : t('tours.paddle.load.phase.download');
|
||||
const phase = t(`tours.paddle.load.phase.${state.progress.phase}`);
|
||||
const share = state.progress.fraction;
|
||||
return share === null ? phase : `${phase} ${new Intl.NumberFormat(language, { style: 'percent' }).format(share)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* PAD-11C: a leg waiting for the water data of its region, which TREK loads
|
||||
* by itself or an admin has to let through. Calm, not red: nothing is wrong,
|
||||
* the data is on its way, and the leg is planned on its own once it is there.
|
||||
* Drawing it straight stays possible for whoever does not want to wait.
|
||||
*/
|
||||
export function PaddleRegionLoadRow({
|
||||
state,
|
||||
disabled,
|
||||
onDrawStraight,
|
||||
}: {
|
||||
state: Extract<PaddleRegionLoadState, { state: 'loading' | 'ready' | 'requested' }>;
|
||||
disabled: boolean;
|
||||
onDrawStraight: () => void;
|
||||
}) {
|
||||
const { t, language } = useTranslation();
|
||||
const fraction = state.state === 'loading' ? (state.progress?.fraction ?? null) : state.state === 'ready' ? 1 : null;
|
||||
const busy = state.state !== 'requested';
|
||||
return (
|
||||
<li data-testid="tour-planner-region-load" className="flex min-w-0 py-0.5 ps-[34px]">
|
||||
<div
|
||||
role="status"
|
||||
className="flex w-full min-w-0 flex-col gap-1.5 rounded-[10px] bg-surface-secondary px-2 py-1.5 ring-1 ring-inset ring-edge-faint"
|
||||
>
|
||||
<span className="flex min-w-0 items-start gap-1.5 font-semibold text-content" style={fs(11.5, 'body')}>
|
||||
{busy ? (
|
||||
<Loader2 size={12} strokeWidth={2.2} className="mt-[2px] flex-none animate-spin" aria-hidden="true" />
|
||||
) : (
|
||||
<Hourglass size={12} strokeWidth={2.2} className="mt-[2px] flex-none" aria-hidden="true" />
|
||||
)}
|
||||
<span className="min-w-0">{headline(state, t)}</span>
|
||||
</span>
|
||||
{state.state === 'loading' && (
|
||||
<span className="flex min-w-0 flex-col gap-1">
|
||||
<span className="flex items-center justify-between gap-2 text-content-muted" style={fs(10.5, 'body')}>
|
||||
<span className="inline-flex min-w-0 items-center gap-1">
|
||||
<CloudDownload size={11} strokeWidth={2.2} className="flex-none" aria-hidden="true" />
|
||||
<span className="truncate">{phaseText(state, t, language)}</span>
|
||||
</span>
|
||||
</span>
|
||||
<span
|
||||
className="relative block h-[3px] w-full overflow-hidden rounded-full bg-surface-tertiary"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<span
|
||||
className={`absolute inset-y-0 start-0 rounded-full bg-accent transition-[width] duration-500 ${fraction === null ? 'w-1/3 animate-pulse' : ''}`}
|
||||
style={fraction === null ? undefined : { width: `${Math.max(4, Math.round(fraction * 100))}%` }}
|
||||
/>
|
||||
</span>
|
||||
<span className="leading-snug text-content-faint" style={fs(10.5, 'body')}>
|
||||
{t('tours.paddle.load.hint')}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
{state.state === 'requested' && state.reason !== 'ask' && (
|
||||
<span className="leading-snug text-content-muted" style={fs(10.5, 'body')}>
|
||||
{t(state.reason === 'too_large' ? 'tours.paddle.load.reason.tooLarge' : 'tours.paddle.load.reason.limit')}
|
||||
</span>
|
||||
)}
|
||||
{state.state !== 'ready' && (
|
||||
<span className="flex flex-wrap gap-1">
|
||||
<button
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
onClick={onDrawStraight}
|
||||
className="inline-flex h-[22px] flex-none items-center gap-1 rounded-full bg-surface-card px-2 font-semibold text-content shadow-sm ring-1 ring-inset ring-edge-faint transition-colors hover:bg-surface-hover disabled:opacity-40"
|
||||
style={fs(10.5)}
|
||||
>
|
||||
<Spline size={11} strokeWidth={2.2} aria-hidden="true" />
|
||||
{t('tours.paddle.drawStraight')}
|
||||
</button>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -7,8 +7,9 @@ import { resetAllStores, seedStore } from '../../../../tests/helpers/store';
|
||||
import { hikePlannerDefaults } from '../../../../tests/helpers/tourPlannerStub';
|
||||
import { useSettingsStore } from '../../../store/settingsStore';
|
||||
import { paddleEstimateOf, paddlePlanPoints } from '../planner/paddlePlanOf';
|
||||
import type { TourPlannerWaypoint } from '../planner/tourPlannerWaypoints';
|
||||
import { portageLegBetween } from '../planner/tourRouteActions';
|
||||
import type { TourPlannerController, TourPlannerWaypoint } from '../planner/useTourPlanner';
|
||||
import type { TourPlannerController } from '../planner/useTourPlanner';
|
||||
import { PaddleEstimateBody, PaddleTimeCard, type SpeedControl } from './PaddleTimeCard';
|
||||
|
||||
/** What the card writes for a time it cannot give: an en dash. */
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
// FE-PADDLE-WAYPOINT-PARTS-001 to 004: the pending portage at the last point and a portage's way on land (PAD-03).
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen } from '../../../../tests/helpers/render';
|
||||
import { PendingPortageRow, PortageLegRow, type PortageWay } from './PaddleWaypointParts';
|
||||
|
||||
const way = (extra: Partial<PortageWay> = {}): PortageWay => ({
|
||||
routed: false,
|
||||
noWay: false,
|
||||
searching: false,
|
||||
onFollow: vi.fn(),
|
||||
onStraighten: vi.fn(),
|
||||
...extra,
|
||||
});
|
||||
|
||||
function openPortage(props: Partial<Parameters<typeof PortageLegRow>[0]> = {}) {
|
||||
render(<PortageLegRow lengthM={320} extraMinutes={null} disabled={false} onExtraChange={vi.fn()} {...props} />);
|
||||
fireEvent.click(screen.getByRole('button', { expanded: false }));
|
||||
}
|
||||
|
||||
describe('PendingPortageRow', () => {
|
||||
it('FE-PADDLE-WAYPOINT-PARTS-001: says to set the point where the boat goes in again, and takes the ask back', () => {
|
||||
const onRemove = vi.fn();
|
||||
render(<PendingPortageRow disabled={false} onRemove={onRemove} />);
|
||||
expect(screen.getByTestId('tour-planner-portage-pending')).toHaveTextContent('Portage from here');
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Do not carry after all' }));
|
||||
expect(onRemove).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-PADDLE-WAYPOINT-PARTS-002: offers no way back on a tour that cannot be edited', () => {
|
||||
render(<PendingPortageRow disabled onRemove={vi.fn()} />);
|
||||
expect(screen.queryByRole('button', { name: 'Do not carry after all' })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('PortageLegRow way', () => {
|
||||
it('FE-PADDLE-WAYPOINT-PARTS-003: switches between following the path and a straight line', () => {
|
||||
const straight = way();
|
||||
openPortage({ way: straight });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Follow the path' }));
|
||||
expect(straight.onFollow).toHaveBeenCalledTimes(1);
|
||||
const routed = way({ routed: true });
|
||||
openPortage({ way: routed });
|
||||
fireEvent.click(screen.getAllByRole('button', { name: 'Straight line' })[1]);
|
||||
expect(routed.onStraighten).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-PADDLE-WAYPOINT-PARTS-004: says why a carry stayed straight, and that the router is asked', () => {
|
||||
openPortage({ way: way({ noWay: true }) });
|
||||
expect(screen.getByTestId('tour-planner-portage-way')).toHaveTextContent('No path without a long detour');
|
||||
openPortage({ way: way({ searching: true }) });
|
||||
expect(screen.getAllByTestId('tour-planner-portage-way')[1]).toHaveTextContent('Looking for a path');
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,10 @@
|
||||
import { DEFAULT_PORTAGE_EXTRA_MINUTES, MAX_PADDLE_STOP_MINUTES, type PaddleLock, type PaddleRole } from '@trek/shared';
|
||||
import { ChevronDown, X } from 'lucide-react';
|
||||
import { ChevronDown, Loader2, X } from 'lucide-react';
|
||||
import { useCallback, useState, type ReactNode } from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { useSettingsStore } from '../../../store/settingsStore';
|
||||
import { formatDistance } from '../../../utils/units';
|
||||
import { Segmented } from '../../shared/dialogParts';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import { PaddleGlyph } from './PaddleGlyph';
|
||||
import { PORTAGE_CSS_COLOR } from './paddlePaint';
|
||||
@@ -199,6 +200,99 @@ function StopCard({
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A portage asked for at the last point, before the point it leads to is set:
|
||||
* dashed in the portage brown, it says where to click next, and can be taken
|
||||
* back. Once the next point is set it becomes a portage like any other.
|
||||
*/
|
||||
export function PendingPortageRow({ disabled, onRemove }: { disabled: boolean; onRemove: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<li data-testid="tour-planner-portage-pending" className="flex min-w-0 py-0.5 ps-[34px]">
|
||||
<div
|
||||
className="flex w-full min-w-0 items-start gap-1.5 rounded-[14px] border border-dashed bg-surface-card py-1 pe-1 ps-1"
|
||||
style={{ borderColor: PORTAGE_CSS_COLOR }}
|
||||
>
|
||||
<span
|
||||
className="grid h-[20px] w-[20px] flex-none place-items-center rounded-full text-surface-card"
|
||||
style={{ background: PORTAGE_CSS_COLOR }}
|
||||
>
|
||||
<PaddleGlyph kind="portage" size={12} strokeWidth={2.4} />
|
||||
</span>
|
||||
<span className="flex min-w-0 flex-1 flex-col py-[2px]">
|
||||
<span className="truncate font-semibold text-content" style={fs(11.5, 'body')}>
|
||||
{t('tours.paddle.portagePending')}
|
||||
</span>
|
||||
<span className="leading-snug text-content-muted" style={fs(11, 'body')}>
|
||||
{t('tours.paddle.portagePendingHint')}
|
||||
</span>
|
||||
</span>
|
||||
{!disabled && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onRemove}
|
||||
aria-label={t('tours.paddle.portagePendingOff')}
|
||||
title={t('tours.paddle.portagePendingOff')}
|
||||
className="grid h-[20px] w-[20px] flex-none place-items-center rounded-full text-content-faint transition-colors hover:bg-surface-hover hover:text-content"
|
||||
>
|
||||
<X size={12} strokeWidth={2.4} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
export interface PortageWay {
|
||||
/** The portage follows the ways on land (its line has a shape of its own). */
|
||||
routed: boolean;
|
||||
/** The router was asked and found no way without a big detour. */
|
||||
noWay: boolean;
|
||||
/** The router is being asked right now. */
|
||||
searching: boolean;
|
||||
onFollow: () => void;
|
||||
onStraighten: () => void;
|
||||
}
|
||||
|
||||
/** Whether a portage follows the ways on land or goes straight, and why it stayed straight. */
|
||||
function PortageWayField({ way, disabled }: { way: PortageWay; disabled: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const value = way.routed ? 'follow' : 'straight';
|
||||
const hint = way.searching
|
||||
? t('tours.paddle.portageWay.searching')
|
||||
: !way.routed && way.noWay
|
||||
? t('tours.paddle.portageWay.noWay')
|
||||
: null;
|
||||
return (
|
||||
<div className="flex min-w-0 flex-col gap-1" data-testid="tour-planner-portage-way">
|
||||
<span className="block truncate text-content" style={fs(12, 'body')}>
|
||||
{t('tours.paddle.portageWay')}
|
||||
</span>
|
||||
<fieldset disabled={disabled || way.searching} className="m-0 min-w-0 border-0 p-0">
|
||||
<Segmented<'follow' | 'straight'>
|
||||
value={value}
|
||||
fill
|
||||
label={t('tours.paddle.portageWay')}
|
||||
onChange={(next) => (next === 'follow' ? way.onFollow() : way.onStraighten())}
|
||||
options={[
|
||||
{
|
||||
value: 'follow',
|
||||
label: t('tours.paddle.portageWay.follow'),
|
||||
icon: way.searching ? <Loader2 size={12} className="animate-spin" aria-hidden="true" /> : undefined,
|
||||
},
|
||||
{ value: 'straight', label: t('tours.paddle.portageWay.straight') },
|
||||
]}
|
||||
/>
|
||||
</fieldset>
|
||||
{hint && (
|
||||
<span className="leading-snug text-content-faint" style={fs(10.5, 'body')}>
|
||||
{hint}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A portage under the point it starts at, in the earth brown the map draws it
|
||||
* in: its length on land and the time for getting out, unloading and back in
|
||||
@@ -211,6 +305,7 @@ export function PortageLegRow({
|
||||
onExtraChange,
|
||||
position,
|
||||
onRemove,
|
||||
way,
|
||||
}: {
|
||||
lengthM: number;
|
||||
extraMinutes: number | null;
|
||||
@@ -220,6 +315,8 @@ export function PortageLegRow({
|
||||
position?: string;
|
||||
/** Takes the portage off a recorded track; a planned tour carries it on its leg instead. */
|
||||
onRemove?: () => void;
|
||||
/** On a planned tour: whether the portage follows the ways on land or goes straight, and the switch between them. */
|
||||
way?: PortageWay;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const unit = useSettingsStore((state) => state.settings.distance_unit);
|
||||
@@ -242,6 +339,7 @@ export function PortageLegRow({
|
||||
{t('tours.paddle.portageInfo')}
|
||||
</p>
|
||||
{onRemove && !disabled && <RemoveStop label={t('tours.paddle.portageRemove')} onRemove={onRemove} />}
|
||||
{way && <PortageWayField way={way} disabled={disabled} />}
|
||||
<StopField
|
||||
label={t('tours.paddle.portageExtra')}
|
||||
hint={extraMinutes === null ? t('tours.paddle.startValue') : undefined}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// FE-PADDLE-WIND-001 to FE-PADDLE-WIND-016: the wind card of a paddle tour (PAD-08) and the section that feeds it.
|
||||
// FE-PADDLE-WIND-001 to FE-PADDLE-WIND-018: the wind card of a paddle tour (PAD-08) and the section that feeds it.
|
||||
// FE-PADDLE-FIGURE-001 to FE-PADDLE-FIGURE-002: the figure badge the card shows its values in.
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
@@ -340,6 +340,30 @@ describe('PaddleWindSection', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('PaddleWindCard on the lakes (PAD-11)', () => {
|
||||
it('FE-PADDLE-WIND-017: on a windy day offers to keep near the shore, and says so once the shore is chosen', () => {
|
||||
const onChoose = vi.fn();
|
||||
const windy = windOf(ready(forecastOf({ hours: [hourOf(12, 22, 34, 270)] })));
|
||||
const { rerender } = render(<PaddleWindCard wind={windy} lakes={{ value: 'direct', onChoose }} />);
|
||||
const advice = screen.getByTestId('paddle-wind-shore-advice');
|
||||
expect(advice).toHaveTextContent('Up to 22 km/h, gusts 34 km/h on this day.');
|
||||
fireEvent.click(within(advice).getByRole('button', { name: 'Plan near the shore' }));
|
||||
expect(onChoose).toHaveBeenCalledWith('shore');
|
||||
|
||||
rerender(<PaddleWindCard wind={windy} lakes={{ value: 'shore', onChoose }} />);
|
||||
expect(screen.queryByTestId('paddle-wind-shore-advice')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('The lakes are planned near the shore.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-PADDLE-WIND-018: says nothing of the shore on a calm day, nor where no lake is crossed', () => {
|
||||
const calm = windOf(ready(forecastOf({ hours: [hourOf(12, 8, 14, 270)] })));
|
||||
const { rerender } = render(<PaddleWindCard wind={calm} lakes={{ value: 'direct', onChoose: vi.fn() }} />);
|
||||
expect(screen.queryByTestId('paddle-wind-shore-advice')).not.toBeInTheDocument();
|
||||
rerender(<PaddleWindCard wind={windOf(ready(forecastOf({ hours: [hourOf(12, 30, 50, 270)] })))} />);
|
||||
expect(screen.queryByTestId('paddle-wind-shore-advice')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('FigureBadge', () => {
|
||||
it('FE-PADDLE-FIGURE-001: holds a label and a value; the warning tone colours the value alone', () => {
|
||||
const { rerender } = render(<FigureBadge testId="figure" label="Height" value="1.2 m" tone="warning" />);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { compassPointOf, type WindForecastResponse, type WindHour } from '@trek/shared';
|
||||
import { compassPointOf, type PaddleLakeStyle, type WindForecastResponse, type WindHour } from '@trek/shared';
|
||||
import { ChevronDown, RefreshCw, WifiOff, Wind } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
@@ -8,6 +8,7 @@ import { fs } from '../../shared/DialogShell';
|
||||
import { Tooltip } from '../../shared/Tooltip';
|
||||
import { RailCard, TourNotice } from '../tourParts';
|
||||
import { FigureBadge } from './FigureBadge';
|
||||
import { windForShore } from './lakeStyleAdvice';
|
||||
import { useTourWind, type TourWind } from './useTourWind';
|
||||
|
||||
type Translate = (key: string, params?: Record<string, unknown>) => string;
|
||||
@@ -209,15 +210,58 @@ function WindHints({ t }: { t: Translate }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** The lake style of the tour being edited, for the wind card to suggest the shore on a windy day. */
|
||||
export interface LakeStyleChoice {
|
||||
value: PaddleLakeStyle;
|
||||
onChoose: (style: PaddleLakeStyle) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* PAD-11: on a windy day, the offer to keep near the shores on the lakes,
|
||||
* with the wind that prompts it; once taken, it says the lakes are planned so.
|
||||
*/
|
||||
function ShoreAdvice({
|
||||
wind,
|
||||
lakes,
|
||||
t,
|
||||
}: {
|
||||
wind: { meanKmh: number; gustsKmh: number };
|
||||
lakes: LakeStyleChoice;
|
||||
t: Translate;
|
||||
}) {
|
||||
if (lakes.value === 'shore') {
|
||||
return (
|
||||
<TourNotice role="status" icon={<Wind size={13} strokeWidth={2} />}>
|
||||
{t('tours.paddle.wind.shoreTaken')}
|
||||
</TourNotice>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<TourNotice tone="warning" icon={<Wind size={13} strokeWidth={2} />}>
|
||||
<span data-testid="paddle-wind-shore-advice" className="flex flex-wrap items-center gap-x-2 gap-y-1">
|
||||
{t('tours.paddle.wind.shoreAdvice', { mean: wind.meanKmh, gusts: wind.gustsKmh })}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => lakes.onChoose('shore')}
|
||||
className="font-semibold underline-offset-2 hover:underline"
|
||||
>
|
||||
{t('tours.paddle.wind.shoreAdopt')}
|
||||
</button>
|
||||
</span>
|
||||
</TourNotice>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* PAD-08: the wind on the day a paddle tour is planned for, at its start. The
|
||||
* mean, the gusts and the direction are figures of their own, with the source
|
||||
* and when it was asked; no value is turned into a verdict, and missing data
|
||||
* is never shown as calm.
|
||||
*/
|
||||
export function PaddleWindCard({ wind }: { wind: TourWind }) {
|
||||
export function PaddleWindCard({ wind, lakes }: { wind: TourWind; lakes?: LakeStyleChoice }) {
|
||||
const { t, locale } = useTranslation();
|
||||
const ready = wind.state.kind === 'ready' && wind.state.forecast.status === 'forecast' ? wind.state.forecast : null;
|
||||
const shoreWind = ready && lakes ? windForShore(ready) : null;
|
||||
return (
|
||||
<RailCard
|
||||
icon={<Wind size={14} strokeWidth={2} />}
|
||||
@@ -249,6 +293,7 @@ export function PaddleWindCard({ wind }: { wind: TourWind }) {
|
||||
) : (
|
||||
<Unavailable wind={wind} t={t} locale={locale} />
|
||||
)}
|
||||
{shoreWind && lakes && <ShoreAdvice wind={shoreWind} lakes={lakes} t={t} />}
|
||||
<WindHints t={t} />
|
||||
</div>
|
||||
</RailCard>
|
||||
@@ -259,10 +304,13 @@ export function PaddleWindCard({ wind }: { wind: TourWind }) {
|
||||
export function PaddleWindSection({
|
||||
placeId,
|
||||
start,
|
||||
lakes,
|
||||
}: {
|
||||
placeId: number | null;
|
||||
start: { lat: number; lng: number } | null;
|
||||
/** Given while the tour is edited and its route crosses a lake: the card may suggest the shore. */
|
||||
lakes?: LakeStyleChoice;
|
||||
}) {
|
||||
const wind = useTourWind(placeId, start);
|
||||
return <PaddleWindCard wind={wind} />;
|
||||
return <PaddleWindCard wind={wind} lakes={lakes} />;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
// FE-PADDLE-LAKE-ADVICE-001 to FE-PADDLE-LAKE-ADVICE-002: when the wind makes the shore worth suggesting (PAD-11 with PAD-08).
|
||||
import type { WindForecastResponse, WindHour } from '@trek/shared';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { crossesLake, windForShore } from './lakeStyleAdvice';
|
||||
|
||||
function forecast(hours: Array<Partial<WindHour> & { hour: number }>): WindForecastResponse {
|
||||
return {
|
||||
status: 'forecast',
|
||||
date: '2026-06-01',
|
||||
lat: 53.4,
|
||||
lng: 12.7,
|
||||
timezone: 'Europe/Berlin',
|
||||
source: 'Open-Meteo',
|
||||
fetched_at: '2026-05-30T08:00:00Z',
|
||||
horizon_days: 16,
|
||||
day: null,
|
||||
hours: hours.map((hour) => ({ speed_kmh: null, gusts_kmh: null, direction_deg: null, ...hour })),
|
||||
} as WindForecastResponse;
|
||||
}
|
||||
|
||||
describe('lakeStyleAdvice', () => {
|
||||
it('FE-PADDLE-LAKE-ADVICE-001: a fresh breeze or strong gusts in the paddling hours suggest the shore; a stormy night does not', () => {
|
||||
expect(windForShore(forecast([{ hour: 10, speed_kmh: 12, gusts_kmh: 22 }]))).toBeNull();
|
||||
expect(windForShore(forecast([{ hour: 14, speed_kmh: 21.4, gusts_kmh: 26 }]))).toEqual({
|
||||
meanKmh: 21,
|
||||
gustsKmh: 26,
|
||||
});
|
||||
expect(windForShore(forecast([{ hour: 14, speed_kmh: 15, gusts_kmh: 31 }]))).toEqual({ meanKmh: 15, gustsKmh: 31 });
|
||||
expect(windForShore(forecast([{ hour: 3, speed_kmh: 40, gusts_kmh: 70 }]))).toBeNull();
|
||||
// An hour without a value is no calm hour, but it is no wind either.
|
||||
expect(windForShore(forecast([{ hour: 12 }]))).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PADDLE-LAKE-ADVICE-002: only a route that crosses a lake makes the lake style matter', () => {
|
||||
const lake = { kind: 'lake' as const, from: 0, to: 1, name: null, source: null, osm_ref: null, grade: null };
|
||||
const leg = (kind: 'lake' | 'water') => ({
|
||||
status: 'ok' as const,
|
||||
geometry: [
|
||||
[53.4, 12.7],
|
||||
[53.5, 12.7],
|
||||
] as [number, number][],
|
||||
segments: [{ ...lake, kind }],
|
||||
distance_m: 1000,
|
||||
snapped_m: { from: 0, to: 0 },
|
||||
});
|
||||
expect(crossesLake(null)).toBe(false);
|
||||
expect(crossesLake({ legs: [leg('water'), null] })).toBe(false);
|
||||
expect(crossesLake({ legs: [leg('water'), leg('lake')] })).toBe(true);
|
||||
expect(crossesLake({ legs: [{ status: 'failed', code: 'offline', at: null }] })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { WindForecastResponse } from '@trek/shared';
|
||||
import type { PaddleTourRoute } from '../planner/paddleRouting';
|
||||
|
||||
/** The hours a day tour is out on the water, as the wind strip shows them. */
|
||||
const FIRST_HOUR = 6;
|
||||
const LAST_HOUR = 21;
|
||||
|
||||
/**
|
||||
* Wind from which open water gets rough for a small boat: a moderate breeze
|
||||
* (Beaufort 4 from 20 km/h) or gusts of 30 km/h, where a crossing turns into
|
||||
* work and a capsize far from the bank into a long swim.
|
||||
*/
|
||||
const MEAN_KMH = 20;
|
||||
const GUSTS_KMH = 30;
|
||||
|
||||
/** Whether the route as planned crosses a lake, so its lake style changes anything. */
|
||||
export function crossesLake(route: Pick<PaddleTourRoute, 'legs'> | null): boolean {
|
||||
return !!route?.legs.some((leg) => leg?.status === 'ok' && leg.segments.some((segment) => segment.kind === 'lake'));
|
||||
}
|
||||
|
||||
/**
|
||||
* PAD-11 with PAD-08: the strongest wind of the paddling hours when it is
|
||||
* enough to keep near the shores on the lakes, else null. Lakes are crossed
|
||||
* straight over as a rule and along the shore only in wind; this says when.
|
||||
*/
|
||||
export function windForShore(forecast: WindForecastResponse): { meanKmh: number; gustsKmh: number } | null {
|
||||
const hours = forecast.hours.filter((hour) => hour.hour >= FIRST_HOUR && hour.hour <= LAST_HOUR);
|
||||
const meanKmh = Math.max(0, ...hours.map((hour) => hour.speed_kmh ?? 0));
|
||||
const gustsKmh = Math.max(0, ...hours.map((hour) => hour.gusts_kmh ?? 0));
|
||||
if (meanKmh < MEAN_KMH && gustsKmh < GUSTS_KMH) return null;
|
||||
return { meanKmh: Math.round(meanKmh), gustsKmh: Math.round(gustsKmh) };
|
||||
}
|
||||
@@ -34,6 +34,8 @@ const PAINT: PaddlePaint = {
|
||||
access: '#4338ca',
|
||||
landing: '#0f766e',
|
||||
portage: '#9a6233',
|
||||
rapids: '#d97706',
|
||||
gap: '#dc2626',
|
||||
disc: '#ffffff',
|
||||
shadow: 'rgba(15, 23, 42, 0.35)',
|
||||
};
|
||||
|
||||
@@ -12,6 +12,8 @@ const PADDLE_PAINT_TOKENS = {
|
||||
access: '--map-paddle-access',
|
||||
landing: '--map-paddle-landing',
|
||||
portage: '--map-portage',
|
||||
rapids: '--map-paddle-rapids',
|
||||
gap: '--map-paddle-gap',
|
||||
disc: '--map-paddle-disc',
|
||||
shadow: '--map-paddle-shadow',
|
||||
} as const;
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
// FE-PORTAGE-ROUTE-001 to 004: a portage laid on the ways on land, never on a detour (PAD-03).
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const valhallaRun = vi.fn();
|
||||
vi.mock('../../Map/valhallaRoute', () => ({ valhallaRun: (...args: unknown[]) => valhallaRun(...args) }));
|
||||
|
||||
const { routePortageLine } = await import('./portageRoute');
|
||||
|
||||
const FROM = { lat: 53.2232, lng: 12.9668 };
|
||||
const TO = { lat: 53.2229, lng: 12.9701 };
|
||||
|
||||
function answer(coordinates: [number, number][]) {
|
||||
return { legs: [], snapped: [], total: { coordinates, distance: 0, duration: 0 } };
|
||||
}
|
||||
|
||||
describe('routePortageLine', () => {
|
||||
beforeEach(() => valhallaRun.mockReset());
|
||||
|
||||
it('FE-PORTAGE-ROUTE-001: asks the walking router on easy ground and starts and ends at the points themselves', async () => {
|
||||
valhallaRun.mockResolvedValue(
|
||||
answer([
|
||||
[53.2233, 12.9672],
|
||||
[53.2226, 12.9686],
|
||||
[53.223, 12.9698],
|
||||
])
|
||||
);
|
||||
const line = await routePortageLine(FROM, TO);
|
||||
expect(valhallaRun).toHaveBeenCalledWith([FROM, TO], 'walking', [], undefined, { max_hiking_difficulty: 1 });
|
||||
expect(line?.[0]).toEqual([FROM.lat, FROM.lng]);
|
||||
expect(line?.[line.length - 1]).toEqual([TO.lat, TO.lng]);
|
||||
expect(line).toHaveLength(5);
|
||||
});
|
||||
|
||||
it('FE-PORTAGE-ROUTE-002: keeps the carry straight when the way is a long detour', async () => {
|
||||
valhallaRun.mockResolvedValue(
|
||||
answer([
|
||||
[53.2233, 12.9672],
|
||||
[53.24, 12.968],
|
||||
[53.223, 12.9698],
|
||||
])
|
||||
);
|
||||
expect(await routePortageLine(FROM, TO)).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PORTAGE-ROUTE-003: keeps the carry straight when no router answers', async () => {
|
||||
valhallaRun.mockResolvedValue(null);
|
||||
expect(await routePortageLine(FROM, TO)).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PORTAGE-ROUTE-004: takes no line of a single point', async () => {
|
||||
valhallaRun.mockResolvedValue(answer([[53.2233, 12.9672]]));
|
||||
expect(await routePortageLine(FROM, TO)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { haversineKm } from '../../../utils/geo';
|
||||
import { valhallaRun } from '../../Map/valhallaRoute';
|
||||
import { lineLengthM } from '../planner/tourFixedLegs';
|
||||
|
||||
type Point = { lat: number; lng: number };
|
||||
|
||||
/**
|
||||
* How much longer than the straight line a carry along the ways may be before
|
||||
* it counts as a detour: a way round a fenced lock is fine, a walk round the
|
||||
* whole lake is not, and then the straight line says more.
|
||||
*/
|
||||
const DETOUR = { factor: 2.5, extraM: 300 } as const;
|
||||
|
||||
/** Paths a paddler carries a boat on: plain hiking ground, never a scramble. */
|
||||
const CARRY_DIFFICULTY = 1;
|
||||
|
||||
/**
|
||||
* PAD-03: the way a portage takes on land, from where the boat leaves the
|
||||
* water to where it goes in again, on the ways a walker would take (the
|
||||
* instance's Valhalla, the router the hikes use). The line starts and ends at
|
||||
* the two points themselves, so the steps from the bank onto the path are
|
||||
* part of it. Null when no router answers, or when the way is a detour.
|
||||
*/
|
||||
export async function routePortageLine(
|
||||
from: Point,
|
||||
to: Point,
|
||||
signal?: AbortSignal
|
||||
): Promise<[number, number][] | null> {
|
||||
// The router answers null, never throws, when it cannot be reached; the carry then stays straight.
|
||||
const run = await valhallaRun([from, to], 'walking', [], signal, { max_hiking_difficulty: CARRY_DIFFICULTY });
|
||||
if (!run || run.total.coordinates.length < 2) return null;
|
||||
const line: [number, number][] = [[from.lat, from.lng], ...run.total.coordinates, [to.lat, to.lng]];
|
||||
const straightM = haversineKm(from, to) * 1000;
|
||||
if (lineLengthM(line) > Math.max(straightM * DETOUR.factor, straightM + DETOUR.extraM)) return null;
|
||||
return line;
|
||||
}
|
||||
@@ -37,7 +37,8 @@ import {
|
||||
selectPaddleObstacle,
|
||||
usePaddleObstacleStore,
|
||||
} from '../../../store/paddleObstacleStore';
|
||||
import type { TourPlannerController, TourPlannerWaypoint } from '../planner/useTourPlanner';
|
||||
import type { TourPlannerWaypoint } from '../planner/tourPlannerWaypoints';
|
||||
import type { TourPlannerController } from '../planner/useTourPlanner';
|
||||
import { usePaddleChecklist } from './usePaddleChecklist';
|
||||
|
||||
type CheckRead = Awaited<ReturnType<typeof tourRepo.obstacleCheck>>;
|
||||
|
||||
@@ -34,6 +34,8 @@ const PAINT: PaddlePaint = {
|
||||
access: '#4338ca',
|
||||
landing: '#0f766e',
|
||||
portage: '#9a6233',
|
||||
rapids: '#d97706',
|
||||
gap: '#dc2626',
|
||||
disc: '#ffffff',
|
||||
shadow: 'rgba(15, 23, 42, 0.35)',
|
||||
};
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
// FE-PADDLE-REGION-LOAD-001 to 005: the planner fetches the water data of a place no region covers (PAD-11C).
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import type { PaddleRegionLoadState } from '@trek/shared';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const load = vi.fn();
|
||||
vi.mock('../../../repo/paddleRegionLoadRepo', () => ({
|
||||
paddleRegionLoadRepo: { load: (...args: unknown[]) => load(...args) },
|
||||
}));
|
||||
|
||||
const { usePaddleRegionLoad } = await import('./usePaddleRegionLoad');
|
||||
|
||||
const REF = { id: 'oberpfalz', name: 'Oberpfalz' };
|
||||
const AT = { lat: 49.0123456, lng: 12.0987654 };
|
||||
const failures = [
|
||||
{ index: 0, code: 'no_region' as const, at: AT },
|
||||
{ index: 1, code: 'no_region' as const, at: AT },
|
||||
{ index: 2, code: 'no_water_path' as const, at: null },
|
||||
];
|
||||
const loading = (fraction: number): PaddleRegionLoadState => ({
|
||||
state: 'loading',
|
||||
region: REF,
|
||||
progress: { phase: 'download', fraction },
|
||||
ahead: 0,
|
||||
});
|
||||
|
||||
describe('usePaddleRegionLoad', () => {
|
||||
beforeEach(() => load.mockReset());
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it('FE-PADDLE-REGION-LOAD-001: asks once per place, and shows its state on every leg ending there', async () => {
|
||||
load.mockResolvedValue([loading(0.4)]);
|
||||
const { result } = renderHook(() => usePaddleRegionLoad(failures, vi.fn()));
|
||||
await waitFor(() => expect(result.current.byLeg.get(0)).toEqual(loading(0.4)));
|
||||
expect(load).toHaveBeenCalledWith([{ lat: 49.01235, lng: 12.09877 }], false, expect.any(AbortSignal));
|
||||
expect(result.current.byLeg.get(1)).toEqual(loading(0.4));
|
||||
expect(result.current.byLeg.has(2)).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-PADDLE-REGION-LOAD-002: follows a load and plans again once, when the data is there', async () => {
|
||||
vi.useFakeTimers();
|
||||
load.mockResolvedValueOnce([loading(0.2)]).mockResolvedValue([{ state: 'ready', region: REF }]);
|
||||
const onReady = vi.fn();
|
||||
const { rerender } = renderHook(() => usePaddleRegionLoad(failures, onReady));
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
});
|
||||
expect(onReady).not.toHaveBeenCalled();
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(2_000);
|
||||
});
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
expect(onReady).toHaveBeenCalledTimes(1);
|
||||
rerender();
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(5_000);
|
||||
});
|
||||
expect(onReady).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('FE-PADDLE-REGION-LOAD-003: asks for nothing without a leg that lacks the data', async () => {
|
||||
renderHook(() => usePaddleRegionLoad([{ index: 0, code: 'not_on_water', at: AT }], vi.fn()));
|
||||
renderHook(() => usePaddleRegionLoad(null, vi.fn()));
|
||||
await Promise.resolve();
|
||||
expect(load).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-PADDLE-REGION-LOAD-004: reads a failed region again on request', async () => {
|
||||
load.mockResolvedValue([{ state: 'failed', region: REF }]);
|
||||
const { result } = renderHook(() => usePaddleRegionLoad(failures, vi.fn()));
|
||||
await waitFor(() => expect(result.current.byLeg.get(0)?.state).toBe('failed'));
|
||||
act(() => result.current.retry());
|
||||
await waitFor(() => expect(load).toHaveBeenLastCalledWith(expect.any(Array), true, expect.any(AbortSignal)));
|
||||
});
|
||||
|
||||
it('FE-PADDLE-REGION-LOAD-005: keeps asking after a failed look, more slowly', async () => {
|
||||
vi.useFakeTimers();
|
||||
load.mockRejectedValueOnce(new Error('offline')).mockResolvedValue([{ state: 'declined', region: REF }]);
|
||||
const { result } = renderHook(() => usePaddleRegionLoad(failures, vi.fn()));
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(10_000);
|
||||
});
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
expect(result.current.byLeg.get(0)?.state).toBe('declined');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
import { MAX_PADDLE_LOAD_POINTS, type PaddleRegionLoadState, type PaddleRoutePoint } from '@trek/shared';
|
||||
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from 'react';
|
||||
import { paddleRegionLoadRepo } from '../../../repo/paddleRegionLoadRepo';
|
||||
import type { PaddleTourRoute } from '../planner/paddleRouting';
|
||||
|
||||
/** How soon the planner asks again: often while a region loads, now and then while it waits for an admin. */
|
||||
const POLL_MS = { loading: 2_000, requested: 30_000, error: 10_000 } as const;
|
||||
|
||||
type Failure = PaddleTourRoute['failures'][number];
|
||||
|
||||
/** A place as the key it is asked and remembered by; five decimals are about a metre. */
|
||||
function keyOf(point: PaddleRoutePoint): string {
|
||||
return `${point.lat.toFixed(5)},${point.lng.toFixed(5)}`;
|
||||
}
|
||||
|
||||
function placeOf(key: string): PaddleRoutePoint {
|
||||
const [lat, lng] = key.split(',').map(Number);
|
||||
return { lat, lng };
|
||||
}
|
||||
|
||||
/** The places the planner asks about: where its legs ran out of water data, each once. */
|
||||
function placeKeysOf(failures: readonly Failure[] | null | undefined): string {
|
||||
const keys = new Set<string>();
|
||||
for (const failure of failures ?? []) {
|
||||
if (failure.code === 'no_region' && failure.at) keys.add(keyOf(failure.at));
|
||||
}
|
||||
return [...keys].slice(0, MAX_PADDLE_LOAD_POINTS).join('|');
|
||||
}
|
||||
|
||||
function nextPoll(states: readonly PaddleRegionLoadState[]): number | null {
|
||||
if (states.some((state) => state.state === 'loading')) return POLL_MS.loading;
|
||||
if (states.some((state) => state.state === 'requested')) return POLL_MS.requested;
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* PAD-11C: where a paddle leg failed for want of water data, the planner
|
||||
* asks the server for it right away; the server loads the region around the
|
||||
* place or asks an admin for it, as the instance is set up. While it loads
|
||||
* the leg shows how far it is, and once it is there the route is planned
|
||||
* again on its own. `onReady` plans again; it is called once per place.
|
||||
*/
|
||||
export function usePaddleRegionLoad(failures: readonly Failure[] | null | undefined, onReady: () => void) {
|
||||
const placesKey = placeKeysOf(failures);
|
||||
const places = useMemo(() => (placesKey ? placesKey.split('|').map(placeOf) : []), [placesKey]);
|
||||
const [states, setStates] = useState<ReadonlyMap<string, PaddleRegionLoadState>>(new Map());
|
||||
const [retryToken, setRetryToken] = useState(0);
|
||||
const readied = useRef(new Set<string>());
|
||||
const retrying = useRef(false);
|
||||
|
||||
/** The answers taken in; the route is planned again where a place's data has just arrived. */
|
||||
const take = useEffectEvent((answers: readonly PaddleRegionLoadState[]) => {
|
||||
setStates(new Map(places.flatMap((place, index) => (answers[index] ? [[keyOf(place), answers[index]]] : []))));
|
||||
const fresh = places.filter((place, index) => {
|
||||
const key = keyOf(place);
|
||||
if (answers[index]?.state !== 'ready' || readied.current.has(key)) return false;
|
||||
readied.current.add(key);
|
||||
return true;
|
||||
});
|
||||
if (fresh.length > 0) onReady();
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (places.length === 0) return undefined;
|
||||
const abort = new AbortController();
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const ask = async () => {
|
||||
const retry = retrying.current;
|
||||
retrying.current = false;
|
||||
let answers: PaddleRegionLoadState[] | null;
|
||||
try {
|
||||
answers = await paddleRegionLoadRepo.load(places, retry, abort.signal);
|
||||
} catch {
|
||||
// The failure row keeps saying why the leg is unplanned; a later look may get through.
|
||||
if (!abort.signal.aborted) timer = setTimeout(() => void ask(), POLL_MS.error);
|
||||
return;
|
||||
}
|
||||
if (abort.signal.aborted || !answers) return;
|
||||
take(answers);
|
||||
const wait = nextPoll(answers);
|
||||
if (wait !== null) timer = setTimeout(() => void ask(), wait);
|
||||
};
|
||||
void ask();
|
||||
return () => {
|
||||
abort.abort();
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [places, retryToken]);
|
||||
|
||||
/** Reads a region again whose last read failed. */
|
||||
const retry = useCallback(() => {
|
||||
retrying.current = true;
|
||||
setRetryToken((token) => token + 1);
|
||||
}, []);
|
||||
|
||||
/** The state of each failed leg's place, by the leg's index. */
|
||||
const byLeg = useMemo(() => {
|
||||
const result = new Map<number, PaddleRegionLoadState>();
|
||||
for (const failure of failures ?? []) {
|
||||
if (failure.code !== 'no_region' || !failure.at) continue;
|
||||
const state = states.get(keyOf(failure.at));
|
||||
if (state) result.set(failure.index, state);
|
||||
}
|
||||
return result;
|
||||
}, [failures, states]);
|
||||
|
||||
return { byLeg, retry };
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
// FE-PORTAGE-ROUTING-001 to 005: portages set in the planner follow the ways on land (PAD-03).
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { TourPlannerWaypoint } from '../planner/tourPlannerWaypoints';
|
||||
import { portageLegBetween } from '../planner/tourRouteActions';
|
||||
|
||||
const routePortageLine = vi.fn();
|
||||
vi.mock('./portageRoute', () => ({ routePortageLine: (...args: unknown[]) => routePortageLine(...args) }));
|
||||
|
||||
const { usePortageRouting } = await import('./usePortageRouting');
|
||||
|
||||
const A: TourPlannerWaypoint = { id: 'a', lat: 53.2232, lng: 12.9668, role: 'start' };
|
||||
const B: TourPlannerWaypoint = { id: 'b', lat: 53.2229, lng: 12.9701, role: 'end' };
|
||||
const WAY: [number, number][] = [
|
||||
[A.lat, A.lng],
|
||||
[53.2226, 12.9686],
|
||||
[B.lat, B.lng],
|
||||
];
|
||||
|
||||
function plannerWith(waypoints: TourPlannerWaypoint[], hasUnsavedChanges: boolean) {
|
||||
const planner = {
|
||||
waypoints,
|
||||
isPaddle: true,
|
||||
hasUnsavedChanges,
|
||||
amendWaypoints: vi.fn((change: (current: TourPlannerWaypoint[]) => TourPlannerWaypoint[]) => {
|
||||
planner.waypoints = change(planner.waypoints);
|
||||
}),
|
||||
editPaddlePoints: vi.fn((change: (current: TourPlannerWaypoint[]) => TourPlannerWaypoint[]) => {
|
||||
planner.waypoints = change(planner.waypoints);
|
||||
}),
|
||||
};
|
||||
return planner;
|
||||
}
|
||||
|
||||
const carried = (): TourPlannerWaypoint[] => [{ ...A, fixedLeg: portageLegBetween(A, B) }, B];
|
||||
|
||||
describe('usePortageRouting', () => {
|
||||
beforeEach(() => routePortageLine.mockReset());
|
||||
|
||||
it('FE-PORTAGE-ROUTING-001: lays a portage the paddler just set on the way the router found', async () => {
|
||||
routePortageLine.mockResolvedValue(WAY);
|
||||
const planner = plannerWith(carried(), true);
|
||||
renderHook(() => usePortageRouting(planner, true));
|
||||
await waitFor(() => expect(planner.amendWaypoints).toHaveBeenCalled());
|
||||
expect(planner.waypoints[0].fixedLeg?.geometry).toEqual(WAY);
|
||||
});
|
||||
|
||||
it('FE-PORTAGE-ROUTING-002: leaves a tour as saved alone, and asks nobody while it cannot be edited', async () => {
|
||||
const saved = plannerWith(carried(), false);
|
||||
renderHook(() => usePortageRouting(saved, true));
|
||||
const locked = plannerWith(carried(), true);
|
||||
renderHook(() => usePortageRouting(locked, false));
|
||||
await Promise.resolve();
|
||||
expect(routePortageLine).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('FE-PORTAGE-ROUTING-003: keeps a carry straight when the router found no way, and says so', async () => {
|
||||
routePortageLine.mockResolvedValue(null);
|
||||
const planner = plannerWith(carried(), true);
|
||||
const { result } = renderHook(() => usePortageRouting(planner, true));
|
||||
await waitFor(() => expect(routePortageLine).toHaveBeenCalledTimes(1));
|
||||
await waitFor(() => expect(result.current.noWay(['a'])).toBe(true));
|
||||
expect(planner.waypoints[0].fixedLeg?.geometry).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('FE-PORTAGE-ROUTING-004: lays a saved straight portage on the way when asked to', async () => {
|
||||
routePortageLine.mockResolvedValue(WAY);
|
||||
const planner = plannerWith(carried(), false);
|
||||
const { result } = renderHook(() => usePortageRouting(planner, true));
|
||||
let found = false;
|
||||
await act(async () => {
|
||||
found = await result.current.follow(['a']);
|
||||
});
|
||||
expect(found).toBe(true);
|
||||
expect(planner.waypoints[0].fixedLeg?.geometry).toEqual(WAY);
|
||||
});
|
||||
|
||||
it('FE-PORTAGE-ROUTING-005: draws a portage straight on request and keeps it so', async () => {
|
||||
const planner = plannerWith([{ ...A, fixedLeg: { ...portageLegBetween(A, B), geometry: WAY } }, B], true);
|
||||
const { result, rerender } = renderHook(() => usePortageRouting(planner, true));
|
||||
act(() => result.current.straighten(['a']));
|
||||
expect(planner.waypoints[0].fixedLeg?.geometry).toEqual([
|
||||
[A.lat, A.lng],
|
||||
[B.lat, B.lng],
|
||||
]);
|
||||
rerender();
|
||||
await Promise.resolve();
|
||||
expect(routePortageLine).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,194 @@
|
||||
import type { TourFixedLeg } from '@trek/shared';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { TourPlannerController } from '../planner/useTourPlanner';
|
||||
import type { PortageWay } from './PaddleWaypointParts';
|
||||
import { routePortageLine } from './portageRoute';
|
||||
|
||||
type Planner = Pick<
|
||||
TourPlannerController,
|
||||
'waypoints' | 'isPaddle' | 'hasUnsavedChanges' | 'amendWaypoints' | 'editPaddlePoints'
|
||||
>;
|
||||
type Point = TourPlannerController['waypoints'][number];
|
||||
type Line = [number, number][];
|
||||
|
||||
/** A portage leg by its two ends, to six decimals (about ten centimetres): the same carry asks once. */
|
||||
function keyOf(from: Point, to: Point): string {
|
||||
return `${from.lat.toFixed(6)},${from.lng.toFixed(6)}>${to.lat.toFixed(6)},${to.lng.toFixed(6)}`;
|
||||
}
|
||||
|
||||
function isStraightPortage(leg: TourFixedLeg | null | undefined): boolean {
|
||||
return leg?.kind === 'portage' && leg.geometry.length === 2;
|
||||
}
|
||||
|
||||
/** The portages still drawn straight, with the point after each. */
|
||||
function straightPortages(points: readonly Point[]) {
|
||||
return points.flatMap((point, index) => {
|
||||
const next = points[index + 1];
|
||||
// A portage the water router found is its own: it already follows the mapped way.
|
||||
return next && !point.auto && isStraightPortage(point.fixedLeg)
|
||||
? [{ id: point.id, from: point, to: next, key: keyOf(point, next) }]
|
||||
: [];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* PAD-03: a portage follows the ways on land instead of cutting straight
|
||||
* across them. A portage the paddler sets, or whose ends they move, is asked
|
||||
* of the router the hikes use and takes its line, unless that line is a
|
||||
* detour; then it stays straight. A tour opened as saved keeps its straight
|
||||
* portages until the paddler asks for the way (`follow`), and one they set
|
||||
* straight on purpose (`straighten`) stays so.
|
||||
*/
|
||||
export function usePortageRouting(planner: Planner, editable: boolean) {
|
||||
const { waypoints, isPaddle, hasUnsavedChanges, amendWaypoints, editPaddlePoints } = planner;
|
||||
/** Carries kept straight: as the tour was saved, or as the paddler set them. */
|
||||
const kept = useRef(new Set<string>());
|
||||
/** What the router answered per carry; null when it found no way worth taking. */
|
||||
const lines = useRef(new Map<string, Line | null>());
|
||||
|
||||
const layIn = useCallback(() => {
|
||||
amendWaypoints((current) => {
|
||||
let changed = false;
|
||||
const next = current.map((point, index) => {
|
||||
const after = current[index + 1];
|
||||
const leg = point.fixedLeg;
|
||||
if (!after || point.auto || !leg || leg.kind !== 'portage' || leg.geometry.length !== 2) return point;
|
||||
const key = keyOf(point, after);
|
||||
const line = kept.current.has(key) ? null : lines.current.get(key);
|
||||
if (!line) return point;
|
||||
changed = true;
|
||||
return { ...point, fixedLeg: { ...leg, geometry: line } };
|
||||
});
|
||||
return changed ? next : current;
|
||||
});
|
||||
}, [amendWaypoints]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPaddle || !editable) return undefined;
|
||||
const legs = straightPortages(waypoints);
|
||||
if (!hasUnsavedChanges) {
|
||||
for (const leg of legs) kept.current.add(leg.key);
|
||||
return undefined;
|
||||
}
|
||||
const wanted = legs.filter((leg) => !kept.current.has(leg.key));
|
||||
if (wanted.some((leg) => lines.current.get(leg.key))) layIn();
|
||||
const missing = wanted.filter((leg) => !lines.current.has(leg.key));
|
||||
if (missing.length === 0) return undefined;
|
||||
const abort = new AbortController();
|
||||
// One after the other: the public router allows about one request a second.
|
||||
void missing
|
||||
.reduce(async (previous, leg) => {
|
||||
await previous;
|
||||
if (abort.signal.aborted) return;
|
||||
const line = await routePortageLine(leg.from, leg.to, abort.signal);
|
||||
if (!abort.signal.aborted) lines.current.set(leg.key, line);
|
||||
}, Promise.resolve())
|
||||
.then(() => {
|
||||
if (!abort.signal.aborted) layIn();
|
||||
});
|
||||
return () => abort.abort();
|
||||
}, [editable, hasUnsavedChanges, isPaddle, layIn, waypoints]);
|
||||
|
||||
/** The carries starting at these points, each with the point after it. */
|
||||
const legsOf = useCallback(
|
||||
(ids: readonly string[]) =>
|
||||
waypoints.flatMap((point, index) => {
|
||||
const next = waypoints[index + 1];
|
||||
return ids.includes(point.id) && next ? [{ point, next, key: keyOf(point, next) }] : [];
|
||||
}),
|
||||
[waypoints]
|
||||
);
|
||||
|
||||
/**
|
||||
* A portage laid on the ways, after it was straight (as saved, or set so),
|
||||
* leg by leg: true once one follows them, false when there is no way worth
|
||||
* taking and it stays straight.
|
||||
*/
|
||||
const follow = useCallback(
|
||||
async (ids: readonly string[]) => {
|
||||
const legs = legsOf(ids);
|
||||
const found = await legs.reduce(async (previous, { point, next, key }) => {
|
||||
const any = await previous;
|
||||
kept.current.delete(key);
|
||||
const line = await routePortageLine(point, next);
|
||||
lines.current.set(key, line);
|
||||
return any || !!line;
|
||||
}, Promise.resolve(false));
|
||||
if (found) layIn();
|
||||
return found;
|
||||
},
|
||||
[layIn, legsOf]
|
||||
);
|
||||
|
||||
/** A portage drawn straight, and kept so. */
|
||||
const straighten = useCallback(
|
||||
(ids: readonly string[]) => {
|
||||
for (const { key } of legsOf(ids)) kept.current.add(key);
|
||||
editPaddlePoints((current) =>
|
||||
current.map((point, index) => {
|
||||
const next = current[index + 1];
|
||||
const leg = point.fixedLeg;
|
||||
if (!ids.includes(point.id) || !next || leg?.kind !== 'portage') return point;
|
||||
return {
|
||||
...point,
|
||||
fixedLeg: {
|
||||
...leg,
|
||||
geometry: [
|
||||
[point.lat, point.lng],
|
||||
[next.lat, next.lng],
|
||||
],
|
||||
},
|
||||
};
|
||||
})
|
||||
);
|
||||
},
|
||||
[editPaddlePoints, legsOf]
|
||||
);
|
||||
|
||||
/** Whether the router found no way worth taking for every leg of a portage. */
|
||||
const noWay = useCallback(
|
||||
(ids: readonly string[]) => {
|
||||
const legs = legsOf(ids);
|
||||
return legs.length > 0 && legs.every(({ key }) => lines.current.get(key) === null);
|
||||
},
|
||||
[legsOf]
|
||||
);
|
||||
|
||||
return { follow, straighten, noWay };
|
||||
}
|
||||
|
||||
type PortageRouting = ReturnType<typeof usePortageRouting>;
|
||||
|
||||
/** The waypoints whose legs make up the portage starting at `index`: one leg, or several in a row. */
|
||||
function portageRunIds(points: readonly Point[], index: number): string[] {
|
||||
const ids: string[] = [];
|
||||
for (let at = index; at < points.length - 1 && points[at]?.fixedLeg?.kind === 'portage'; at += 1) {
|
||||
ids.push(points[at].id);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* PAD-03: the way of the portage starting at a waypoint, for its card:
|
||||
* whether it follows the ways on land, why it stayed straight, and the switch
|
||||
* between the two. Undefined where no portage starts.
|
||||
*/
|
||||
export function usePortageWay(
|
||||
points: readonly Point[],
|
||||
routing: PortageRouting,
|
||||
index: number
|
||||
): PortageWay | undefined {
|
||||
const [searching, setSearching] = useState(false);
|
||||
const ids = portageRunIds(points, index);
|
||||
if (ids.length === 0) return undefined;
|
||||
return {
|
||||
routed: ids.every((id) => (points.find((point) => point.id === id)?.fixedLeg?.geometry.length ?? 0) > 2),
|
||||
noWay: routing.noWay(ids),
|
||||
searching,
|
||||
onFollow: () => {
|
||||
setSearching(true);
|
||||
void routing.follow(ids).finally(() => setSearching(false));
|
||||
},
|
||||
onStraighten: () => routing.straighten(ids),
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user