mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 18:04:18 +00:00
feat(tours): paddle obstacle card, admin regions panel and obstacle marks on the route band
PAD-05B: a click on an obstacle on the map or on the route band opens its card in the look of the via ferrata card: the kind with its glyph, the name, how it stands to the route (on it at a distance along it, near it with the link marked unclear, or only in the area), the paddling rule its tags give with canoe read before boat, a condition as written, height, grade, hours and fees, the source with the date of the data and the OpenStreetMap link. A missing rule reads as unknown, never as allowed, and a portage way recorded as private says so. Objects only in the area show from zoom 13 on, on Leaflet and GL alike; on GL the lines only near the route are dashed as on Leaflet, one click handler picks the marker over the line, and a picked marker no longer flickers. The route band marks the obstacles on and near the route by their share of the measured line. The obstacle notice also names an answer cut at its limit. PAD-05A: the admin area gets a Paddle water data card under the addons, on desktop and phone: a search in Geofabrik's list with each region's path, the regions with their state (waiting, reading with its progress, ready with objects and data date, failed with the reason), reading again and removing after a confirmation. The list follows a read without reloading. Region changes write audit rows. Map colours of paddle objects and portages come from theme tokens read at draw time, as the via ferratas do; the ferrata layer now shares that reader. The rail takes the planner page's parts as one bag, the map hit tests of the tour layers are one helper, and the unused noWaterData string is gone from every locale.
This commit is contained in:
@@ -0,0 +1,278 @@
|
||||
import type { PaddleRegion, PaddleRegionCatalogEntry } from '@trek/shared';
|
||||
import { Check, ChevronRight, Loader2, Plus, RefreshCw, Search, Trash2, Waves, WifiOff } from 'lucide-react';
|
||||
import { useId } from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import {
|
||||
SettingRows,
|
||||
SETTINGS_BUTTON,
|
||||
SETTINGS_ICON_BUTTON,
|
||||
SettingsCard,
|
||||
SettingsHint,
|
||||
StatusPill,
|
||||
} from '../../Settings/settingsKit';
|
||||
import ConfirmDialog from '../../shared/ConfirmDialog';
|
||||
import { EditorField, INPUT } from '../../shared/dialogParts';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import ErrorBoundary from '../../shared/ErrorBoundary';
|
||||
import { Tooltip } from '../../shared/Tooltip';
|
||||
import { progressPercent, regionStatusTone } from './paddleRegionsModel';
|
||||
import { usePaddleRegionsAdmin } from './usePaddleRegionsAdmin';
|
||||
|
||||
type Admin = ReturnType<typeof usePaddleRegionsAdmin>;
|
||||
|
||||
/**
|
||||
* PAD-05A in the admin area: the regions TREK reads paddle obstacles for,
|
||||
* picked from Geofabrik's list. Both the desktop and the phone admin show
|
||||
* this one card under the addons, while the Tours addon is on.
|
||||
*/
|
||||
export default function PaddleRegionsPanel() {
|
||||
return (
|
||||
<ErrorBoundary boundaryId="paddle-regions">
|
||||
<Panel />
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
||||
function Panel() {
|
||||
const { t } = useTranslation();
|
||||
const admin = usePaddleRegionsAdmin();
|
||||
if (!admin.toursOn) return null;
|
||||
return (
|
||||
<SettingsCard
|
||||
icon={Waves}
|
||||
title={t('admin.paddleRegions.title')}
|
||||
hint={t('admin.paddleRegions.hint')}
|
||||
badge={admin.regions.length > 0 ? <StatusPill>{admin.regions.length}</StatusPill> : undefined}
|
||||
>
|
||||
{admin.offline && (
|
||||
<p
|
||||
role="status"
|
||||
className="m-0 flex items-center gap-2 rounded-[12px] bg-warning-soft px-3.5 py-2.5 text-warning"
|
||||
style={fs(12.5, 'body')}
|
||||
>
|
||||
<WifiOff size={14} className="flex-none" />
|
||||
{t('admin.paddleRegions.offline')}
|
||||
</p>
|
||||
)}
|
||||
{admin.error && !admin.offline && (
|
||||
<div
|
||||
role="alert"
|
||||
className="flex flex-wrap items-center gap-3 rounded-[12px] bg-danger-soft px-3.5 py-2.5 text-danger"
|
||||
style={fs(12.5, 'body')}
|
||||
>
|
||||
<span className="min-w-0 flex-1 basis-48">{admin.error}</span>
|
||||
<button type="button" onClick={admin.retry} className={SETTINGS_BUTTON} style={fs(12.5, 'body')}>
|
||||
{t('admin.paddleRegions.retry')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<fieldset disabled={admin.offline} className="m-0 flex min-w-0 flex-col gap-4 border-0 p-0">
|
||||
<CatalogSearch admin={admin} />
|
||||
<RegionList admin={admin} />
|
||||
</fieldset>
|
||||
<SettingsHint>{t('admin.paddleRegions.attribution')}</SettingsHint>
|
||||
<ConfirmDialog
|
||||
isOpen={admin.removing !== null}
|
||||
onClose={admin.cancelRemove}
|
||||
onConfirm={admin.confirmRemove}
|
||||
title={t('admin.paddleRegions.remove')}
|
||||
message={t('admin.paddleRegions.removeMessage', { name: admin.removing?.name ?? '' })}
|
||||
confirmLabel={t('common.remove')}
|
||||
/>
|
||||
</SettingsCard>
|
||||
);
|
||||
}
|
||||
|
||||
/** A Geofabrik region with the regions it lies in, outermost first, so two of one name tell apart. */
|
||||
function RegionPath({ hit }: { hit: PaddleRegionCatalogEntry }) {
|
||||
if (hit.path.length === 0) return null;
|
||||
return (
|
||||
<span className="flex min-w-0 flex-wrap items-center gap-0.5 text-content-faint" style={fs(11.5)}>
|
||||
{hit.path.map((part, index) => (
|
||||
<span key={`${part}-${index}`} className="inline-flex items-center gap-0.5">
|
||||
{index > 0 && <ChevronRight size={11} className="flex-none rtl:rotate-180" aria-hidden="true" />}
|
||||
{part}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function CatalogSearch({ admin }: { admin: Admin }) {
|
||||
const { t } = useTranslation();
|
||||
const id = useId();
|
||||
const { search } = admin;
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<EditorField label={t('admin.paddleRegions.search')} htmlFor={id}>
|
||||
<div className="relative">
|
||||
<Search
|
||||
size={14}
|
||||
className="pointer-events-none absolute start-3 top-1/2 -translate-y-1/2 text-content-faint"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<input
|
||||
id={id}
|
||||
type="search"
|
||||
className={`${INPUT} ps-9`}
|
||||
value={search.query}
|
||||
onChange={(event) => search.setQuery(event.target.value)}
|
||||
placeholder={t('admin.paddleRegions.searchPlaceholder')}
|
||||
autoComplete="off"
|
||||
/>
|
||||
</div>
|
||||
</EditorField>
|
||||
{search.searching && (
|
||||
<p role="status" className="m-0 flex items-center gap-2 text-content-muted" style={fs(12.5, 'body')}>
|
||||
<Loader2 size={14} className="flex-none animate-spin" />
|
||||
{t('common.loading')}
|
||||
</p>
|
||||
)}
|
||||
{search.error && (
|
||||
<p role="alert" className="m-0 text-danger" style={fs(12.5, 'body')}>
|
||||
{search.error}
|
||||
</p>
|
||||
)}
|
||||
{search.hits && search.hits.length === 0 && <SettingsHint>{t('admin.paddleRegions.noHits')}</SettingsHint>}
|
||||
{search.hits && search.hits.length > 0 && (
|
||||
<SettingRows>
|
||||
{search.hits.map((hit) => (
|
||||
<div key={hit.id} className="flex items-center gap-3 py-2 pe-2 ps-3.5" data-testid="paddle-region-hit">
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<span className="truncate font-medium text-content" style={fs(13, 'body')}>
|
||||
{hit.name}
|
||||
</span>
|
||||
<RegionPath hit={hit} />
|
||||
</div>
|
||||
{admin.added.has(hit.id) ? (
|
||||
<StatusPill icon={<Check size={11} strokeWidth={2.4} />}>{t('admin.paddleRegions.added')}</StatusPill>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
disabled={admin.busyId !== null}
|
||||
onClick={() => void admin.add(hit.id)}
|
||||
className={SETTINGS_BUTTON}
|
||||
style={fs(12.5, 'body')}
|
||||
>
|
||||
{admin.busyId === hit.id ? (
|
||||
<Loader2 size={13} className="animate-spin" />
|
||||
) : (
|
||||
<Plus size={13} strokeWidth={2.2} />
|
||||
)}
|
||||
{t('common.add')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</SettingRows>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RegionList({ admin }: { admin: Admin }) {
|
||||
const { t } = useTranslation();
|
||||
if (admin.loading) {
|
||||
return (
|
||||
<p role="status" className="m-0 flex items-center gap-2 text-content-muted" style={fs(12.5, 'body')}>
|
||||
<Loader2 size={14} className="flex-none animate-spin" />
|
||||
{t('common.loading')}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
if (admin.regions.length === 0) {
|
||||
return (
|
||||
<div className="rounded-[12px] border border-dashed border-edge px-4 py-5 text-center">
|
||||
<SettingsHint>{t('admin.paddleRegions.empty')}</SettingsHint>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<SettingRows>
|
||||
{admin.regions.map((region) => (
|
||||
<RegionRow key={region.id} region={region} admin={admin} />
|
||||
))}
|
||||
</SettingRows>
|
||||
);
|
||||
}
|
||||
|
||||
function RegionStatus({ region }: { region: PaddleRegion }) {
|
||||
const { t, language } = useTranslation();
|
||||
const percent = progressPercent(region);
|
||||
const label =
|
||||
region.status === 'importing' && region.progress
|
||||
? t(`admin.paddleRegions.phase.${region.progress.phase}`)
|
||||
: t(`admin.paddleRegions.status.${region.status}`);
|
||||
const share =
|
||||
percent === null ? '' : ` ${new Intl.NumberFormat(language, { style: 'percent' }).format(percent / 100)}`;
|
||||
return (
|
||||
<StatusPill
|
||||
tone={regionStatusTone(region.status)}
|
||||
icon={region.status === 'importing' ? <Loader2 size={11} className="animate-spin" /> : undefined}
|
||||
>
|
||||
{label}
|
||||
{share}
|
||||
</StatusPill>
|
||||
);
|
||||
}
|
||||
|
||||
function RegionRow({ region, admin }: { region: PaddleRegion; admin: Admin }) {
|
||||
const { t, language } = useTranslation();
|
||||
const busy = admin.busyId === region.id;
|
||||
const date = region.source_timestamp
|
||||
? new Date(region.source_timestamp).toLocaleDateString(language, { dateStyle: 'medium' })
|
||||
: null;
|
||||
return (
|
||||
<div
|
||||
className={`flex items-center gap-3 py-2.5 pe-2 ps-3 ${busy ? 'opacity-60' : ''}`}
|
||||
data-testid="paddle-region-row"
|
||||
>
|
||||
<span
|
||||
aria-hidden
|
||||
className="grid h-8 w-8 flex-none place-items-center rounded-[10px] bg-surface-tertiary text-content-secondary"
|
||||
>
|
||||
<Waves size={15} strokeWidth={1.9} />
|
||||
</span>
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-1">
|
||||
<span className="truncate font-medium text-content" style={fs(13, 'body')}>
|
||||
{region.name}
|
||||
</span>
|
||||
<span className="flex flex-wrap items-center gap-1.5">
|
||||
<RegionStatus region={region} />
|
||||
{region.imported_at && (
|
||||
<StatusPill>{t('admin.paddleRegions.objects', { count: region.feature_count })}</StatusPill>
|
||||
)}
|
||||
{region.imported_at && date && <StatusPill>{t('admin.paddleRegions.asOf', { date })}</StatusPill>}
|
||||
</span>
|
||||
{region.status === 'failed' && region.error && (
|
||||
<p className="m-0 line-clamp-2 break-words text-danger" style={fs(11.5)} title={region.error}>
|
||||
{region.error}
|
||||
{region.imported_at ? ` ${t('admin.paddleRegions.keptData')}` : ''}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<Tooltip label={t('admin.paddleRegions.refresh')}>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`${t('admin.paddleRegions.refresh')} ${region.name}`}
|
||||
disabled={admin.busyId !== null || region.status === 'queued' || region.status === 'importing'}
|
||||
onClick={() => void admin.refresh(region.id)}
|
||||
className={SETTINGS_ICON_BUTTON}
|
||||
>
|
||||
<RefreshCw size={14} strokeWidth={2} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Tooltip label={t('admin.paddleRegions.remove')}>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`${t('admin.paddleRegions.remove')} ${region.name}`}
|
||||
disabled={admin.busyId !== null}
|
||||
onClick={() => admin.askRemove(region)}
|
||||
className={`${SETTINGS_ICON_BUTTON} hover:!text-danger`}
|
||||
>
|
||||
<Trash2 size={14} strokeWidth={2} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { PaddleRegion } from '@trek/shared';
|
||||
|
||||
/** A region waiting for its read or being read: the list asks again until none is. */
|
||||
export function isReading(region: Pick<PaddleRegion, 'status'>): boolean {
|
||||
return region.status === 'queued' || region.status === 'importing';
|
||||
}
|
||||
|
||||
/** The share of a read under way as a whole percent, or null while its size is unknown. */
|
||||
export function progressPercent(region: Pick<PaddleRegion, 'progress'>): number | null {
|
||||
const fraction = region.progress?.fraction;
|
||||
return fraction === null || fraction === undefined ? null : Math.round(fraction * 100);
|
||||
}
|
||||
|
||||
/** The status badge's tone: what state the read is in, never whether the water is safe. */
|
||||
export function regionStatusTone(status: PaddleRegion['status']): 'neutral' | 'accent' | 'success' | 'danger' {
|
||||
if (status === 'importing') return 'accent';
|
||||
if (status === 'ready') return 'success';
|
||||
if (status === 'failed') return 'danger';
|
||||
return 'neutral';
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import type { PaddleRegion, PaddleRegionCatalogEntry } from '@trek/shared';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useNetworkMode } from '../../../hooks/useNetworkMode';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { paddleRegionErrorCode, paddleRegionRepo } from '../../../repo/paddleRegionRepo';
|
||||
import { useAddonStore } from '../../../store/addonStore';
|
||||
import { getApiErrorMessage } from '../../../types';
|
||||
import { useToast } from '../../shared/Toast';
|
||||
import { isReading } from './paddleRegionsModel';
|
||||
|
||||
/** How often the list is asked again while a region waits or is read. */
|
||||
export const PADDLE_REGIONS_POLL_MS = import.meta.env.MODE === 'test' ? 50 : 3000;
|
||||
/** How long typing rests before Geofabrik's list is searched. */
|
||||
export const CATALOG_SEARCH_DEBOUNCE_MS = import.meta.env.MODE === 'test' ? 10 : 350;
|
||||
|
||||
type Translate = ReturnType<typeof useTranslation>['t'];
|
||||
|
||||
function errorText(t: Translate, err: unknown): string {
|
||||
const code = paddleRegionErrorCode(err);
|
||||
if (code === 'offline') return t('admin.paddleRegions.offline');
|
||||
if (code === 'catalog_unavailable') return t('admin.paddleRegions.catalogUnavailable');
|
||||
return getApiErrorMessage(err, t('common.error'));
|
||||
}
|
||||
|
||||
/**
|
||||
* The regions as the server holds them, asked again every few seconds while
|
||||
* any of them is read, and on `reload` after a change. Every answer is set
|
||||
* from the request's own callback, so a slow one never overwrites a newer.
|
||||
*/
|
||||
function useRegionList(active: boolean, offline: boolean, t: Translate) {
|
||||
const [regions, setRegions] = useState<PaddleRegion[]>([]);
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [asked, setAsked] = useState(0);
|
||||
useEffect(() => {
|
||||
if (!active || offline) return;
|
||||
let cancelled = false;
|
||||
paddleRegionRepo.list().then(
|
||||
(list) => {
|
||||
if (cancelled) return;
|
||||
setRegions(list);
|
||||
setError(null);
|
||||
setLoaded(true);
|
||||
},
|
||||
(err: unknown) => {
|
||||
if (cancelled) return;
|
||||
setError(errorText(t, err));
|
||||
setLoaded(true);
|
||||
}
|
||||
);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [active, offline, t, asked]);
|
||||
const reading = regions.some(isReading);
|
||||
useEffect(() => {
|
||||
if (!active || offline || !reading) return;
|
||||
const timer = window.setInterval(() => setAsked((n) => n + 1), PADDLE_REGIONS_POLL_MS);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [active, offline, reading]);
|
||||
const reload = useCallback(() => setAsked((n) => n + 1), []);
|
||||
return { regions, loading: !loaded && !offline, error, reload };
|
||||
}
|
||||
|
||||
/** Geofabrik's list searched as the admin types, the last search winning. */
|
||||
function useCatalogSearch(offline: boolean, t: Translate) {
|
||||
const [query, setQuery] = useState('');
|
||||
const [result, setResult] = useState<{
|
||||
needle: string;
|
||||
hits: PaddleRegionCatalogEntry[] | null;
|
||||
error: string | null;
|
||||
} | null>(null);
|
||||
const needle = query.trim();
|
||||
const wanted = !offline && needle.length >= 2;
|
||||
useEffect(() => {
|
||||
if (!wanted) return;
|
||||
const controller = new AbortController();
|
||||
const timer = window.setTimeout(() => {
|
||||
paddleRegionRepo
|
||||
.catalog(needle, controller.signal)
|
||||
.then((hits) => {
|
||||
if (!controller.signal.aborted) setResult({ needle, hits, error: null });
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (!controller.signal.aborted) setResult({ needle, hits: null, error: errorText(t, err) });
|
||||
});
|
||||
}, CATALOG_SEARCH_DEBOUNCE_MS);
|
||||
return () => {
|
||||
controller.abort();
|
||||
window.clearTimeout(timer);
|
||||
};
|
||||
}, [needle, wanted, t]);
|
||||
// An answer counts only for the words it was asked for.
|
||||
const current = wanted && result?.needle === needle ? result : null;
|
||||
return { query, setQuery, hits: current?.hits ?? null, searching: wanted && !current, error: current?.error ?? null };
|
||||
}
|
||||
|
||||
/**
|
||||
* PAD-05A in the admin area: the regions TREK reads paddle data for, a search
|
||||
* in Geofabrik's list to add one, reading a region again and removing it
|
||||
* after a confirmation. Shown only while the Tours addon is on; the status of
|
||||
* a read follows without reloading the page.
|
||||
*/
|
||||
export function usePaddleRegionsAdmin() {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const { offline } = useNetworkMode();
|
||||
const toursOn = useAddonStore((state) => state.isEnabled('tours'));
|
||||
const list = useRegionList(toursOn, offline, t);
|
||||
const search = useCatalogSearch(offline, t);
|
||||
const [busyId, setBusyId] = useState<string | null>(null);
|
||||
const [removing, setRemoving] = useState<PaddleRegion | null>(null);
|
||||
const pending = useRef(false);
|
||||
const { reload } = list;
|
||||
|
||||
const run = useCallback(
|
||||
async (id: string, action: () => Promise<unknown>, done?: string) => {
|
||||
if (pending.current) return;
|
||||
pending.current = true;
|
||||
setBusyId(id);
|
||||
try {
|
||||
await action();
|
||||
if (done) toast.success(done);
|
||||
} catch (err) {
|
||||
toast.error(errorText(t, err));
|
||||
} finally {
|
||||
pending.current = false;
|
||||
setBusyId(null);
|
||||
reload();
|
||||
}
|
||||
},
|
||||
[reload, t, toast]
|
||||
);
|
||||
|
||||
const { setQuery } = search;
|
||||
const add = useCallback(
|
||||
(id: string) =>
|
||||
run(
|
||||
id,
|
||||
async () => {
|
||||
await paddleRegionRepo.add(id);
|
||||
setQuery('');
|
||||
},
|
||||
t('admin.paddleRegions.toast.added')
|
||||
),
|
||||
[run, setQuery, t]
|
||||
);
|
||||
const refresh = useCallback((id: string) => run(id, () => paddleRegionRepo.refresh(id)), [run]);
|
||||
const confirmRemove = useCallback(() => {
|
||||
const region = removing;
|
||||
setRemoving(null);
|
||||
if (region) void run(region.id, () => paddleRegionRepo.remove(region.id), t('admin.paddleRegions.toast.removed'));
|
||||
}, [removing, run, t]);
|
||||
const added = useMemo(() => new Set(list.regions.map((region) => region.id)), [list.regions]);
|
||||
|
||||
return {
|
||||
toursOn,
|
||||
offline,
|
||||
regions: list.regions,
|
||||
loading: list.loading,
|
||||
error: list.error,
|
||||
retry: reload,
|
||||
search,
|
||||
added,
|
||||
busyId,
|
||||
add,
|
||||
refresh,
|
||||
removing,
|
||||
askRemove: setRemoving,
|
||||
cancelRemove: () => setRemoving(null),
|
||||
confirmRemove,
|
||||
};
|
||||
}
|
||||
@@ -5,20 +5,12 @@ import type { Ferrata } from '@trek/shared';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { formatDistance } from '../../utils/units';
|
||||
import { MAP_CONTROL_SHADOW } from '../Map/mapControlShadow';
|
||||
import { MAP_CARD_GLASS } from '../Map/mapControlShadow';
|
||||
import { SoftPill } from '../Planner/planParts';
|
||||
import { fs } from '../shared/DialogShell';
|
||||
import { type FerrataGroup, ferrataLabel } from './ferrataGroups';
|
||||
import { ferrataOsmUrl } from './ferrataModel';
|
||||
|
||||
/** The map controls' frosted glass, so the card reads as one of them. */
|
||||
const MAP_GLASS = {
|
||||
background: 'var(--sidebar-bg)',
|
||||
backdropFilter: 'blur(20px) saturate(180%)',
|
||||
WebkitBackdropFilter: 'blur(20px) saturate(180%)',
|
||||
boxShadow: MAP_CONTROL_SHADOW,
|
||||
};
|
||||
|
||||
/**
|
||||
* One via ferrata, picked on the map: its name, the route it belongs to, its
|
||||
* grade range and total length as badges, and the way back to the source.
|
||||
@@ -57,7 +49,7 @@ export default function FerrataDetailCard({
|
||||
return (
|
||||
<article
|
||||
className={`rounded-2xl p-3 text-content ${width ? '' : 'w-max min-w-[min(18rem,calc(100vw_-_2rem))] max-w-[22.5rem]'}`}
|
||||
style={{ ...MAP_GLASS, width }}
|
||||
style={{ ...MAP_CARD_GLASS, width }}
|
||||
data-testid="ferrata-detail-card"
|
||||
>
|
||||
<div className="flex items-start gap-2">
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useRef } from 'react';
|
||||
|
||||
import { useMapCardDismiss } from '../Map/useMapCardDismiss';
|
||||
import FerrataDetailCard from './FerrataDetailCard';
|
||||
import type { FerrataGroup } from './ferrataGroups';
|
||||
import type { FerrataSelection } from './useFerrataMapLayer';
|
||||
@@ -39,26 +40,7 @@ export default function FerrataDetailOverlay({
|
||||
onTourIds?: ReadonlySet<string>;
|
||||
}) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const open = !!selection;
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onDown = (event: PointerEvent) => {
|
||||
const card = ref.current;
|
||||
if (card && event.target instanceof Node && card.contains(event.target)) return;
|
||||
onOutsidePress?.();
|
||||
onClose();
|
||||
};
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape' && !event.defaultPrevented) onClose();
|
||||
};
|
||||
document.addEventListener('pointerdown', onDown, true);
|
||||
document.addEventListener('keydown', onKey);
|
||||
return () => {
|
||||
document.removeEventListener('pointerdown', onDown, true);
|
||||
document.removeEventListener('keydown', onKey);
|
||||
};
|
||||
}, [open, onClose, onOutsidePress]);
|
||||
useMapCardDismiss(ref, !!selection, onClose, onOutsidePress);
|
||||
|
||||
if (!selection) return null;
|
||||
return (
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { readMapPaint, sameMapPaint } from '../Map/mapPaint';
|
||||
|
||||
/**
|
||||
* The colours the via ferrata lines are drawn in.
|
||||
*
|
||||
@@ -10,9 +12,9 @@
|
||||
*
|
||||
* Map paint cannot take a `var(--token)`: Leaflet writes the colour into an
|
||||
* SVG `stroke` attribute and GL paint wants a resolved colour string. So the
|
||||
* `--map-ferrata*` tokens are read off the document when the layer draws (the
|
||||
* precedent is the hazard overlay in useHazardLayerGL), which keeps light and
|
||||
* dark mode apart without a colour literal in the layer.
|
||||
* `--map-ferrata*` tokens are read off the document when the layer draws
|
||||
* (`mapPaint.ts`; the precedent is the hazard overlay in useHazardLayerGL),
|
||||
* which keeps light and dark mode apart without a colour literal in the layer.
|
||||
*/
|
||||
export interface FerrataPaint {
|
||||
/** The dashed line itself. */
|
||||
@@ -23,27 +25,16 @@ export interface FerrataPaint {
|
||||
highlight: string;
|
||||
}
|
||||
|
||||
const TOKENS = {
|
||||
export const FERRATA_TOKENS = {
|
||||
line: '--map-ferrata',
|
||||
casing: '--map-ferrata-casing',
|
||||
highlight: '--map-ferrata-lit',
|
||||
} as const;
|
||||
|
||||
/** What a token resolves to on the root, or `currentColor` where nothing defines it (a test DOM). */
|
||||
function token(name: string, style: CSSStyleDeclaration | null): string {
|
||||
const value = style?.getPropertyValue(name).trim();
|
||||
return value || 'currentColor';
|
||||
}
|
||||
|
||||
export function ferrataPaint(): FerrataPaint {
|
||||
const style = typeof document === 'undefined' ? null : getComputedStyle(document.documentElement);
|
||||
return {
|
||||
line: token(TOKENS.line, style),
|
||||
casing: token(TOKENS.casing, style),
|
||||
highlight: token(TOKENS.highlight, style),
|
||||
};
|
||||
return readMapPaint(FERRATA_TOKENS);
|
||||
}
|
||||
|
||||
export function sameFerrataPaint(a: FerrataPaint, b: FerrataPaint): boolean {
|
||||
return a.line === b.line && a.casing === b.casing && a.highlight === b.highlight;
|
||||
return sameMapPaint(a, b);
|
||||
}
|
||||
|
||||
@@ -1,30 +1,7 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useMapPaint } from '../Map/mapPaint';
|
||||
import { FERRATA_TOKENS, type FerrataPaint } from './ferrataPaint';
|
||||
|
||||
import { type FerrataPaint, ferrataPaint, sameFerrataPaint } from './ferrataPaint';
|
||||
|
||||
/** The attributes `applyAppearance()` writes on `<html>` that change what the tokens resolve to. */
|
||||
const THEME_ATTRIBUTES = ['class', 'style', 'data-scheme'];
|
||||
|
||||
/**
|
||||
* The line colours, resolved again whenever the light/dark class, the colour
|
||||
* scheme or a custom accent on `<html>` changes. Map paint holds resolved
|
||||
* strings rather than `var(--token)`, so without this a theme toggle would leave
|
||||
* the lines in the old scheme's colours. Same observer approach as `useIsDark`,
|
||||
* which only watches the class. The reference only changes when a colour does,
|
||||
* so a memo keyed on it does not churn.
|
||||
*/
|
||||
/** The line colours, resolved again whenever the theme on `<html>` changes (see `useMapPaint`). */
|
||||
export function useFerrataPaint(): FerrataPaint {
|
||||
const [paint, setPaint] = useState(ferrataPaint);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof document === 'undefined') return;
|
||||
const observer = new MutationObserver(() => {
|
||||
const next = ferrataPaint();
|
||||
setPaint((current) => (sameFerrataPaint(current, next) ? current : next));
|
||||
});
|
||||
observer.observe(document.documentElement, { attributes: true, attributeFilter: THEME_ATTRIBUTES });
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
return paint;
|
||||
return useMapPaint(FERRATA_TOKENS);
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import type mapboxgl from 'mapbox-gl'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { useTranslation } from '../../i18n/TranslationContext'
|
||||
import { applySatellite } from './glRasterLayers'
|
||||
import { useTourMapLayersGL } from './mapRasterOverlay'
|
||||
import { isTourLayerHit, useTourMapLayersGL } from './mapRasterOverlay'
|
||||
import { MapLayerSwitcher, TourMapLayerSwitcher, MAP_LAYER_SWITCHER_INSET, type BaseLayer, type TourBaseLayer } from './MapLayerSwitcher'
|
||||
import { MapLockPill } from './MapLockPill'
|
||||
import { useMarkerThumbs } from './useMarkerThumbs'
|
||||
@@ -33,8 +33,7 @@ import { nightPauseMarker, NIGHT_PAUSE_MIN_ZOOM } from './nightPauseMarker'
|
||||
import { clusterPois, poiClusterMarkup, poiClusterList, POI_CLUSTER_DETAIL_ZOOM } from './poiClusters'
|
||||
import { groupCoincidentPlaces } from './coincidentPlaces'
|
||||
import { useHazardLayerGL } from './useHazardLayerGL'
|
||||
import { type FerrataGlMap, isFerrataHit } from '../Ferratas/useFerrataLayerGL'
|
||||
import { isPaddleHit } from '../Tours/paddle/usePaddleLayerGL'
|
||||
import type { FerrataGlMap } from '../Ferratas/useFerrataLayerGL'
|
||||
import { formatViaDwell } from './routeViaDwell'
|
||||
import { useDawarichTrailGL } from './useDawarichTrailGL'
|
||||
import { bindDayBoundaryDrag } from './dayBoundaryDrag'
|
||||
@@ -1430,8 +1429,7 @@ export function MapViewGL({
|
||||
&& typeof map.queryRenderedFeatures === 'function'
|
||||
&& map.queryRenderedFeatures(e.point, { layers: ['trip-route-hit'] }).length > 0
|
||||
) return
|
||||
if (isFerrataHit(map, e.point)) return // a picked via ferrata opens its card instead
|
||||
if (isPaddleHit(map, e.point)) return // so does a picked paddle obstacle
|
||||
if (isTourLayerHit(map, e.point)) return // a picked via ferrata or paddle obstacle opens its card instead
|
||||
onClickRefs.current.map?.({ latlng: { lat: e.lngLat.lat, lng: e.lngLat.lng } })
|
||||
})
|
||||
// Emit the viewport bbox (pan/zoom + once on first idle) so the POI-explore
|
||||
|
||||
@@ -8,3 +8,11 @@
|
||||
* exactly that reason — the others were the ones that needed to match it.
|
||||
*/
|
||||
export const MAP_CONTROL_SHADOW = '0 2px 10px rgba(0,0,0,0.25)'
|
||||
|
||||
/** The frosted glass of the map's floating cards (a ferrata's, a paddle obstacle's), so they read as its controls. */
|
||||
export const MAP_CARD_GLASS = {
|
||||
background: 'var(--sidebar-bg)',
|
||||
backdropFilter: 'blur(20px) saturate(180%)',
|
||||
WebkitBackdropFilter: 'blur(20px) saturate(180%)',
|
||||
boxShadow: MAP_CONTROL_SHADOW,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
/**
|
||||
* Colours for map paint, read off the theme. Map paint cannot take a
|
||||
* `var(--token)`: Leaflet writes the colour into an SVG attribute and GL
|
||||
* paint wants a resolved colour string. So the map layers name the tokens
|
||||
* they draw with, and the colours are read off the document when they draw,
|
||||
* which keeps light and dark mode apart without a colour literal in a layer.
|
||||
*/
|
||||
|
||||
/** The attributes `applyAppearance()` writes on `<html>` that change what the tokens resolve to. */
|
||||
const THEME_ATTRIBUTES = ['class', 'style', 'data-scheme'];
|
||||
|
||||
/** What each token resolves to on the root, `currentColor` where nothing defines it (a test DOM). */
|
||||
export function readMapPaint<K extends string>(tokens: Readonly<Record<K, string>>): Record<K, string> {
|
||||
const style = typeof document === 'undefined' ? null : getComputedStyle(document.documentElement);
|
||||
const keys = Object.keys(tokens) as K[];
|
||||
return Object.fromEntries(
|
||||
keys.map((key) => [key, style?.getPropertyValue(tokens[key]).trim() || 'currentColor'])
|
||||
) as Record<K, string>;
|
||||
}
|
||||
|
||||
export function sameMapPaint<K extends string>(
|
||||
a: Readonly<Record<K, string>>,
|
||||
b: Readonly<Record<K, string>>
|
||||
): boolean {
|
||||
return (Object.keys(a) as K[]).every((key) => a[key] === b[key]);
|
||||
}
|
||||
|
||||
/**
|
||||
* The colours, read again whenever the light or dark class, the colour scheme
|
||||
* or a custom accent on `<html>` changes; without this a theme toggle would
|
||||
* leave a layer in the old scheme's colours. The answer only changes identity
|
||||
* when a colour does, so a memo keyed on it does not churn. `tokens` is a
|
||||
* constant of the caller's module.
|
||||
*/
|
||||
export function useMapPaint<K extends string>(tokens: Readonly<Record<K, string>>): Record<K, string> {
|
||||
const [paint, setPaint] = useState(() => readMapPaint(tokens));
|
||||
useEffect(() => {
|
||||
if (typeof document === 'undefined') return;
|
||||
const observer = new MutationObserver(() => {
|
||||
const next = readMapPaint(tokens);
|
||||
setPaint((current) => (sameMapPaint(current, next) ? current : next));
|
||||
});
|
||||
observer.observe(document.documentElement, { attributes: true, attributeFilter: THEME_ATTRIBUTES });
|
||||
return () => observer.disconnect();
|
||||
}, [tokens]);
|
||||
return paint;
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import type { Map } from 'mapbox-gl';
|
||||
import type { PaddleMapLayer } from '../Tours/paddle/paddleMapLayer';
|
||||
import { type PaddleGlMap, usePaddleLayerGL } from '../Tours/paddle/usePaddleLayerGL';
|
||||
import { useEffect } from 'react';
|
||||
import { useFerrataMapLayerGL } from '../Ferratas/useFerrataLayerGL';
|
||||
import { isFerrataHit, useFerrataMapLayerGL } from '../Ferratas/useFerrataLayerGL';
|
||||
import type { FerrataMapLayer } from '../Ferratas/useFerrataMapLayer';
|
||||
import type { PaddleMapLayer } from '../Tours/paddle/paddleMapLayer';
|
||||
import { isPaddleHit, type PaddleGlMap, usePaddleLayerGL } from '../Tours/paddle/usePaddleLayerGL';
|
||||
import { OWN_LAYER_PREFIXES } from './glRasterLayers';
|
||||
|
||||
/**
|
||||
@@ -115,3 +115,12 @@ export function useTourMapLayersGL(
|
||||
useRasterOverlaysGL(map, overlays);
|
||||
usePaddleLayerGL(map as unknown as PaddleGlMap | null, paddle);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a click at `point` landed on an object of the tour layers, a via
|
||||
* ferrata or a paddle obstacle. The maps ask this before their own click
|
||||
* handler, so picking one opens its card instead of also setting a waypoint.
|
||||
*/
|
||||
export function isTourLayerHit<Point>(map: Parameters<typeof isFerrataHit<Point>>[0], point: Point): boolean {
|
||||
return isFerrataHit(map, point) || isPaddleHit(map, point);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { useEffect, type RefObject } from 'react';
|
||||
|
||||
/**
|
||||
* Closes a card floating over the map on a press anywhere outside it and on
|
||||
* Escape, while it is open. The press outside is handed to `onOutsidePress`
|
||||
* as well, so the map under it can leave the click that follows alone (see
|
||||
* `useOutsidePressGuard`). A press on another object closes this card first,
|
||||
* and the click then opens that object's.
|
||||
*/
|
||||
export function useMapCardDismiss(
|
||||
ref: RefObject<HTMLElement | null>,
|
||||
open: boolean,
|
||||
onClose: () => void,
|
||||
onOutsidePress?: () => void
|
||||
): void {
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onDown = (event: PointerEvent) => {
|
||||
const card = ref.current;
|
||||
if (card && event.target instanceof Node && card.contains(event.target)) return;
|
||||
onOutsidePress?.();
|
||||
onClose();
|
||||
};
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape' && !event.defaultPrevented) onClose();
|
||||
};
|
||||
document.addEventListener('pointerdown', onDown, true);
|
||||
document.addEventListener('keydown', onKey);
|
||||
return () => {
|
||||
document.removeEventListener('pointerdown', onDown, true);
|
||||
document.removeEventListener('keydown', onKey);
|
||||
};
|
||||
}, [open, onClose, onOutsidePress, ref]);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { render, screen } from '../../../tests/helpers/render';
|
||||
import TourWorkspaceRail from './TourWorkspaceRail';
|
||||
import TourWorkspaceRail, { type TourWorkspaceRailParts } from './TourWorkspaceRail';
|
||||
import type { GpxConversion } from './conversion/useGpxConversion';
|
||||
import type { TourPlannerController } from './planner/useTourPlanner';
|
||||
import type { RecordedTrack } from './useRecordedTrack';
|
||||
@@ -23,18 +23,13 @@ function wanderer(overrides: Partial<WandererBrowser>): WandererBrowser {
|
||||
return { open: false, enabled: true, openBrowser: vi.fn(), ...overrides } as unknown as WandererBrowser;
|
||||
}
|
||||
|
||||
function workspace(browser: WandererBrowser): TourWorkspaceRailParts {
|
||||
return { tourPlanner: planner, wandererBrowser: browser, tourConversion: conversion, recordedTrack };
|
||||
}
|
||||
|
||||
describe('TourWorkspaceRail', () => {
|
||||
it('RS-04: shows the wanderer trails in place of the editor while they are browsed', () => {
|
||||
render(
|
||||
<TourWorkspaceRail
|
||||
planner={planner}
|
||||
wanderer={wanderer({ open: true })}
|
||||
conversion={conversion}
|
||||
recordedTrack={recordedTrack}
|
||||
canEdit
|
||||
canAssign
|
||||
/>
|
||||
);
|
||||
render(<TourWorkspaceRail workspace={workspace(wanderer({ open: true }))} canEdit canAssign />);
|
||||
expect(screen.getByText('wanderer trails')).toBeInTheDocument();
|
||||
expect(screen.queryByText('tour editor')).not.toBeInTheDocument();
|
||||
});
|
||||
@@ -42,16 +37,7 @@ describe('TourWorkspaceRail', () => {
|
||||
it('RS-04: offers the wanderer trails from the editor only while wanderer may be used', () => {
|
||||
const browser = wanderer({});
|
||||
seen.rail.length = 0;
|
||||
const view = render(
|
||||
<TourWorkspaceRail
|
||||
planner={planner}
|
||||
wanderer={browser}
|
||||
conversion={conversion}
|
||||
recordedTrack={recordedTrack}
|
||||
canEdit
|
||||
canAssign={false}
|
||||
/>
|
||||
);
|
||||
const view = render(<TourWorkspaceRail workspace={workspace(browser)} canEdit canAssign={false} />);
|
||||
expect(screen.getByText('tour editor')).toBeInTheDocument();
|
||||
expect(seen.rail[seen.rail.length - 1]).toMatchObject({
|
||||
planner,
|
||||
@@ -62,16 +48,7 @@ describe('TourWorkspaceRail', () => {
|
||||
onOpenWanderer: browser.openBrowser,
|
||||
});
|
||||
|
||||
view.rerender(
|
||||
<TourWorkspaceRail
|
||||
planner={planner}
|
||||
wanderer={wanderer({ enabled: false })}
|
||||
conversion={conversion}
|
||||
recordedTrack={recordedTrack}
|
||||
canEdit
|
||||
canAssign
|
||||
/>
|
||||
);
|
||||
view.rerender(<TourWorkspaceRail workspace={workspace(wanderer({ enabled: false }))} canEdit canAssign />);
|
||||
expect(seen.rail[seen.rail.length - 1]?.onOpenWanderer).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,38 +1,40 @@
|
||||
import type { GpxConversion } from './conversion/useGpxConversion';
|
||||
import type { TrackPaddlePlan } from './paddle/useTrackPaddlePlan';
|
||||
import { TourPlannerRail } from './planner/TourPlannerPanels';
|
||||
import type { TourPlannerController } from './planner/useTourPlanner';
|
||||
import type { TrackPaddlePlan } from './paddle/useTrackPaddlePlan';
|
||||
import type { RecordedTrack } from './useRecordedTrack';
|
||||
import WandererBrowserRail from './wanderer/WandererBrowserRail';
|
||||
import type { WandererBrowser } from './wanderer/useWandererBrowser';
|
||||
|
||||
/** The tours workspace's left rail: the tour editor, or the wanderer trails while those are browsed. */
|
||||
export default function TourWorkspaceRail({
|
||||
planner,
|
||||
wanderer,
|
||||
conversion,
|
||||
recordedTrack,
|
||||
trackPaddlePlan,
|
||||
canEdit,
|
||||
canAssign,
|
||||
}: {
|
||||
planner: TourPlannerController;
|
||||
wanderer: WandererBrowser;
|
||||
conversion: GpxConversion;
|
||||
/** What the tours workspace hands its left rail: the parts of the planner page's state, by their names there. */
|
||||
export interface TourWorkspaceRailParts {
|
||||
tourPlanner: TourPlannerController;
|
||||
wandererBrowser: WandererBrowser;
|
||||
tourConversion: GpxConversion;
|
||||
recordedTrack: RecordedTrack;
|
||||
/** The portages and locks of a recorded paddle track in view. */
|
||||
trackPaddlePlan?: TrackPaddlePlan;
|
||||
}
|
||||
|
||||
/** The tours workspace's left rail: the tour editor, or the wanderer trails while those are browsed. */
|
||||
export default function TourWorkspaceRail({
|
||||
workspace,
|
||||
canEdit,
|
||||
canAssign,
|
||||
}: {
|
||||
workspace: TourWorkspaceRailParts;
|
||||
canEdit: boolean;
|
||||
canAssign: boolean;
|
||||
}) {
|
||||
const { tourPlanner, wandererBrowser: wanderer, tourConversion, recordedTrack, trackPaddlePlan } = workspace;
|
||||
return wanderer.open ? (
|
||||
<WandererBrowserRail browser={wanderer} />
|
||||
) : (
|
||||
<TourPlannerRail
|
||||
planner={planner}
|
||||
planner={tourPlanner}
|
||||
canEdit={canEdit}
|
||||
canAssign={canAssign}
|
||||
conversion={conversion}
|
||||
conversion={tourConversion}
|
||||
recordedTrack={recordedTrack}
|
||||
trackPaddlePlan={trackPaddlePlan}
|
||||
onOpenWanderer={wanderer.enabled ? wanderer.openBrowser : undefined}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import { Tooltip } from '../../shared/Tooltip';
|
||||
|
||||
/**
|
||||
* A figure as a badge holding its value as a white badge, the planner's
|
||||
* badge-in-badge look: the wind of the day, a weir's height, an access rule.
|
||||
* What it means exactly can sit in its tooltip.
|
||||
*/
|
||||
export function FigureBadge({
|
||||
label,
|
||||
value,
|
||||
icon,
|
||||
info,
|
||||
tone = 'neutral',
|
||||
testId,
|
||||
}: {
|
||||
label?: string;
|
||||
value: string;
|
||||
icon?: ReactNode;
|
||||
info?: string;
|
||||
/** `warning` colours the value: a rule that forbids, a way recorded as private. */
|
||||
tone?: 'neutral' | 'warning';
|
||||
testId?: string;
|
||||
}) {
|
||||
const badge = (
|
||||
<span
|
||||
data-testid={testId}
|
||||
className="inline-flex h-[24px] min-w-0 flex-none items-center gap-1 whitespace-nowrap rounded-full bg-surface-secondary pe-[3px] ps-[3px] text-content-muted"
|
||||
style={fs(10.5, 'body')}
|
||||
>
|
||||
{label && <span className="ps-1">{label}</span>}
|
||||
<span
|
||||
className={`inline-flex h-[18px] min-w-0 flex-none items-center gap-1 rounded-full bg-surface-card px-1.5 font-geist font-semibold tabular-nums shadow-sm ${tone === 'warning' ? 'text-warning' : 'text-content'}`}
|
||||
style={fs(11)}
|
||||
>
|
||||
{icon}
|
||||
<span className="truncate">{value}</span>
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
return info ? <Tooltip label={info}>{badge}</Tooltip> : badge;
|
||||
}
|
||||
@@ -1,8 +1,14 @@
|
||||
import L from 'leaflet';
|
||||
import { useMemo } from 'react';
|
||||
import { Marker, Polyline, Tooltip } from 'react-leaflet';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Marker, Polyline, Tooltip, useMap, useMapEvents } from 'react-leaflet';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { markerSize, paddleMarkerHtml, type PaddleMapItem, type PaddleMapLayer } from './paddleMapLayer';
|
||||
import {
|
||||
markerSize,
|
||||
paddleItemsAtZoom,
|
||||
paddleMarkerHtml,
|
||||
type PaddleMapItem,
|
||||
type PaddleMapLayer,
|
||||
} from './paddleMapLayer';
|
||||
|
||||
const LINE_WEIGHT = { on_route: 4, near: 3, area: 2 } as const;
|
||||
const LINE_OPACITY = { on_route: 1, near: 0.85, area: 0.5 } as const;
|
||||
@@ -30,13 +36,18 @@ function useLabel() {
|
||||
* The paddle obstacles on the Leaflet map (PAD-05B): each line on a white
|
||||
* casing in its category's colour, dashed while it is only near the route,
|
||||
* and a round marker with its glyph; the quieter, the less it bears on the
|
||||
* route. A click picks the object and goes no further, so it never also sets
|
||||
* a waypoint under it.
|
||||
* route, and the objects only in the area wait for a closer zoom. A click
|
||||
* picks the object and goes no further, so it never also sets a waypoint
|
||||
* under it.
|
||||
*/
|
||||
export function PaddleLayerLeaflet({ layer }: { layer?: PaddleMapLayer }) {
|
||||
const label = useLabel();
|
||||
const items = layer?.items;
|
||||
const map = useMap();
|
||||
const [zoom, setZoom] = useState(() => map.getZoom());
|
||||
useMapEvents({ zoomend: () => setZoom(map.getZoom()) });
|
||||
const selectedRef = layer?.selectedRef ?? null;
|
||||
const all = layer?.items;
|
||||
const items = useMemo(() => (all ? paddleItemsAtZoom(all, zoom, selectedRef) : undefined), [all, zoom, selectedRef]);
|
||||
// Rebuilt only when the items or the selection change, not on every render of the map.
|
||||
const icons = useMemo(
|
||||
() => new Map((items ?? []).map((item) => [item.feature.ref, iconOf(item, item.feature.ref === selectedRef)])),
|
||||
@@ -56,7 +67,11 @@ export function PaddleLayerLeaflet({ layer }: { layer?: PaddleMapLayer }) {
|
||||
<Polyline
|
||||
key={`${item.feature.ref}-casing`}
|
||||
positions={item.line}
|
||||
pathOptions={{ color: '#ffffff', weight: LINE_WEIGHT[item.relation] + 3, opacity: LINE_OPACITY[item.relation] }} // theme-lint-disable map casing
|
||||
pathOptions={{
|
||||
color: item.disc,
|
||||
weight: LINE_WEIGHT[item.relation] + 3,
|
||||
opacity: LINE_OPACITY[item.relation],
|
||||
}}
|
||||
interactive={false}
|
||||
/>
|
||||
) : null
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
import { ExternalLink, X } from 'lucide-react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { useSettingsStore } from '../../../store/settingsStore';
|
||||
import type { DistanceUnit } from '../../../types';
|
||||
import { formatDistance } from '../../../utils/units';
|
||||
import { MAP_CARD_GLASS } from '../../Map/mapControlShadow';
|
||||
import { SoftPill } from '../../Planner/planParts';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import { FigureBadge } from './FigureBadge';
|
||||
import { PaddleGlyph } from './PaddleGlyph';
|
||||
import { OBSTACLE_GLYPH } from './paddleGlyphPaths';
|
||||
import { KNOWN_ACCESS_VALUES, metresOf, osmUrlOf, type PaddleObstacleDetail } from './paddleObstacleModel';
|
||||
import { paddleKindCss } from './paddlePaint';
|
||||
|
||||
const ACCESS_KEYS: readonly string[] = KNOWN_ACCESS_VALUES;
|
||||
|
||||
/** How the object stands to the route: on it at a distance along it, near it and uncertain, or only in the area. */
|
||||
function RelationBadges({ detail, unit }: { detail: PaddleObstacleDetail; unit: DistanceUnit }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="mt-2 flex flex-wrap items-center gap-1.5" data-testid="paddle-obstacle-relation">
|
||||
{detail.relation === 'on_route' && (
|
||||
<FigureBadge
|
||||
label={t('tours.paddle.obstacleCard.onRoute')}
|
||||
value={formatDistance((detail.alongM ?? 0) / 1000, unit)}
|
||||
info={t('tours.paddle.obstacleCard.alongInfo')}
|
||||
/>
|
||||
)}
|
||||
{detail.relation === 'near' && (
|
||||
<>
|
||||
<FigureBadge
|
||||
label={t('tours.paddle.obstacleCard.near')}
|
||||
value={formatDistance((detail.distanceM ?? 0) / 1000, unit)}
|
||||
info={t('tours.paddle.obstacleCard.distanceInfo')}
|
||||
/>
|
||||
<SoftPill>{t('tours.paddle.obstacleCard.uncertain')}</SoftPill>
|
||||
</>
|
||||
)}
|
||||
{detail.relation === 'area' && <SoftPill>{t('tours.paddle.obstacleCard.area')}</SoftPill>}
|
||||
{detail.privateWay && <SoftPill tone="warning">{t('tours.paddle.obstacleCard.privateWay')}</SoftPill>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The paddling rule the tags give (canoe read before boat), its condition as written, and the facts worth knowing. */
|
||||
function AccessAndFacts({ detail, unit }: { detail: PaddleObstacleDetail; unit: DistanceUnit }) {
|
||||
const { t } = useTranslation();
|
||||
const { access } = detail;
|
||||
const accessValue = (value: string) =>
|
||||
ACCESS_KEYS.includes(value) ? t(`tours.paddle.obstacleCard.accessValue.${value}`) : value;
|
||||
const factValue = (key: string, value: string) => {
|
||||
const metres = key === 'height' || key === 'width' ? metresOf(value) : null;
|
||||
return metres === null ? value : formatDistance(metres / 1000, unit);
|
||||
};
|
||||
const ruled = access.source !== null && access.value !== null;
|
||||
return (
|
||||
<div className="mt-1.5 flex flex-wrap items-center gap-1.5" data-testid="paddle-obstacle-access">
|
||||
{ruled && (
|
||||
<FigureBadge
|
||||
label={t(`tours.paddle.obstacleCard.access.${access.source ?? 'access'}`)}
|
||||
value={accessValue(access.value ?? '')}
|
||||
tone={access.forbidden || access.private ? 'warning' : 'neutral'}
|
||||
/>
|
||||
)}
|
||||
{!ruled && !access.condition && <SoftPill>{t('tours.paddle.obstacleCard.noAccessInfo')}</SoftPill>}
|
||||
{access.condition && (
|
||||
<FigureBadge
|
||||
label={t('tours.paddle.obstacleCard.condition')}
|
||||
value={access.condition}
|
||||
info={access.condition}
|
||||
/>
|
||||
)}
|
||||
{detail.facts.map((fact) => (
|
||||
<FigureBadge
|
||||
key={fact.key}
|
||||
label={t(`tours.paddle.obstacleCard.fact.${fact.key === 'whitewater:section_grade' ? 'grade' : fact.key}`)}
|
||||
value={factValue(fact.key, fact.value)}
|
||||
info={fact.value}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The way to the source and how current it is; a record in the data is no check on site. */
|
||||
function SourceLines({ detail }: { detail: PaddleObstacleDetail }) {
|
||||
const { t, language } = useTranslation();
|
||||
const date = detail.dataAsOf ? new Date(detail.dataAsOf).toLocaleDateString(language, { dateStyle: 'medium' }) : null;
|
||||
return (
|
||||
<>
|
||||
<a
|
||||
href={osmUrlOf(detail.feature.ref)}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="mt-3 inline-flex items-center gap-1 font-medium text-content hover:underline"
|
||||
style={fs(12, 'body')}
|
||||
>
|
||||
{t('ferratas.viewInOsm')}
|
||||
<ExternalLink size={13} aria-hidden="true" />
|
||||
</a>
|
||||
<p className="mt-2 border-t border-edge-faint pt-2 text-content-faint" style={fs(9)}>
|
||||
{date ? t('tours.paddle.obstacleCard.source', { date }) : t('tours.paddle.obstacleCard.sourceUndated')}{' '}
|
||||
{t('ferratas.attribution')}
|
||||
</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* One paddle object picked on the map or in the checklist (PAD-05B), in the
|
||||
* look of the via ferrata card: what it is, how it stands to the route (an
|
||||
* object only near it is said to be uncertain, never on it), the paddling
|
||||
* rule its tags give with canoe read before boat, the facts worth knowing,
|
||||
* and where the data comes from and how current it is. A missing rule reads
|
||||
* as unknown, never as allowed; the card says it is data, not a check on site.
|
||||
* `children` takes what the checklist adds below the facts.
|
||||
*/
|
||||
export default function PaddleObstacleCard({
|
||||
detail,
|
||||
onClose,
|
||||
width,
|
||||
children,
|
||||
}: {
|
||||
detail: PaddleObstacleDetail;
|
||||
onClose?: () => void;
|
||||
width?: number;
|
||||
children?: ReactNode;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const unit = useSettingsStore((s) => s.settings.distance_unit) ?? 'metric';
|
||||
const { feature } = detail;
|
||||
const kind = t(`tours.paddle.obstacle.kind.${feature.kind}`);
|
||||
const color = paddleKindCss(feature.kind);
|
||||
return (
|
||||
<article
|
||||
className={`rounded-2xl p-3 text-content ${width ? '' : 'w-max min-w-[min(18rem,calc(100vw_-_2rem))] max-w-[22.5rem]'}`}
|
||||
style={{ ...MAP_CARD_GLASS, width }}
|
||||
data-testid="paddle-obstacle-card"
|
||||
>
|
||||
<div className="flex items-start gap-2">
|
||||
<span
|
||||
className="grid h-7 w-7 flex-none place-items-center rounded-full bg-surface-card shadow-sm"
|
||||
style={{ color, boxShadow: `inset 0 0 0 2px ${color}` }}
|
||||
>
|
||||
<PaddleGlyph kind={OBSTACLE_GLYPH[feature.kind]} size={15} strokeWidth={2.3} />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<h3 className="line-clamp-2 break-words font-semibold" style={fs(14, 'body')} title={feature.name ?? kind}>
|
||||
{feature.name ?? kind}
|
||||
</h3>
|
||||
{feature.name && <p className="truncate text-caption text-content-muted">{kind}</p>}
|
||||
</div>
|
||||
{onClose && (
|
||||
<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>
|
||||
<RelationBadges detail={detail} unit={unit} />
|
||||
<AccessAndFacts detail={detail} unit={unit} />
|
||||
{detail.note && (
|
||||
<p className="mt-2 line-clamp-3 break-words text-content-muted" style={fs(11.5, 'body')} title={detail.note}>
|
||||
{detail.note}
|
||||
</p>
|
||||
)}
|
||||
{children}
|
||||
<SourceLines detail={detail} />
|
||||
</article>
|
||||
);
|
||||
}
|
||||
@@ -5,21 +5,31 @@ import { usePaddleObstacleStore } from '../../../store/paddleObstacleStore';
|
||||
import { TourNotice } from '../tourParts';
|
||||
|
||||
/** The oldest data date among the regions, as a short local date; the route is only as current as its oldest part. */
|
||||
function dataDate(regions: readonly { source_timestamp?: string | null }[], language: string): string {
|
||||
const times = regions.map((region) => region.source_timestamp).filter((time): time is string => !!time).sort();
|
||||
return times[0] ? new Date(times[0]).toLocaleDateString(language, { dateStyle: 'medium' }) : '';
|
||||
function dataDate(regions: readonly { source_timestamp?: string | null }[], language: string): string | null {
|
||||
const times = regions
|
||||
.map((region) => region.source_timestamp)
|
||||
.filter((time): time is string => !!time)
|
||||
.sort();
|
||||
return times[0] ? new Date(times[0]).toLocaleDateString(language, { dateStyle: 'medium' }) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* PAD-05B: what TREK knows about the water along the route, in one line under
|
||||
* the boat fields. It never reads as an all-clear: covered or not, the
|
||||
* paddler checks the water, and where nothing is known it says so instead of
|
||||
* leaving an empty map to be read as open water.
|
||||
* the boat fields and in the recorded track's rail. It never reads as an
|
||||
* all-clear: covered or not, the paddler checks the water, where nothing is
|
||||
* known it says so instead of leaving an empty map to be read as open water,
|
||||
* and an answer cut at its limit says that more is there.
|
||||
*/
|
||||
export function PaddleObstacleNotice() {
|
||||
const { t, language } = useTranslation();
|
||||
const { status, coverage, related, regions } = usePaddleObstacleStore(
|
||||
useShallow((state) => ({ status: state.status, coverage: state.coverage, related: state.related, regions: state.regions }))
|
||||
const { status, coverage, related, regions, truncated } = usePaddleObstacleStore(
|
||||
useShallow((state) => ({
|
||||
status: state.status,
|
||||
coverage: state.coverage,
|
||||
related: state.related,
|
||||
regions: state.regions,
|
||||
truncated: state.truncated,
|
||||
}))
|
||||
);
|
||||
const warn = <AlertTriangle size={13} strokeWidth={2} />;
|
||||
if (status === 'idle' || status === 'loading') {
|
||||
@@ -29,11 +39,14 @@ export function PaddleObstacleNotice() {
|
||||
</TourNotice>
|
||||
);
|
||||
}
|
||||
if (status === 'offline') return <TourNotice icon={<WifiOff size={13} strokeWidth={2} />}>{t('tours.paddle.obstacles.offline')}</TourNotice>;
|
||||
if (status === 'offline')
|
||||
return <TourNotice icon={<WifiOff size={13} strokeWidth={2} />}>{t('tours.paddle.obstacles.offline')}</TourNotice>;
|
||||
if (status === 'error') return <TourNotice icon={warn}>{t('tours.paddle.obstacles.error')}</TourNotice>;
|
||||
const date = dataDate(regions, language);
|
||||
const date = dataDate(regions, language) ?? t('tours.paddle.obstacles.dateUnknown');
|
||||
if (coverage === 'none') return <TourNotice icon={warn}>{t('tours.paddle.obstacles.none')}</TourNotice>;
|
||||
if (coverage === 'partial') return <TourNotice icon={warn}>{t('tours.paddle.obstacles.partial', { date })}</TourNotice>;
|
||||
if (coverage === 'partial')
|
||||
return <TourNotice icon={warn}>{t('tours.paddle.obstacles.partial', { date })}</TourNotice>;
|
||||
if (truncated) return <TourNotice icon={warn}>{t('tours.paddle.obstacles.truncated')}</TourNotice>;
|
||||
return (
|
||||
<TourNotice role="status" icon={<Info size={13} strokeWidth={2} />}>
|
||||
{related.length
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { useCallback, useMemo, useRef, type ReactNode } from 'react';
|
||||
import { useShallow } from 'zustand/react/shallow';
|
||||
import { selectPaddleObstacle, usePaddleObstacleStore } from '../../../store/paddleObstacleStore';
|
||||
import { useMapCardDismiss } from '../../Map/useMapCardDismiss';
|
||||
import PaddleObstacleCard from './PaddleObstacleCard';
|
||||
import { paddleObstacleDetail, type PaddleObstacleDetail } from './paddleObstacleModel';
|
||||
|
||||
/**
|
||||
* The picked paddle object's card over the planner map (PAD-05B), where a
|
||||
* via ferrata's card sits and closing as that one does: on a press outside
|
||||
* it and on Escape, the press handed on so the map leaves its click alone.
|
||||
* The pick lives in the obstacle store, so the map and the checklist open
|
||||
* and close the same card. `extra` adds the checklist's part for the object.
|
||||
*/
|
||||
export default function PaddleObstacleOverlay({
|
||||
onOutsidePress,
|
||||
insetEnd,
|
||||
bottom,
|
||||
width,
|
||||
extra,
|
||||
}: {
|
||||
onOutsidePress?: () => void;
|
||||
insetEnd: number;
|
||||
bottom: number;
|
||||
width?: number;
|
||||
extra?: (detail: PaddleObstacleDetail) => ReactNode;
|
||||
}) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const { features, related, regions, selectedRef } = usePaddleObstacleStore(
|
||||
useShallow((state) => ({
|
||||
features: state.features,
|
||||
related: state.related,
|
||||
regions: state.regions,
|
||||
selectedRef: state.selectedRef,
|
||||
}))
|
||||
);
|
||||
const detail = useMemo(
|
||||
() => paddleObstacleDetail({ features, related, regions, selectedRef }),
|
||||
[features, related, regions, selectedRef]
|
||||
);
|
||||
const close = useCallback(() => selectPaddleObstacle(null), []);
|
||||
useMapCardDismiss(ref, !!detail, close, onOutsidePress);
|
||||
|
||||
if (!detail) 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="paddle-obstacle-overlay"
|
||||
>
|
||||
<PaddleObstacleCard detail={detail} onClose={close} width={width}>
|
||||
{extra?.(detail)}
|
||||
</PaddleObstacleCard>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,11 +1,16 @@
|
||||
import type { PaddleLayout } from '@trek/shared';
|
||||
import { useMemo } from 'react';
|
||||
import { useShallow } from 'zustand/react/shallow';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { selectPaddleObstacle, usePaddleObstacleStore } from '../../../store/paddleObstacleStore';
|
||||
import { useSettingsStore } from '../../../store/settingsStore';
|
||||
import { formatDistance } from '../../../utils/units';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import { Tooltip } from '../../shared/Tooltip';
|
||||
import { PORTAGE_LINE_COLOR } from '../planner/tourRouteStyle';
|
||||
import { PaddleGlyph } from './PaddleGlyph';
|
||||
import { OBSTACLE_GLYPH } from './paddleGlyphPaths';
|
||||
import { routeStripObstacles } from './paddleObstacleModel';
|
||||
import { paddleKindCss, PORTAGE_CSS_COLOR } from './paddlePaint';
|
||||
|
||||
/** Water in the band and in the tiles that explain it: the info blue of the theme. */
|
||||
export const WATER_COLOR = 'var(--info)';
|
||||
@@ -16,13 +21,26 @@ const MIN_SHARE = 1.5;
|
||||
/**
|
||||
* A paddle tour from put-in to take-out as one band, to scale: water in the
|
||||
* planner's blue, portages in the earth brown the map draws them in, each lock
|
||||
* a mark at its place (struck through where a portage carries round it). It
|
||||
* a mark at its place (struck through where a portage carries round it). The
|
||||
* obstacles the data knows on or near the route sit on it too, ringed in the
|
||||
* colour of their kind, dashed when only near; a click opens one's card. It
|
||||
* stands where a hike shows its elevation profile; a paddle tour has none.
|
||||
*/
|
||||
export function PaddleRouteStrip({ layout, compact = false }: { layout: PaddleLayout; compact?: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const unit = useSettingsStore((state) => state.settings.distance_unit) ?? 'metric';
|
||||
const { related, routeLengthM, selectedRef } = usePaddleObstacleStore(
|
||||
useShallow((state) => ({
|
||||
related: state.related,
|
||||
routeLengthM: state.routeLengthM,
|
||||
selectedRef: state.selectedRef,
|
||||
}))
|
||||
);
|
||||
const total = layout.totalM;
|
||||
const obstacles = useMemo(
|
||||
() => (compact ? [] : routeStripObstacles(related, routeLengthM, total)),
|
||||
[compact, related, routeLengthM, total]
|
||||
);
|
||||
if (total <= 0 || layout.stretches.length === 0) return null;
|
||||
const share = (m: number) => Math.max(MIN_SHARE, (m / total) * 100);
|
||||
const km = (m: number) => formatDistance(m / 1000, unit);
|
||||
@@ -35,13 +53,39 @@ export function PaddleRouteStrip({ layout, compact = false }: { layout: PaddleLa
|
||||
<span
|
||||
data-testid="paddle-route-strip-lock"
|
||||
className={`absolute top-1/2 z-10 grid h-4 w-4 -translate-x-1/2 -translate-y-1/2 place-items-center rounded-full bg-surface-card text-content-secondary shadow-sm ring-1 ring-edge rtl:translate-x-1/2 ${lock.bypassed ? 'opacity-45' : ''}`}
|
||||
// rtl-lint-disable the band runs from the put-in, along the line, in both directions alike
|
||||
style={{ insetInlineStart: `${(lock.atM / total) * 100}%` }}
|
||||
>
|
||||
<PaddleGlyph kind="lock" size={10} strokeWidth={2.6} />
|
||||
</span>
|
||||
</Tooltip>
|
||||
))}
|
||||
{obstacles.map((obstacle) => {
|
||||
const kind = t(`tours.paddle.obstacle.kind.${obstacle.kind}`);
|
||||
const color = paddleKindCss(obstacle.kind);
|
||||
const picked = obstacle.ref === selectedRef;
|
||||
return (
|
||||
<Tooltip
|
||||
key={obstacle.ref}
|
||||
label={`${obstacle.name ? `${kind}: ${obstacle.name}` : kind} ${km(obstacle.atM)}`}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="paddle-route-strip-obstacle"
|
||||
aria-label={obstacle.name ? `${kind}: ${obstacle.name}` : kind}
|
||||
aria-pressed={picked}
|
||||
onClick={() => selectPaddleObstacle(picked ? null : obstacle.ref)}
|
||||
className={`absolute top-1/2 grid h-4 w-4 -translate-x-1/2 -translate-y-1/2 place-items-center rounded-full bg-surface-card shadow-sm rtl:translate-x-1/2 ${picked ? 'z-30 scale-125' : 'z-20'} ${obstacle.relation === 'near' && !picked ? 'opacity-60' : ''}`}
|
||||
style={{
|
||||
insetInlineStart: `${(obstacle.atM / total) * 100}%`,
|
||||
color,
|
||||
border: `1.5px ${obstacle.relation === 'near' && !picked ? 'dashed' : 'solid'} ${color}`,
|
||||
}}
|
||||
>
|
||||
<PaddleGlyph kind={OBSTACLE_GLYPH[obstacle.kind]} size={9} strokeWidth={2.6} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
);
|
||||
})}
|
||||
<div className="flex h-2.5 w-full gap-[2px] overflow-hidden rounded-full">
|
||||
{layout.stretches.map((stretch) => {
|
||||
const land = stretch.kind === 'portage';
|
||||
@@ -57,7 +101,7 @@ export function PaddleRouteStrip({ layout, compact = false }: { layout: PaddleLa
|
||||
style={{
|
||||
flexGrow: share(length),
|
||||
flexBasis: 0,
|
||||
...(land ? { background: PORTAGE_LINE_COLOR } : {}),
|
||||
...(land ? { background: PORTAGE_CSS_COLOR } : {}),
|
||||
}}
|
||||
/>
|
||||
</Tooltip>
|
||||
|
||||
@@ -18,8 +18,8 @@ import type { TourPlannerController } from '../planner/useTourPlanner';
|
||||
import { InfoDot, RailCard, TourNotice } from '../tourParts';
|
||||
import { formatPlannedTourDuration } from '../tourPresentation';
|
||||
import { PaddleGlyph } from './PaddleGlyph';
|
||||
import { PORTAGE_CSS_COLOR } from './paddlePaint';
|
||||
import { PaddleRouteStrip, WATER_COLOR } from './PaddleRouteStrip';
|
||||
import { PORTAGE_LINE_COLOR } from '../planner/tourRouteStyle';
|
||||
|
||||
const minutes = (value: number | null) => (value === null ? '–' : formatPlannedTourDuration(value));
|
||||
|
||||
@@ -284,7 +284,7 @@ function PartTiles({
|
||||
<PartTile
|
||||
testId="paddle-time-carry"
|
||||
icon={<PaddleGlyph kind="portage" size={12} strokeWidth={2.4} />}
|
||||
color={PORTAGE_LINE_COLOR}
|
||||
color={PORTAGE_CSS_COLOR}
|
||||
label={t('tours.paddle.time.carry')}
|
||||
measures={
|
||||
<MeasureGroup
|
||||
@@ -310,7 +310,7 @@ function PartTiles({
|
||||
<PartTile
|
||||
testId="paddle-time-out-in"
|
||||
icon={<PaddleGlyph kind="take_out" size={12} strokeWidth={2.4} />}
|
||||
color={PORTAGE_LINE_COLOR}
|
||||
color={PORTAGE_CSS_COLOR}
|
||||
label={t('tours.paddle.time.outIn')}
|
||||
measures={<MeasureBadge>{`${estimate.portageCount}×`}</MeasureBadge>}
|
||||
time={minutes(estimate.portageExtraMinutes)}
|
||||
|
||||
@@ -1,17 +1,12 @@
|
||||
import {
|
||||
DEFAULT_PORTAGE_EXTRA_MINUTES,
|
||||
MAX_PADDLE_STOP_MINUTES,
|
||||
type PaddleLock,
|
||||
type PaddleRole,
|
||||
} from '@trek/shared';
|
||||
import { DEFAULT_PORTAGE_EXTRA_MINUTES, MAX_PADDLE_STOP_MINUTES, type PaddleLock, type PaddleRole } from '@trek/shared';
|
||||
import { ChevronDown, 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 { fs } from '../../shared/DialogShell';
|
||||
import { PORTAGE_LINE_COLOR } from '../planner/tourRouteStyle';
|
||||
import { PaddleGlyph } from './PaddleGlyph';
|
||||
import { PORTAGE_CSS_COLOR } from './paddlePaint';
|
||||
|
||||
const ROLE_GLYPH = { put_in: 'put_in', take_out: 'take_out', re_entry: 'put_in', final_take_out: 'take_out' } as const;
|
||||
|
||||
@@ -29,7 +24,7 @@ export function PaddleRolePill({ role }: { role: PaddleRole }) {
|
||||
kind={ROLE_GLYPH[role]}
|
||||
size={11}
|
||||
strokeWidth={2.4}
|
||||
style={land ? { color: PORTAGE_LINE_COLOR } : undefined}
|
||||
style={land ? { color: PORTAGE_CSS_COLOR } : undefined}
|
||||
/>
|
||||
{t(`tours.paddle.role.${role}`)}
|
||||
</span>
|
||||
@@ -233,7 +228,7 @@ export function PortageLegRow({
|
||||
<StopCard
|
||||
testId="tour-planner-portage-leg"
|
||||
glyph={<PaddleGlyph kind="portage" size={12} strokeWidth={2.4} />}
|
||||
color={PORTAGE_LINE_COLOR}
|
||||
color={PORTAGE_CSS_COLOR}
|
||||
title={t('tours.paddle.portage')}
|
||||
pills={
|
||||
<>
|
||||
@@ -306,7 +301,6 @@ export function LockRow({
|
||||
</>
|
||||
}
|
||||
>
|
||||
|
||||
<StopField label={t('tours.paddle.lockWait')}>
|
||||
<MinutesInput
|
||||
testId="tour-planner-lock-wait"
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { compassPointOf, type WindForecastResponse, type WindHour } from '@trek/shared';
|
||||
import { ChevronDown, RefreshCw, WifiOff, Wind } from 'lucide-react';
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { formatDate } from '../../../utils/formatters';
|
||||
import { SoftPill } from '../../Planner/planParts';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import { Tooltip } from '../../shared/Tooltip';
|
||||
import { RailCard, TourNotice } from '../tourParts';
|
||||
import { FigureBadge } from './FigureBadge';
|
||||
import { useTourWind, type TourWind } from './useTourWind';
|
||||
|
||||
type Translate = (key: string, params?: Record<string, unknown>) => string;
|
||||
@@ -45,37 +46,6 @@ function directionName(degrees: number | null, t: Translate): string | null {
|
||||
return degrees === null ? null : t(`tours.paddle.wind.dir.${compassPointOf(degrees)}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* A figure of the day as a badge holding its value as a white badge, in the
|
||||
* planner's badge-in-badge look; what it means exactly is in its tooltip.
|
||||
*/
|
||||
function DayFigure({ label, value, icon, info, testId }: {
|
||||
label?: string;
|
||||
value: string;
|
||||
icon?: ReactNode;
|
||||
info: string;
|
||||
testId: string;
|
||||
}) {
|
||||
return (
|
||||
<Tooltip label={info}>
|
||||
<span
|
||||
data-testid={testId}
|
||||
className="inline-flex h-[24px] min-w-0 flex-none items-center gap-1 rounded-full bg-surface-secondary pe-[3px] ps-[3px] text-content-muted"
|
||||
style={fs(10.5, 'body')}
|
||||
>
|
||||
{label && <span className="ps-1">{label}</span>}
|
||||
<span
|
||||
className="inline-flex h-[18px] flex-none items-center gap-1 rounded-full bg-surface-card px-1.5 font-geist font-semibold tabular-nums text-content shadow-sm"
|
||||
style={fs(11)}
|
||||
>
|
||||
{icon}
|
||||
{value}
|
||||
</span>
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The day's hours as columns: the mean wind as a bar, the gusts as the paler
|
||||
* bar behind it, an arrow the way it blows on top. An hour the source left
|
||||
@@ -108,10 +78,16 @@ function HourStrip({ hours, t }: { hours: readonly WindHour[]; t: Translate }) {
|
||||
className={`relative flex h-12 w-full items-end justify-center overflow-hidden rounded-[3px] ${known ? 'bg-surface-secondary' : 'border border-dashed border-edge'}`}
|
||||
>
|
||||
{hour.gusts_kmh !== null && (
|
||||
<span className="absolute inset-x-0 bottom-0 bg-info-soft" style={{ height: height(hour.gusts_kmh) }} />
|
||||
<span
|
||||
className="absolute inset-x-0 bottom-0 bg-info-soft"
|
||||
style={{ height: height(hour.gusts_kmh) }}
|
||||
/>
|
||||
)}
|
||||
{known && (
|
||||
<span className="relative w-full rounded-t-[2px] bg-info" style={{ height: height(hour.speed_kmh) }} />
|
||||
<span
|
||||
className="relative w-full rounded-t-[2px] bg-info"
|
||||
style={{ height: height(hour.speed_kmh) }}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
<span className="font-geist tabular-nums text-content-faint" style={fs(9.5)}>
|
||||
@@ -134,20 +110,20 @@ function Forecast({ forecast, t, locale }: { forecast: WindForecastResponse; t:
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex flex-wrap gap-1">
|
||||
{from !== null && (
|
||||
<DayFigure
|
||||
<FigureBadge
|
||||
testId="paddle-wind-direction"
|
||||
value={directionName(from, t) ?? ''}
|
||||
icon={<FlowArrow from={from} size={11} />}
|
||||
info={t('tours.paddle.wind.fromInfo', { direction: directionName(from, t) ?? '' })}
|
||||
/>
|
||||
)}
|
||||
<DayFigure
|
||||
<FigureBadge
|
||||
testId="paddle-wind-mean"
|
||||
label={t('tours.paddle.wind.mean')}
|
||||
value={day?.speed_max_kmh == null ? '–' : `${day.speed_max_kmh} km/h`}
|
||||
info={t('tours.paddle.wind.meanInfo')}
|
||||
/>
|
||||
<DayFigure
|
||||
<FigureBadge
|
||||
testId="paddle-wind-gusts"
|
||||
label={t('tours.paddle.wind.gusts')}
|
||||
value={day?.gusts_max_kmh == null ? '–' : `${day.gusts_max_kmh} km/h`}
|
||||
@@ -198,8 +174,9 @@ function Unavailable({ wind, t, locale }: { wind: TourWind; t: Translate; locale
|
||||
</TourNotice>
|
||||
);
|
||||
}
|
||||
const key = state.kind === 'ready' ? 'tours.paddle.wind.past' : `tours.paddle.wind.${state.kind}`;
|
||||
return <TourNotice icon={<Wind size={13} strokeWidth={2} />}>{t(key)}</TourNotice>;
|
||||
// A day without a forecast to ask for: past, not on a day, a day without a date, a tour without a start.
|
||||
const notice = state.kind === 'ready' ? t('tours.paddle.wind.past') : t(`tours.paddle.wind.${state.kind}`);
|
||||
return <TourNotice icon={<Wind size={13} strokeWidth={2} />}>{notice}</TourNotice>;
|
||||
}
|
||||
|
||||
/** What wind means for a paddler, in general terms; it rates no passage and clears nothing. */
|
||||
@@ -215,7 +192,11 @@ function WindHints({ t }: { t: Translate }) {
|
||||
style={fs(11.5, 'body')}
|
||||
>
|
||||
<span className="min-w-0 flex-1 truncate">{t('tours.paddle.wind.hintsTitle')}</span>
|
||||
<ChevronDown size={13} strokeWidth={2.2} className={`flex-none transition-transform ${open ? 'rotate-180' : ''}`} />
|
||||
<ChevronDown
|
||||
size={13}
|
||||
strokeWidth={2.2}
|
||||
className={`flex-none transition-transform ${open ? 'rotate-180' : ''}`}
|
||||
/>
|
||||
</button>
|
||||
{open && (
|
||||
<ul className="m-0 mt-2 flex list-disc flex-col gap-1.5 ps-4 text-content-muted" style={fs(11.5, 'body')}>
|
||||
@@ -263,7 +244,11 @@ export function PaddleWindCard({ wind }: { wind: TourWind }) {
|
||||
}
|
||||
>
|
||||
<div data-testid="paddle-wind-card" className="flex flex-col gap-3">
|
||||
{ready ? <Forecast forecast={ready} t={t} locale={locale} /> : <Unavailable wind={wind} t={t} locale={locale} />}
|
||||
{ready ? (
|
||||
<Forecast forecast={ready} t={t} locale={locale} />
|
||||
) : (
|
||||
<Unavailable wind={wind} t={t} locale={locale} />
|
||||
)}
|
||||
<WindHints t={t} />
|
||||
</div>
|
||||
</RailCard>
|
||||
@@ -271,7 +256,13 @@ export function PaddleWindCard({ wind }: { wind: TourWind }) {
|
||||
}
|
||||
|
||||
/** The wind card for one tour: its days read from the trip, its start as the place the forecast is for. */
|
||||
export function PaddleWindSection({ placeId, start }: { placeId: number | null; start: { lat: number; lng: number } | null }) {
|
||||
export function PaddleWindSection({
|
||||
placeId,
|
||||
start,
|
||||
}: {
|
||||
placeId: number | null;
|
||||
start: { lat: number; lng: number } | null;
|
||||
}) {
|
||||
const wind = useTourWind(placeId, start);
|
||||
return <PaddleWindCard wind={wind} />;
|
||||
}
|
||||
|
||||
@@ -69,10 +69,7 @@ function TrackMarksCard({ plan }: { plan: TrackPaddlePlan }) {
|
||||
const pick = (kind: TrackPick) => () => plan.startPick(kind);
|
||||
const empty = plan.marks.portages.length === 0 && plan.marks.locks.length === 0;
|
||||
return (
|
||||
<RailCard
|
||||
icon={<PaddleGlyph kind="portage" size={14} />}
|
||||
title={t('tours.paddle.marks.title')}
|
||||
>
|
||||
<RailCard icon={<PaddleGlyph kind="portage" size={14} />} title={t('tours.paddle.marks.title')}>
|
||||
<div data-testid="track-marks-card" className="flex flex-col gap-2.5">
|
||||
{plan.canEdit && (
|
||||
<div className="flex gap-1.5">
|
||||
@@ -97,7 +94,10 @@ function TrackMarksCard({ plan }: { plan: TrackPaddlePlan }) {
|
||||
</div>
|
||||
)}
|
||||
{hint && (
|
||||
<TourNotice tone={plan.refused ? 'warning' : 'neutral'} icon={<MousePointerClick size={13} strokeWidth={2} />}>
|
||||
<TourNotice
|
||||
tone={plan.refused ? 'warning' : 'neutral'}
|
||||
icon={<MousePointerClick size={13} strokeWidth={2} />}
|
||||
>
|
||||
{hint}
|
||||
</TourNotice>
|
||||
)}
|
||||
|
||||
@@ -5,16 +5,7 @@ import type { PaddleObstacleKind } from '@trek/shared';
|
||||
* React glyph and the map markers (Leaflet takes markup, not components).
|
||||
*/
|
||||
export type PaddleGlyphKind =
|
||||
| 'lock'
|
||||
| 'weir'
|
||||
| 'dam'
|
||||
| 'rapids'
|
||||
| 'waterfall'
|
||||
| 'put_in'
|
||||
| 'take_out'
|
||||
| 'portage'
|
||||
| 'hazard'
|
||||
| 'access';
|
||||
'lock' | 'weir' | 'dam' | 'rapids' | 'waterfall' | 'put_in' | 'take_out' | 'portage' | 'hazard' | 'access';
|
||||
|
||||
const WAVE = 'M3 18c1.5-1.5 3-1.5 4.5 0s3 1.5 4.5 0 3-1.5 4.5 0 3 1.5 4.5 0';
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { PaddleFeature, PaddleObstacleKind, RelatedObstacle } from '@trek/shared';
|
||||
import type { PaddleFeature, RelatedObstacle } from '@trek/shared';
|
||||
import { OBSTACLE_GLYPH, PADDLE_GLYPH_PATHS, paddleGlyphSvg, type PaddleGlyphKind } from './paddleGlyphPaths';
|
||||
import { paddleKindPaint, type PaddlePaint } from './paddlePaint';
|
||||
|
||||
/**
|
||||
* PAD-05B: the paddle obstacles as the planner maps draw them, one model for
|
||||
@@ -10,34 +11,15 @@ import { OBSTACLE_GLYPH, PADDLE_GLYPH_PATHS, paddleGlyphSvg, type PaddleGlyphKin
|
||||
*/
|
||||
|
||||
export type PaddleMapRelation = 'on_route' | 'near' | 'area';
|
||||
type Category = 'obstacle' | 'access' | 'landing' | 'portage';
|
||||
|
||||
const CATEGORY: Record<PaddleObstacleKind, Category> = {
|
||||
weir: 'obstacle',
|
||||
dam: 'obstacle',
|
||||
lock: 'obstacle',
|
||||
lock_gate: 'obstacle',
|
||||
waterfall: 'obstacle',
|
||||
rapids: 'obstacle',
|
||||
hazard: 'obstacle',
|
||||
access: 'access',
|
||||
put_in: 'landing',
|
||||
egress: 'landing',
|
||||
slipway: 'landing',
|
||||
portage: 'portage',
|
||||
};
|
||||
|
||||
export const CATEGORY_COLOR: Record<Category, string> = {
|
||||
obstacle: '#334155', // theme-lint-disable map colour
|
||||
access: '#4338ca', // theme-lint-disable map colour
|
||||
landing: '#0f766e', // theme-lint-disable map colour
|
||||
portage: '#9a6233', // theme-lint-disable map colour
|
||||
};
|
||||
|
||||
export interface PaddleMapItem {
|
||||
feature: PaddleFeature;
|
||||
relation: PaddleMapRelation;
|
||||
/** Its kind's colour, resolved for map paint. */
|
||||
color: string;
|
||||
/** The marker's disc and the lines' casing, in the map's own white (or dark). */
|
||||
disc: string;
|
||||
shadow: string;
|
||||
glyph: PaddleGlyphKind;
|
||||
/** Where its marker sits: the point itself, or the middle of its line. */
|
||||
marker: [number, number];
|
||||
@@ -65,14 +47,20 @@ function markerOf(feature: PaddleFeature, line: [number, number][] | null): [num
|
||||
}
|
||||
|
||||
/** The items to draw: the related ones as they stand to the route, the rest of the area quietly. */
|
||||
export function paddleMapItems(features: readonly PaddleFeature[], related: readonly RelatedObstacle[]): PaddleMapItem[] {
|
||||
export function paddleMapItems(
|
||||
features: readonly PaddleFeature[],
|
||||
related: readonly RelatedObstacle[],
|
||||
paint: PaddlePaint
|
||||
): PaddleMapItem[] {
|
||||
const relations = new Map(related.map((entry) => [entry.feature.ref, entry.relation]));
|
||||
return features.map((feature) => {
|
||||
const line = lineOf(feature);
|
||||
return {
|
||||
feature,
|
||||
relation: relations.get(feature.ref) ?? 'area',
|
||||
color: CATEGORY_COLOR[CATEGORY[feature.kind]],
|
||||
color: paddleKindPaint(feature.kind, paint),
|
||||
disc: paint.disc,
|
||||
shadow: paint.shadow,
|
||||
glyph: OBSTACLE_GLYPH[feature.kind],
|
||||
marker: markerOf(feature, line),
|
||||
line,
|
||||
@@ -80,6 +68,27 @@ export function paddleMapItems(features: readonly PaddleFeature[], related: read
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Objects that are only in the area show from this zoom on, on Leaflet and GL
|
||||
* alike, so an overview of a long tour stays calm; the ones on or near the
|
||||
* route always show, and so does a picked one.
|
||||
*/
|
||||
export const PADDLE_AREA_MIN_ZOOM = 13;
|
||||
|
||||
/** Whether an item is drawn as one of the area's quiet objects, which wait for PADDLE_AREA_MIN_ZOOM. */
|
||||
export function isAreaOnly(item: PaddleMapItem, selectedRef: string | null): boolean {
|
||||
return item.relation === 'area' && item.feature.ref !== selectedRef;
|
||||
}
|
||||
|
||||
/** The items a map at `zoom` shows. */
|
||||
export function paddleItemsAtZoom(
|
||||
items: readonly PaddleMapItem[],
|
||||
zoom: number,
|
||||
selectedRef: string | null
|
||||
): PaddleMapItem[] {
|
||||
return zoom >= PADDLE_AREA_MIN_ZOOM ? [...items] : items.filter((item) => !isAreaOnly(item, selectedRef));
|
||||
}
|
||||
|
||||
/** The marker's size in pixels by how it stands to the route; a selected one is larger still. */
|
||||
export function markerSize(relation: PaddleMapRelation, selected: boolean): number {
|
||||
if (selected) return 36;
|
||||
@@ -97,7 +106,7 @@ export function paddleMarkerHtml(item: PaddleMapItem, selected: boolean): string
|
||||
const dash = item.relation === 'near' && !selected ? 'dashed' : 'solid';
|
||||
const opacity = item.relation === 'area' && !selected ? 0.6 : 1;
|
||||
const glyph = paddleGlyphSvg(item.glyph, Math.round(size * 0.58), item.color);
|
||||
const style = `width:${size}px;height:${size}px;border-radius:9999px;background:#fff;border:${ring}px ${dash} ${item.color};box-shadow:0 1px 3px rgba(15,23,42,.35);display:grid;place-items:center;box-sizing:border-box;opacity:${opacity}`; // theme-lint-disable map marker on the map's own white
|
||||
const style = `width:${size}px;height:${size}px;border-radius:9999px;background:${item.disc};border:${ring}px ${dash} ${item.color};box-shadow:0 1px 3px ${item.shadow};display:grid;place-items:center;box-sizing:border-box;opacity:${opacity}`;
|
||||
return `<div style="${style}">${glyph}</div>`;
|
||||
}
|
||||
|
||||
@@ -117,12 +126,13 @@ export function paddleMarkerSvg(item: PaddleMapItem, selected: boolean): string
|
||||
const paths = PADDLE_GLYPH_PATHS[item.glyph].map((d) => `<path d="${d}"/>`).join('');
|
||||
return (
|
||||
`<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" opacity="${opacity}">` +
|
||||
`<circle cx="${size / 2}" cy="${size / 2}" r="${r}" fill="#fff" stroke="${item.color}" stroke-width="${ring}"${dash}/>` + // theme-lint-disable marker disc
|
||||
`<circle cx="${size / 2}" cy="${size / 2}" r="${r}" fill="${item.disc}" stroke="${item.color}" stroke-width="${ring}"${dash}/>` +
|
||||
`<svg x="${offset}" y="${offset}" width="${glyph}" height="${glyph}" viewBox="0 0 24 24" fill="none" stroke="${item.color}" stroke-width="2.3" stroke-linecap="round" stroke-linejoin="round">${paths}</svg></svg>`
|
||||
);
|
||||
}
|
||||
|
||||
/** The name of a marker's image on a GL map, one per look. */
|
||||
/** The name of a marker's image on a GL map, one per look; a theme change draws new ones. */
|
||||
export function paddleMarkerImageId(item: PaddleMapItem, selected: boolean): string {
|
||||
return `trek-paddle-${item.glyph}-${item.color.slice(1)}-${item.relation}${selected ? '-sel' : ''}`;
|
||||
const tint = `${item.color}-${item.disc}`.replace(/[^a-z0-9]/gi, '');
|
||||
return `trek-paddle-${item.glyph}-${tint}-${item.relation}${selected ? '-sel' : ''}`;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import {
|
||||
PADDLE_BLOCKING_KINDS,
|
||||
paddleAccessOf,
|
||||
type PaddleAccess,
|
||||
type PaddleCoverageRegion,
|
||||
type PaddleFeature,
|
||||
type PaddleObstacleKind,
|
||||
type RelatedObstacle,
|
||||
} from '@trek/shared';
|
||||
import type { PaddleMapRelation } from './paddleMapLayer';
|
||||
|
||||
/**
|
||||
* PAD-05B: what the obstacle card and the route band show of one paddle
|
||||
* object, worked out of the obstacle store without React. Nothing here turns
|
||||
* a missing value into a permission: an object without an access tag says it
|
||||
* has none, and an object only near the route stays "near", never "on it".
|
||||
*/
|
||||
|
||||
/** The tags the card names, each with a label of its own; everything else of the kept tags stays behind. */
|
||||
export const OBSTACLE_FACT_KEYS = [
|
||||
'height',
|
||||
'width',
|
||||
'whitewater:section_grade',
|
||||
'opening_hours',
|
||||
'seasonal',
|
||||
'fee',
|
||||
'operator',
|
||||
] as const;
|
||||
export type ObstacleFactKey = (typeof OBSTACLE_FACT_KEYS)[number];
|
||||
|
||||
/** The access values the card puts into words; any other value is shown as OSM has it. */
|
||||
export const KNOWN_ACCESS_VALUES = ['yes', 'no', 'private', 'permissive', 'designated'] as const;
|
||||
|
||||
export interface PaddleObstacleDetail {
|
||||
feature: PaddleFeature;
|
||||
relation: PaddleMapRelation;
|
||||
/** Metres between the route and the object; null for an object only in the area. */
|
||||
distanceM: number | null;
|
||||
/** Metres from the start of the route to where it comes closest; null for an object only in the area. */
|
||||
alongM: number | null;
|
||||
/** The date the object's region is current to, ISO 8601; null when unknown. */
|
||||
dataAsOf: string | null;
|
||||
access: PaddleAccess;
|
||||
/** A carrying way someone recorded as private: never a way round that is open to anyone. */
|
||||
privateWay: boolean;
|
||||
facts: { key: ObstacleFactKey; value: string }[];
|
||||
/** The free text OSM holds about it, shown as written. */
|
||||
note: string | null;
|
||||
}
|
||||
|
||||
/** The object in OpenStreetMap, for the source link. */
|
||||
export function osmUrlOf(ref: string): string {
|
||||
return `https://www.openstreetmap.org/${ref}`;
|
||||
}
|
||||
|
||||
/** The one an obstacle checklist decides about: a lock's parts together, everything else on its own. */
|
||||
export function obstacleKeyOf(feature: Pick<PaddleFeature, 'ref' | 'group_key'>): string {
|
||||
return feature.group_key ?? feature.ref;
|
||||
}
|
||||
|
||||
export function isBlockingKind(kind: PaddleObstacleKind): boolean {
|
||||
return PADDLE_BLOCKING_KINDS.includes(kind);
|
||||
}
|
||||
|
||||
/** The picked object with everything the card says about it, or null when nothing (or nothing known) is picked. */
|
||||
export function paddleObstacleDetail(state: {
|
||||
features: readonly PaddleFeature[];
|
||||
related: readonly RelatedObstacle[];
|
||||
regions: readonly PaddleCoverageRegion[];
|
||||
selectedRef: string | null;
|
||||
}): PaddleObstacleDetail | null {
|
||||
const feature = state.selectedRef ? state.features.find((entry) => entry.ref === state.selectedRef) : undefined;
|
||||
if (!feature) return null;
|
||||
const related = state.related.find((entry) => entry.feature.ref === feature.ref);
|
||||
const tags = feature.tags;
|
||||
const access = paddleAccessOf(tags);
|
||||
const portageAccess = tags['portage:access'] ?? tags.access;
|
||||
return {
|
||||
feature,
|
||||
relation: related?.relation ?? 'area',
|
||||
distanceM: related ? related.distanceM : null,
|
||||
alongM: related ? related.alongM : null,
|
||||
dataAsOf: state.regions.find((region) => region.id === feature.region_id)?.source_timestamp ?? null,
|
||||
access,
|
||||
privateWay: feature.kind === 'portage' && (access.private || portageAccess === 'private'),
|
||||
facts: OBSTACLE_FACT_KEYS.flatMap((key) => {
|
||||
const value = tags[key]?.trim();
|
||||
return value ? [{ key, value }] : [];
|
||||
}),
|
||||
note: tags.description?.trim() || tags.note?.trim() || null,
|
||||
};
|
||||
}
|
||||
|
||||
export interface RouteStripObstacle {
|
||||
ref: string;
|
||||
kind: PaddleObstacleKind;
|
||||
name: string | null;
|
||||
relation: 'on_route' | 'near';
|
||||
/** Where it sits on the band, in the band's own metres. */
|
||||
atM: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The obstacles to mark on the route band: the ones a paddler has to decide
|
||||
* about, on the route or near it, placed by their share of the measured route
|
||||
* so they sit right on a band drawn to another length. Access rules run along
|
||||
* whole stretches and are left to the map and the card.
|
||||
*/
|
||||
export function routeStripObstacles(
|
||||
related: readonly RelatedObstacle[],
|
||||
measuredLengthM: number,
|
||||
bandLengthM: number
|
||||
): RouteStripObstacle[] {
|
||||
if (measuredLengthM <= 0 || bandLengthM <= 0) return [];
|
||||
return related.flatMap((entry) => {
|
||||
const { feature } = entry;
|
||||
if (feature.kind === 'access' || !isBlockingKind(feature.kind)) return [];
|
||||
const share = Math.min(1, Math.max(0, entry.alongM / measuredLengthM));
|
||||
return [
|
||||
{ ref: feature.ref, kind: feature.kind, name: feature.name, relation: entry.relation, atM: share * bandLengthM },
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
/** A length tag as a number of metres when it is one ("1.5", "2"); null for anything with its own unit or words. */
|
||||
export function metresOf(value: string): number | null {
|
||||
return /^\d+(\.\d+)?$/.test(value) ? Number(value) : null;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { PaddleObstacleKind } from '@trek/shared';
|
||||
import { useMapPaint } from '../../Map/mapPaint';
|
||||
|
||||
/**
|
||||
* The colours of paddle objects and carried stretches (styles/paddle.css):
|
||||
* a kind of object has its colour, never one for safe or unsafe. Map paint
|
||||
* reads them resolved (`usePaddlePaint`); markup on the page takes the CSS
|
||||
* variable itself (`paddleKindCss`), which follows the theme on its own.
|
||||
*/
|
||||
export const PADDLE_PAINT_TOKENS = {
|
||||
obstacle: '--map-paddle-obstacle',
|
||||
access: '--map-paddle-access',
|
||||
landing: '--map-paddle-landing',
|
||||
portage: '--map-portage',
|
||||
disc: '--map-paddle-disc',
|
||||
shadow: '--map-paddle-shadow',
|
||||
} as const;
|
||||
|
||||
export type PaddlePaint = Record<keyof typeof PADDLE_PAINT_TOKENS, string>;
|
||||
type Category = 'obstacle' | 'access' | 'landing' | 'portage';
|
||||
|
||||
const CATEGORY: Record<PaddleObstacleKind, Category> = {
|
||||
weir: 'obstacle',
|
||||
dam: 'obstacle',
|
||||
lock: 'obstacle',
|
||||
lock_gate: 'obstacle',
|
||||
waterfall: 'obstacle',
|
||||
rapids: 'obstacle',
|
||||
hazard: 'obstacle',
|
||||
access: 'access',
|
||||
put_in: 'landing',
|
||||
egress: 'landing',
|
||||
slipway: 'landing',
|
||||
portage: 'portage',
|
||||
};
|
||||
|
||||
/** The resolved colour of a kind, for map paint. */
|
||||
export function paddleKindPaint(kind: PaddleObstacleKind, paint: PaddlePaint): string {
|
||||
return paint[CATEGORY[kind]];
|
||||
}
|
||||
|
||||
/** The colour of a kind as a CSS variable, for markup on the page (the card, the route band). */
|
||||
export function paddleKindCss(kind: PaddleObstacleKind): string {
|
||||
return `var(${PADDLE_PAINT_TOKENS[CATEGORY[kind]]})`;
|
||||
}
|
||||
|
||||
/** A carried stretch's brown, for markup on the page. */
|
||||
export const PORTAGE_CSS_COLOR = `var(${PADDLE_PAINT_TOKENS.portage})`;
|
||||
|
||||
/** The paddle colours resolved for map paint, again whenever the theme changes. */
|
||||
export function usePaddlePaint(): PaddlePaint {
|
||||
return useMapPaint(PADDLE_PAINT_TOKENS);
|
||||
}
|
||||
@@ -1,15 +1,30 @@
|
||||
import type { Map } from 'mapbox-gl';
|
||||
import type { ExpressionSpecification, Map, MapMouseEvent } from 'mapbox-gl';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { markerSize, paddleMarkerImageId, paddleMarkerSvg, type PaddleMapItem, type PaddleMapLayer } from './paddleMapLayer';
|
||||
import {
|
||||
isAreaOnly,
|
||||
markerSize,
|
||||
PADDLE_AREA_MIN_ZOOM,
|
||||
paddleMarkerImageId,
|
||||
paddleMarkerSvg,
|
||||
type PaddleMapItem,
|
||||
type PaddleMapLayer,
|
||||
} from './paddleMapLayer';
|
||||
|
||||
/** One map type for both engines, as the ferrata layer has: MapLibre answers every call made here. */
|
||||
export type PaddleGlMap = Map;
|
||||
|
||||
const SOURCE = 'trek-paddle';
|
||||
const CASING = 'trek-paddle-casing';
|
||||
const CASING_AREA = 'trek-paddle-casing-area';
|
||||
const LINE = 'trek-paddle-line';
|
||||
const LINE_NEAR = 'trek-paddle-line-near';
|
||||
const LINE_AREA = 'trek-paddle-line-area';
|
||||
const PINS = 'trek-paddle-pins';
|
||||
const LAYERS = [CASING, LINE, PINS];
|
||||
const PINS_AREA = 'trek-paddle-pins-area';
|
||||
/** Bottom to top, as they are added. */
|
||||
const LAYERS = [CASING_AREA, CASING, LINE_AREA, LINE, LINE_NEAR, PINS_AREA, PINS];
|
||||
/** The layers a click can land on, the markers first. */
|
||||
const HIT_LAYERS = [PINS, PINS_AREA, LINE, LINE_NEAR, LINE_AREA];
|
||||
|
||||
const WIDTH = { on_route: 4, near: 3, area: 2 } as const;
|
||||
const OPACITY = { on_route: 1, near: 0.85, area: 0.5 } as const;
|
||||
@@ -18,6 +33,7 @@ function collection(items: readonly PaddleMapItem[], selectedRef: string | null)
|
||||
const features: GeoJSON.Feature[] = [];
|
||||
for (const item of items) {
|
||||
const selected = item.feature.ref === selectedRef;
|
||||
const area = isAreaOnly(item, selectedRef);
|
||||
if (item.line) {
|
||||
features.push({
|
||||
type: 'Feature',
|
||||
@@ -27,7 +43,9 @@ function collection(items: readonly PaddleMapItem[], selectedRef: string | null)
|
||||
color: item.color,
|
||||
width: WIDTH[item.relation],
|
||||
opacity: OPACITY[item.relation],
|
||||
near: item.relation === 'near',
|
||||
near: item.relation === 'near' && !selected,
|
||||
casing: item.disc,
|
||||
area,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -38,61 +56,112 @@ function collection(items: readonly PaddleMapItem[], selectedRef: string | null)
|
||||
ref: item.feature.ref,
|
||||
icon: paddleMarkerImageId(item, selected),
|
||||
order: selected ? 3 : item.relation === 'on_route' ? 2 : item.relation === 'near' ? 1 : 0,
|
||||
area,
|
||||
},
|
||||
});
|
||||
}
|
||||
return { type: 'FeatureCollection', features };
|
||||
}
|
||||
|
||||
/** Draws each marker look the map does not have yet; a look is an image of its own. */
|
||||
function addImages(map: PaddleGlMap, items: readonly PaddleMapItem[], selectedRef: string | null, gone: () => boolean) {
|
||||
/**
|
||||
* Draws each marker look the map does not have yet, the picked look beside the
|
||||
* plain one, so picking an object never shows a marker whose image is still
|
||||
* loading.
|
||||
*/
|
||||
function addImages(map: PaddleGlMap, items: readonly PaddleMapItem[], gone: () => boolean) {
|
||||
for (const item of items) {
|
||||
const selected = item.feature.ref === selectedRef;
|
||||
const id = paddleMarkerImageId(item, selected);
|
||||
if (map.hasImage(id)) continue;
|
||||
const image = new Image(markerSize(item.relation, selected) * 2, markerSize(item.relation, selected) * 2);
|
||||
image.onload = () => {
|
||||
if (!gone() && !map.hasImage(id)) map.addImage(id, image, { pixelRatio: 2 });
|
||||
};
|
||||
image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(paddleMarkerSvg(item, selected))}`;
|
||||
for (const selected of [false, true]) {
|
||||
const id = paddleMarkerImageId(item, selected);
|
||||
if (map.hasImage(id)) continue;
|
||||
const size = markerSize(item.relation, selected) * 2;
|
||||
const image = new Image(size, size);
|
||||
image.onload = () => {
|
||||
if (!gone() && !map.hasImage(id)) map.addImage(id, image, { pixelRatio: 2 });
|
||||
};
|
||||
image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(paddleMarkerSvg(item, selected))}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const isLine: ExpressionSpecification = ['==', ['geometry-type'], 'LineString'];
|
||||
const isPoint: ExpressionSpecification = ['==', ['geometry-type'], 'Point'];
|
||||
const inArea: ExpressionSpecification = ['==', ['get', 'area'], true];
|
||||
const notArea: ExpressionSpecification = ['!=', ['get', 'area'], true];
|
||||
const isNear: ExpressionSpecification = ['==', ['get', 'near'], true];
|
||||
const notNear: ExpressionSpecification = ['!=', ['get', 'near'], true];
|
||||
|
||||
function addLayers(map: PaddleGlMap, data: GeoJSON.FeatureCollection): void {
|
||||
map.addSource(SOURCE, { type: 'geojson', data });
|
||||
const lines: ['==', ['geometry-type'], string] = ['==', ['geometry-type'], 'LineString'];
|
||||
map.addLayer({
|
||||
const lineLayout = { 'line-cap': 'round', 'line-join': 'round' } as const;
|
||||
const casingPaint = {
|
||||
'line-color': ['get', 'casing'] as ExpressionSpecification,
|
||||
'line-width': ['+', ['get', 'width'], 3] as ExpressionSpecification,
|
||||
'line-opacity': ['get', 'opacity'] as ExpressionSpecification,
|
||||
};
|
||||
const linePaint = {
|
||||
'line-color': ['get', 'color'] as ExpressionSpecification,
|
||||
'line-width': ['get', 'width'] as ExpressionSpecification,
|
||||
'line-opacity': ['get', 'opacity'] as ExpressionSpecification,
|
||||
};
|
||||
const pinLayout = {
|
||||
'icon-image': ['get', 'icon'] as ExpressionSpecification,
|
||||
'icon-allow-overlap': true,
|
||||
'icon-ignore-placement': true,
|
||||
'symbol-sort-key': ['get', 'order'] as ExpressionSpecification,
|
||||
};
|
||||
// The objects only in the area wait for PADDLE_AREA_MIN_ZOOM; a hidden layer is also no click target.
|
||||
const area = { minzoom: PADDLE_AREA_MIN_ZOOM };
|
||||
const add = map.addLayer.bind(map);
|
||||
add({
|
||||
id: CASING_AREA,
|
||||
type: 'line',
|
||||
source: SOURCE,
|
||||
filter: ['all', isLine, inArea],
|
||||
layout: lineLayout,
|
||||
paint: casingPaint,
|
||||
...area,
|
||||
});
|
||||
add({
|
||||
id: CASING,
|
||||
type: 'line',
|
||||
source: SOURCE,
|
||||
filter: lines,
|
||||
layout: { 'line-cap': 'round', 'line-join': 'round' },
|
||||
paint: {
|
||||
'line-color': '#ffffff', // theme-lint-disable map casing
|
||||
'line-width': ['+', ['get', 'width'], 3],
|
||||
'line-opacity': ['get', 'opacity'],
|
||||
},
|
||||
filter: ['all', isLine, notArea],
|
||||
layout: lineLayout,
|
||||
paint: casingPaint,
|
||||
});
|
||||
map.addLayer({
|
||||
add({
|
||||
id: LINE_AREA,
|
||||
type: 'line',
|
||||
source: SOURCE,
|
||||
filter: ['all', isLine, inArea],
|
||||
layout: lineLayout,
|
||||
paint: linePaint,
|
||||
...area,
|
||||
});
|
||||
add({
|
||||
id: LINE,
|
||||
type: 'line',
|
||||
source: SOURCE,
|
||||
filter: lines,
|
||||
layout: { 'line-cap': 'round', 'line-join': 'round' },
|
||||
paint: { 'line-color': ['get', 'color'], 'line-width': ['get', 'width'], 'line-opacity': ['get', 'opacity'] },
|
||||
filter: ['all', isLine, notArea, notNear],
|
||||
layout: lineLayout,
|
||||
paint: linePaint,
|
||||
});
|
||||
map.addLayer({
|
||||
id: PINS,
|
||||
type: 'symbol',
|
||||
// A dash cannot follow a property, so the lines only near the route have a layer of their own, as on Leaflet.
|
||||
add({
|
||||
id: LINE_NEAR,
|
||||
type: 'line',
|
||||
source: SOURCE,
|
||||
filter: ['==', ['geometry-type'], 'Point'],
|
||||
layout: {
|
||||
'icon-image': ['get', 'icon'],
|
||||
'icon-allow-overlap': true,
|
||||
'icon-ignore-placement': true,
|
||||
'symbol-sort-key': ['get', 'order'],
|
||||
},
|
||||
filter: ['all', isLine, notArea, isNear],
|
||||
layout: lineLayout,
|
||||
paint: { ...linePaint, 'line-dasharray': [2, 1.6] },
|
||||
});
|
||||
add({ id: PINS_AREA, type: 'symbol', source: SOURCE, filter: ['all', isPoint, inArea], layout: pinLayout, ...area });
|
||||
add({ id: PINS, type: 'symbol', source: SOURCE, filter: ['all', isPoint, notArea], layout: pinLayout });
|
||||
}
|
||||
|
||||
/** The paddle layers this map has now; a style still loading or one rebuilt by a basemap change may have none. */
|
||||
function presentHitLayers(map: { getLayer?(id: string): unknown }): string[] {
|
||||
return HIT_LAYERS.filter((id) => map.getLayer?.(id));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -101,19 +170,23 @@ function addLayers(map: PaddleGlMap, data: GeoJSON.FeatureCollection): void {
|
||||
* also setting a waypoint under it.
|
||||
*/
|
||||
export function isPaddleHit<Point>(
|
||||
map: { getLayer?(id: string): unknown; queryRenderedFeatures?(point: Point, options: { layers: string[] }): unknown[] },
|
||||
map: {
|
||||
getLayer?(id: string): unknown;
|
||||
queryRenderedFeatures?(point: Point, options: { layers: string[] }): unknown[];
|
||||
},
|
||||
point: Point
|
||||
): boolean {
|
||||
if (typeof map.getLayer !== 'function' || typeof map.queryRenderedFeatures !== 'function') return false;
|
||||
const layers = [PINS, LINE].filter((id) => map.getLayer?.(id));
|
||||
const layers = presentHitLayers(map);
|
||||
return layers.length > 0 && map.queryRenderedFeatures(point, { layers }).length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* PAD-05B on a GL map (MapLibre or Mapbox, the 2D planner and the 3D
|
||||
* terrain alike): the paddle objects as lines on a white casing and as round
|
||||
* glyph markers, in the same look as on Leaflet. Kept through a basemap
|
||||
* change, which rebuilds the style and drops them, and removed with the layer.
|
||||
* glyph markers, in the same look as on Leaflet, the ones only in the area
|
||||
* from PADDLE_AREA_MIN_ZOOM on. Kept through a basemap change, which rebuilds
|
||||
* the style and drops them, and removed with the layer.
|
||||
*/
|
||||
export function usePaddleLayerGL(map: PaddleGlMap | null, layer: PaddleMapLayer | undefined) {
|
||||
const onSelect = useRef(layer?.onSelect);
|
||||
@@ -127,12 +200,16 @@ export function usePaddleLayerGL(map: PaddleGlMap | null, layer: PaddleMapLayer
|
||||
if (!map || !items?.length) return;
|
||||
let gone = false;
|
||||
const data = collection(items, selectedRef);
|
||||
let applied: GeoJSON.FeatureCollection | null = null;
|
||||
const apply = () => {
|
||||
try {
|
||||
addImages(map, items, selectedRef, () => gone);
|
||||
const source = map.getSource(SOURCE) as { setData?: (next: GeoJSON.FeatureCollection) => void } | undefined;
|
||||
// Every image the map takes fires styledata again; data already handed over is not sent twice.
|
||||
if (source?.setData && applied === data) return;
|
||||
addImages(map, items, () => gone);
|
||||
if (source?.setData) source.setData(data);
|
||||
else addLayers(map, data);
|
||||
applied = data;
|
||||
} catch {
|
||||
// A style still loading takes the layers on its next styledata event.
|
||||
}
|
||||
@@ -147,8 +224,12 @@ export function usePaddleLayerGL(map: PaddleGlMap | null, layer: PaddleMapLayer
|
||||
|
||||
useEffect(() => {
|
||||
if (!map) return;
|
||||
const click = (event: { features?: Array<{ properties?: { ref?: unknown } }> }) => {
|
||||
const ref = event.features?.[0]?.properties?.ref;
|
||||
// One handler for all of them, so a marker over a line picks the marker's object, never both.
|
||||
const click = (event: MapMouseEvent) => {
|
||||
const layers = presentHitLayers(map);
|
||||
if (layers.length === 0) return;
|
||||
const [hit] = map.queryRenderedFeatures(event.point, { layers });
|
||||
const ref: unknown = hit?.properties?.ref;
|
||||
if (typeof ref === 'string') onSelect.current?.(ref);
|
||||
};
|
||||
const enter = () => {
|
||||
@@ -157,14 +238,14 @@ export function usePaddleLayerGL(map: PaddleGlMap | null, layer: PaddleMapLayer
|
||||
const leave = () => {
|
||||
map.getCanvas().style.cursor = '';
|
||||
};
|
||||
for (const id of [PINS, LINE]) {
|
||||
map.on('click', id, click);
|
||||
map.on('click', click);
|
||||
for (const id of HIT_LAYERS) {
|
||||
map.on('mouseenter', id, enter);
|
||||
map.on('mouseleave', id, leave);
|
||||
}
|
||||
return () => {
|
||||
for (const id of [PINS, LINE]) {
|
||||
map.off('click', id, click);
|
||||
map.off('click', click);
|
||||
for (const id of HIT_LAYERS) {
|
||||
map.off('mouseenter', id, enter);
|
||||
map.off('mouseleave', id, leave);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { relateObstaclesToRoute, type PaddleCoverageState } from '@trek/shared';
|
||||
import { measuredRouteLengthM, relateObstaclesToRoute, type PaddleCoverageState } from '@trek/shared';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
PaddleObstaclesOfflineError,
|
||||
@@ -7,7 +7,11 @@ import {
|
||||
type PaddleObstaclesAround,
|
||||
type Tile,
|
||||
} from '../../../repo/paddleObstacleRepo';
|
||||
import { clearPaddleObstacles, publishPaddleObstacles, type PaddleObstacleStatus } from '../../../store/paddleObstacleStore';
|
||||
import {
|
||||
clearPaddleObstacles,
|
||||
publishPaddleObstacles,
|
||||
type PaddleObstacleStatus,
|
||||
} from '../../../store/paddleObstacleStore';
|
||||
|
||||
type Line = readonly (readonly [number, number])[];
|
||||
|
||||
@@ -59,6 +63,7 @@ export function usePaddleObstacleSync(line: Line | null, active: boolean) {
|
||||
() => (current?.data && line ? relateObstaclesToRoute(line, current.data.features) : []),
|
||||
[current, line]
|
||||
);
|
||||
const routeLengthM = useMemo(() => (line ? measuredRouteLengthM(line) : 0), [line]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!key) {
|
||||
@@ -70,11 +75,12 @@ export function usePaddleObstacleSync(line: Line | null, active: boolean) {
|
||||
status: current?.status ?? 'loading',
|
||||
features: current?.data?.features ?? [],
|
||||
related,
|
||||
routeLengthM,
|
||||
coverage,
|
||||
regions: current?.data?.regions ?? [],
|
||||
truncated: current?.data?.truncated ?? false,
|
||||
});
|
||||
}, [current, key, related]);
|
||||
}, [current, key, related, routeLengthM]);
|
||||
|
||||
useEffect(() => () => clearPaddleObstacles(), []);
|
||||
}
|
||||
|
||||
@@ -83,7 +83,11 @@ export function useTrackPaddlePlan({ tripId, planner, canEdit, onSaved }: TrackP
|
||||
if (!paddleTour || saving || !canEdit) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
const body = { paddle_speed_kmh: state.speeds.paddle, portage_speed_kmh: state.speeds.portage, track_marks: state.marks };
|
||||
const body = {
|
||||
paddle_speed_kmh: state.speeds.paddle,
|
||||
portage_speed_kmh: state.speeds.portage,
|
||||
track_marks: state.marks,
|
||||
};
|
||||
const result = await tourRepo.updatePaddlePlan(tripId, paddleTour.place_id, body);
|
||||
markTrackMarksSaved(result.tour.track_marks, {
|
||||
paddle: result.tour.paddle_speed_kmh ?? null,
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useTrackMarkToolStore } from '../../../store/trackMarkToolStore';
|
||||
import { splitTrackByPortages } from '../../../utils/paddleTrackMarks';
|
||||
import type { TourPlannerController } from '../planner/useTourPlanner';
|
||||
import type { TourRoutePart } from '../planner/tourRouting';
|
||||
import type { TourPlannerController } from '../planner/useTourPlanner';
|
||||
|
||||
/**
|
||||
* The recorded paddle track in view, cut where portages are marked on it, as
|
||||
|
||||
@@ -32,7 +32,10 @@ describe('TourTypeFields (PAD-01)', () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Lake' }));
|
||||
expect(paddleTour.paddle.setBoatType).toHaveBeenCalledWith('canoe');
|
||||
expect(paddleTour.paddle.setWaterContext).toHaveBeenCalledWith('lake');
|
||||
expect(screen.getByRole('status')).toBeInTheDocument();
|
||||
// Two notes speak here: what the tour still needs, and what is known about obstacles on the water.
|
||||
const notes = screen.getAllByRole('status').map((note) => note.textContent);
|
||||
expect(notes).toContain('Choose the boat and the water to save this paddle tour.');
|
||||
expect(notes).toContain('Loading the obstacles along the route …');
|
||||
});
|
||||
|
||||
it('reads a typed speed with either decimal separator, and an empty field as the suggestion', () => {
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
type PaddleWaterContext,
|
||||
type PlannableTourType,
|
||||
} from '@trek/shared';
|
||||
import { AlertTriangle, Info, Mountain, Waves } from 'lucide-react';
|
||||
import { Info, Mountain, Waves } from 'lucide-react';
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { SoftPill } from '../../Planner/planParts';
|
||||
|
||||
@@ -24,13 +24,13 @@ import { toggleTourPlacing, useTourPlaceToolStore } from '../../../store/tourPla
|
||||
import { formatDistance } from '../../../utils/units';
|
||||
import { FerrataGlyph } from '../../Ferratas/FerrataGlyph';
|
||||
import { SoftPill } from '../../Planner/planParts';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import { ContextMenu, useContextMenu } from '../../shared/ContextMenu';
|
||||
import { fs } from '../../shared/DialogShell';
|
||||
import { Tooltip } from '../../shared/Tooltip';
|
||||
import { RailCard, TourNotice } from '../tourParts';
|
||||
import { LockIcon, PortageIcon } from '../paddle/PaddleGlyph';
|
||||
import { LockRow, PaddleRolePill, PortageLegRow } from '../paddle/PaddleWaypointParts';
|
||||
import { usePaddleWaypointActions } from '../paddle/usePaddleWaypointActions';
|
||||
import { RailCard, TourNotice } from '../tourParts';
|
||||
import { paddlePlanPoints, paddleRolesById } from './paddlePlanOf';
|
||||
import { lineLengthM } from './tourFixedLegs';
|
||||
import type { TourPlannerController } from './useTourPlanner';
|
||||
@@ -324,7 +324,12 @@ function WaypointRowActions({
|
||||
const portage = point.fixedLeg?.kind === 'portage';
|
||||
const hasLeg = index < lastIndex;
|
||||
const items = [
|
||||
{ label: t('tours.planner.moveUp'), icon: ArrowUp, disabled: index === 0, onClick: () => planner.moveWaypoint(point.id, -1) },
|
||||
{
|
||||
label: t('tours.planner.moveUp'),
|
||||
icon: ArrowUp,
|
||||
disabled: index === 0,
|
||||
onClick: () => planner.moveWaypoint(point.id, -1),
|
||||
},
|
||||
{
|
||||
label: t('tours.planner.moveDown'),
|
||||
icon: ArrowDown,
|
||||
@@ -332,21 +337,26 @@ function WaypointRowActions({
|
||||
onClick: () => planner.moveWaypoint(point.id, 1),
|
||||
},
|
||||
...(!planner.isPaddle && hasLeg && point.fixedLeg?.kind !== 'ferrata'
|
||||
? [{ divider: true }, {
|
||||
label: t(free ? 'tours.planner.routeLeg' : 'tours.planner.freeLeg'),
|
||||
icon: Spline,
|
||||
onClick: () => planner.toggleWaypointFreeLeg(point.id),
|
||||
}]
|
||||
? [
|
||||
{ divider: true },
|
||||
{
|
||||
label: t(free ? 'tours.planner.routeLeg' : 'tours.planner.freeLeg'),
|
||||
icon: Spline,
|
||||
onClick: () => planner.toggleWaypointFreeLeg(point.id),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(planner.isPaddle
|
||||
? [
|
||||
{ divider: true },
|
||||
...(hasLeg
|
||||
? [{
|
||||
label: t(portage ? 'tours.paddle.portageOff' : 'tours.paddle.portageOn'),
|
||||
icon: PortageIcon,
|
||||
onClick: () => paddle.togglePortage(point.id),
|
||||
}]
|
||||
? [
|
||||
{
|
||||
label: t(portage ? 'tours.paddle.portageOff' : 'tours.paddle.portageOn'),
|
||||
icon: PortageIcon,
|
||||
onClick: () => paddle.togglePortage(point.id),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{
|
||||
label: t(point.lock ? 'tours.paddle.lockRemove' : 'tours.paddle.lockAdd'),
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { MAX_PLANNED_TOUR_DURATION_MINUTES, paddleLockSchema, plannableTourTypeSchema, type PlannableTourType, type TourMaxHikingDifficulty } from '@trek/shared'
|
||||
import type { PaddleFieldValues } from './usePaddleFields'
|
||||
import type { TourPlannerWaypoint } from './useTourPlanner'
|
||||
import {
|
||||
MAX_PLANNED_TOUR_DURATION_MINUTES,
|
||||
paddleLockSchema,
|
||||
plannableTourTypeSchema,
|
||||
type PlannableTourType,
|
||||
type TourMaxHikingDifficulty,
|
||||
} from '@trek/shared';
|
||||
import type { PaddleFieldValues } from './usePaddleFields';
|
||||
import type { TourPlannerWaypoint } from './useTourPlanner';
|
||||
|
||||
/**
|
||||
* The tour planner's draft as it is kept in local storage between visits, and
|
||||
@@ -9,59 +15,71 @@ import type { TourPlannerWaypoint } from './useTourPlanner'
|
||||
* half read.
|
||||
*/
|
||||
export interface DraftPayload {
|
||||
version: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
|
||||
name: string
|
||||
description?: string
|
||||
website?: string
|
||||
plannedDurationMinutes?: number | null
|
||||
breakAdditionalMinutes?: number | null
|
||||
waypoints: TourPlannerWaypoint[]
|
||||
maxHikingDifficulty?: TourMaxHikingDifficulty
|
||||
editingPlaceId?: number | null
|
||||
version: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;
|
||||
name: string;
|
||||
description?: string;
|
||||
website?: string;
|
||||
plannedDurationMinutes?: number | null;
|
||||
breakAdditionalMinutes?: number | null;
|
||||
waypoints: TourPlannerWaypoint[];
|
||||
maxHikingDifficulty?: TourMaxHikingDifficulty;
|
||||
editingPlaceId?: number | null;
|
||||
/** The import a new tour is being planned from; carried until it is saved. */
|
||||
derivedFromPlaceId?: number | null
|
||||
tourType?: PlannableTourType
|
||||
paddle?: PaddleFieldValues
|
||||
derivedFromPlaceId?: number | null;
|
||||
tourType?: PlannableTourType;
|
||||
paddle?: PaddleFieldValues;
|
||||
}
|
||||
|
||||
const DRAFT_VERSIONS: ReadonlyArray<DraftPayload['version']> = [1, 2, 3, 4, 5, 6, 7, 8]
|
||||
const DRAFT_VERSIONS: ReadonlyArray<DraftPayload['version']> = [1, 2, 3, 4, 5, 6, 7, 8];
|
||||
|
||||
function optionalString(value: unknown): boolean {
|
||||
return value === undefined || typeof value === 'string'
|
||||
return value === undefined || typeof value === 'string';
|
||||
}
|
||||
|
||||
function optionalMinutes(value: number | null | undefined): boolean {
|
||||
return value === undefined || value === null
|
||||
|| (Number.isInteger(value) && value >= 0 && value <= MAX_PLANNED_TOUR_DURATION_MINUTES)
|
||||
return (
|
||||
value === undefined ||
|
||||
value === null ||
|
||||
(Number.isInteger(value) && value >= 0 && value <= MAX_PLANNED_TOUR_DURATION_MINUTES)
|
||||
);
|
||||
}
|
||||
|
||||
function optionalPlaceId(value: number | null | undefined): boolean {
|
||||
return value == null || (Number.isInteger(value) && value > 0)
|
||||
return value == null || (Number.isInteger(value) && value > 0);
|
||||
}
|
||||
|
||||
function optionalDifficulty(value: number | null | undefined): boolean {
|
||||
return value == null || (Number.isInteger(value) && value >= 1 && value <= 6)
|
||||
return value == null || (Number.isInteger(value) && value >= 1 && value <= 6);
|
||||
}
|
||||
|
||||
function validDraftWaypoint(point: TourPlannerWaypoint): boolean {
|
||||
return !!point && typeof point.id === 'string'
|
||||
&& Number.isFinite(point.lat) && Math.abs(point.lat) <= 90
|
||||
&& Number.isFinite(point.lng) && Math.abs(point.lng) <= 180
|
||||
&& (point.lock == null || paddleLockSchema.safeParse(point.lock).success)
|
||||
return (
|
||||
!!point &&
|
||||
typeof point.id === 'string' &&
|
||||
Number.isFinite(point.lat) &&
|
||||
Math.abs(point.lat) <= 90 &&
|
||||
Number.isFinite(point.lng) &&
|
||||
Math.abs(point.lng) <= 180 &&
|
||||
(point.lock == null || paddleLockSchema.safeParse(point.lock).success)
|
||||
);
|
||||
}
|
||||
|
||||
export function validDraft(value: unknown): value is DraftPayload {
|
||||
if (!value || typeof value !== 'object') return false
|
||||
const draft = value as Partial<DraftPayload>
|
||||
return draft.version !== undefined && DRAFT_VERSIONS.includes(draft.version) && typeof draft.name === 'string'
|
||||
&& optionalString(draft.description)
|
||||
&& optionalString(draft.website)
|
||||
&& optionalMinutes(draft.plannedDurationMinutes)
|
||||
&& optionalMinutes(draft.breakAdditionalMinutes)
|
||||
&& optionalPlaceId(draft.editingPlaceId) &&
|
||||
optionalPlaceId(draft.derivedFromPlaceId)
|
||||
&& optionalDifficulty(draft.maxHikingDifficulty)
|
||||
&& (draft.tourType === undefined || plannableTourTypeSchema.safeParse(draft.tourType).success)
|
||||
&& Array.isArray(draft.waypoints)
|
||||
&& draft.waypoints.every(validDraftWaypoint)
|
||||
if (!value || typeof value !== 'object') return false;
|
||||
const draft = value as Partial<DraftPayload>;
|
||||
return (
|
||||
draft.version !== undefined &&
|
||||
DRAFT_VERSIONS.includes(draft.version) &&
|
||||
typeof draft.name === 'string' &&
|
||||
optionalString(draft.description) &&
|
||||
optionalString(draft.website) &&
|
||||
optionalMinutes(draft.plannedDurationMinutes) &&
|
||||
optionalMinutes(draft.breakAdditionalMinutes) &&
|
||||
optionalPlaceId(draft.editingPlaceId) &&
|
||||
optionalPlaceId(draft.derivedFromPlaceId) &&
|
||||
optionalDifficulty(draft.maxHikingDifficulty) &&
|
||||
(draft.tourType === undefined || plannableTourTypeSchema.safeParse(draft.tourType).success) &&
|
||||
Array.isArray(draft.waypoints) &&
|
||||
draft.waypoints.every(validDraftWaypoint)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -135,7 +135,9 @@ export function alignFreeLegs<T extends RoutePoint>(points: readonly T[], allFre
|
||||
}
|
||||
return {
|
||||
...kept,
|
||||
fixedLeg: isPortage(leg) ? portageLegBetween(point, next, leg.extra_minutes ?? null) : freeLegBetween(point, next),
|
||||
fixedLeg: isPortage(leg)
|
||||
? portageLegBetween(point, next, leg.extra_minutes ?? null)
|
||||
: freeLegBetween(point, next),
|
||||
};
|
||||
});
|
||||
return allFree ? extrasOnFirstLeg(aligned) : aligned;
|
||||
@@ -170,7 +172,9 @@ export function setPortageExtraMinutes<T extends RoutePoint>(
|
||||
minutes: number | null
|
||||
): T[] {
|
||||
return points.map((point) =>
|
||||
point.id === id && isPortage(point.fixedLeg) ? { ...point, fixedLeg: { ...point.fixedLeg, extra_minutes: minutes } } : point
|
||||
point.id === id && isPortage(point.fixedLeg)
|
||||
? { ...point, fixedLeg: { ...point.fixedLeg, extra_minutes: minutes } }
|
||||
: point
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import type { TourRoutePart } from './tourRouting';
|
||||
|
||||
/**
|
||||
* PAD-03: a portage on the map, in an earth brown over a white rim, dotted the
|
||||
* way the map draws a walk: the boat is carried there, not paddled. Map
|
||||
* colours are literals by design.
|
||||
* PAD-03: a portage on the map, in an earth brown over a rim in the map's own
|
||||
* white, dotted the way the map draws a walk: the boat is carried there, not
|
||||
* paddled. The colours come resolved from the paddle tokens (`usePaddlePaint`).
|
||||
*/
|
||||
export const PORTAGE_LINE_COLOR = '#9a6233'; // theme-lint-disable map colour of a carried stretch
|
||||
const PORTAGE_CASING_COLOR = '#ffffff'; // theme-lint-disable rim under the carried stretch
|
||||
export interface PortagePaint {
|
||||
line: string;
|
||||
casing: string;
|
||||
}
|
||||
|
||||
export interface TourRouteStyle {
|
||||
/** Per line: dotted (a hand-drawn stretch of a hike, a portage) or solid. */
|
||||
@@ -21,10 +23,14 @@ export interface TourRouteStyle {
|
||||
* look alike. A paddle tour is drawn by hand throughout, so its water is the
|
||||
* plain line and only its portages stand out, dotted and brown.
|
||||
*/
|
||||
export function tourRouteStyle(parts: readonly TourRoutePart[] | null, isPaddle: boolean): TourRouteStyle {
|
||||
export function tourRouteStyle(
|
||||
parts: readonly TourRoutePart[] | null,
|
||||
isPaddle: boolean,
|
||||
portage: PortagePaint
|
||||
): TourRouteStyle {
|
||||
if (!parts?.length) return { walking: null, colors: null };
|
||||
const walking = parts.map((part) => (isPaddle ? !!part.land : part.free));
|
||||
const colors = parts.map((part) => (part.land ? { line: PORTAGE_LINE_COLOR, casing: PORTAGE_CASING_COLOR } : undefined));
|
||||
const colors = parts.map((part) => (part.land ? { line: portage.line, casing: portage.casing } : undefined));
|
||||
return {
|
||||
walking: walking.some(Boolean) ? walking : null,
|
||||
colors: colors.some(Boolean) ? colors : null,
|
||||
|
||||
@@ -15,7 +15,12 @@ export interface PaddleFieldValues {
|
||||
portageSpeedKmh?: number | null;
|
||||
}
|
||||
|
||||
export const NO_PADDLE_FIELDS: PaddleFieldValues = { boatType: null, waterContext: null, speedKmh: null, portageSpeedKmh: null };
|
||||
export const NO_PADDLE_FIELDS: PaddleFieldValues = {
|
||||
boatType: null,
|
||||
waterContext: null,
|
||||
speedKmh: null,
|
||||
portageSpeedKmh: null,
|
||||
};
|
||||
|
||||
/** The paddle fields of a saved tour, or none for a hike or a list cached before they existed. */
|
||||
export function paddleFieldsOf(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { MAX_PLANNED_TOUR_DURATION_MINUTES, paddleSpeedKmhSchema, plannableTourTypeSchema, tourWebsiteSchema, type PlannableTourType, type TourCreateResponse, type TourFixedLeg, type TourListItem, type TourWaypointRole, type TourMaxHikingDifficulty, type PaddleLock } from '@trek/shared'
|
||||
import { MAX_PLANNED_TOUR_DURATION_MINUTES, paddleSpeedKmhSchema, tourWebsiteSchema, type PlannableTourType, type TourCreateResponse, type TourFixedLeg, type TourListItem, type TourWaypointRole, type TourMaxHikingDifficulty, type PaddleLock } from '@trek/shared'
|
||||
import { tourRepo } from '../../../repo/tourRepo'
|
||||
import { randomId } from '../../../utils/randomId'
|
||||
import { analyzeRouteGeometry, type RouteProfileFocus } from '../../../utils/routeGeometry'
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import type { GeoJSONSource, Map as MapLibreMap } from 'maplibre-gl';
|
||||
import { useCallback, useEffect, useRef, useState, type RefObject } from 'react';
|
||||
import { isFerrataHit } from '../../Ferratas/useFerrataLayerGL';
|
||||
import { isPaddleHit } from '../paddle/usePaddleLayerGL';
|
||||
import type { TourBaseLayer } from '../../Map/MapLayerSwitcher';
|
||||
import { isTourLayerHit } from '../../Map/mapRasterOverlay';
|
||||
import {
|
||||
addTerrainLayers,
|
||||
DEM_SOURCE,
|
||||
@@ -70,9 +69,9 @@ function createTerrainMap(
|
||||
attributionControl: { compact: true },
|
||||
});
|
||||
// Clicking the terrain adds a control point, the same as on the flat planner map;
|
||||
// a click on a via ferrata opens its card instead.
|
||||
// a click on a via ferrata or a paddle obstacle opens its card instead.
|
||||
map.on('click', (event) => {
|
||||
if (isFerrataHit(map, event.point) || isPaddleHit(map, event.point)) return;
|
||||
if (isTourLayerHit(map, event.point)) return;
|
||||
scene.current.onAdd?.(event.lngLat.lat, event.lngLat.lng);
|
||||
});
|
||||
map.on('style.load', () => {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import type { FerrataBbox } from '@trek/shared';
|
||||
import { type PaddleGlMap, usePaddleLayerGL } from '../paddle/usePaddleLayerGL';
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import type { DistanceIndexedProfileSample, RouteProfileFocus } from '../../../utils/routeGeometry';
|
||||
import type { FerrataMapLayer } from '../../Ferratas/useFerrataMapLayer';
|
||||
import type { TourBaseLayer, TourLayerOffer } from '../../Map/MapLayerSwitcher';
|
||||
import { useRasterOverlaysGL, type RasterOverlayGlMap } from '../../Map/mapRasterOverlay';
|
||||
import { usePaddleLayerGL, type PaddleGlMap } from '../paddle/usePaddleLayerGL';
|
||||
import { trackData, type PanelWidths, type TrackColorMode } from './terrainLayers';
|
||||
import { useTerrainFerratas } from './useTerrainFerratas';
|
||||
import { frameCamera, useTerrainMap, type TerrainScene } from './useTerrainMap';
|
||||
|
||||
Reference in New Issue
Block a user