Merge dev into feat/native-apps

Brings the native apps branch up to dev (NestJS-only server, MikroORM
repositories, tracked sessions, per-domain locales, the lint ratchets) and
ports its new code onto that architecture:

- server: /api/auth/native moves onto injected services. The session is
  minted by the auth domain's new LoginSessionService (login bookkeeping and
  SessionsService.issue in one transaction), the one-time codes live behind a
  NativeHandoffStore port with a capped in-memory implementation that drops
  expired codes on write instead of running a timer, both routes declare
  response contracts, and the exchange answers { success: true }. Unit and
  e2e suites run on createTestModule and the ORM factories.
- shared: native strings for az, et, sk and th, native wired into every
  locale, the address placeholder as a full URL.
- client: the account and export changes go into dev's shared hooks
  (useAccountSettings, useTripExport), the native server card is a
  desktop/phone pair on useNativeServer, the hand-off call moves out of the
  page hook into native/, best-effort native failures go through
  reportError instead of the console, and the address screen is known to
  knip and lint:i18n-keys.
- package-lock.json regenerated on Linux.
This commit is contained in:
Maurice
2026-10-25 17:04:15 +01:00
11842 changed files with 1361077 additions and 180501 deletions
@@ -0,0 +1,45 @@
import L from 'leaflet';
import { useCallback, useEffect } from 'react';
import { useMap } from 'react-leaflet';
import { MAX_ZOOM_RASTER, type ViewportPadding } from '../../utils/mapViewport';
import { ASSISTANT_CAMERA_MS, centreOf, coverPadding, useCameraRequest, useUserMoveClock } from './assistantCamera';
import type { AssistantCamera } from './mapViewContract';
interface AssistantCameraControllerProps {
camera: AssistantCamera | null | undefined;
/** The planner's padding for its panels, in pixels per edge. */
padding: ViewportPadding;
}
/**
* Moves the Leaflet map where the assistant asks: `fit` frames the points,
* `pan` brings their centre into view only when it is outside. Zoomed in no
* further than a day fit, the same scale the GL map stops at.
*/
export function AssistantCameraController({ camera, padding }: AssistantCameraControllerProps) {
const map = useMap();
const getContainer = useCallback(() => map.getContainer(), [map]);
const userMovedAt = useUserMoveClock(getContainer, true);
const request = useCameraRequest(camera, userMovedAt);
useEffect(() => {
request((next) => {
const duration = ASSISTANT_CAMERA_MS / 1000;
if (next.mode === 'pan') {
const centre = centreOf(next.points);
if (!map.getBounds().contains(centre)) map.panTo(centre, { animate: next.animate, duration });
return;
}
const box = coverPadding(padding, next.cover);
map.fitBounds(L.latLngBounds(next.points), {
paddingTopLeft: [box.left, box.top],
paddingBottomRight: [box.right, box.bottom],
maxZoom: MAX_ZOOM_RASTER,
animate: next.animate,
duration,
});
});
}, [map, padding, request]);
return null;
}
@@ -0,0 +1,58 @@
import L from 'leaflet';
import { useEffect, useLayoutEffect, useRef } from 'react';
import { useMap } from 'react-leaflet';
import { GHOST_SIZE, mountGhosts, setGhostHot, type GhostHandlers } from './assistantGhostMarker';
import type { AssistantGhost } from './mapViewContract';
interface AssistantGhostLayerProps {
ghosts: readonly AssistantGhost[] | undefined;
hoveredId: string | null | undefined;
onHover?: (id: string | null) => void;
onClick?: (id: string) => void;
}
/** Above the place pins, so a suggestion on a busy day is never buried under the stops it joins. */
const GHOST_Z_OFFSET = 900;
/**
* The assistant's suggestions on the Leaflet map, outside the cluster group:
* a suggestion stands on its own until it is decided. The name shows in the
* map's own tooltip, built from text. A hover only toggles a class on the
* element; the pins are rebuilt when the suggestions change, never on hover.
*/
export function AssistantGhostLayer({ ghosts, hoveredId, onHover, onClick }: AssistantGhostLayerProps) {
const map = useMap();
const handlers = useRef<GhostHandlers>({ onHover, onClick });
useLayoutEffect(() => {
handlers.current = { onHover, onClick };
}, [onHover, onClick]);
const elements = useRef<ReadonlyMap<string, HTMLElement>>(new Map());
useEffect(() => {
if (!ghosts?.length) return;
const mounted = mountGhosts(
ghosts,
(el, ghost) => {
const icon = L.divIcon({ html: el, className: 'trek-ghost-pin', iconSize: [GHOST_SIZE, GHOST_SIZE] });
const label = document.createElement('span');
label.textContent = ghost.name;
const marker = L.marker([ghost.lat, ghost.lng], { icon, keyboard: false, zIndexOffset: GHOST_Z_OFFSET })
.bindTooltip(label, { direction: 'top', offset: [0, -GHOST_SIZE / 2], className: 'map-tooltip' })
.addTo(map);
return { remove: () => marker.remove() };
},
handlers
);
elements.current = mounted.elements;
return () => {
mounted.dispose();
elements.current = new Map();
};
}, [ghosts, map]);
useEffect(() => {
setGhostHot(elements.current, hoveredId);
}, [ghosts, hoveredId]);
return null;
}
@@ -0,0 +1,161 @@
/**
* FE-MAP-ROUTE-001 to FE-MAP-ROUTE-004
*
* The chat's routes on the Leaflet map: a rim under each line and nothing
* but an invisible fat line taking the pointer; dashes for a way not chosen,
* faint for the way a change replaces; the hard grades over the line, a disc
* at the start and a ring at the end; the named stops only while lit; and
* the pointer onto, along and off a line reported by its key; a line that
* lights up brought to the front. What Leaflet makes of the options is
* Leaflet's: the paths come back as data here.
*/
import { fireEvent, render, screen } from '@testing-library/react';
import type { ReactNode, Ref } from 'react';
import { describe, expect, it, vi } from 'vitest';
import type { AssistantRouteLine } from '../../types/assistantMap';
import { AssistantGhostLineLayer } from './AssistantGhostLineLayer';
type Handlers = Record<string, ((event?: unknown) => void) | undefined>;
const bringToFront = vi.hoisted(() => vi.fn());
vi.mock('react-leaflet', async () => {
const { useImperativeHandle } = await vi.importActual<typeof import('react')>('react');
return {
FeatureGroup: ({ children, ref }: { children?: ReactNode; ref?: Ref<{ bringToFront: () => void }> }) => {
useImperativeHandle(ref, () => ({ bringToFront }));
return <div data-testid="group">{children}</div>;
},
Polyline: ({
positions,
pathOptions,
interactive,
eventHandlers,
}: {
positions: unknown;
pathOptions?: Record<string, unknown>;
interactive?: boolean;
eventHandlers?: Handlers;
}) => (
<div
data-testid="polyline"
data-points={JSON.stringify(positions)}
data-color={String(pathOptions?.color ?? '')}
data-weight={String(pathOptions?.weight ?? '')}
data-opacity={String(pathOptions?.opacity ?? '')}
data-dash={String(pathOptions?.dashArray ?? '')}
data-dash-named={String(pathOptions ? 'dashArray' in pathOptions : false)}
data-interactive={String(interactive)}
onMouseEnter={() => eventHandlers?.mouseover?.()}
onMouseLeave={() => eventHandlers?.mouseout?.()}
onMouseMove={() => eventHandlers?.mousemove?.({ latlng: { lat: 47.78, lng: 12.6 } })}
onClick={() => eventHandlers?.click?.({ latlng: { lat: 47.79, lng: 12.61 } })}
/>
),
CircleMarker: ({
center,
pathOptions,
children,
}: {
center: [number, number];
pathOptions?: Record<string, unknown>;
children?: ReactNode;
}) => (
<div data-testid="disc" data-center={JSON.stringify(center)} data-fill={String(pathOptions?.fillColor ?? '')}>
{children}
</div>
),
Tooltip: ({ children }: { children?: ReactNode }) => <span data-testid="stop-name">{children}</span>,
};
});
const LINE: AssistantRouteLine = {
id: 'c1:look:route',
ref: 'c1',
lines: [
[
[47.77, 12.59],
[47.78, 12.6],
[47.79, 12.62],
],
],
color: '#0a84ff',
casing: '#ffffff',
ends: { start: [47.77, 12.59], end: [47.79, 12.62] },
stops: [{ lat: 47.78, lng: 12.6, label: 'Strausshütte' }],
tints: [
{
line: [
[47.78, 12.6],
[47.79, 12.62],
],
color: '#7c3aed',
},
],
};
const paths = () => screen.queryAllByTestId('polyline');
/** What a path was asked for, as plain data. */
const asked = (el: HTMLElement | undefined) => ({ ...el?.dataset });
describe('AssistantGhostLineLayer', () => {
it('FE-MAP-ROUTE-001: a rim, the line, its hard grade and its ends; only the invisible line takes the pointer', () => {
render(<AssistantGhostLineLayer lines={[LINE]} />);
const [rim, core, grade, hit] = paths();
expect(asked(rim)).toMatchObject({ color: '#ffffff', weight: '7', interactive: 'false' });
expect(asked(core)).toMatchObject({ color: '#0a84ff', weight: '4', dash: '', interactive: 'false' });
expect(asked(grade)).toMatchObject({ color: '#7c3aed', interactive: 'false' });
expect(asked(hit)).toMatchObject({ weight: '16', opacity: '0', interactive: 'undefined' });
const discs = screen.getAllByTestId('disc');
expect(discs.map((disc) => disc.dataset.fill)).toEqual(['#0a84ff', '#ffffff']);
// The stops show only while the line is lit.
expect(screen.queryByTestId('stop-name')).not.toBeInTheDocument();
});
it('FE-MAP-ROUTE-002: dashed, faint, a loop with one disc, and the lit line with its named stops', () => {
const loop: AssistantRouteLine = { ...LINE, dashed: true, dim: true, ends: { start: [47.77, 12.59], end: null } };
const { rerender } = render(<AssistantGhostLineLayer lines={[loop]} />);
expect(asked(paths()[1])).toMatchObject({ dash: '6 7', opacity: '0.45' });
expect(screen.getAllByTestId('disc')).toHaveLength(1);
rerender(<AssistantGhostLineLayer lines={[{ ...LINE, hot: true }]} />);
expect(screen.getByTestId('stop-name')).toHaveTextContent('Strausshütte');
rerender(<AssistantGhostLineLayer lines={[]} />);
expect(paths()).toHaveLength(0);
});
it('FE-MAP-ROUTE-003: the pointer onto, along and off a line, and a tap on it, report its key and where', () => {
const onHover = vi.fn();
const onPoint = vi.fn();
render(<AssistantGhostLineLayer lines={[LINE]} onHover={onHover} onPoint={onPoint} />);
const hit = paths()[3] as HTMLElement;
fireEvent.mouseEnter(hit);
fireEvent.mouseMove(hit);
fireEvent.click(hit);
fireEvent.mouseLeave(hit);
expect(onHover.mock.calls).toEqual([['c1'], [null]]);
expect(onPoint.mock.calls).toEqual([
['c1', 47.78, 12.6],
['c1', 47.79, 12.61],
]);
});
it('FE-MAP-ROUTE-004: a dashed way that lights up loses its dashes and comes to the front; a calm one stays put', () => {
bringToFront.mockClear();
const way: AssistantRouteLine = { ...LINE, dashed: true };
const other: AssistantRouteLine = { ...LINE, id: 'c2:look:route', ref: 'c2' };
const { rerender } = render(<AssistantGhostLineLayer lines={[way, other]} />);
expect(asked(paths()[1])).toMatchObject({ dash: '6 7' });
expect(bringToFront).not.toHaveBeenCalled();
// The same line, now lit, which the route model draws solid: its dash is asked away by name,
// so Leaflet's merged style drops it.
rerender(<AssistantGhostLineLayer lines={[other, { ...way, dashed: false, hot: true }]} />);
const lit = screen.getAllByTestId('group')[1];
const core = lit?.querySelectorAll<HTMLElement>('[data-testid="polyline"]')[1];
expect(asked(core)).toMatchObject({ dash: '', dashNamed: 'true' });
expect(bringToFront).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,134 @@
import type { FeatureGroup as LeafletFeatureGroup, LeafletMouseEvent } from 'leaflet';
import { useEffect, useRef } from 'react';
import { CircleMarker, FeatureGroup, Polyline, Tooltip } from 'react-leaflet';
import type { AssistantRouteLine } from '../../types/assistantMap';
/** A rim under the line, the line, and the invisible fat line that takes the pointer. */
const CASING_WEIGHT = 7;
const CORE_WEIGHT = 4;
const HIT_WEIGHT = 16;
/** A way not chosen, or one joined straight between its stops. */
const DASH = '6 7';
/** The way a change replaces, beside the new one. */
const DIM_OPACITY = 0.45;
const END_RADIUS = 5;
const STOP_RADIUS = 4;
const ROUND = { lineCap: 'round', lineJoin: 'round' } as const;
interface LineHandlers {
onHover?: (ref: string | null) => void;
onPoint?: (ref: string, lat: number, lng: number) => void;
}
/**
* One route the chat shows: its rim and its line (dashed while it is a way
* not chosen or only its stops joined straight, faint while it is the way a
* change replaces), its hard grades over it, a disc at its start and a ring
* at its end, its named stops with their names while it is lit, and a wide
* invisible line on top that reports the pointer: onto it, along it (for the route's profile)
* and off it. Nothing but the invisible line takes the pointer, so the plan's
* own lines and pins stay where a click lands. Leaflet keeps each path where
* it was first drawn, whatever order the lines come in later, so a line that
* lights up is brought to the front by hand.
*/
function GhostLine({ line, onHover, onPoint }: { line: AssistantRouteLine } & LineHandlers) {
const group = useRef<LeafletFeatureGroup | null>(null);
useEffect(() => {
if (line.hot) group.current?.bringToFront();
}, [line.hot]);
const opacity = line.dim ? DIM_OPACITY : 1;
const point = (event: LeafletMouseEvent) => onPoint?.(line.ref, event.latlng.lat, event.latlng.lng);
return (
<FeatureGroup ref={group}>
<Polyline
positions={line.lines}
interactive={false}
pathOptions={{ color: line.casing, weight: CASING_WEIGHT, opacity: opacity * 0.9, ...ROUND }}
/>
<Polyline
positions={line.lines}
interactive={false}
pathOptions={{
color: line.color,
weight: CORE_WEIGHT,
opacity,
// Always named: Leaflet merges a new style into the old one, so a dash left out would stay drawn.
dashArray: line.dashed ? DASH : undefined,
...ROUND,
}}
/>
{line.tints?.map((tint, index) => (
<Polyline
key={index}
positions={tint.line}
interactive={false}
pathOptions={{ color: tint.color, weight: CORE_WEIGHT, opacity, ...ROUND }}
/>
))}
{line.ends && (
<CircleMarker
center={line.ends.start}
radius={END_RADIUS}
interactive={false}
pathOptions={{ color: line.casing, weight: 2, fillColor: line.color, fillOpacity: 1, opacity }}
/>
)}
{line.ends?.end && (
<CircleMarker
center={line.ends.end}
radius={END_RADIUS}
interactive={false}
pathOptions={{ color: line.color, weight: 3, fillColor: line.casing, fillOpacity: 1, opacity }}
/>
)}
{line.hot &&
line.stops?.map((stop, index) => (
<CircleMarker
key={index}
center={[stop.lat, stop.lng]}
radius={STOP_RADIUS}
interactive={false}
pathOptions={{ color: line.casing, weight: 2, fillColor: line.color, fillOpacity: 1 }}
>
<Tooltip permanent direction="top" className="map-tooltip">
{stop.label}
</Tooltip>
</CircleMarker>
))}
<Polyline
positions={line.lines}
bubblingMouseEvents={false}
pathOptions={{ color: line.casing, weight: HIT_WEIGHT, opacity: 0 }}
eventHandlers={{
mouseover: () => onHover?.(line.ref),
mouseout: () => onHover?.(null),
mousemove: point,
click: point,
}}
/>
</FeatureGroup>
);
}
interface AssistantGhostLineLayerProps extends LineHandlers {
lines: readonly AssistantRouteLine[] | undefined;
}
/**
* The routes the chat shows on the Leaflet map, in the order they come
* (the store's route model puts the one under the pointer last; here a line
* brings itself to the front when it lights up). Over the plan's lines,
* under its pins. The twin of
* useAssistantGhostLinesGL.
*/
export function AssistantGhostLineLayer({ lines, onHover, onPoint }: AssistantGhostLineLayerProps) {
if (!lines?.length) return null;
return (
<>
{lines.map((line) => (
<GhostLine key={line.id} line={line} onHover={onHover} onPoint={onPoint} />
))}
</>
);
}
@@ -0,0 +1,100 @@
/**
* FE-MAP-ASSIST-LEAFLET-001 to 003
*
* The assistant on the Leaflet map, against real Leaflet: ghosts outside the
* clusters that only change a class on hover, a camera that frames with the
* same scale limit as a day fit and skips the request it mounted with, and
* the pop on a real pin.
*/
import L from 'leaflet';
import { MapContainer } from 'react-leaflet';
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import { act, render } from '../../../tests/helpers/render';
import { MAX_ZOOM_RASTER } from '../../utils/mapViewport';
import { AssistantMapLeaflet } from './AssistantMapLeaflet';
import type { AssistantCamera, AssistantMapProps } from './mapViewContract';
const PADDING = { top: 60, right: 40, bottom: 60, left: 40 };
const NO_PIN = () => null;
const sized = ['clientWidth', 'clientHeight'] as const;
const originals = new Map<string, PropertyDescriptor | undefined>();
beforeAll(() => {
for (const key of sized) {
originals.set(key, Object.getOwnPropertyDescriptor(HTMLElement.prototype, key));
Object.defineProperty(HTMLElement.prototype, key, {
configurable: true,
get: () => (key === 'clientWidth' ? 1000 : 700),
});
}
});
afterAll(() => {
for (const key of sized) {
const original = originals.get(key);
if (original) Object.defineProperty(HTMLElement.prototype, key, original);
else delete (HTMLElement.prototype as unknown as Record<string, unknown>)[key];
}
});
afterEach(() => vi.restoreAllMocks());
function onMap(assistant: AssistantMapProps, markerEl: (id: number) => HTMLElement | null = NO_PIN) {
return (
<MapContainer center={[41.9, 12.5]} zoom={12} style={{ width: 1000, height: 700 }}>
<AssistantMapLeaflet assistant={assistant} padding={PADDING} markerEl={markerEl} />
</MapContainer>
);
}
const GHOSTS = [{ id: 'c1', lat: 41.9, lng: 12.48, name: 'Pantheon' }];
describe('AssistantMapLeaflet', () => {
it('FE-MAP-ASSIST-LEAFLET-001: a ghost stands on the map and is marked while its suggestion is hovered', () => {
const onHover = vi.fn();
const view = render(onMap({ assistantGhosts: GHOSTS, assistantHoveredId: null, onAssistantGhostHover: onHover }));
const ghost = view.container.querySelector<HTMLElement>('.trek-ghost');
expect(ghost?.getAttribute('aria-label')).toBe('Pantheon');
ghost?.dispatchEvent(new Event('pointerenter'));
expect(onHover).toHaveBeenCalledWith('c1');
view.rerender(onMap({ assistantGhosts: GHOSTS, assistantHoveredId: 'c1', onAssistantGhostHover: onHover }));
expect(view.container.querySelectorAll('.trek-ghost')).toHaveLength(1);
expect(view.container.querySelector('.trek-ghost')).toBe(ghost);
expect(ghost?.classList.contains('is-hot')).toBe(true);
});
it('FE-MAP-ASSIST-LEAFLET-002: the camera skips the request it mounted with and frames a new one', () => {
const fit = vi.spyOn(L.Map.prototype, 'fitBounds');
const cam = (key: string): AssistantCamera => ({
key,
points: [
[41.8, 12.4],
[42, 12.6],
],
mode: 'fit',
animate: false,
auto: false,
cover: { side: 'left', px: 400 },
});
const view = render(onMap({ assistantCamera: cam('1') }));
expect(fit).not.toHaveBeenCalled();
view.rerender(onMap({ assistantCamera: cam('2') }));
expect(fit).toHaveBeenCalledOnce();
expect(fit.mock.calls[0]?.[1]).toMatchObject({
paddingTopLeft: [400, 60],
paddingBottomRight: [40, 60],
maxZoom: MAX_ZOOM_RASTER,
animate: false,
});
});
it('FE-MAP-ASSIST-LEAFLET-003: a place that just arrived pops on its own pin', async () => {
const pin = document.createElement('div');
pin.appendChild(document.createElement('div'));
render(onMap({ poppedPlaceIds: [5] }, (id) => (id === 5 ? pin : null)));
await act(async () => {
await new Promise((resolve) => requestAnimationFrame(() => resolve(null)));
});
expect(pin.classList.contains('trek-place-pop')).toBe(true);
});
});
@@ -0,0 +1,42 @@
import type { ViewportPadding } from '../../utils/mapViewport';
import { useAssistantMarkerClasses } from './assistantCamera';
import { AssistantCameraController } from './AssistantCameraController';
import { AssistantGhostLayer } from './AssistantGhostLayer';
import { AssistantGhostLineLayer } from './AssistantGhostLineLayer';
import { useReportViewLeaflet } from './assistantViewport';
import type { AssistantMapProps } from './mapViewContract';
interface AssistantMapLeafletProps {
assistant: AssistantMapProps;
/** The planner's padding for its panels, for the camera's fits. */
padding: ViewportPadding;
/** The element of a place's pin, when it has one on the map now. */
markerEl: (placeId: number) => HTMLElement | null;
}
/**
* Everything the assistant does on the Leaflet map, mounted inside the map
* container as one child, so MapView only hands its props on: the routes
* its cards show, the ghosts, the camera, the pop and pulse on the real
* pins, and the part of the map the assistant is told is on screen.
*/
export function AssistantMapLeaflet({ assistant, padding, markerEl }: AssistantMapLeafletProps) {
useAssistantMarkerClasses(markerEl, assistant.poppedPlaceIds, assistant.assistantPulsePlaceId);
useReportViewLeaflet();
return (
<>
<AssistantGhostLineLayer
lines={assistant.assistantRouteLines}
onHover={assistant.onAssistantRouteHover}
onPoint={assistant.onAssistantRoutePoint}
/>
<AssistantGhostLayer
ghosts={assistant.assistantGhosts}
hoveredId={assistant.assistantHoveredId}
onHover={assistant.onAssistantGhostHover}
onClick={assistant.onAssistantGhostClick}
/>
<AssistantCameraController camera={assistant.assistantCamera} padding={padding} />
</>
);
}
@@ -1,8 +1,10 @@
// FE-COMP-MAPLAYER-001 to FE-COMP-MAPLAYER-006
// FE-COMP-MAPLAYER-001 to FE-COMP-MAPLAYER-024
import React from 'react'
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '../../../tests/helpers/render'
import { MapLayerSwitcher, MAP_ROUND_CONTROL_SIZE } from './MapLayerSwitcher'
import { MapLayerSwitcher, TourMapLayerSwitcher, MAP_ROUND_CONTROL_SIZE } from './MapLayerSwitcher'
import type { FerrataMapLayer } from '../Ferratas/useFerrataMapLayer'
import type { ToggleableRasterOverlay } from './mapRasterOverlay'
describe('MapLayerSwitcher', () => {
it('FE-COMP-MAPLAYER-001: on the default layer, offers the switch to satellite', () => {
@@ -42,7 +44,55 @@ describe('MapLayerSwitcher', () => {
expect(button.style.background).toBe('transparent')
})
it('FE-COMP-MAPLAYER-006: the shell is as wide as the size its neighbours are placed off', () => {
it('FE-COMP-MAPLAYER-006: offers all three Tours-only base layers', () => {
render(<TourMapLayerSwitcher active="default" onChange={() => {}} />)
expect(screen.getByRole('button', { name: 'Map' })).toHaveAttribute('aria-pressed', 'true')
expect(screen.getByRole('button', { name: 'Topo' })).toHaveAttribute('aria-pressed', 'false')
expect(screen.getByRole('button', { name: 'Satellite' })).toHaveAttribute('aria-pressed', 'false')
})
it('FE-COMP-MAPLAYER-007: reports a per-view Topo selection', () => {
const onChange = vi.fn()
render(<TourMapLayerSwitcher active="default" onChange={onChange} />)
fireEvent.click(screen.getByRole('button', { name: 'Topo' }))
expect(onChange).toHaveBeenCalledWith('topo')
})
it('FE-COMP-MAPLAYER-018: offers the hiking map only where the tour type and the admin offer it (MAP-01)', () => {
const onChange = vi.fn()
const { rerender } = render(<TourMapLayerSwitcher active="default" onChange={onChange} layers={{ bases: ['default', 'topo', 'satellite'] }} />)
expect(screen.queryByRole('button', { name: 'Hiking' })).toBeNull()
rerender(<TourMapLayerSwitcher active="default" onChange={onChange} layers={{ bases: ['default', 'topo', 'hiking', 'satellite'] }} />)
fireEvent.click(screen.getByRole('button', { name: 'Hiking' }))
expect(onChange).toHaveBeenCalledWith('hiking')
})
it('FE-COMP-MAPLAYER-019: a hiking map that stopped answering says so on its segment, and only while it is shown', () => {
const baseHealth = { base: 'hiking' as const, down: true, onTileError: vi.fn(), onTileLoad: vi.fn() }
const layers = { bases: ['default', 'hiking'] as const, baseHealth }
const { rerender } = render(<TourMapLayerSwitcher active="hiking" onChange={() => {}} layers={layers} />)
const segment = screen.getByRole('button', { name: 'Hiking' })
expect(segment).toHaveAttribute('aria-pressed', 'true')
expect(segment).toHaveTextContent('!')
expect(screen.getByRole('status')).toHaveTextContent('OpenHikingMap is not answering right now')
rerender(<TourMapLayerSwitcher active="default" onChange={() => {}} layers={layers} />)
expect(screen.getByRole('button', { name: 'Hiking' })).not.toHaveTextContent('!')
expect(screen.queryByRole('status')).toBeNull()
})
it('FE-COMP-MAPLAYER-020: CyclOSM sits in the switch as Cycling and says so when it stops answering (BIK-06)', () => {
const baseHealth = { base: 'cycle' as const, down: true, onTileError: vi.fn(), onTileLoad: vi.fn() }
render(<TourMapLayerSwitcher active="cycle" onChange={() => {}} layers={{ bases: ['default', 'cycle'], baseHealth }} />)
expect(screen.getByRole('button', { name: 'Cycling' })).toHaveTextContent('!')
expect(screen.getByRole('status')).toHaveTextContent('CyclOSM is not answering right now')
expect(screen.queryByRole('button', { name: 'Hiking' })).toBeNull()
})
it('FE-COMP-MAPLAYER-008: the shell is as wide as the size its neighbours are placed off', () => {
render(<MapLayerSwitcher active="default" onToggle={() => {}} />)
const button = screen.getByRole('button')
const shell = button.parentElement as HTMLElement
@@ -55,3 +105,210 @@ describe('MapLayerSwitcher', () => {
expect(parseFloat(button.style.width) + 2 * parseFloat(shell.style.padding)).toBe(MAP_ROUND_CONTROL_SIZE)
})
})
describe('TourMapLayerSwitcher 3D switch', () => {
it('FE-COMP-MAPLAYER-009: offers no 3D switch on a map that has no terrain mode', () => {
render(<TourMapLayerSwitcher active="default" onChange={() => {}} />)
expect(screen.queryByRole('button', { name: '3D' })).toBeNull()
})
it('FE-COMP-MAPLAYER-010: toggles the terrain mode and shows whether it is on', () => {
const onToggleTerrain = vi.fn()
const { rerender } = render(<TourMapLayerSwitcher active="topo" onChange={() => {}} onToggleTerrain={onToggleTerrain} />)
const off = screen.getByRole('button', { name: '3D' })
expect(off).toHaveAttribute('aria-pressed', 'false')
expect(off).toHaveClass('text-content-muted')
expect(off.style.background).toBe('transparent')
fireEvent.click(off)
expect(onToggleTerrain).toHaveBeenCalledTimes(1)
rerender(<TourMapLayerSwitcher active="topo" onChange={() => {}} onToggleTerrain={onToggleTerrain} terrainActive />)
const on = screen.getByRole('button', { name: '3D' })
expect(on).toHaveAttribute('aria-pressed', 'true')
expect(on).toHaveClass('bg-accent', 'text-accent-text')
expect(on.style.background).toBe('')
// The base layer stays selectable beside it.
expect(screen.getByRole('button', { name: 'Topo' })).toHaveAttribute('aria-pressed', 'true')
})
})
const ferrataLayer = (overrides: Partial<FerrataMapLayer> = {}): FerrataMapLayer => ({
active: false,
onToggle: vi.fn(),
status: 'idle',
count: 0,
groups: [],
selectedId: null,
onSelect: vi.fn(),
...overrides,
})
describe('TourMapLayerSwitcher via ferrata switch', () => {
it('FE-COMP-MAPLAYER-011: offers no via ferrata switch without a layer', () => {
const { container } = render(<TourMapLayerSwitcher active="default" onChange={() => {}} />)
expect(screen.queryByRole('button', { name: 'Via ferratas' })).toBeNull()
expect(container.firstElementChild).toHaveAttribute('role', 'group')
})
it('FE-COMP-MAPLAYER-012: the switch toggles the layer, pressed and in the accent while it is on', () => {
const layer = ferrataLayer()
const { rerender } = render(<TourMapLayerSwitcher active="topo" onChange={() => {}} ferrataLayer={layer} />)
const off = screen.getByRole('button', { name: 'Via ferratas' })
expect(off).toHaveAttribute('aria-pressed', 'false')
expect(off).toHaveClass('text-content-muted')
fireEvent.click(off)
expect(layer.onToggle).toHaveBeenCalledTimes(1)
rerender(<TourMapLayerSwitcher active="topo" onChange={() => {}} ferrataLayer={ferrataLayer({ active: true, status: 'loading' })} />)
const on = screen.getByRole('button', { name: 'Via ferratas' })
expect(on).toHaveAttribute('aria-pressed', 'true')
expect(on).toHaveClass('bg-accent', 'text-accent-text')
})
it('FE-COMP-MAPLAYER-013: the count rides in the switch as a badge, nothing beside the pill, and none while off', () => {
const { container, rerender } = render(<TourMapLayerSwitcher active="default" onChange={() => {}} ferrataLayer={ferrataLayer({ count: 4 })} />)
expect(screen.queryByTestId('ferrata-count-badge')).toBeNull()
expect(container.firstElementChild).toHaveAttribute('role', 'group')
rerender(<TourMapLayerSwitcher active="default" onChange={() => {}} ferrataLayer={ferrataLayer({ active: true, status: 'ready', count: 4 })} />)
const badge = screen.getByTestId('ferrata-count-badge')
expect(badge).toHaveTextContent('4')
expect(badge).toHaveAttribute('data-tone', 'default')
expect(screen.getByRole('button', { name: 'Via ferratas' })).toContainElement(badge)
expect(screen.getByRole('status')).toHaveTextContent('4 via ferrata routes')
expect(screen.queryByTestId('ferrata-status-pill')).toBeNull()
})
it('FE-COMP-MAPLAYER-014: a tiny spinner in the badge while tiles load', () => {
render(<TourMapLayerSwitcher active="default" onChange={() => {}} ferrataLayer={ferrataLayer({ active: true, status: 'loading', count: 2 })} />)
const badge = screen.getByTestId('ferrata-count-badge')
expect(badge).toContainElement(screen.getByTestId('ferrata-count-spinner'))
expect(badge).not.toHaveTextContent('2')
expect(screen.getByRole('status')).toHaveTextContent('Loading via ferratas…')
})
it('FE-COMP-MAPLAYER-015: offline, the mirrors down or the view too wide: a warning tone, the reason in the tooltip', async () => {
const { rerender } = render(<TourMapLayerSwitcher active="default" onChange={() => {}} ferrataLayer={ferrataLayer({ active: true, status: 'offline', count: 1 })} />)
expect(screen.getByTestId('ferrata-count-badge')).toHaveAttribute('data-tone', 'warning')
expect(screen.getByTestId('ferrata-count-badge')).toHaveClass('bg-warning-soft', 'text-warning')
expect(screen.getByRole('status')).toHaveTextContent('Via ferratas need a connection')
rerender(<TourMapLayerSwitcher active="default" onChange={() => {}} ferrataLayer={ferrataLayer({ active: true, status: 'tooLarge' })} />)
fireEvent.mouseEnter(screen.getByRole('button', { name: 'Via ferratas' }))
expect(await screen.findByRole('tooltip')).toHaveTextContent('Zoom in to load via ferratas')
rerender(<TourMapLayerSwitcher active="default" onChange={() => {}} ferrataLayer={ferrataLayer({ active: true, status: 'error' })} />)
expect(screen.getByTestId('ferrata-count-badge')).toHaveAttribute('data-tone', 'warning')
expect(screen.getByRole('status')).toHaveTextContent('Overpass unreachable')
})
it('FE-COMP-MAPLAYER-016: sits beside the 3D switch behind one divider', () => {
render(
<TourMapLayerSwitcher active="default" onChange={() => {}} onToggleTerrain={() => {}}
ferrataLayer={ferrataLayer({ active: true, status: 'ready', count: 2 })} />
)
const group = screen.getByRole('group')
expect(group.querySelectorAll('span.bg-edge')).toHaveLength(1)
const buttons = Array.from(group.querySelectorAll('button')).map((button) => button.getAttribute('aria-label') ?? button.textContent)
expect(buttons.slice(-2)).toEqual(['Via ferratas', '3D'])
})
it('FE-COMP-MAPLAYER-017: the "set points" switch leads the tools on its icon, pressed in the accent while on', async () => {
const onToggle = vi.fn()
const { rerender } = render(
<TourMapLayerSwitcher active="default" onChange={() => {}} onToggleTerrain={() => {}}
ferrataLayer={ferrataLayer()} placeTool={{ active: true, onToggle }} />
)
const group = screen.getByRole('group')
expect(group.querySelectorAll('span.bg-edge')).toHaveLength(1)
const buttons = Array.from(group.querySelectorAll('button')).map((button) => button.getAttribute('aria-label') ?? button.textContent)
expect(buttons.slice(-3)).toEqual(['Set points', 'Via ferratas', '3D'])
const tool = screen.getByRole('button', { name: 'Set points' })
expect(tool).toHaveAttribute('aria-pressed', 'true')
expect(tool).toHaveClass('bg-accent', 'text-accent-text')
expect(tool).not.toHaveTextContent('Set points')
fireEvent.click(tool)
expect(onToggle).toHaveBeenCalledTimes(1)
fireEvent.mouseEnter(tool)
expect(await screen.findByRole('tooltip')).toHaveTextContent('Set points')
rerender(<TourMapLayerSwitcher active="default" onChange={() => {}} placeTool={{ active: false, onToggle }} />)
expect(screen.getByRole('button', { name: 'Set points' })).toHaveAttribute('aria-pressed', 'false')
expect(screen.getByRole('button', { name: 'Set points' })).toHaveClass('text-content-muted')
})
})
const pisteOverlay = (overrides: Partial<ToggleableRasterOverlay> = {}): ToggleableRasterOverlay => ({
id: 'pistes',
url: 'https://tiles.opensnowmap.org/pistes/{z}/{x}/{y}.png',
attribution: 'OpenSnowMap',
minZoom: 9,
maxZoom: 18,
active: false,
status: 'off',
belowMinZoom: false,
onToggle: vi.fn(),
onTileError: vi.fn(),
onTileLoad: vi.fn(),
...overrides,
})
describe('TourMapLayerSwitcher piste switch (SKI-01)', () => {
it('FE-COMP-MAPLAYER-021: the pistes switch sits on its icon alone, named by its tooltip, and offers no key while off', async () => {
const overlay = pisteOverlay()
render(<TourMapLayerSwitcher active="default" onChange={() => {}} ferrataLayer={ferrataLayer()} layers={{ overlays: [overlay] }} />)
const toggle = screen.getByRole('button', { name: 'Pistes, cross-country trails and lifts' })
expect(toggle).toHaveAttribute('aria-pressed', 'false')
expect(toggle.textContent).toBe('')
expect(screen.queryByTestId('piste-key-button')).toBeNull()
fireEvent.click(toggle)
expect(overlay.onToggle).toHaveBeenCalledTimes(1)
fireEvent.mouseEnter(toggle)
expect(await screen.findByRole('tooltip')).toHaveTextContent('Pistes, cross-country trails and lifts')
})
it('FE-COMP-MAPLAYER-022: on, the switch is pressed in the accent and the key rides beside it in the same pill', () => {
render(<TourMapLayerSwitcher active="default" onChange={() => {}} layers={{ overlays: [pisteOverlay({ active: true, status: 'on' })] }} />)
const toggle = screen.getByRole('button', { name: 'Pistes, cross-country trails and lifts' })
expect(toggle).toHaveAttribute('aria-pressed', 'true')
expect(toggle).toHaveClass('bg-accent', 'text-accent-text')
const key = screen.getByTestId('piste-key-button')
expect(screen.getByRole('group')).toContainElement(key)
expect(key).toHaveAccessibleName('Piste key')
})
it('FE-COMP-MAPLAYER-023: a piste source that stopped answering shows the warning badge, says so, and keeps the key readable', async () => {
render(<TourMapLayerSwitcher active="default" onChange={() => {}} layers={{ overlays: [pisteOverlay({ active: true, status: 'down' })] }} />)
const toggle = screen.getByRole('button', { name: 'Pistes, cross-country trails and lifts' })
expect(toggle).toHaveAttribute('data-status', 'down')
expect(toggle).toHaveTextContent('!')
expect(screen.getByTestId('piste-key-button')).toBeInTheDocument()
expect(screen.getByRole('status')).toHaveTextContent('Pistes are not loading. The map and your route still work.')
fireEvent.mouseEnter(toggle)
expect(await screen.findByRole('tooltip')).toHaveTextContent('Pistes are not loading.')
})
it('FE-COMP-MAPLAYER-024: on further out than the pistes reach, the switch stays pressed in the soft accent and says to zoom in', async () => {
const { rerender } = render(
<TourMapLayerSwitcher active="default" onChange={() => {}} layers={{ overlays: [pisteOverlay({ active: true, status: 'on', belowMinZoom: true })] }} />
)
const toggle = screen.getByRole('button', { name: 'Pistes, cross-country trails and lifts' })
expect(toggle).toHaveAttribute('aria-pressed', 'true')
expect(toggle).toHaveAttribute('data-below-min-zoom', 'true')
expect(toggle).toHaveClass('bg-accent-soft', 'text-accent')
expect(screen.getByRole('status')).toHaveTextContent('Zoom in to see the pistes')
fireEvent.mouseEnter(toggle)
expect(await screen.findByRole('tooltip')).toHaveTextContent('Zoom in to see the pistes')
// The key stays at hand and opens with the same line on top.
fireEvent.click(screen.getByTestId('piste-key-button'))
expect(await screen.findByTestId('piste-key-zoom-in')).toHaveTextContent('Zoom in to see the pistes')
// A source that stopped answering says so instead, and close enough the switch is plainly on.
rerender(<TourMapLayerSwitcher active="default" onChange={() => {}} layers={{ overlays: [pisteOverlay({ active: true, status: 'down', belowMinZoom: true })] }} />)
expect(screen.getByRole('status')).toHaveTextContent('Pistes are not loading.')
rerender(<TourMapLayerSwitcher active="default" onChange={() => {}} layers={{ overlays: [pisteOverlay({ active: true, status: 'on' })] }} />)
const plain = screen.getByRole('button', { name: 'Pistes, cross-country trails and lifts' })
expect(plain).not.toHaveAttribute('data-below-min-zoom')
expect(plain).toHaveClass('bg-accent', 'text-accent-text')
expect(screen.getByRole('status')).toHaveTextContent('')
})
})
+288 -9
View File
@@ -1,9 +1,29 @@
import { Map as MapIcon, Satellite } from 'lucide-react'
import { Anchor, Bike, Footprints, Loader2, Map as MapIcon, MapPinPlus, Mountain, MountainSnow, Rotate3d, Satellite } from 'lucide-react'
import type { PaddleMapLayer } from '../Tours/paddle/paddleMapLayer'
import { PisteKeyButton } from '../Tours/winter/PisteKey'
import type { ComponentType } from 'react'
import { useTranslation } from '../../i18n'
import { FerrataLineIcon } from '../Ferratas/FerrataGlyph'
import type { FerrataMapLayer } from '../Ferratas/useFerrataMapLayer'
import type { FerrataStatus } from '../Ferratas/useTripFerratas'
import { fs } from '../shared/DialogShell'
import { Tooltip } from '../shared/Tooltip'
import { MAP_CONTROL_SHADOW } from './mapControlShadow'
import { FROSTED_SHELL, segmentStyle } from './mapControlShadow'
import type { ToggleableRasterOverlay } from './mapRasterOverlay'
import type { BaseMapHealth, TourRasterBase } from './tourRasterBases'
export type BaseLayer = 'default' | 'satellite'
export type TourBaseLayer = BaseLayer | TourRasterBase
/** What a tour's type offers on the planner map (P2B-06): its base layers, and the overlays beside the ferratas. */
export interface TourLayerOffer {
bases?: readonly TourBaseLayer[]
overlays?: readonly ToggleableRasterOverlay[]
/** PAD-05B: the paddle obstacles around a paddle tour, drawn by every renderer. */
paddle?: PaddleMapLayer
/** MAP-01, BIK-06: whether the map on terms shown (OpenHikingMap, CyclOSM) answers; the maps report into it. */
baseHealth?: BaseMapHealth
}
// Where the switcher sits and how much room it takes, so a control placed beside it
// (the phone's compass) is positioned off the same numbers instead of guessing them.
@@ -28,13 +48,7 @@ export function MapLayerSwitcher({ active, onToggle }: { active: BaseLayer; onTo
const label = isSatellite ? t('map.baseLayer.switchToDefault') : t('map.baseLayer.switchToSatellite')
return (
<div style={{
display: 'inline-flex', alignItems: 'center', padding: 4, borderRadius: 999, pointerEvents: 'auto',
background: 'var(--sidebar-bg)',
backdropFilter: 'blur(20px) saturate(180%)',
WebkitBackdropFilter: 'blur(20px) saturate(180%)',
boxShadow: MAP_CONTROL_SHADOW,
}}>
<div style={FROSTED_SHELL}>
{/* Same tooltip as its neighbours on the map, for the same reasons — see
TripRouteOverviewPill. To the right, though: this one sits at the
bottom left of the map, where a tooltip to the left would land on the
@@ -61,3 +75,268 @@ export function MapLayerSwitcher({ active, onToggle }: { active: BaseLayer; onTo
</div>
)
}
const TOUR_LAYERS = [
{ id: 'default', labelKey: 'map.baseLayer.default', Icon: MapIcon },
{ id: 'topo', labelKey: 'map.baseLayer.topo', Icon: Mountain },
{ id: 'hiking', labelKey: 'map.baseLayer.hiking', Icon: Footprints },
{ id: 'cycle', labelKey: 'map.baseLayer.cycle', Icon: Bike },
{ id: 'satellite', labelKey: 'map.baseLayer.satellite', Icon: Satellite },
] as const
type Translate = (key: string, params?: Record<string, string | number>) => string
/** What the via ferrata layer is doing, in words, for the toggle's tooltip and the screen reader. */
function ferrataStatusLabel(status: Exclude<FerrataStatus, 'idle'>, count: number, t: Translate): string {
switch (status) {
case 'loading':
return t('ferratas.loading')
case 'error':
return t('ferratas.error')
case 'offline':
return t('ferratas.offline')
case 'tooLarge':
return t('ferratas.zoomIn')
case 'ready':
return t('ferratas.count', { count })
}
}
/**
* The via ferrata switch with its count as a badge: how many ferratas reach
* into the view, a small spinner while tiles load, and the warning tone when
* there is a reason it cannot load (offline, the mirrors down, the view too
* wide), which the tooltip names. Nothing beside the switch, so the bottom row
* stays one pill wide. `compact` drops the word and keeps the icon and the
* badge; the tooltip and the accessible name still say what it is.
*/
function FerrataToggle({ layer, compact = false }: { layer: FerrataMapLayer; compact?: boolean }) {
const { t } = useTranslation()
const { active, status, count } = layer
const live = active && status !== 'idle' ? ferrataStatusLabel(status, count, t) : null
const problem = status === 'error' || status === 'offline' || status === 'tooLarge'
return (
<>
<Tooltip label={live ?? t('ferratas.layer')} placement="top">
<button
type="button"
onClick={layer.onToggle}
aria-label={t('ferratas.layer')}
aria-pressed={active}
className={active ? 'bg-accent text-accent-text' : 'text-content-muted'}
style={segmentStyle(active)}
>
<FerrataLineIcon size={15} strokeWidth={2} />
{!compact && <span>{t('ferratas.layer')}</span>}
{live && (
<span
aria-hidden
data-testid="ferrata-count-badge"
data-tone={problem ? 'warning' : 'default'}
className={`inline-flex h-[18px] min-w-[18px] items-center justify-center rounded-full px-1 font-semibold tabular-nums leading-none ${
problem ? 'bg-warning-soft text-warning' : 'bg-accent-text text-accent'
}`}
style={fs(10)}
>
{status === 'loading'
? <Loader2 size={10} strokeWidth={2.5} className="motion-safe:animate-spin" data-testid="ferrata-count-spinner" />
: count}
</span>
)}
</button>
</Tooltip>
{/* Polite, so a screen reader hears the count arrive without being interrupted. */}
<span role="status" aria-live="polite" className="sr-only">{live ?? ''}</span>
</>
)
}
/** The tour map's "set points" tool: while on, a click on the map places a point. */
export interface MapPlaceTool {
active: boolean
onToggle: () => void
}
/** The switch for the "set points" tool, on its icon, named by its tooltip. */
function PlaceToolToggle({ tool }: { tool: MapPlaceTool }) {
const { t } = useTranslation()
const label = t('tours.planner.placePoints')
return (
<Tooltip label={label} placement="top">
<button
type="button"
onClick={tool.onToggle}
aria-label={label}
aria-pressed={tool.active}
data-testid="map-place-tool"
className={tool.active ? 'bg-accent text-accent-text' : 'text-content-muted'}
style={segmentStyle(tool.active)}
>
<MapPinPlus size={15} strokeWidth={2} />
</button>
</Tooltip>
)
}
/** How an overlay the planner can offer is named and drawn on its switch. */
interface OverlayLook {
Icon: typeof Anchor
labelKey: string
downKey: string
/** On its icon alone, named by its tooltip, so the row stays short beside a type's other switches. */
iconOnly?: boolean
/** What the switch says while the map is further out than the overlay's first tiles. */
zoomInKey?: string
/** The overlay's key, beside its switch while the layer is on; told when nothing of it is drawn yet. */
Key?: ComponentType<{ belowMinZoom: boolean }>
}
const OVERLAY_LOOK: Record<string, OverlayLook> = {
seamarks: { Icon: Anchor, labelKey: 'tours.map.seamarks', downKey: 'tours.map.seamarksDown' },
// SKI-01: the row already holds the maps and 3D, so the pistes go by their icon.
pistes: {
Icon: MountainSnow,
labelKey: 'tours.map.pistes',
downKey: 'tours.map.pistesDown',
zoomInKey: 'tours.map.pistesZoomIn',
iconOnly: true,
Key: PisteKeyButton,
},
}
/** The warning mark on a switch whose source stopped answering; the tooltip says what it means. */
function DownBadge() {
return (
<span aria-hidden className="inline-flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-warning-soft px-1 font-semibold leading-none text-warning" style={fs(10)}>
!
</span>
)
}
/**
* The switch for a transparent overlay (the seamarks, the pistes), the way the via
* ferrata switch looks: on in the accent, and in the warning tone with a badge
* once its source stopped answering, which the tooltip names. The map and the
* planning go on without it. Switched on further out than its first tiles, it
* stays pressed in the soft accent and its tooltip says to zoom in, so an empty
* map does not read as broken. An overlay with a key shows the key's button
* beside the switch while it is on, also when the source is down, so the colours stay readable.
*/
function OverlayToggle({ overlay, compact }: { overlay: ToggleableRasterOverlay; compact: boolean }) {
const { t } = useTranslation()
const look = OVERLAY_LOOK[overlay.id]
if (!look) return null
const label = t(look.labelKey)
const down = overlay.status === 'down'
const on = overlay.status !== 'off'
const zoomIn = !down && overlay.belowMinZoom && look.zoomInKey ? t(look.zoomInKey) : null
const notice = down ? t(look.downKey) : zoomIn
const tone = zoomIn ? 'bg-accent-soft text-accent' : 'bg-accent text-accent-text'
return (
<>
<Tooltip label={notice ?? label} placement="top">
<button
type="button"
onClick={overlay.onToggle}
aria-label={label}
aria-pressed={on}
data-testid={`map-overlay-${overlay.id}`}
data-status={overlay.status}
data-below-min-zoom={zoomIn ? true : undefined}
className={on ? tone : 'text-content-muted'}
style={segmentStyle(on)}
>
<look.Icon size={15} strokeWidth={2} />
{!compact && !look.iconOnly && <span>{label}</span>}
{down && <DownBadge />}
</button>
</Tooltip>
{look.Key && on && <look.Key belowMinZoom={!!zoomIn} />}
<span role="status" aria-live="polite" className="sr-only">{notice ?? ''}</span>
</>
)
}
/**
* Per-view Tours control. It never reads or writes the global map setting.
* `compact` shows the base layers and the via ferrata switch by their icons
* alone, each named by its tooltip, for a bottom row that has to share its
* width (the 3D map's, beside the flyover dock).
*/
export function TourMapLayerSwitcher({
active,
onChange,
onToggleTerrain,
terrainActive = false,
ferrataLayer,
placeTool,
layers,
compact = false,
}: {
active: TourBaseLayer
onChange: (layer: TourBaseLayer) => void
/** The base layers and overlays this tour's type offers; all three bases and no overlay when left out. */
layers?: TourLayerOffer
/** Offers the 3D terrain switch beside the base layers. */
onToggleTerrain?: () => void
terrainActive?: boolean
/** Offers the via ferrata switch, with its count badge, beside the base layers. */
ferrataLayer?: FerrataMapLayer
/** Offers the "set points" switch, while a tour is being edited. */
placeTool?: MapPlaceTool
compact?: boolean
}) {
const { t } = useTranslation()
const bases = layers?.bases
const overlays = layers?.overlays
// A map on terms is a best-effort service: while it is shown and stops answering, its segment says so.
const health = layers?.baseHealth
return (
<div style={{ ...FROSTED_SHELL, gap: 2 }} role="group" aria-label={t('settings.mapStyle')}>
{TOUR_LAYERS.filter(({ id }) => !bases || bases.includes(id)).map(({ id, labelKey, Icon }) => {
const selected = active === id
const label = t(labelKey)
const down = !!health?.down && health.base === id && active === id
const downLabel = id === 'cycle' ? t('map.baseLayer.cycleDown') : t('map.baseLayer.hikingDown')
return (
<Tooltip key={id} label={down ? downLabel : label} placement="top" disabled={!compact && !down}>
<button
type="button"
onClick={() => onChange(id)}
aria-pressed={selected}
aria-label={compact ? label : undefined}
className={selected ? 'bg-accent-soft text-accent' : 'text-content-muted'}
style={segmentStyle(selected)}
>
<Icon size={15} strokeWidth={2} />
{!compact && <span>{label}</span>}
{down && <DownBadge />}
</button>
</Tooltip>
)
})}
{health?.down && active === health.base && (
<span role="status" aria-live="polite" className="sr-only">
{health.base === 'cycle' ? t('map.baseLayer.cycleDown') : t('map.baseLayer.hikingDown')}
</span>
)}
{(ferrataLayer || onToggleTerrain || placeTool || !!overlays?.length) && <span aria-hidden className="mx-0.5 h-5 w-px bg-edge" />}
{placeTool && <PlaceToolToggle tool={placeTool} />}
{ferrataLayer && <FerrataToggle layer={ferrataLayer} compact={compact} />}
{overlays?.map(overlay => <OverlayToggle key={overlay.id} overlay={overlay} compact={compact} />)}
{onToggleTerrain && (
<button
type="button"
onClick={onToggleTerrain}
aria-pressed={terrainActive}
className={terrainActive ? 'bg-accent text-accent-text' : 'text-content-muted'}
style={segmentStyle(terrainActive)}
>
<Rotate3d size={15} strokeWidth={2} />
<span>3D</span>
</button>
)}
</div>
)
}
+21
View File
@@ -0,0 +1,21 @@
import { Lock, Unlock } from 'lucide-react'
import { useTranslation } from '../../i18n'
import { MapTogglePill } from './MapTogglePill'
/**
* Locks the map view (#2010): picking days and places then leaves the camera where it is.
* Sits on top of the base-layer switcher, the other control about the view itself.
*/
export function MapLockPill({ locked, onToggle }: { locked: boolean; onToggle: () => void }) {
const { t } = useTranslation()
return (
<MapTogglePill
active={locked}
onToggle={onToggle}
label={locked ? t('map.lock.unlock') : t('map.lock.lock')}
testId="map-lock-pill"
tooltipPlacement="right"
icon={locked ? <Lock size={16} strokeWidth={2} /> : <Unlock size={16} strokeWidth={2} />}
/>
)
}
@@ -0,0 +1,68 @@
import type { ReactNode } from 'react'
import { Tooltip } from '../shared/Tooltip'
import { MAP_CONTROL_SHADOW } from './mapControlShadow'
/**
* One round on/off control in the frosted shell every map control wears, so a new
* one lines up with the compass, the layer switcher and the overview toggle.
*/
export function MapTogglePill({ active, onToggle, label, icon, testId, tooltipPlacement = 'left', badge = 0, opensDialog = false }: {
active: boolean
onToggle: () => void
label: string
icon: ReactNode
testId?: string
/** Away from the edge the control hugs: left on the right edge, right on the left one. */
tooltipPlacement?: 'left' | 'right'
/** A count pinned to the top right corner while above zero (how many filters are on, say). */
badge?: number
/**
* The control opens a dialog instead of switching something on and off (the phone
* map's places filter): it then announces the dialog, not a pressed state it
* does not have. `active` still lights it.
*/
opensDialog?: boolean
}) {
return (
<div style={{
position: 'relative',
display: 'inline-flex', alignItems: 'center', padding: 4, borderRadius: 999, pointerEvents: 'auto',
background: 'var(--sidebar-bg)',
backdropFilter: 'blur(20px) saturate(180%)',
WebkitBackdropFilter: 'blur(20px) saturate(180%)',
boxShadow: MAP_CONTROL_SHADOW,
}}>
{/* TREK's own tooltip, not the browser's: the native one ignores the colour
scheme, waits a second and a half, and cannot be read on a touch device. */}
<Tooltip label={label} placement={tooltipPlacement}>
<button
type="button"
onClick={onToggle}
aria-label={label}
aria-pressed={opensDialog ? undefined : active}
aria-haspopup={opensDialog ? 'dialog' : undefined}
data-testid={testId}
className={active ? 'text-accent' : 'text-content-muted'}
style={{
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
width: 34, height: 34, borderRadius: 999, border: 'none', cursor: 'pointer',
background: 'transparent', padding: 0,
transition: 'background 0.14s, color 0.14s',
}}
onMouseEnter={e => { e.currentTarget.style.background = 'var(--bg-hover)' }}
onMouseLeave={e => { e.currentTarget.style.background = 'transparent' }}
>
{icon}
</button>
</Tooltip>
{badge > 0 && (
<span
aria-hidden="true"
className="pointer-events-none absolute -right-[3px] -top-[3px] box-border flex h-4 min-w-[16px] items-center justify-center rounded-full bg-accent px-1 font-geist text-[0.5625rem] font-bold tabular-nums text-accent-text"
>
{badge}
</span>
)}
</div>
)
}
+51
View File
@@ -0,0 +1,51 @@
import { Check, Undo2 } from 'lucide-react';
import { fs } from '../shared/DialogShell';
import { MAP_CONTROL_SHADOW } from './mapControlShadow';
export interface MapUndoHintProps {
message: string;
undoLabel: string;
onUndo: () => void;
/** True while the pointer rests on the hint, so it does not vanish under it. */
onHold?: (held: boolean) => void;
}
/**
* A short note at the foot of the map that something just happened there, with
* the way back: a glass pill like the map's other controls. The caller places it
* and decides how long it stays.
*/
export function MapUndoHint({ message, undoLabel, onUndo, onHold }: Readonly<MapUndoHintProps>) {
return (
<div
role="status"
aria-live="polite"
data-testid="map-undo-hint"
className="trek-toast-enter pointer-events-auto flex max-w-full items-center gap-2 rounded-full p-1 ps-3 text-content"
style={{
background: 'var(--sidebar-bg)',
backdropFilter: 'blur(20px) saturate(180%)',
WebkitBackdropFilter: 'blur(20px) saturate(180%)',
boxShadow: MAP_CONTROL_SHADOW,
}}
onMouseEnter={() => onHold?.(true)}
onMouseLeave={() => onHold?.(false)}
onFocus={() => onHold?.(true)}
onBlur={() => onHold?.(false)}
>
<Check size={14} strokeWidth={2.4} className="flex-none text-accent" aria-hidden />
<span className="min-w-0 truncate font-semibold" style={fs(12, 'body')}>
{message}
</span>
<button
type="button"
onClick={onUndo}
className="bg-accent-soft flex h-[30px] flex-none items-center gap-1.5 rounded-full px-3 font-semibold text-accent hover:opacity-90"
style={fs(11)}
>
<Undo2 size={13} strokeWidth={2.2} aria-hidden />
{undoLabel}
</button>
</div>
);
}
@@ -0,0 +1,486 @@
/**
* Clicking a place pin after the map has been dragged (#2504).
*
* Nothing Leaflet-related is mocked here on purpose. The bug lived in the space between
* our drag wiring and Leaflet's own event routing: the pins swallow mousedown so a drag
* onto a day can start without the map sliding away, and Leaflet only forgets that the
* map was panned when it sees the next mousedown. A mocked react-leaflet, like the one
* MapView.test.tsx uses, has no such memory and kept passing throughout.
*
* The click itself has to keep taking Leaflet's route and the page's: it is what closes
* an open popup on the map, and an open context menu beside it.
*/
import React, { useState } from 'react'
import { flushSync } from 'react-dom'
import { describe, it, expect, vi, beforeAll, afterAll, afterEach } from 'vitest'
import { render, waitFor, act } from '../../../tests/helpers/render'
import { resetAllStores } from '../../../tests/helpers/store'
import { buildPlace } from '../../../tests/helpers/factories'
import { AMAP_ROAD } from '../../constants/mapDefaults'
import { useSettingsStore } from '../../store/settingsStore'
vi.mock('../../hooks/useGeolocation', () => ({
useGeolocation: () => ({ position: null, mode: 'off', error: null, errorCode: null, cycleMode: vi.fn(), setMode: vi.fn() }),
}))
// What the via ferrata layer draws is FerrataLayerLeaflet's own suite; here only what the
// renderer hands it. jsdom has no SVG renderer for Leaflet to draw real lines into.
vi.mock('../Ferratas/FerrataLayerLeaflet', () => ({
FerrataMapLayerLeaflet: ({ layer }: { layer?: { active: boolean; groups: readonly unknown[] } }) =>
layer?.active ? <div data-testid="ferrata-leaflet-layer" data-count={layer.groups.length} /> : null,
}))
vi.mock('../../services/photoService', () => ({
getCached: vi.fn(() => null),
isLoading: vi.fn(() => false),
fetchPhoto: vi.fn(),
onThumbReady: vi.fn(() => () => {}),
getAllThumbs: vi.fn(() => ({})),
}))
import L from 'leaflet'
import { MapView } from './MapView'
import { ContextMenu } from '../shared/ContextMenu'
import type { Ferrata } from '@trek/shared'
import { groupFerratas } from '../Ferratas/ferrataGroups'
// Every map this file builds, newest last, for the tests that reach past the component.
const maps: L.Map[] = []
L.Map.addInitHook(function (this: L.Map) { maps.push(this) })
// A raster template keeps the basemap a plain TileLayer: the vector default needs WebGL.
const RASTER = 'https://tiles.example.test/{z}/{x}/{y}.png'
// Leaflet sizes the map from the container, which jsdom lays out at 0 x 0. The cluster
// group only draws pins inside the visible bounds, so the map needs a real size.
const sized = ['clientWidth', 'clientHeight'] as const
const originals = new Map<string, PropertyDescriptor | undefined>()
beforeAll(() => {
// The pans here are synthetic and instant. With inertia, Leaflet would carry them on in
// animation frames that can land after a test has already unmounted its map.
L.Map.mergeOptions({ inertia: false })
for (const key of sized) {
originals.set(key, Object.getOwnPropertyDescriptor(HTMLElement.prototype, key))
Object.defineProperty(HTMLElement.prototype, key, { configurable: true, get: () => (key === 'clientWidth' ? 1000 : 700) })
}
})
afterAll(() => {
L.Map.mergeOptions({ inertia: true })
for (const key of sized) {
const original = originals.get(key)
if (original) Object.defineProperty(HTMLElement.prototype, key, original)
else delete (HTMLElement.prototype as unknown as Record<string, unknown>)[key]
}
})
afterEach(() => {
resetAllStores()
})
/** Leaflet only starts a pan for the primary button, which it reads off `which`. */
function mouse(type: string, x: number, y: number): MouseEvent {
const event = new MouseEvent(type, { bubbles: true, cancelable: true, button: 0, clientX: x, clientY: y })
Object.defineProperty(event, 'which', { value: 1 })
return event
}
/** Drag the map by its background, the way a user pans it. */
function panMap(container: Element) {
act(() => {
container.dispatchEvent(mouse('mousedown', 300, 300))
container.dispatchEvent(mouse('mousemove', 340, 320))
container.dispatchEvent(mouse('mousemove', 380, 340))
container.dispatchEvent(mouse('mouseup', 380, 340))
})
}
/** A plain click on an element: press, release, click, all on the same spot. */
function clickOn(el: Element) {
act(() => {
el.dispatchEvent(mouse('mousedown', 500, 350))
el.dispatchEvent(mouse('mouseup', 500, 350))
el.dispatchEvent(mouse('click', 500, 350))
})
}
/** The Leaflet marker that renders `el`; throws when the map has none. */
function markerOf(map: L.Map, el: Element): L.Marker {
let found: L.Marker | null = null
map.eachLayer(layer => {
if (layer instanceof L.Marker && layer.getElement() === el) found = layer
})
if (!found) throw new Error('no marker renders this element')
return found
}
function pointer(type: string, x: number, y: number): Event {
const event = new Event(type, { bubbles: true, cancelable: true })
Object.defineProperties(event, {
button: { value: 0 },
clientX: { value: x },
clientY: { value: y },
pointerId: { value: 1 },
})
return event
}
// Two stops a few hundred metres apart in Nara: separate pins at this zoom, not a cluster.
const places = [
{ ...buildPlace({ id: 1, name: 'Todai-ji', lat: 34.689, lng: 135.8398 }), category_name: null, category_color: null, category_icon: null },
{ ...buildPlace({ id: 2, name: 'Kasuga Taisha', lat: 34.6812, lng: 135.8484 }), category_name: null, category_color: null, category_icon: null },
]
async function renderMap() {
const onMarkerClick = vi.fn()
const onMapClick = vi.fn()
const view = render(
<MapView places={places} center={[34.685, 135.844]} zoom={15} tileUrl={RASTER} onMarkerClick={onMarkerClick} onMapClick={onMapClick} />,
)
const container = view.container.querySelector('.leaflet-container') as HTMLElement
// The cluster group takes its markers in on a timer (chunkedLoading).
await waitFor(() => expect(container.querySelectorAll('.leaflet-marker-icon[draggable="true"]').length).toBe(2))
const pins = [...container.querySelectorAll('.leaflet-marker-icon[draggable="true"]')] as HTMLElement[]
return { container, pins, onMarkerClick, onMapClick }
}
describe('MapView on a real Leaflet map', () => {
it('RC-08: previews waypoint drags locally and commits only at pointer up without panning', async () => {
const waypoint = { id: 'via-1', lat: 34.689, lng: 135.8398, role: 'via' as const }
const waypoints = [waypoint]
const onMove = vi.fn(() => true)
const onSelect = vi.fn()
const onMapClick = vi.fn()
const view = render(
<MapView
places={[]}
center={[waypoint.lat, waypoint.lng]}
zoom={15}
tileUrl={RASTER}
plannerWaypoints={waypoints}
onPlannerWaypointClick={onSelect}
onPlannerWaypointMove={onMove}
onMapClick={onMapClick}
focusKey="tour:1"
focusPoints={[[waypoint.lat, waypoint.lng]]}
routeProfileFocus={null}
/>
)
const map = maps[maps.length - 1]
await waitFor(() => expect(view.container.querySelector('.tour-planner-waypoint-marker')).not.toBeNull())
const pin = view.container.querySelector('.tour-planner-waypoint-marker') as HTMLElement
const marker = markerOf(map, pin)
const start = map.latLngToContainerPoint([waypoint.lat, waypoint.lng])
const end = start.add([30, 20])
const expected = map.containerPointToLatLng(end)
const center = map.getCenter()
act(() => {
pin.dispatchEvent(pointer('pointerdown', start.x, start.y))
pin.dispatchEvent(mouse('mousedown', start.x, start.y))
pin.dispatchEvent(pointer('pointermove', end.x, end.y))
})
expect(marker.getLatLng().lat).toBeCloseTo(expected.lat, 6)
expect(marker.getLatLng().lng).toBeCloseTo(expected.lng, 6)
expect(onMove).not.toHaveBeenCalled()
expect(waypoints[0]).toEqual(waypoint)
view.rerender(
<MapView
places={[]}
center={[waypoint.lat, waypoint.lng]}
zoom={15}
tileUrl={RASTER}
plannerWaypoints={waypoints}
onPlannerWaypointClick={onSelect}
onPlannerWaypointMove={onMove}
onMapClick={onMapClick}
focusKey="tour:1"
focusPoints={[[waypoint.lat, waypoint.lng]]}
routeProfileFocus={{ distanceMeters: 100, elevationMeters: 0, lat: 34.69, lng: 135.84, sampleIndex: 0 }}
/>
)
expect(marker.getLatLng().lat).toBeCloseTo(expected.lat, 6)
expect(marker.getLatLng().lng).toBeCloseTo(expected.lng, 6)
act(() => {
pin.dispatchEvent(pointer('pointerup', end.x, end.y))
pin.dispatchEvent(mouse('mouseup', end.x, end.y))
pin.dispatchEvent(mouse('click', end.x, end.y))
})
expect(onMove).toHaveBeenCalledOnce()
expect(onMove).toHaveBeenCalledWith(waypoint.id, expected.lat, expected.lng)
expect(onSelect).not.toHaveBeenCalled()
expect(onMapClick).not.toHaveBeenCalled()
expect(map.getCenter().lat).toBeCloseTo(center.lat, 6)
expect(map.getCenter().lng).toBeCloseTo(center.lng, 6)
view.rerender(
<MapView
places={[]}
center={[waypoint.lat, waypoint.lng]}
zoom={15}
tileUrl={RASTER}
plannerWaypoints={[{ ...waypoint, lat: expected.lat, lng: expected.lng }]}
onPlannerWaypointClick={onSelect}
onPlannerWaypointMove={onMove}
onMapClick={onMapClick}
focusKey="tour:1"
focusPoints={[[expected.lat, expected.lng]]}
routeProfileFocus={{ distanceMeters: 100, elevationMeters: 0, lat: 34.69, lng: 135.84, sampleIndex: 0 }}
/>
)
expect(map.getCenter().lat).toBeCloseTo(center.lat, 6)
expect(map.getCenter().lng).toBeCloseTo(center.lng, 6)
})
it('RC-08: cancellation restores the marker and a plain click still selects without affecting map-add', async () => {
const waypoint = { id: 'start', lat: 34.689, lng: 135.8398, role: 'start' as const }
const onMove = vi.fn(() => true)
const onSelect = vi.fn()
const onMapClick = vi.fn()
const view = render(
<MapView
places={[]}
center={[waypoint.lat, waypoint.lng]}
zoom={15}
tileUrl={RASTER}
plannerWaypoints={[waypoint]}
onPlannerWaypointClick={onSelect}
onPlannerWaypointMove={onMove}
onMapClick={onMapClick}
/>
)
const map = maps[maps.length - 1]
await waitFor(() => expect(view.container.querySelector('.tour-planner-waypoint-marker')).not.toBeNull())
const pin = view.container.querySelector('.tour-planner-waypoint-marker') as HTMLElement
const marker = markerOf(map, pin)
const start = map.latLngToContainerPoint([waypoint.lat, waypoint.lng])
const end = start.add([30, 20])
act(() => {
pin.dispatchEvent(pointer('pointerdown', start.x, start.y))
pin.dispatchEvent(pointer('pointermove', end.x, end.y))
pin.dispatchEvent(pointer('pointercancel', end.x, end.y))
})
expect(marker.getLatLng().lat).toBeCloseTo(waypoint.lat, 6)
expect(marker.getLatLng().lng).toBeCloseTo(waypoint.lng, 6)
expect(onMove).not.toHaveBeenCalled()
clickOn(pin)
expect(onSelect).toHaveBeenCalledOnce()
expect(onSelect).toHaveBeenCalledWith(waypoint.id)
expect(onMapClick).not.toHaveBeenCalled()
act(() => { map.fire('click', { latlng: L.latLng(34.7, 135.85) }) })
expect(onMapClick).toHaveBeenCalledOnce()
})
it('uses WGS-84 for Tours-local Topo over global Amap and preserves a Beijing click through layer switches', async () => {
useSettingsStore.setState({ settings: { ...useSettingsStore.getState().settings, map_base_layer: 'default' } })
const beijing = { ...buildPlace({ id: 201, name: 'Beijing', lat: 39.9042, lng: 116.4074 }), category_name: null, category_color: null, category_icon: null }
const onMapClick = vi.fn()
const route: [number, number][][] = [[[39.9042, 116.4074], [39.9052, 116.4084]]]
const waypoints = [{ id: 'beijing', lat: 39.9042, lng: 116.4074, role: 'start' as const }]
const renderLayer = (viewBaseLayer: 'default' | 'topo' | 'satellite') => (
<MapView
places={[beijing]}
center={[39.9042, 116.4074]}
zoom={15}
tileUrl={AMAP_ROAD}
viewBaseLayer={viewBaseLayer}
onViewBaseLayerChange={vi.fn()}
route={route}
plannerWaypoints={waypoints}
onMapClick={onMapClick}
/>
)
const view = render(renderLayer('default'))
await waitFor(() => expect(view.container.querySelector('.leaflet-container')).toBeInTheDocument())
let map = maps[maps.length - 1]
expect(map.options.crs).toBeTruthy()
expect(map.options.crs?.code).toBe('TREK:GCJ02')
const retainedCenter = L.latLng(39.91, 116.41)
act(() => map.setView(retainedCenter, 13))
view.rerender(renderLayer('topo'))
await waitFor(() => expect(maps[maps.length - 1]).not.toBe(map))
map = maps[maps.length - 1]
expect(map.options.crs).toBe(L.CRS.EPSG3857)
expect(map.getCenter().lat).toBeCloseTo(retainedCenter.lat, 5)
expect(map.getCenter().lng).toBeCloseTo(retainedCenter.lng, 5)
const expectedClick = L.latLng(39.9042, 116.4074)
const pixel = map.latLngToContainerPoint(expectedClick)
const roundTrip = map.containerPointToLatLng(pixel)
const pixelTolerance = map.distance(expectedClick, map.containerPointToLatLng(pixel.add([1, 1])))
map.fire('click', { latlng: roundTrip })
expect(onMapClick).toHaveBeenCalledOnce()
expect(map.distance(onMapClick.mock.calls[0][0].latlng, expectedClick)).toBeLessThanOrEqual(pixelTolerance)
view.rerender(renderLayer('satellite'))
await waitFor(() => expect(maps[maps.length - 1]).not.toBe(map))
map = maps[maps.length - 1]
expect(map.options.crs?.code).toBe('TREK:GCJ02')
expect(map.getCenter().lat).toBeCloseTo(retainedCenter.lat, 5)
expect(map.getCenter().lng).toBeCloseTo(retainedCenter.lng, 5)
expect(waypoints).toEqual([{ id: 'beijing', lat: 39.9042, lng: 116.4074, role: 'start' }])
expect(route).toEqual([[[39.9042, 116.4074], [39.9052, 116.4084]]])
})
it('FE-MAPCLICK-001: a pin opens its place on a map nobody has dragged yet', async () => {
const { pins, onMarkerClick, onMapClick } = await renderMap()
clickOn(pins[0])
expect(onMarkerClick).toHaveBeenCalledTimes(1)
// Still the marker's click, not one on the empty map behind it.
expect(onMapClick).not.toHaveBeenCalled()
})
it('FE-MAPCLICK-002: a pin still opens its place after the map was dragged (#2504)', async () => {
const { container, pins, onMarkerClick, onMapClick } = await renderMap()
panMap(container)
clickOn(pins[0])
expect(onMarkerClick).toHaveBeenCalledTimes(1)
// And again: the report was that every click after the pan went nowhere.
clickOn(pins[1])
expect(onMarkerClick).toHaveBeenCalledTimes(2)
expect(onMarkerClick.mock.calls.map(call => call[0]).sort()).toEqual([1, 2])
expect(onMapClick).not.toHaveBeenCalled()
})
it('FE-MAPCLICK-003: the click that ends a pan still counts for nothing', async () => {
const { container, onMarkerClick, onMapClick } = await renderMap()
panMap(container)
// The browser aims the click that closes a drag at the element both ends share,
// which is the map rather than the pin the pointer happened to stop on. Leaflet
// swallows it, and must go on doing so: it is not a click on the empty map either.
act(() => { container.dispatchEvent(mouse('click', 380, 340)) })
expect(onMarkerClick).not.toHaveBeenCalled()
expect(onMapClick).not.toHaveBeenCalled()
})
it("FE-MAPCLICK-004: a pin on a touch screen keeps Leaflet's own click and no drag wiring", async () => {
const original = Object.getOwnPropertyDescriptor(window.navigator, 'maxTouchPoints')
Object.defineProperty(window.navigator, 'maxTouchPoints', { configurable: true, value: 5 })
try {
const onMarkerClick = vi.fn()
const view = render(<MapView places={places} center={[34.685, 135.844]} zoom={15} tileUrl={RASTER} onMarkerClick={onMarkerClick} />)
const container = view.container.querySelector('.leaflet-container') as HTMLElement
await waitFor(() => expect(container.querySelectorAll('.leaflet-marker-icon').length).toBe(2))
const pin = container.querySelector('.leaflet-marker-icon') as HTMLElement
expect(pin.getAttribute('draggable')).toBeNull()
clickOn(pin)
expect(onMarkerClick).toHaveBeenCalledTimes(1)
} finally {
if (original) Object.defineProperty(window.navigator, 'maxTouchPoints', original)
else delete (window.navigator as unknown as Record<string, unknown>).maxTouchPoints
}
})
it('FE-MAPCLICK-005: the place a pin opens stays open when the pin redraws mid-click', async () => {
// The selection a pin makes redraws its icon, which replaces the element the click
// landed on. Leaflet has to have found the pin before that happens: reading the target
// afterwards, it finds it cut out of the map and takes the click for one on the empty
// background, which would close the place again straight away.
const onMapClick = vi.fn()
function Planner() {
const [selected, setSelected] = useState<number | null>(null)
return (
<>
<output data-testid="selected">{selected ?? ''}</output>
<MapView
places={places} center={[34.685, 135.844]} zoom={15} tileUrl={RASTER}
selectedPlaceId={selected}
onMarkerClick={(id: number) => flushSync(() => setSelected(id))}
onMapClick={() => { onMapClick(); setSelected(null) }}
/>
</>
)
}
const view = render(<Planner />)
const container = view.container.querySelector('.leaflet-container') as HTMLElement
await waitFor(() => expect(container.querySelectorAll('.leaflet-marker-icon[draggable="true"]').length).toBe(2))
const pin = container.querySelector('.leaflet-marker-icon[draggable="true"]') as HTMLElement
// The pointer lands on the photo inside the pin, which the redraw replaces.
clickOn(pin.firstElementChild as HTMLElement)
expect(onMapClick).not.toHaveBeenCalled()
expect(view.getByTestId('selected').textContent).not.toBe('')
})
it('FE-MAPCLICK-006: a pin click after a pan still closes an open popup on the map', async () => {
const { container, pins, onMarkerClick } = await renderMap()
const map = maps[maps.length - 1]
panMap(container)
// A hazard or plugin popup, as the planner opens them. Leaflet closes those on the
// "preclick" it sends ahead of every click it routes, a pin's included.
const popup = L.popup({ autoPan: false }).setLatLng([34.685, 135.844]).setContent('Road closed')
act(() => { popup.openOn(map) })
expect(map.hasLayer(popup)).toBe(true)
clickOn(pins[0])
expect(onMarkerClick).toHaveBeenCalledTimes(1)
expect(map.hasLayer(popup)).toBe(false)
})
it('FE-MAPCLICK-007: a pin click after a pan still reaches the page and closes an open context menu', async () => {
const onClose = vi.fn()
const onMarkerClick = vi.fn()
const view = render(
<>
{/* The menu the places list and the day plan open on a right click. It closes on
any click that reaches the document. */}
<ContextMenu menu={{ x: 20, y: 20, items: [{ label: 'Edit' }] }} onClose={onClose} />
<MapView places={places} center={[34.685, 135.844]} zoom={15} tileUrl={RASTER} onMarkerClick={onMarkerClick} />
</>,
)
const container = view.container.querySelector('.leaflet-container') as HTMLElement
await waitFor(() => expect(container.querySelectorAll('.leaflet-marker-icon[draggable="true"]').length).toBe(2))
const pin = container.querySelector('.leaflet-marker-icon[draggable="true"]') as HTMLElement
panMap(container)
clickOn(pin)
expect(onMarkerClick).toHaveBeenCalledTimes(1)
expect(onClose).toHaveBeenCalledTimes(1)
})
it('FE-MAPCLICK-008: pressing a pin after a pan still holds the map still for a drag onto a day', async () => {
const { container, pins } = await renderMap()
const map = maps[maps.length - 1]
panMap(container)
const before = map.getCenter()
// Press on the pin and move off it, as the start of a drag towards the day plan.
act(() => {
pins[0].dispatchEvent(mouse('mousedown', 500, 350))
document.dispatchEvent(mouse('mousemove', 560, 390))
document.dispatchEvent(mouse('mousemove', 620, 430))
document.dispatchEvent(mouse('mouseup', 620, 430))
})
expect(map.getCenter()).toEqual(before)
// The pan handler is back on, and the background still pans the map.
expect(map.dragging.enabled()).toBe(true)
panMap(container)
expect(map.getCenter()).not.toEqual(before)
})
it('RC-10: the tour layer pill offers the via ferrata switch, and the layer is drawn only while it is on', async () => {
const ferrata: Ferrata = { id: 'way/42', name: 'Via delle Trincee', grade: { raw: '4', level: 4, plus: null }, routeName: null,
geometry: [[46.52, 11.8], [46.53, 11.81]], osmUrl: 'https://www.openstreetmap.org/way/42' }
const layer = {
active: false, onToggle: vi.fn(), status: 'idle' as const, count: 0, groups: groupFerratas([ferrata]),
selectedId: null, onSelect: vi.fn(),
}
const view = render(
<MapView places={[]} center={[46.52, 11.8]} zoom={13} tileUrl={RASTER}
viewBaseLayer="topo" onViewBaseLayerChange={vi.fn()} ferrataLayer={layer} />,
)
const toggle = await view.findByRole('button', { name: 'Via ferratas' })
expect(toggle).toHaveAttribute('aria-pressed', 'false')
expect(view.queryByTestId('ferrata-leaflet-layer')).toBeNull()
act(() => toggle.click())
expect(layer.onToggle).toHaveBeenCalledOnce()
view.rerender(
<MapView places={[]} center={[46.52, 11.8]} zoom={13} tileUrl={RASTER}
viewBaseLayer="topo" onViewBaseLayerChange={vi.fn()} ferrataLayer={{ ...layer, active: true, status: 'ready', count: 1 }} />,
)
await waitFor(() => expect(view.getByTestId('ferrata-leaflet-layer')).toHaveAttribute('data-count', '1'))
expect(view.getByRole('button', { name: 'Via ferratas' })).toHaveAttribute('aria-pressed', 'true')
expect(view.getByTestId('ferrata-count-badge')).toHaveTextContent('1')
})
})
+343 -8
View File
@@ -5,13 +5,17 @@ import { act, fireEvent, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { resetAllStores } from '../../../tests/helpers/store'
import { buildPlace, buildReservation } from '../../../tests/helpers/factories'
import { MAP_MAX_ZOOM } from '../../constants/mapDefaults'
import { AMAP_ROAD, AMAP_SATELLITE, MAP_MAX_ZOOM, OPENTOPOMAP_TILE_URL } from '../../constants/mapDefaults'
import { useAuthStore } from '../../store/authStore'
import { useSettingsStore } from '../../store/settingsStore'
import { CATEGORY_ICON_MAP } from '../shared/categoryIcons'
import * as photoService from '../../services/photoService'
import { Coffee, MapPin, Mountain, Signpost, type LucideIcon } from 'lucide-react'
import { renderIconMarkup } from '../../utils/iconMarkup'
const mapMock = vi.hoisted(() => ({
getContainer: vi.fn(() => document.createElement('div')),
getCenter: vi.fn(() => ({ lat: 0, lng: 0 })),
panTo: vi.fn(),
setView: vi.fn(),
fitBounds: vi.fn(),
@@ -90,10 +94,10 @@ const clusterMock = vi.hoisted(() => {
vi.mock('react-leaflet', () => ({
// center/zoom are surfaced so tests can assert the camera the map is built
// with; maxZoom because a cluster refuses to attach to a map without one.
MapContainer: ({ children, center, zoom, maxZoom }: any) => (
<div data-testid="map-container" data-center={JSON.stringify(center)} data-zoom={zoom} data-maxzoom={maxZoom}>{children}</div>
MapContainer: ({ children, center, zoom, maxZoom, crs }: any) => (
<div data-testid="map-container" data-center={JSON.stringify(center)} data-zoom={zoom} data-maxzoom={maxZoom} data-crs={crs?.code ?? 'EPSG:3857'}>{children}</div>
),
TileLayer: () => <div data-testid="tile-layer" />,
TileLayer: ({ url }: any) => <div data-testid="tile-layer" data-url={url} />,
Marker: ({ children, eventHandlers, position, icon, zIndexOffset, ref }: any) => (
<div
ref={node => {
@@ -146,7 +150,14 @@ vi.mock('react-leaflet', () => ({
onClick={() => eventHandlers?.click?.()}
/>
),
CircleMarker: () => <div data-testid="circle-marker" />,
CircleMarker: ({ center, interactive, pathOptions }: any) => (
<div
data-testid={pathOptions?.className === 'tour-profile-focus-marker' ? 'profile-focus-marker' : 'circle-marker'}
data-center={JSON.stringify(center)}
data-interactive={String(interactive)}
data-path-options={JSON.stringify(pathOptions ?? null)}
/>
),
Circle: () => <div data-testid="circle" />,
Tooltip: ({ children }: any) => <>{children}</>,
useMap: () => mapMock,
@@ -193,7 +204,12 @@ vi.mock('../../services/photoService', () => ({
getAllThumbs: vi.fn(() => ({})),
}))
vi.mock('./gcj02Crs', () => ({
crsForBasemap: (gcj02: boolean) => gcj02 ? { code: 'TREK:GCJ02' } : undefined,
}))
import { MapView } from './MapView'
import type { RouteVia } from '../../types'
// Helper: build a place with the extra fields MapView uses (category_name/color/icon)
// that exist on joined DB rows but are not in the base Place TypeScript type.
@@ -229,6 +245,58 @@ describe('MapView', () => {
expect(screen.getByTestId('map-container')).toBeTruthy()
})
it('uses the CRS of the Tours-visible layer and preserves the viewport across datum switches', () => {
useSettingsStore.setState({ settings: { ...useSettingsStore.getState().settings, map_base_layer: 'default' } })
const beijing = buildMapPlace({ id: 201, name: 'Beijing', lat: 39.9042, lng: 116.4074 })
const onViewBaseLayerChange = vi.fn()
const route = [[[39.9042, 116.4074], [39.9052, 116.4084]]] as [number, number][][]
const plannerWaypoints = [{ id: 'start', lat: 39.9042, lng: 116.4074, role: 'start' as const }]
const routeProfileFocus = { distanceMeters: 100, elevationMeters: 0, lat: 39.9047, lng: 116.4079, sampleIndex: 0 }
const props = (viewBaseLayer: 'default' | 'topo' | 'hiking' | 'satellite') => ({
places: [beijing], center: [39.9042, 116.4074] as [number, number], zoom: 15,
route, plannerWaypoints, routeProfileFocus, tileUrl: AMAP_ROAD, viewBaseLayer, onViewBaseLayerChange,
})
const { rerender } = render(<MapView {...props('default')} />)
const defaultMap = screen.getByTestId('map-container')
expect(defaultMap).toHaveAttribute('data-crs', 'TREK:GCJ02')
expect(screen.getAllByTestId('marker').some(marker => marker.getAttribute('data-lat') === '39.9042'
&& marker.getAttribute('data-lng') === '116.4074')).toBe(true)
expect(screen.getByTestId('tile-layer')).toHaveAttribute('data-url', AMAP_ROAD)
const movedCenter = { lat: 39.91, lng: 116.41 }
mapMock.getCenter.mockReturnValue(movedCenter)
mapMock.getZoom.mockReturnValue(13)
const saveCamera = mapMock.on.mock.calls.find(([event]) => event === 'moveend zoomend')?.[1] as (() => void) | undefined
act(() => saveCamera?.())
rerender(<MapView {...props('topo')} />)
const topoMap = screen.getByTestId('map-container')
expect(topoMap).not.toBe(defaultMap)
expect(topoMap).toHaveAttribute('data-crs', 'EPSG:3857')
expect(topoMap).toHaveAttribute('data-center', JSON.stringify([movedCenter.lat, movedCenter.lng]))
expect(topoMap).toHaveAttribute('data-zoom', '13')
expect(screen.getByTestId('tile-layer')).toHaveAttribute('data-url', OPENTOPOMAP_TILE_URL)
expect(screen.getAllByTestId('polyline').every(polyline => polyline.getAttribute('data-points') === JSON.stringify(route[0]))).toBe(true)
expect(screen.getByTestId('profile-focus-marker')).toHaveAttribute('data-center', JSON.stringify([routeProfileFocus.lat, routeProfileFocus.lng]))
// MAP-01: OpenHikingMap is drawn in WGS-84 like topo, from its own template.
rerender(<MapView {...props('hiking')} />)
expect(screen.getByTestId('map-container')).toHaveAttribute('data-crs', 'EPSG:3857')
expect(screen.getByTestId('tile-layer')).toHaveAttribute('data-url', 'https://tile.openmaps.fr/openhikingmap/{z}/{x}/{y}.png')
rerender(<MapView {...props('satellite')} />)
const satelliteMap = screen.getByTestId('map-container')
expect(satelliteMap).not.toBe(topoMap)
expect(satelliteMap).toHaveAttribute('data-crs', 'TREK:GCJ02')
expect(screen.getByTestId('tile-layer')).toHaveAttribute('data-url', AMAP_SATELLITE)
rerender(<MapView {...props('default')} />)
expect(screen.getByTestId('map-container')).toHaveAttribute('data-crs', 'TREK:GCJ02')
expect(screen.getByTestId('tile-layer')).toHaveAttribute('data-url', AMAP_ROAD)
expect(useSettingsStore.getState().settings.map_base_layer).toBe('default')
expect(onViewBaseLayerChange).not.toHaveBeenCalled()
})
it('FE-COMP-MAPVIEW-002: renders one marker per place', () => {
const places = [
buildMapPlace({ id: 1, lat: 48.8584, lng: 2.2945 }),
@@ -347,6 +415,192 @@ describe('MapView', () => {
expect(screen.queryByTestId('polyline')).toBeNull()
})
it('moves a passive semantic profile focus marker without changing the map camera', () => {
const focus = { distanceMeters: 120, elevationMeters: 340, lat: 48.123, lng: 11.456, sampleIndex: 3 }
const focusPoints: [number, number][] = [[48.1, 11.4], [48.2, 11.5]]
const route: [number, number][][] = [[[48.1, 11.4], [48.2, 11.5]]]
mapMock.fitBounds.mockClear()
mapMock.panTo.mockClear()
mapMock.setView.mockClear()
const { rerender } = render(<MapView places={[]} route={route} fitKey={7} focusPoints={focusPoints} routeProfileFocus={focus} />)
const mapContainer = screen.getByTestId('map-container')
mapMock.fitBounds.mockClear()
expect(screen.getByTestId('profile-focus-marker')).toHaveAttribute('data-center', '[48.123,11.456]')
expect(screen.getByTestId('profile-focus-marker')).toHaveAttribute('data-interactive', 'false')
expect(JSON.parse(screen.getByTestId('profile-focus-marker').getAttribute('data-path-options')!)).toMatchObject({
color: 'var(--bg-card)', fillColor: 'var(--text-muted)',
})
const movedFocus = { ...focus, lat: 48.16, lng: 11.47 }
rerender(<MapView places={[]} route={route} fitKey={7} focusPoints={focusPoints} routeProfileFocus={movedFocus} />)
expect(screen.getByTestId('profile-focus-marker')).toHaveAttribute('data-center', '[48.16,11.47]')
expect(screen.getByTestId('map-container')).toBe(mapContainer)
expect(mapMock.fitBounds).not.toHaveBeenCalled()
expect(mapMock.panTo).not.toHaveBeenCalled()
expect(mapMock.setView).not.toHaveBeenCalled()
rerender(<MapView places={[]} route={route} fitKey={7} focusPoints={focusPoints} routeProfileFocus={null} />)
expect(screen.queryByTestId('profile-focus-marker')).toBeNull()
expect(mapMock.fitBounds).not.toHaveBeenCalled()
rerender(<MapView places={[]} fitKey={8} focusPoints={[[48, 11], [48.3, 11.8]]} />)
expect(mapMock.fitBounds).toHaveBeenCalled()
})
it('honors a location-search camera intent and preserves it through later route updates', () => {
const searchPoint: [number, number] = [35.0116, 135.7681];
const { rerender } = render(
<MapView
places={[]}
route={null}
followSelection={false}
focusKey="tour:0:search:1"
focusPoints={[searchPoint]}
/>
);
expect(mapMock.fitBounds).toHaveBeenCalledOnce();
expect(mapMock.fitBounds).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ maxZoom: 16 }));
const mapContainer = screen.getByTestId('map-container');
mapMock.fitBounds.mockClear();
rerender(
<MapView
places={[]}
route={[[searchPoint, [35.02, 135.77]]]}
followSelection={false}
focusKey="tour:0:search:1"
focusPoints={[searchPoint, [35.02, 135.77]]}
/>
);
expect(mapMock.fitBounds).not.toHaveBeenCalled();
expect(screen.getByTestId('map-container')).toBe(mapContainer);
rerender(
<MapView
places={[]}
followSelection={false}
focusKey="tour:1"
focusPoints={[
[46.8, 9.5],
[47.1, 10.1],
]}
/>
);
expect(mapMock.fitBounds).toHaveBeenCalledOnce();
});
it('frames Tour focus once, ignores waypoint and route updates, then honors a new focus intent', () => {
const route: [number, number][][] = [[[48, 11], [48.2, 11.3]]]
const { rerender } = render(
<MapView places={[]} route={null} followSelection={false} focusKey={1} focusPoints={[]} />,
)
expect(mapMock.fitBounds).not.toHaveBeenCalled()
rerender(<MapView places={[]} route={route} followSelection={false} focusKey={1} focusPoints={[[48, 11], [48.2, 11.3]]} />)
expect(mapMock.fitBounds).toHaveBeenCalledOnce()
mapMock.fitBounds.mockClear()
rerender(
<MapView
places={[]}
route={[[[48, 11], [48.2, 11.3], [48.4, 11.6]]]}
followSelection={false}
focusKey={1}
focusPoints={[[48, 11], [48.2, 11.3], [48.4, 11.6]]}
/>,
)
expect(mapMock.fitBounds).not.toHaveBeenCalled()
const mapContainer = screen.getByTestId('map-container')
const retainedCenter = { lat: 35.2, lng: 135.8 }
mapMock.getCenter.mockReturnValue(retainedCenter)
mapMock.getZoom.mockReturnValue(12)
mapMock.setView([retainedCenter.lat, retainedCenter.lng], 12)
mapMock.fitBounds.mockClear()
mapMock.setView.mockClear()
mapMock.panTo.mockClear()
rerender(<MapView places={[]} followSelection={false} focusKey={2} focusPoints={[]} />)
expect(screen.getByTestId('map-container')).toBe(mapContainer)
expect(mapMock.fitBounds).not.toHaveBeenCalled()
expect(mapMock.setView).not.toHaveBeenCalled()
expect(mapMock.panTo).not.toHaveBeenCalled()
expect(mapMock.getCenter()).toEqual(retainedCenter)
expect(mapMock.getZoom()).toBe(12)
rerender(
<MapView places={[]} followSelection={false} focusKey={2} focusPoints={[[48, 11], [48.5, 11.8]]} />,
)
expect(mapMock.fitBounds).toHaveBeenCalledOnce()
})
it('FE-COMP-MAPVIEW-089: a frame handed over while the map is built lands at once, a later one flies', () => {
// The map opens on a guess framed for the browser window. A map in a smaller box, the
// collection's beside its list, hands its own frame over at once, and must open there
// rather than show the guess and then fly to the frame.
const cafes: [number, number][] = [[48.21, 16.37], [38.71, -9.14], [55.7, 12.55]]
const { rerender } = render(<MapView places={[]} focusKey="list:17" focusPoints={cafes} />)
expect(mapMock.fitBounds.mock.calls).toEqual([[expect.anything(), expect.objectContaining({ animate: false, maxZoom: 16 })]])
mapMock.fitBounds.mockClear()
// Another list on the same map is a change the user asked for, and it flies as before.
const viewpoints: [number, number][] = [[60.12, 6.74], [44.15, 9.65], [47.56, 13.65]]
rerender(<MapView places={[]} focusKey="list:20" focusPoints={viewpoints} />)
expect(mapMock.fitBounds.mock.calls).toEqual([[expect.anything(), expect.objectContaining({ animate: true, maxZoom: 16 })]])
})
it('keeps selection fit and the pending route-arrival refit for semantic changes', () => {
const selectedPlace = buildMapPlace({ id: 901, lat: 48, lng: 11 })
const route: [number, number][][] = [[[48, 11], [48.2, 11.3]]]
const { rerender } = render(<MapView places={[]} route={null} fitKey={0} />)
mapMock.fitBounds.mockClear()
rerender(<MapView places={[selectedPlace]} route={null} fitKey={1} />)
expect(mapMock.fitBounds).toHaveBeenCalled()
mapMock.fitBounds.mockClear()
rerender(<MapView places={[selectedPlace]} route={route} fitKey={2} />)
expect(mapMock.fitBounds).toHaveBeenCalled()
})
it.each([
['two-point', [[48, 2], [49, 3]]],
['elevation', [[48, 2, 12.5], [49, 3, 22.75]]],
['long track', Array.from({ length: 1200 }, (_, index) => [48 + index / 100000, 2 + index / 100000])],
['loop', [[48, 2], [48.1, 2.1], [48, 2]]],
['point-to-point Tour', [[48, 2], [48.5, 2.5], [49, 3]]],
])('renders valid %s geometry unchanged', (_label, geometry) => {
render(<MapView places={[buildMapPlace({ route_geometry: JSON.stringify(geometry) })]} />)
const lines = screen.getAllByTestId('polyline')
expect(lines).toHaveLength(3)
const expected = geometry.map(([lat, lng]) => [lat, lng])
expect(JSON.parse(lines[1].getAttribute('data-points') || '[]')).toEqual(expected)
})
it.each([
['malformed JSON', 'not json'],
['non-array JSON', '{"coordinates":[]}'],
['one point', '[[48,2]]'],
['missing coordinate dimension', '[[48],[49,3]]'],
['string coordinates', '[[48,"2"],[49,3]]'],
['NaN token', '[[48,2],[NaN,3]]'],
['Infinity token', '[[48,2],[49,Infinity]]'],
['out-of-range latitude', '[[48,2],[91,3]]'],
['out-of-range longitude', '[[48,2],[49,181]]'],
['all-invalid coordinates', '[[91,2],[49,181]]'],
])('skips %s geometry without passing invalid points to Leaflet', (_label, geometry) => {
expect(() => render(<MapView places={[buildMapPlace({ route_geometry: geometry })]} />)).not.toThrow()
expect(screen.queryByTestId('polyline')).toBeNull()
})
it('filters invalid points while preserving the original order of a renderable track', () => {
const geometry = '[[48,2],null,[91,4],[48.5,2.5],[49,3]]'
render(<MapView places={[buildMapPlace({ route_geometry: geometry })]} />)
const lines = screen.getAllByTestId('polyline')
expect(lines).toHaveLength(3)
expect(JSON.parse(lines[1].getAttribute('data-points') || '[]')).toEqual([[48, 2], [48.5, 2.5], [49, 3]])
})
// ── Track colours (#776) ──────────────────────────────────────────────────
// The style has to travel through pathOptions: react-leaflet only calls
// setStyle when that object's reference changes, so bare color/weight props
@@ -753,10 +1007,90 @@ describe('MapView explore POIs', () => {
expect(markersWithZ('500')).toHaveLength(2)
expect(poiIcons).toHaveLength(1)
})
const pinGlyph = (Icon: LucideIcon) => React.createElement(Icon, { size: 13, color: 'white', strokeWidth: 2.5 })
const poiPinHtmls = async () => (await leafletMock()).divIcon.mock.calls
.filter(c => JSON.stringify((c[0] as { iconSize: number[] }).iconSize) === '[26,26]')
.map(c => (c[0] as { html: string }).html)
it('FE-COMP-MAPVIEW-084: a core POI pin is the disc it always was', () => {
render(<MapView pois={[buildPoi({ osm_id: 'node/20' })]} />)
expect(iconHtmlOf(markersWithZ('500')[0])).toBe(
'<div style="position:relative;width:26px;height:26px;border-radius:50%;background:#B45309;border:2px solid white;box-shadow:0 1px 5px rgba(0,0,0,0.3);display:flex;align-items:center;justify-content:center;cursor:pointer;overflow:hidden;">'
+ `${renderIconMarkup(pinGlyph(Coffee))}</div>`,
)
})
it('FE-COMP-MAPVIEW-085: a plugin POI pin takes the colour and icon its POI carries, checked first', () => {
render(<MapView pois={[
buildPoi({ osm_id: 'plugin:trail-finder:1', category: 'plugin:trail-finder/pins-085', color: '#2f855a', icon: 'Signpost' }),
buildPoi({ osm_id: 'plugin:trail-finder:2', category: 'plugin:trail-finder/bad-085', color: 'red;background:url(https://evil.example/x)', icon: '<img src=x onerror=alert(1)>' }),
]} />)
const [good, bad] = markersWithZ('500').map(iconHtmlOf)
expect(good).toContain('background:#2f855a;')
expect(good).toContain(renderIconMarkup(pinGlyph(Signpost)))
expect(bad).toContain('background:#6b7280;')
expect(bad).toContain(renderIconMarkup(pinGlyph(MapPin)))
expect(bad).not.toContain('evil.example')
expect(bad).not.toContain('<img')
})
it('FE-COMP-MAPVIEW-086: two plugin looks never share a cached pin, one look is built once', async () => {
const trail = { category: 'plugin:trail-finder/trails-086', color: '#2f855a', icon: 'Signpost' }
const { rerender } = render(<MapView pois={[
buildPoi({ osm_id: 'plugin:trail-finder:a', ...trail }),
buildPoi({ osm_id: 'plugin:trail-finder:b', ...trail, lat: 48.3 }),
buildPoi({ osm_id: 'plugin:water:c', category: 'plugin:water/wells-086', color: '#3182ce', icon: 'Mountain' }),
]} />)
expect(await poiPinHtmls()).toHaveLength(2)
const [first, second, well] = markersWithZ('500').map(iconHtmlOf)
expect(second).toBe(first)
expect(first).toContain('#2f855a')
expect(well).toContain('#3182ce')
expect(well).toContain(renderIconMarkup(pinGlyph(Mountain)))
// The plugin changed its colour in an update: the same category gets a new pin.
rerender(<MapView pois={[buildPoi({ osm_id: 'plugin:trail-finder:a', ...trail, color: '#c53030' })]} />)
expect(iconHtmlOf(markersWithZ('500')[0])).toContain('background:#c53030;')
})
it('FE-COMP-MAPVIEW-087: a plugin POI tooltip lists its detail rows as text, a core one stays the bare name', () => {
render(<MapView pois={[
buildPoi({ osm_id: 'node/30', name: 'Café Central' }),
buildPoi({
osm_id: 'plugin:trail-finder:3', category: 'plugin:trail-finder/pins-087', color: '#2f855a', icon: 'Signpost',
name: '<img src=x onerror=alert(1)>',
details: [{ label: 'Length', value: '12.4 km' }, { label: '<b onclick=alert(2)>Fee</b>', value: '"><svg onload=alert(3)>' }],
}),
]} />)
const [core, plugin] = markersWithZ('500')
expect(core.querySelector('[data-testid="poi-details"]')).toBeNull()
const details = plugin.querySelector('[data-testid="poi-details"]')!
expect([...details.querySelectorAll('span')].map(el => el.textContent)).toEqual([
'Length', '12.4 km', '<b onclick=alert(2)>Fee</b>', '"><svg onload=alert(3)>',
])
expect(plugin.textContent).toContain('<img src=x onerror=alert(1)>')
expect(plugin.querySelectorAll('img, b, svg')).toHaveLength(0)
// Sized by its content up to the cap, since the 0px tooltip pane gives it nothing to fill.
expect([...(details.parentElement as HTMLElement).classList]).toEqual(expect.arrayContaining(['w-max', 'max-w-56']))
})
it('FE-COMP-MAPVIEW-088: a long tooltip label wraps inside a capped column and leaves its value the wider share', () => {
render(<MapView pois={[buildPoi({
osm_id: 'plugin:trail-finder:4', category: 'plugin:trail-finder/pins-088', color: '#2f855a', icon: 'Signpost',
details: [{ label: 'Wheelchair accessible toilet, ground fl', value: 'Step-free via the side door on the left' }],
})]} />)
const details = markersWithZ('500')[0].querySelector('[data-testid="poi-details"]')!
expect(details.classList).toContain('grid-cols-[fit-content(45%)_1fr]')
const [label, value] = [...details.querySelectorAll('span')]
expect(label.classList).toContain('[overflow-wrap:anywhere]')
expect(value.classList).toContain('[overflow-wrap:anywhere]')
})
})
describe('MapView plugin route vias', () => {
const via = (overrides: Record<string, any> = {}) => ({ lat: 48.5, lng: 2.5, tone: 'default', ...overrides })
// Cast, not typed: one case hands in a tone outside RouteVia's union on purpose.
const via = (overrides: Partial<Record<keyof RouteVia, unknown>> = {}) =>
({ lat: 48.5, lng: 2.5, tone: 'default', ...overrides }) as RouteVia
it('FE-COMP-MAPVIEW-037: draws a tone dot for each via point', () => {
render(<MapView routeVias={[via({ tone: 'success' }), via({ tone: 'danger', lat: 48.7 })]} />)
@@ -822,10 +1156,11 @@ describe('MapView plugin route vias', () => {
})
describe('MapView map event wiring', () => {
it('FE-COMP-MAPVIEW-043: reports the viewport bbox once the map is ready and again on every move', () => {
it('FE-COMP-MAPVIEW-043: reports the viewport bbox and its zoom once the map is ready and again on every move', () => {
const onViewportChange = vi.fn()
mapMock.getZoom.mockReturnValue(10)
render(<MapView onViewportChange={onViewportChange} />)
expect(onViewportChange).toHaveBeenCalledWith({ south: 47, west: 1, north: 49, east: 3 })
expect(onViewportChange).toHaveBeenCalledWith({ south: 47, west: 1, north: 49, east: 3 }, 10)
const moveend = handlerFor('moveend')
const zoomend = handlerFor('zoomend')
+245 -225
View File
@@ -1,12 +1,15 @@
import { useEffect, useRef, useState, useMemo, useCallback, createElement, memo } from 'react'
import { useEffect, useRef, useState, useMemo, useCallback, memo, type ComponentType } from 'react'
import DOM from 'react-dom'
import { renderIconMarkup } from '../../utils/iconMarkup'
import { categoryIconSvg } from './categoryIconSvg'
import { MapContainer, TileLayer, Marker, Polyline, CircleMarker, Circle, useMap, Tooltip } from 'react-leaflet'
import MarkerClusterGroup from 'react-leaflet-cluster'
import { makeMarkerDraggable, makePoiDraggable, draggedPoiId } from './markerDrag'
import { CLUSTER_OPTIONS, createClusterIcon, revealInCluster, type ClusterGroupLike } from './markerCluster'
import RoadtripViaMarkers from './RoadtripViaMarkers'
import PlannerWaypointMarker from './PlannerWaypointMarker'
import HazardLayers from './HazardLayers'
import { RouteHitBand } from './RouteHitBand'
import { formatViaDwell } from './routeViaDwell'
import { ALT_CASING, ALT_LABEL_TEXT } from '../Roadtrip/alternativeColors'
import { serviceMarkerHtml, serviceMarkerOuter } from '../Roadtrip/serviceMarker'
import type { AlternativeOverlay } from '../Roadtrip/alternativeOverlays'
@@ -37,7 +40,7 @@ import L from 'leaflet'
import 'leaflet.markercluster/dist/MarkerCluster.css'
import 'leaflet.markercluster/dist/MarkerCluster.Default.css'
import { mapsApi } from '../../api/client'
import { CATEGORY_ICON_MAP } from '../shared/categoryIcons'
import { AssistantMapLeaflet } from './AssistantMapLeaflet'
import PlaceHoverCard from './PlaceHoverCard'
import { ratingBadgeHtml } from './ratingBadge'
import ReservationOverlay from './ReservationOverlay'
@@ -46,32 +49,33 @@ import { PluginMapLayers } from './MapPluginLayers'
import { useTransportRoutes } from '../../hooks/useTransportRoutes'
import { visibleRouteReservations } from '../../utils/reservationRoutes'
import { safeHexColor } from '../../utils/safeColor'
import { placeMarkerLook } from './markerLook'
import { escapeHtml } from '@trek/shared'
import type { Day, Reservation, RouteVia } from '../../types'
import type { Day, Place, Reservation, RouteVia } from '../../types'
import type { MapHoverInfo } from './mapHover'
import { nightPauseMarker, NIGHT_PAUSE_MIN_ZOOM } from './nightPauseMarker'
import NightPauseTooltip from './NightPauseTooltip'
import ClusteredPois from './ClusteredPois'
import { NightPauseDrag } from './NightPauseDrag'
import type { DayBoundaryControls } from './dayBoundaryDrag'
import { POI_CATEGORY_BY_KEY, type Poi } from './poiCategories'
import type { Poi } from './poiCategories'
import { poiDetailRowKey, poiDetailRows, poiPinCacheKey, poiPinParts } from './poiMarker'
import { resolveTrackColor, hasManualTrackColor } from './trackColors'
import { SelectedTrackLine, TrackLines } from './TrackLines'
import DawarichTrailLayer from './DawarichTrailLayer'
import { OFM_POSITRON, DEFAULT_MAP_CENTER, DEFAULT_MAP_ZOOM, MAP_MAX_ZOOM, SATELLITE_TILE_URL, SATELLITE_TILE_MAXZOOM, AMAP_SATELLITE, attributionForTile } from '../../constants/mapDefaults'
import { tileHealthHandlers, tourRasterBaseOf } from './tourRasterBases'
import { crsForBasemap } from './gcj02Crs'
import { isGcj02Basemap, resolveBasemap } from '../../utils/tileUrl'
import VectorBasemap from './VectorBasemap'
import { useSettingsStore } from '../../store/settingsStore'
import { MapLayerSwitcher, MAP_LAYER_SWITCHER_INSET } from './MapLayerSwitcher'
import { TourMapLayersLeaflet } from './RasterOverlayLeaflet'
import { MapLayerSwitcher, TourMapLayerSwitcher, MAP_LAYER_SWITCHER_INSET, type TourBaseLayer } from './MapLayerSwitcher'
import { MapLockPill } from './MapLockPill'
import { computeMapViewport, TILE_SIZE_RASTER, type ViewportPadding } from '../../utils/mapViewport'
import { parseRenderableRouteGeometry } from '../../utils/routeGeometry'
function categoryIconSvg(iconName: string | null | undefined, size: number): string {
const IconComponent = (iconName && CATEGORY_ICON_MAP[iconName]) || CATEGORY_ICON_MAP['MapPin']
try {
return renderIconMarkup(createElement(IconComponent, { size, color: 'white', strokeWidth: 2.5 }))
} catch { return '' }
}
import type { Place } from '../../types'
import type { MapViewProps } from './mapViewContract'
// Fix default marker icons for vite. `_getIconUrl` is a Leaflet-internal field
// not present in the public typings, so narrow to delete it.
@@ -104,12 +108,6 @@ function routeViaIcon(tone: string): L.DivIcon {
return icon
}
function formatViaDwell(seconds: number): string {
const h = Math.floor(seconds / 3600)
const m = Math.round((seconds % 3600) / 60)
return h > 0 ? `${h} h ${m} min` : `${m} min`
}
function nightPauseIcon(via: RouteVia): L.DivIcon {
const key = `night:${via.nightPause!.day}:${via.nightPause!.atPlace}`
const cached = viaIconCache.get(key)
@@ -135,7 +133,8 @@ function RouteViaMarker({ via, controls, eventHandlers, children }: {
* Shows image_url if available, otherwise category icon in colored circle.
*/
function createPlaceIcon(place, orderNumbers, isSelected) {
const cacheKey = `${place.id}:${isSelected}:${place.image_url || ''}:${place.category_color || ''}:${place.category_icon || ''}:${place.stop_type || ''}:${orderNumbers?.join(',') || ''}:${(place as { rating_avg?: number | null }).rating_avg ?? ''}`
const look = placeMarkerLook(place, isSelected)
const cacheKey = `${place.id}:${isSelected}:${look.key}:${place.image_url || ''}:${place.category_color || ''}:${place.category_icon || ''}:${place.stop_type || ''}:${orderNumbers?.join(',') || ''}:${(place as { rating_avg?: number | null }).rating_avg ?? ''}`
const cached = iconCache.get(cacheKey)
if (cached) return cached
@@ -150,11 +149,10 @@ function createPlaceIcon(place, orderNumbers, isSelected) {
iconCache.set(cacheKey, icon)
return icon
}
const size = isSelected ? 44 : 36
const { size, borderWidth } = look
// Allow-listed, not escaped: the value lands in style="…" of a divIcon, where
// escaping stops the attribute breakout but still permits a CSS url().
const borderColor = isSelected ? '#111827' : safeHexColor(place.category_color, 'white')
const borderWidth = isSelected ? 3 : 2.5
const shadow = isSelected
? '0 0 0 3px rgba(17,24,39,0.25), 0 4px 14px rgba(0,0,0,0.3)'
: '0 2px 8px rgba(0,0,0,0.22)'
@@ -163,7 +161,7 @@ function createPlaceIcon(place, orderNumbers, isSelected) {
// Number badges (bottom-right), or the rating where there are none: a numbered stop
// is one already planned into a day, and the rating answers the question asked before
// that. The two never want the same corner at the same time.
let badgeHtml = ratingBadgeHtml((place as { rating_avg?: number | null }).rating_avg)
let badgeHtml = look.showRating ? ratingBadgeHtml((place as { rating_avg?: number | null }).rating_avg) : ''
if (orderNumbers && orderNumbers.length > 0) {
const label = orderNumbers.join(' · ')
badgeHtml = `<span style="
@@ -182,7 +180,7 @@ function createPlaceIcon(place, orderNumbers, isSelected) {
// Prefer base64 data URLs (no zoom lag); also accept same-origin proxy + uploaded
// custom images (#1136) as a fallback while the thumb is still being generated
if (place.image_url && (place.image_url.startsWith('data:') || place.image_url.startsWith('/api/maps/place-photo/') || place.image_url.startsWith('/uploads/'))) {
if (look.showPhoto && place.image_url && (place.image_url.startsWith('data:') || place.image_url.startsWith('/api/maps/place-photo/') || place.image_url.startsWith('/uploads/'))) {
const imgIcon = L.divIcon({
className: '',
html: `<div style="
@@ -193,7 +191,7 @@ function createPlaceIcon(place, orderNumbers, isSelected) {
width:${size}px;height:${size}px;border-radius:50%;
border:${borderWidth}px solid ${borderColor};
box-shadow:${shadow};
overflow:hidden;background:${bgColor};
overflow:hidden;background:${bgColor};${look.circleCss}
">
${markerPhotoHtml(place.image_url)}
</div>
@@ -216,9 +214,9 @@ function createPlaceIcon(place, orderNumbers, isSelected) {
background:${bgColor};
display:flex;align-items:center;justify-content:center;
cursor:pointer;position:relative;
will-change:transform;contain:layout style;
will-change:transform;contain:layout style;${look.circleCss}
">
${categoryIconSvg(place.category_icon, isSelected ? 18 : 15)}
${categoryIconSvg(place.category_icon, look.iconSize)}
${badgeHtml}
</div>`,
iconSize: [size, size],
@@ -232,18 +230,18 @@ function createPlaceIcon(place, orderNumbers, isSelected) {
// Small coloured pin for an OSM "explore" POI — distinct from the photo-circle
// markers of planned places; the colour matches its pill category.
const poiIconCache = new Map<string, L.DivIcon>()
function createPoiIcon(category: string, brandWikidata?: string | null) {
function createPoiIcon(poi: Pick<Poi, 'category' | 'icon' | 'color'>, brandWikidata?: string | null) {
// One flat disc in the category's colour with its icon, and never the chain's logo.
// The brands turned a corridor full of petrol stations into a row of advertisements,
// they were unreadable at pin size, and a brand with no logo on file fell back to a
// different picture entirely — so no two pins looked alike. `brandWikidata` is kept in
// the signature because the callers still have it; it simply no longer changes anything.
void brandWikidata
const cached = poiIconCache.get(category)
// A plugin category's key carries its colour and icon too, so two looks never share a pin.
const cacheKey = poiPinCacheKey(poi)
const cached = poiIconCache.get(cacheKey)
if (cached) return cached
const cat = POI_CATEGORY_BY_KEY[category]
const color = cat?.color || '#6b7280'
const svg = cat ? renderIconMarkup(createElement(cat.Icon, { size: 13, color: 'white', strokeWidth: 2.5 })) : ''
const { color, svg } = poiPinParts(poi)
const icon = L.divIcon({
className: '',
html: `<div style="position:relative;width:26px;height:26px;border-radius:50%;background:${color};border:2px solid white;box-shadow:0 1px 5px rgba(0,0,0,0.3);display:flex;align-items:center;justify-content:center;cursor:pointer;overflow:hidden;">${svg}</div>`,
@@ -251,10 +249,37 @@ function createPoiIcon(category: string, brandWikidata?: string | null) {
iconAnchor: [13, 13],
tooltipAnchor: [0, -14],
})
poiIconCache.set(category, icon)
poiIconCache.set(cacheKey, icon)
return icon
}
/**
* The hover tooltip of an explore POI: its name, and for a plugin POI the rows the
* plugin knows about it (the GL hover card shows the same, see buildPoiPopupHtml).
* React text throughout, so nothing a plugin sends is ever read as markup. A POI
* without rows keeps the bare name it has always had.
*/
function PoiTooltipBody({ poi }: Readonly<{ poi: Poi }>) {
const rows = poiDetailRows(poi)
if (!rows.length) return poi.name
// w-max because Leaflet's tooltip pane is 0px wide: without an intrinsic width the
// tooltip shrinks to its narrowest layout and the values wrap a letter per line. The
// label column stops at 45% and wraps, so a long label leaves its value room too.
return (
<div className="w-max max-w-56 whitespace-normal">
<div className="truncate font-semibold">{poi.name}</div>
<div className="mt-1 grid grid-cols-[fit-content(45%)_1fr] gap-x-1.5 font-normal" data-testid="poi-details">
{rows.map(row => (
<div key={poiDetailRowKey(row)} className="contents">
<span className="text-content-muted [overflow-wrap:anywhere]">{row.label}</span>
<span className="[overflow-wrap:anywhere]">{row.value}</span>
</div>
))}
</div>
</div>
)
}
// Clears the hover tooltip the moment the camera starts moving and suppresses
// re-showing it until the move ends: after a click-recenter the marker slides
// away under a stationary cursor, so the browser never fires mouseout — and
@@ -309,14 +334,14 @@ function PoiDropTarget({ onPoiDropOnRoute }: { onPoiDropOnRoute?: (osmId: string
}
// Emits the current viewport bbox on pan/zoom so the POI-explore pill can fetch
// OSM places for the visible area.
function ViewportController({ onViewportChange }: { onViewportChange?: (b: { south: number; west: number; north: number; east: number }) => void }) {
// OSM places for the visible area, with the zoom an overlay's minimum is read against.
function ViewportController({ onViewportChange }: { onViewportChange?: MapViewProps['onViewportChange'] }) {
const map = useMap()
useEffect(() => {
if (!onViewportChange) return
const emit = () => {
const b = map.getBounds()
onViewportChange({ south: b.getSouth(), west: b.getWest(), north: b.getNorth(), east: b.getEast() })
onViewportChange({ south: b.getSouth(), west: b.getWest(), north: b.getNorth(), east: b.getEast() }, map.getZoom())
}
map.whenReady(emit) // ensure the first bbox is captured once the map is laid out
map.on('moveend', emit)
@@ -326,7 +351,23 @@ function ViewportController({ onViewportChange }: { onViewportChange?: (b: { sou
return null
}
function MapCameraSnapshot({ onChange }: { onChange: (center: [number, number], zoom: number) => void }) {
const map = useMap()
useEffect(() => {
const save = () => {
const center = map.getCenter()
onChange([center.lat, center.lng], map.getZoom())
}
map.whenReady(save)
map.on('moveend zoomend', save)
return () => { map.off('moveend zoomend', save) }
}, [map, onChange])
return null
}
interface SelectionControllerProps {
/** False while the traveller locked the map (#2010): a pick changes nothing on it. */
follow: boolean
places: Place[]
selectedPlaceId: number | null
dayPlaces: Place[]
@@ -334,12 +375,12 @@ interface SelectionControllerProps {
paddingOpts: L.FitBoundsOptions
}
function SelectionController({ places, selectedPlaceId, dayPlaces, selectedPlace, paddingOpts }: SelectionControllerProps) {
function SelectionController({ follow, places, selectedPlaceId, dayPlaces, selectedPlace, paddingOpts }: SelectionControllerProps) {
const map = useMap()
const prev = useRef(null)
useEffect(() => {
if (selectedPlaceId && selectedPlaceId !== prev.current) {
if (follow && selectedPlaceId && selectedPlaceId !== prev.current) {
// Pan to the selected place without changing zoom. Offset the centre by the
// side-panel + bottom-inspector padding so the pin lands in the middle of the
// *visible* map area rather than the geometric centre (where the bottom panel
@@ -358,7 +399,7 @@ function SelectionController({ places, selectedPlaceId, dayPlaces, selectedPlace
}
}
prev.current = selectedPlaceId
}, [selectedPlaceId, places, dayPlaces, selectedPlace, map])
}, [selectedPlaceId, places, dayPlaces, selectedPlace, map, follow])
return null
}
@@ -386,31 +427,16 @@ function MapController({ center, zoom }: MapControllerProps) {
// fit to that day's destinations immediately, then — once the day's route has
// finished computing asynchronously — re-fit once more to include the full route
// polyline, so a route that bulges past its stops stays in view (#1128).
interface BoundsControllerProps {
// The focus props are the contract's, documented there once rather than copied here.
interface BoundsControllerProps extends Pick<MapViewProps, 'focusPoints' | 'focusKey' | 'fitPadding'> {
places: Place[]
routeCoords: [number, number][]
fitKey: number
paddingOpts: L.FitBoundsOptions
/** The map was built already framed on these places, so the opening fit has nothing to do. */
framedOnMount?: boolean
/**
* An explicit stretch of map to frame, independent of the day being shown.
*
* `fitKey` cannot express this: it carries no coordinates, and each renderer decides
* for itself that it means "the selected day". Weighing the ways of driving one leg
* needs that leg on screen, which is neither the day nor the trip.
*/
focusPoints?: [number, number][]
/**
* What the caller's own chrome covers while `focusPoints` is framed, in pixels per edge.
*
* `paddingOpts` knows the planner's panels and nothing else, and on a phone it is a flat
* margin. A shell that lays its own bars over the map passes what they cover, so the
* frame lands in the part still visible. Only the fit on `focusPoints` reads it.
* Compared by value: the same numbers in a new object do not refit, while new numbers
* refit the points already handed over, because the chrome they must clear has moved.
*/
fitPadding?: ViewportPadding
/** False while the map is locked (#2010): an arriving route no longer re-fits it. */
follow?: boolean
}
/** A padding box as Leaflet's fit options spell it, corner pairs rather than edges. */
@@ -421,11 +447,14 @@ function leafletPadding(box: ViewportPadding): L.FitBoundsOptions {
}
}
function BoundsController({ places, routeCoords, fitKey, paddingOpts, framedOnMount = false, focusPoints, fitPadding }: BoundsControllerProps) {
function BoundsController({ places, routeCoords, fitKey, paddingOpts, framedOnMount = false, focusPoints, focusKey, fitPadding, follow = true }: BoundsControllerProps) {
const map = useMap()
const prevFitKey = useRef(-1)
const awaitingRoute = useRef(false)
const fitRan = useRef(false)
const didInitialFocus = useRef(false)
const prevFocusKey = useRef(focusKey)
const built = useRef(false)
const fitTo = useCallback((coords: [number, number][], padding: L.FitBoundsOptions = paddingOpts) => {
if (coords.length === 0) return
@@ -446,7 +475,7 @@ function BoundsController({ places, routeCoords, fitKey, paddingOpts, framedOnMo
* (#1982). MapViewGL never had the nudge, so this also brings the two
* renderers back into agreement.
*/
map.fitBounds(bounds, { ...padding, maxZoom: 16, animate: true })
map.fitBounds(bounds, { maxZoom: 16, animate: true, ...padding })
}
} catch {}
}, [map, paddingOpts])
@@ -475,6 +504,8 @@ function BoundsController({ places, routeCoords, fitKey, paddingOpts, framedOnMo
useEffect(() => {
if (!awaitingRoute.current || routeCoords.length === 0) return
awaitingRoute.current = false
// A map locked since that fit keeps its view when the route turns up (#2010).
if (!follow) return
fitTo([...places.map(p => [p.lat, p.lng] as [number, number]), ...routeCoords])
}, [routeCoords]) // eslint-disable-line react-hooks/exhaustive-deps
@@ -485,11 +516,21 @@ function BoundsController({ places, routeCoords, fitKey, paddingOpts, framedOnMo
// Frame whatever was handed over. Nothing happens when it empties, so closing the
// picker leaves the map where the user left it rather than snapping back.
useEffect(() => {
// The first run is the map being built. A frame handed over by then is where the map
// opens, so it lands at once instead of flying in from the window-sized opening guess.
const opening = !built.current
built.current = true
if (!focusPoints?.length) return
if (focusKey !== undefined) {
const shouldFit = !didInitialFocus.current || focusKey !== prevFocusKey.current
prevFocusKey.current = focusKey
if (!shouldFit) return
didInitialFocus.current = true
}
// A day fit that has not run yet must not overwrite this a moment later.
awaitingRoute.current = false
fitTo(focusPoints, fitPadding ? leafletPadding(fitPadding) : paddingOpts)
}, [focusPoints, fitPaddingKey]) // eslint-disable-line react-hooks/exhaustive-deps
fitTo(focusPoints, { ...(fitPadding ? leafletPadding(fitPadding) : paddingOpts), animate: !opening })
}, [focusPoints, focusKey, fitPaddingKey]) // eslint-disable-line react-hooks/exhaustive-deps
return null
}
@@ -542,10 +583,8 @@ function MapContextMenuHandler({ onContextMenu }: { onContextMenu: ((e: L.Leafle
// Travel times are shown in the day sidebar (per-segment connectors), not on the map.
// Module-level photo cache shared with PlaceAvatar
import { getCached, isLoading, fetchPhoto, onThumbReady, getAllThumbs } from '../../services/photoService'
import { isCustomPlaceImage, markerPhotoHtml, photoCacheKey, photoSourcesKey } from './placePhoto'
import { useAuthStore } from '../../store/authStore'
import { useMarkerThumbs } from './useMarkerThumbs'
import { markerPhotoHtml, placePhotoFull, placePhotoUrl } from './placePhoto'
import { useGeolocation } from '../../hooks/useGeolocation'
import LocationButton from './LocationButton'
import { useIsPhone } from '../../mobile/useIsPhone'
@@ -622,6 +661,32 @@ function LeafletLocationLayer({ position, mode }: { position: GeoPosition | null
)
}
/**
* Make a place pin a drag source without losing its clicks to an old pan.
*
* The drag wiring swallows mousedown so the map holds still while a drag starts. Leaflet
* tells a click from the end of a pan by a flag it only clears on the next mousedown it
* sees, so once the map had been dragged, every click on a pin was taken for the tail of
* that pan and dropped, until something else on the map was pressed (#2504). A press on
* the pin now clears that flag itself, as the map would have. Switching the pan handler
* off and on again is the public way to do that, and nothing is being panned at that
* moment. The click then takes Leaflet's normal route, so it still closes open popups
* and still reaches listeners further up the page, like an open context menu.
*/
function wireDraggablePin(el: HTMLElement, placeId: number, map: L.Map): () => void {
const undoDrag = makeMarkerDraggable(el, placeId)
const forgetPan = (e: MouseEvent) => {
if (e.button !== 0 || !map.dragging.enabled()) return
map.dragging.disable()
map.dragging.enable()
}
el.addEventListener('mousedown', forgetPan)
return () => {
undoDrag()
el.removeEventListener('mousedown', forgetPan)
}
}
interface MemoMarkerProps {
place: any
isSelected: boolean
@@ -640,6 +705,7 @@ const MemoMarker = memo(function MemoMarker({
place, isSelected, orderNumbers, photoUrl, onClickPlace, onHover, onHoverOut, draggable, onRegister,
}: MemoMarkerProps) {
const icon = createPlaceIcon({ ...place, image_url: photoUrl }, orderNumbers, isSelected)
const map = useMap()
const cleanupRef = useRef<(() => void) | null>(null)
// react-leaflet compares `position` by reference and calls setLatLng whenever it
// differs, and the cluster group answers a moved child by taking it out and putting
@@ -658,12 +724,12 @@ const MemoMarker = memo(function MemoMarker({
// so the wiring is redone on every add rather than once on mount.
add: (e: any) => {
cleanupRef.current?.()
cleanupRef.current = draggable ? makeMarkerDraggable(e.target.getElement() as HTMLElement, place.id) : null
cleanupRef.current = draggable ? wireDraggablePin(e.target.getElement() as HTMLElement, place.id, map) : null
},
remove: () => { cleanupRef.current?.(); cleanupRef.current = null },
click: () => onClickPlace(place.id),
mouseover: (e: any) => onHover(place, e.originalEvent.clientX, e.originalEvent.clientY),
mousemove: (e: any) => onHover(place, e.originalEvent.clientX, e.originalEvent.clientY),
mouseover: (e: any) => onHover({ ...place, photo: placePhotoFull(place) }, e.originalEvent.clientX, e.originalEvent.clientY),
mousemove: (e: any) => onHover({ ...place, photo: placePhotoFull(place) }, e.originalEvent.clientX, e.originalEvent.clientY),
mouseout: onHoverOut,
}}
zIndexOffset={isSelected ? 1000 : 0}
@@ -671,6 +737,11 @@ const MemoMarker = memo(function MemoMarker({
)
})
/** The look of a planner control point, drawn by PlannerWaypointMarker and kept beside the route blue. */
function plannerWaypointPinCss(size: number, selected: boolean): string {
return `display:flex;width:${size}px;height:${size}px;align-items:center;justify-content:center;border-radius:9999px;background:#0a84ff;color:white;border:${selected ? 3 : 2}px solid white;box-shadow:0 2px 7px rgba(0,0,0,.4);font:700 11px system-ui`
}
export const MapView = memo(function MapView({
places = [],
dayPlaces = [],
@@ -678,6 +749,12 @@ export const MapView = memo(function MapView({
// One colour pair per entry of `route`, or absent for the blue the route has always
// been. Only the road trip passes these, and only while colouring by day is on.
routeColors = null,
// One flag per entry of `route`: a walked stretch is drawn dashed (#2532).
routeWalking = null,
// False while the map is locked (#2010): picking a place leaves the view alone.
followSelection = true,
// Given, the lock that sets followSelection sits above the layer switcher (#2010).
onToggleFollow,
routeSegments = [],
selectedPlaceId = null,
// The selected place itself, for when no pin on this map stands for it.
@@ -692,6 +769,7 @@ export const MapView = memo(function MapView({
// the shape a caller without one gets.
tileUrl = OFM_POSITRON,
fitKey = 0,
focusKey,
dayOrderMap = {},
leftWidth = 0,
rightWidth = 0,
@@ -730,7 +808,20 @@ export const MapView = memo(function MapView({
activeAlternative,
onChooseAlternative,
onHighlightAlternative,
}: any) {
plannerWaypoints = [],
selectedPlannerWaypointId = null,
onPlannerWaypointClick,
onPlannerWaypointMove,
routeProfileFocus = null,
viewBaseLayer, onViewBaseLayerChange, onToggleTerrain3d, ferrataLayer, placeTool, tourLayers,
...assistant
}: MapViewProps) {
const globalBaseLayer = useSettingsStore(s => s.settings.map_base_layer) || 'default'
const updateSetting = useSettingsStore(s => s.updateSetting)
const baseLayer = (viewBaseLayer ?? globalBaseLayer) as TourBaseLayer
const hasViewBaseLayer = viewBaseLayer !== undefined && typeof onViewBaseLayerChange === 'function'
const isSatellite = baseLayer === 'satellite'
const tourRaster = tourRasterBaseOf(baseLayer) // topo, OpenHikingMap or CyclOSM, the Tours planner's own
// The caller hands over whatever the user configured; what kind of basemap
// that is decides which layer draws it. A saved raster template still wins,
// the default is a vector style.
@@ -742,14 +833,14 @@ export const MapView = memo(function MapView({
* decided before the map is constructed, because Leaflet cannot change a map's
* CRS afterwards — hence the whole map, not just the tile layer.
*/
const isGcjBasemap = basemap.kind === 'raster' && isGcj02Basemap(basemap.url)
const isGcjBasemap = !tourRaster && basemap.kind === 'raster' && isGcj02Basemap(basemap.url)
const gcjCrs = useMemo(() => crsForBasemap(isGcjBasemap), [isGcjBasemap])
const poiMarkers = useMemo(() => (pois as Poi[]).map((poi: Poi) => (
<Marker
key={`poi-${poi.osm_id}`}
alt={poi.name}
position={[poi.lat, poi.lng]}
icon={createPoiIcon(poi.category, poi.brand_wikidata)}
icon={createPoiIcon(poi, poi.brand_wikidata)}
zIndexOffset={500}
eventHandlers={{
click: () => onPoiClick?.(poi),
@@ -765,7 +856,7 @@ export const MapView = memo(function MapView({
},
}}
>
<Tooltip direction="top" offset={[0, -10]} opacity={1} className="map-tooltip">{poi.name}</Tooltip>
<Tooltip direction="top" offset={[0, -10]} opacity={1} className="map-tooltip"><PoiTooltipBody poi={poi} /></Tooltip>
</Marker>
)), [pois, onPoiClick, onPoiDropOnRoute])
const visibleReservations = useMemo(() => (
@@ -776,8 +867,11 @@ export const MapView = memo(function MapView({
// Dynamic padding: account for sidebars + bottom inspector + day detail panel
// The chrome overlaying the map (side panels, day detail). Kept as a plain box so both the
// Leaflet fit options and the opening-camera maths can read the same numbers.
// Followed rather than read once: a phone turned sideways and back crosses
// the breakpoint twice, and the padding here and the locate button further
// down used to stay with whatever the map saw when it mounted.
const isMobile = useIsPhone()
const paddingBox = useMemo((): ViewportPadding => {
const isMobile = typeof window !== 'undefined' && window.innerWidth < 768
if (isMobile) return { top: 20, right: 40, bottom: 20, left: 40 }
return {
top: 60,
@@ -785,7 +879,7 @@ export const MapView = memo(function MapView({
bottom: hasInspector ? 320 : hasDayDetail ? 280 : 60,
left: leftWidth + 40,
}
}, [leftWidth, rightWidth, hasInspector, hasDayDetail])
}, [isMobile, leftWidth, rightWidth, hasInspector, hasDayDetail])
const paddingOpts = useMemo(() => leafletPadding(paddingBox), [paddingBox])
@@ -801,6 +895,10 @@ export const MapView = memo(function MapView({
})
return { center: framed?.center ?? center, zoom: framed?.zoom ?? zoom, framed: framed !== null }
})
const cameraSnapshotRef = useRef<{ center: [number, number]; zoom: number } | null>(null)
const saveCameraSnapshot = useCallback((cameraCenter: [number, number], cameraZoom: number) => {
cameraSnapshotRef.current = { center: cameraCenter, zoom: cameraZoom }
}, [])
// Hover state for the single tooltip overlay (replaces per-marker <Tooltip>)
const [hoveredPlace, setHoveredPlace] = useState<MapHoverInfo | null>(null)
@@ -847,77 +945,15 @@ export const MapView = memo(function MapView({
setTooltipPos(null)
}, [])
// photoUrls: only base64 thumbs for smooth map zoom
const [photoUrls, setPhotoUrls] = useState<Record<string, string>>(getAllThumbs)
const placesPhotosEnabled = useAuthStore(s => s.placesPhotosEnabled)
// Batch photo state updates through a RAF so N simultaneous photo loads
// collapse into a single re-render instead of N separate renders.
const pendingThumbsRef = useRef<Record<string, string>>({})
const thumbRafRef = useRef<number | null>(null)
const photoSources = useMemo(() => photoSourcesKey(places), [places])
// Flattened [lat,lng] points of the selected day's route, so the bounds fit can
// include the full polyline once it has been computed.
const routeCoords = useMemo<[number, number][]>(() => (route || []).flat() as [number, number][], [route])
useEffect(() => {
if (!places || places.length === 0 || !placesPhotosEnabled) return
const cleanups: (() => void)[] = []
const setThumb = (cacheKey: string, thumb: string) => {
pendingThumbsRef.current[cacheKey] = thumb
if (thumbRafRef.current !== null) return
thumbRafRef.current = requestAnimationFrame(() => {
thumbRafRef.current = null
const pending = pendingThumbsRef.current
pendingThumbsRef.current = {}
setPhotoUrls(prev => {
const hasChange = Object.entries(pending).some(([k, v]) => prev[k] !== v)
return hasChange ? { ...prev, ...pending } : prev
})
})
}
for (const place of places) {
// A custom uploaded image is shown directly — never auto-fetch a provider
// photo for it (the request would 404 for OSM-only places and the fetched
// thumb would shadow the user's own image). (#1136)
if (isCustomPlaceImage(place.image_url)) continue
const cacheKey = photoCacheKey(place)
if (!cacheKey) continue
const cached = getCached(cacheKey)
if (cached?.thumbDataUrl) {
setThumb(cacheKey, cached.thumbDataUrl)
continue
}
cleanups.push(onThumbReady(cacheKey, thumb => setThumb(cacheKey, thumb)))
if (!cached && !isLoading(cacheKey)) {
const photoId =
(place.image_url?.startsWith('/api/maps/place-photo/') ? place.image_url : null)
|| place.google_place_id
|| place.osm_id
|| place.image_url
if (photoId || (place.lat && place.lng)) {
fetchPhoto(cacheKey, photoId || `coords:${place.lat}:${place.lng}`, place.lat, place.lng, place.name)
}
}
}
return () => {
cleanups.forEach(fn => fn())
if (thumbRafRef.current !== null) {
cancelAnimationFrame(thumbRafRef.current)
thumbRafRef.current = null
}
}
}, [photoSources, placesPhotosEnabled])
const photoUrls = useMarkerThumbs(places)
const isTouchDevice = typeof window !== 'undefined' && navigator.maxTouchPoints > 0
// Drag a marker onto a day (#891). Pointer-driven, so it is off wherever
// HTML5 drag does not exist — and the day plan is not on screen there anyway.
const markersDraggable = !isTouchDevice
const markersDraggable = !isTouchDevice && !assistant.markersLocked
/**
* Reaching a stop that shares its coordinates with others.
@@ -936,6 +972,7 @@ export const MapView = memo(function MapView({
if (marker) placeMarkersRef.current.set(id, marker)
else placeMarkersRef.current.delete(id)
}, [])
const assistantMarkerEl = useCallback((id: number) => (placeMarkersRef.current.get(id) as L.Marker | undefined)?.getElement() ?? null, [])
useEffect(() => {
if (selectedPlaceId == null) return
@@ -954,9 +991,7 @@ export const MapView = memo(function MapView({
const markers = useMemo(() => places.map((place) => {
const isSelected = place.id === selectedPlaceId
const pck = photoCacheKey(place)
// A custom uploaded image wins over the auto-fetched thumb; otherwise fall back.
const photoUrl = isCustomPlaceImage(place.image_url) ? place.image_url! : ((pck && photoUrls[pck]) || place.image_url || null)
const photoUrl = placePhotoUrl(place, photoUrls)
const orderNumbers = dayOrderMap[place.id] ?? null
return (
<MemoMarker
@@ -978,73 +1013,23 @@ export const MapView = memo(function MapView({
// of points), so it hangs off `places` alone — a selection change must not
// re-parse every track.
const gpxTracks = useMemo(() => places.flatMap(place => {
if (!place.route_geometry) return []
try {
const coords = JSON.parse(place.route_geometry) as [number, number][]
if (!coords || coords.length < 2) return []
return [{ place, coords, cased: hasManualTrackColor(place), color: resolveTrackColor(place) }]
} catch { return [] }
const geometry = parseRenderableRouteGeometry(place.route_geometry)
if (!geometry) return []
const coords: [number, number][] = geometry.map(([lat, lng]) => [lat, lng])
return [{ place, coords, cased: hasManualTrackColor(place), color: resolveTrackColor(place) }]
}), [places])
// Keeps the click handler out of the polyline memo below: `handleMarkerClick`
// Keeps the click handler out of the track lines' memo (TrackLines): `handleMarkerClick`
// changes on every selection, and depending on it would redraw all tracks.
const markerClickRef = useRef(handleMarkerClick)
markerClickRef.current = handleMarkerClick
const gpxPolylines = useMemo(() => (
<>
{/* Casings live in their own pane below the lines. Leaflet stacks paths by
insertion order, so drawing them inline would put the casing of a track
added later — or of one just given a colour — on top of an earlier
track's line. Always rendered, hidden via opacity when there is no
colour, so toggling one never remounts the path. */}
{gpxTracks.map(({ place, coords, cased }) => (
<Polyline
key={`gpx-${place.id}-casing`}
positions={coords}
pane={hasCasingPane ? TRACK_CASING_PANE : undefined}
pathOptions={{ color: '#ffffff', weight: 6.5, opacity: cased ? 0.7 : 0, lineCap: 'round', lineJoin: 'round' }}
interactive={false}
/>
))}
{/* pathOptions, not bare color/weight props: react-leaflet only calls
setStyle when the pathOptions reference changes, so bare props would
stick at their mount-time colour and a repaint would never arrive. */}
{gpxTracks.map(({ place, coords, cased, color }) => (
<Polyline
key={`gpx-${place.id}`}
positions={coords}
pathOptions={{ color, weight: 3.5, opacity: cased ? 0.9 : 0.75 }}
interactive={false}
/>
))}
{/* Invisible fat line on top so the track can actually be hit — 3.5px is
not a target, least of all on touch, and the start markers cluster below
zoom 11. bubblingMouseEvents is essential: paths bubble to the map by
default (markers do not), and the map's own click handler clears the
selection this one just made. */}
{gpxTracks.map(({ place, coords }) => (
<Polyline
key={`gpx-${place.id}-hit`}
positions={coords}
pathOptions={{ color: '#000', weight: 14, opacity: 0, lineCap: 'round', lineJoin: 'round' }}
bubblingMouseEvents={false}
eventHandlers={{ click: () => markerClickRef.current(place.id) }}
/>
))}
</>
), [gpxTracks, hasCasingPane])
const TooltipOverlay = !hoverDisabled && hoveredPlace && tooltipPos && !isTouchDevice
&& (!hoveredPlace.routeVia || routeVias.includes(hoveredPlace.routeVia))
const { position: userPosition, mode: trackingMode, error: trackingError, errorCode: trackingErrorCode, cycleMode: cycleTrackingMode } = useGeolocation()
// Desktop browsers only get IP-based geolocation (city-level accuracy),
// so the button would be misleading. Mobile, where real GPS lives, keeps it.
// The width is followed rather than read once: a phone turned sideways and
// back crosses the breakpoint twice, and the button used to stay with
// whatever the map saw when it mounted.
const isMobile = useIsPhone()
// When the day-detail panel is open it slides up over the map (bottom: navh+20,
// height var(--day-panel-h)) and covers the button's band, so lift the button
// above it; otherwise keep the plain bottom-nav offset. #1348
@@ -1052,9 +1037,6 @@ export const MapView = memo(function MapView({
? 'calc(var(--bottom-nav-h, 84px) + 20px + var(--day-panel-h, 0px) + 12px)'
: 'calc(var(--bottom-nav-h, 84px) + 12px)'
const baseLayer = useSettingsStore(s => s.settings.map_base_layer) || 'default'
const updateSetting = useSettingsStore(s => s.updateSetting)
const isSatellite = baseLayer === 'satellite'
const toggleBaseLayer = useCallback(() => {
// Store flips state synchronously (instant, works offline); a failed save is logged there.
updateSetting('map_base_layer', isSatellite ? 'default' : 'satellite').catch(() => {})
@@ -1082,8 +1064,8 @@ export const MapView = memo(function MapView({
// the cluster group away on every template or API-key edit.
key={isGcjBasemap ? 'gcj02' : 'wgs84'}
id="trek-map"
center={initialView.center}
zoom={initialView.zoom}
center={cameraSnapshotRef.current?.center ?? initialView.center}
zoom={cameraSnapshotRef.current?.zoom ?? initialView.zoom}
zoomControl={false}
// On the map itself, not left to the base layer. Leaflet reads its zoom
// ceiling from the map options or, failing that, from a GridLayer that
@@ -1117,6 +1099,17 @@ export const MapView = memo(function MapView({
updateWhenIdle={true}
referrerPolicy="strict-origin-when-cross-origin"
/>
) : tourRaster ? (
<TileLayer
key={baseLayer}
url={tourRaster.url}
attribution={tourRaster.attribution}
maxNativeZoom={tourRaster.maxZoom}
maxZoom={MAP_MAX_ZOOM}
keepBuffer={8} updateWhenZooming={false} updateWhenIdle={true}
referrerPolicy="strict-origin-when-cross-origin"
eventHandlers={tileHealthHandlers(tourLayers?.baseHealth, baseLayer)}
/>
) : basemap.kind === 'vector' ? (
<VectorBasemap style={basemap.style} />
) : (
@@ -1133,8 +1126,9 @@ export const MapView = memo(function MapView({
)}
<MapController center={center} zoom={zoom} />
<BoundsController places={dayPlaces.length > 0 ? dayPlaces : places} routeCoords={dayPlaces.length > 0 ? routeCoords : []} fitKey={fitKey} paddingOpts={paddingOpts} framedOnMount={initialView.framed} focusPoints={focusPoints} fitPadding={fitPadding} />
<SelectionController places={places} selectedPlaceId={selectedPlaceId} dayPlaces={dayPlaces} selectedPlace={selectedPlace} paddingOpts={paddingOpts} />
{hasViewBaseLayer && <MapCameraSnapshot onChange={saveCameraSnapshot} />}
<BoundsController places={dayPlaces.length > 0 ? dayPlaces : places} routeCoords={dayPlaces.length > 0 ? routeCoords : []} fitKey={fitKey} paddingOpts={paddingOpts} framedOnMount={initialView.framed} focusPoints={focusPoints} focusKey={focusKey} fitPadding={fitPadding} follow={followSelection} />
<SelectionController follow={followSelection} places={places} selectedPlaceId={selectedPlaceId} dayPlaces={dayPlaces} selectedPlace={selectedPlace} paddingOpts={paddingOpts} />
<MapClickHandler onClick={onMapClick} />
<MapContextMenuHandler onContextMenu={onMapContextMenu} />
<CameraHoverGuard movingRef={mapMovingRef} onMoveStart={clearHover} onZoom={setMapZoom} />
@@ -1147,22 +1141,21 @@ export const MapView = memo(function MapView({
</MarkerClusterGroup>
{/* Apple-Maps style: darker-blue casing under a bright-blue core, rounded.
The casing carries the click when the route can be reshaped: it is the wider of
the two, so it is the one a pointer actually lands on. */}
{route && route.length > 0 && route.flatMap((seg, i) => seg.length > 1 ? [
When the route can be reshaped an invisible band wider than both takes the click. */}
{route && route.length > 0 && route.flatMap((seg, i) => seg.length < 2 ? [] : routeWalking?.[i] ? [
// Walked, so dashed and without the casing: the drive is the solid line (#2532).
<Polyline
key={`${i}-walk`}
positions={seg}
pathOptions={{ color: routeColors?.[i]?.line ?? '#0a84ff', weight: 4, opacity: 1, dashArray: '1 9', lineCap: 'round', lineJoin: 'round' }}
interactive={false}
/>,
] : [
<Polyline
key={`${i}-casing`}
positions={seg}
pathOptions={{ color: routeColors?.[i]?.casing ?? '#0a5cc2', weight: 8, opacity: 1, lineCap: 'round', lineJoin: 'round' }}
interactive={!!onRouteClick}
eventHandlers={onRouteClick ? {
click: (e: { latlng: { lat: number; lng: number }; originalEvent: MouseEvent }) => {
// Stops the map's own click, which would otherwise open the add-place menu
// underneath the new via.
e.originalEvent.stopPropagation()
onRouteClick(e.latlng.lat, e.latlng.lng)
},
} : undefined}
interactive={false}
/>,
<Polyline
key={`${i}-core`}
@@ -1170,7 +1163,8 @@ export const MapView = memo(function MapView({
pathOptions={{ color: routeColors?.[i]?.line ?? '#0a84ff', weight: 5, opacity: 1, lineCap: 'round', lineJoin: 'round' }}
interactive={false}
/>,
] : [])}
...(onRouteClick ? [<RouteHitBand key={`${i}-hit`} positions={seg} onRouteClick={onRouteClick} />] : []),
])}
{/* The last bit to a place the road does not reach.
Dashed and thin, over the route rather than under it, because it is the one
@@ -1236,9 +1230,32 @@ export const MapView = memo(function MapView({
<RoadtripViaMarkers viasByDay={roadtripVias} onMoveVia={onMoveVia} onRemoveVia={onRemoveVia} />
) : null}
{plannerWaypoints.map((point, index) => (
<PlannerWaypointMarker
key={`planner-waypoint-${point.id}`}
point={point}
index={index}
selected={point.id === selectedPlannerWaypointId}
onClick={onPlannerWaypointClick}
onMove={onPlannerWaypointMove}
pinCss={plannerWaypointPinCss}
/>
))}
{/* GPX imported route geometries */}
<TrackCasingPane onReady={setHasCasingPane} />
{gpxPolylines}
<TrackLines tracks={gpxTracks} casingPane={hasCasingPane ? TRACK_CASING_PANE : undefined} selectRef={markerClickRef} />
<SelectedTrackLine tracks={gpxTracks} selectedPlaceId={selectedPlaceId} />
{routeProfileFocus && (
<CircleMarker
center={[routeProfileFocus.lat, routeProfileFocus.lng]}
radius={8}
pathOptions={{ className: 'tour-profile-focus-marker', color: 'var(--bg-card)', weight: 3, fillColor: 'var(--text-muted)', fillOpacity: 1 }}
interactive={false}
bubblingMouseEvents={false}
/>
)}
<ReservationOverlay
reservations={visibleReservations}
@@ -1249,6 +1266,7 @@ export const MapView = memo(function MapView({
/>
{hazards?.length > 0 && <HazardLayers hazards={hazards} />}
<TourMapLayersLeaflet ferrataLayer={ferrataLayer} overlays={tourLayers?.overlays} paddle={tourLayers?.paddle} />
{/* The route as it was actually recorded (#2279). Drawn in the casing
pane's sibling order so it sits under the planned route rather than
@@ -1280,6 +1298,7 @@ export const MapView = memo(function MapView({
</RouteViaMarker>
))}
<PluginMapMarkers tripId={tripId} />
<AssistantMapLeaflet assistant={assistant} padding={paddingBox} markerEl={assistantMarkerEl} />
<PluginMapLayers tripId={tripId} />
</MapContainer>
{isMobile && <LocationButton
@@ -1292,12 +1311,12 @@ export const MapView = memo(function MapView({
{/* 20px off the sidebar, not 12: the pill is round and frosted, so at the
smaller gap its shadow ran into the sidebar edge and the two read as one
surface. */}
{/* Bottom left, whatever else is on screen. Opening a place used to send it to the
top of the map, which read as the control moving house rather than as room being
made: the inspector is a centred card at most 800 wide, so the corner it would
have been clearing is one the card never reaches. */}
<div style={{ position: 'absolute', left: leftWidth + MAP_LAYER_SWITCHER_INSET, bottom: switcherBottom, zIndex: 1000, pointerEvents: 'none' }}>
<MapLayerSwitcher active={baseLayer} onToggle={toggleBaseLayer} />
<div style={{ position: 'absolute', left: leftWidth + MAP_LAYER_SWITCHER_INSET, bottom: switcherBottom, zIndex: 1000, pointerEvents: 'none', display: 'flex', flexDirection: 'column', gap: 8 }}>
{onToggleFollow && <MapLockPill locked={!followSelection} onToggle={onToggleFollow} />}
{hasViewBaseLayer
? <TourMapLayerSwitcher active={baseLayer} onChange={onViewBaseLayerChange}
onToggleTerrain={onToggleTerrain3d} ferrataLayer={ferrataLayer} placeTool={placeTool} layers={tourLayers} />
: <MapLayerSwitcher active={globalBaseLayer} onToggle={toggleBaseLayer} />}
</div>
</div>
@@ -1314,8 +1333,9 @@ export const MapView = memo(function MapView({
categoryColor={hoveredPlace.category_color}
address={hoveredPlace.address}
rating={hoveredPlace.rating_avg}
photo={hoveredPlace.photo}
/>
)}
</>
)
})
}) satisfies ComponentType<MapViewProps>
+10 -8
View File
@@ -5,8 +5,10 @@ import { useSettingsStore } from '../../store/settingsStore'
import { MapView } from './MapView'
import ErrorBoundary from '../shared/ErrorBoundary'
import { MapViewGLMapbox, MapViewGLMaplibre } from './glLazy'
import { useGlRenderer } from './glSupport'
import { useRoadtripHazards } from './useRoadtripHazards'
import { useTranslation } from '../../i18n/TranslationContext'
import type { MapViewAutoProps, MapViewProps } from './mapViewContract'
// Auto-selects the map renderer based on user settings. Keeps the existing
// Leaflet MapView untouched so the Mapbox GL variant can mature iteratively
@@ -16,21 +18,21 @@ import { useTranslation } from '../../i18n/TranslationContext'
// tiles via sync/tilePrefetcher.ts). GL maps are best-effort offline — their
// vector tiles are cached opportunistically by the Service Worker as you view
// them online (see the GL tile rules in vite.config.js), not prefetched.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function MapViewAuto(props: any) {
export function MapViewAuto(props: MapViewAutoProps) {
const { t } = useTranslation()
const hazards = useRoadtripHazards(props.tripId, !!props.clusterLoosely)
// `dawarichTrack` arrives as a prop rather than being fetched here: the pill
// that switches it on lives at page level and needs the load status, so the
// fetch sits in useTripPlanner and both shells read the same one.
const mapProps = { ...props, hazards: hazards.feed?.hazards }
// The one cast between what callers pass and what the renderers type: pins
// without trip_id (see MapViewAutoProps). Neither renderer reads trip_id.
const mapProps = { ...props, hazards: hazards.feed?.hazards } as MapViewProps
const provider = useSettingsStore(s => s.settings.map_provider)
const token = useSettingsStore(s => s.settings.mapbox_access_token)
// Fall back to Leaflet when Mapbox is selected but no token is set,
// so trip planner never shows an empty map due to a missing token.
const glProvider = provider === 'maplibre-gl' ? 'maplibre-gl'
: provider === 'mapbox-gl' && token ? 'mapbox-gl'
: null
// Fall back to Leaflet when Mapbox is selected but no token is set, or when the
// browser has no WebGL2 (both GL engines need it), so the trip planner never
// shows an empty map or one that fails to start.
const glProvider = useGlRenderer(provider, token)
// One chunk per engine: picking the binding here is what keeps mapbox-gl and
// maplibre-gl out of each other's downloads.
const MapViewGL = glProvider === 'maplibre-gl' ? MapViewGLMaplibre : MapViewGLMapbox
@@ -0,0 +1,88 @@
/**
* The trip map without WebGL2 (FE-COMP-MAPAUTO-WEBGL-*).
*
* A browser that cannot give a GL engine its WebGL2 context sees the Leaflet map
* with the user's tiles, never a map that fails to start: up front when the probe
* says no, and the moment the GL map's own constructor is refused when it said yes.
*/
import { useEffect } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { render, screen } from '../../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { useSettingsStore } from '../../store/settingsStore';
import { resetWebGLProbe } from '../../utils/webgl';
import { buildGlMap } from './glSupport';
import { MapViewAuto } from './MapViewAuto';
const gl = vi.hoisted(() => ({ refuse: false }));
vi.mock('./MapView', () => ({
MapView: () => <div data-testid="leaflet-map" />,
}));
/** Stands in for MapViewGL: builds its map the way the real one does, through buildGlMap. */
function FakeGlMap() {
useEffect(() => {
buildGlMap(() => {
if (!gl.refuse) return {};
const err = new Error('WebGL2 is required to display this map.');
err.name = 'GPUInitializationError';
throw err;
});
}, []);
return <div data-testid="gl-map" />;
}
vi.mock('./glLazy', () => ({ MapViewGLMaplibre: FakeGlMap, MapViewGLMapbox: FakeGlMap }));
vi.mock('./useRoadtripHazards', () => ({ useRoadtripHazards: () => ({ feed: null }) }));
const realGetContext = HTMLCanvasElement.prototype.getContext;
function browserWithWebGL2(available: boolean) {
const ctx = { getExtension: () => ({ loseContext: () => {} }) };
HTMLCanvasElement.prototype.getContext = vi.fn((type: string) =>
available && type === 'webgl2' ? ctx : null
) as unknown as typeof realGetContext;
}
beforeEach(() => {
resetAllStores();
resetWebGLProbe();
gl.refuse = false;
seedStore(useSettingsStore, { settings: { map_provider: 'maplibre-gl', mapbox_access_token: '' } });
});
afterEach(() => {
HTMLCanvasElement.prototype.getContext = realGetContext;
resetWebGLProbe();
});
describe('MapViewAuto without WebGL2', () => {
it('FE-COMP-MAPAUTO-WEBGL-001: draws the MapLibre map where WebGL2 is there', async () => {
browserWithWebGL2(true);
render(<MapViewAuto places={[]} />);
expect(await screen.findByTestId('gl-map')).toBeInTheDocument();
expect(screen.queryByTestId('leaflet-map')).not.toBeInTheDocument();
});
it('FE-COMP-MAPAUTO-WEBGL-002: draws the Leaflet map when the browser has no WebGL2', () => {
browserWithWebGL2(false);
render(<MapViewAuto places={[]} />);
expect(screen.getByTestId('leaflet-map')).toBeInTheDocument();
expect(screen.queryByTestId('gl-map')).not.toBeInTheDocument();
});
it('FE-COMP-MAPAUTO-WEBGL-003: falls back to Leaflet when the GPU refuses the context the probe promised', async () => {
browserWithWebGL2(true);
gl.refuse = true;
render(<MapViewAuto places={[]} />);
expect(await screen.findByTestId('leaflet-map')).toBeInTheDocument();
expect(screen.queryByTestId('gl-map')).not.toBeInTheDocument();
});
});
@@ -0,0 +1,599 @@
import { act } from '@testing-library/react';
import * as maplibregl from 'maplibre-gl';
import React from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { render } from '../../../tests/helpers/render';
import { resetAllStores } from '../../../tests/helpers/store';
import type { GeoPosition, TrackingMode } from '../../hooks/useGeolocation';
import { useSettingsStore } from '../../store/settingsStore';
// The planner-waypoint, location-search and antimeridian camera cases of MapViewGL, and
// the tour map's via ferrata layer (RC-10), with the same map doubles as MapViewGL.test.tsx.
// Stable fake map so fitBounds call counts survive re-renders. The canvas
// container is a single element so listeners registered by the component are
// reachable from tests via dispatchEvent.
const glCanvasContainer = vi.hoisted(() => document.createElement('div'));
const glMap = vi.hoisted(() => ({
on: vi.fn(),
off: vi.fn(),
once: vi.fn(),
loaded: vi.fn().mockReturnValue(true),
fitBounds: vi.fn(),
flyTo: vi.fn(),
jumpTo: vi.fn(),
getZoom: vi.fn().mockReturnValue(10),
getCenter: vi.fn(() => ({ lng: 0, lat: 0 })),
addControl: vi.fn(),
removeControl: vi.fn(),
remove: vi.fn(),
addSource: vi.fn(),
getSource: vi.fn().mockReturnValue(null),
addLayer: vi.fn(),
// Every overlay that adds a layer takes it away again on cleanup; a real
// MapLibre/Mapbox map has both halves, and a double with only the adding half
// fails the teardown rather than the behaviour under test.
removeLayer: vi.fn(),
removeSource: vi.fn(),
setLayoutProperty: vi.fn(),
setFilter: vi.fn(),
hasImage: vi.fn().mockReturnValue(false),
addImage: vi.fn(),
removeImage: vi.fn(),
getStyle: vi.fn().mockReturnValue({ layers: [] }),
isStyleLoaded: vi.fn().mockReturnValue(true),
getCanvasContainer: vi.fn(() => glCanvasContainer),
getContainer: vi.fn(() => glCanvasContainer),
getLayer: vi.fn().mockReturnValue(null),
queryRenderedFeatures: vi.fn().mockReturnValue([]),
querySourceFeatures: vi.fn().mockReturnValue([]),
unproject: vi.fn(() => ({ lng: 2.3522, lat: 48.8566 })),
// The MapLibre place pins position themselves with this, so a mock without it
// never exercises the path the real map takes.
project: vi.fn((lngLat: [number, number]) => ({ x: lngLat[0] * 10, y: lngLat[1] * 10 })),
getBounds: vi.fn(() => ({ getSouth: () => 0, getWest: () => 0, getNorth: () => 1, getEast: () => 1 })),
easeTo: vi.fn(),
getCanvas: vi.fn(() => document.createElement('canvas')),
getBearing: vi.fn(() => 0),
setTerrain: vi.fn(),
setConfigProperty: vi.fn(),
queryTerrainElevation: vi.fn((): number | null => null),
}));
const glBounds = vi.hoisted(() => {
const state = {
instances: [] as Array<{ extend: ReturnType<typeof vi.fn> }>,
};
return {
get instances() {
return state.instances;
},
clear: () => {
state.instances = [];
},
create: () => {
const bounds = {
extend: vi.fn(() => bounds),
};
state.instances.push(bounds);
return bounds;
},
};
});
// Markers and popups are created through the mocked GL constructors, so the
// tests can reach the very instances the component built (their DOM element,
// the coordinates they were placed at, the popup content they were given).
interface FakeMarker {
element: HTMLElement;
lngLat: number[] | null;
setLngLat: (ll: number[]) => FakeMarker;
getLngLat: () => { lng: number; lat: number };
addTo: (map: unknown) => FakeMarker;
remove: () => void;
getElement: () => HTMLElement;
}
interface FakePopup {
setLngLat: (ll: unknown) => FakePopup;
setHTML: (html: string) => FakePopup;
setText: (text: string) => FakePopup;
setDOMContent: (node: HTMLElement) => FakePopup;
addTo: (map: unknown) => FakePopup;
remove: () => void;
}
const glMarkers = vi.hoisted(() => {
const created: FakeMarker[] = [];
return {
get created() {
return created;
},
clear: () => {
created.length = 0;
},
make: (opts?: { element?: HTMLElement }): FakeMarker => {
const element = opts?.element ?? document.createElement('div');
const marker: FakeMarker = {
element,
lngLat: null,
setLngLat: vi.fn((ll: number[]) => {
marker.lngLat = ll;
return marker;
}),
getLngLat: vi.fn(() => ({ lng: Number(marker.lngLat?.[0] ?? 0), lat: Number(marker.lngLat?.[1] ?? 0) })),
addTo: vi.fn((_map: unknown) => marker),
remove: vi.fn(),
getElement: vi.fn(() => element),
};
created.push(marker);
return marker;
},
};
});
const glPopup = vi.hoisted((): FakePopup => {
const popup: FakePopup = {
setLngLat: vi.fn((_ll: unknown) => popup),
setHTML: vi.fn((_html: string) => popup),
setText: vi.fn((_text: string) => popup),
setDOMContent: vi.fn((_node: HTMLElement) => popup),
addTo: vi.fn((_map: unknown) => popup),
remove: vi.fn(),
};
return popup;
});
vi.mock('mapbox-gl', () => ({
default: {
accessToken: '',
Map: vi.fn(function () {
return glMap;
}),
Marker: vi.fn(function (opts?: { element?: HTMLElement }) {
return glMarkers.make(opts);
}),
LngLatBounds: vi.fn(function () {
return glBounds.create();
}),
NavigationControl: vi.fn(),
Popup: vi.fn(function () {
return glPopup;
}),
},
}));
vi.mock('mapbox-gl/dist/mapbox-gl.css', () => ({}));
// maplibre-gl 6 has no default export, so the fakes are named exports.
vi.mock('maplibre-gl', () => ({
Map: vi.fn(function () {
return glMap;
}),
Marker: vi.fn(function (opts?: { element?: HTMLElement }) {
return glMarkers.make(opts);
}),
LngLatBounds: vi.fn(function () {
return glBounds.create();
}),
NavigationControl: vi.fn(),
Popup: vi.fn(function () {
return glPopup;
}),
}));
vi.mock('maplibre-gl/dist/maplibre-gl.css', () => ({}));
vi.mock('./mapboxSetup', () => ({
isStandardFamily: vi.fn(() => false),
supportsCustom3d: vi.fn(() => false),
wantsTerrain: vi.fn(() => false),
addCustom3dBuildings: vi.fn(),
addTerrainAndSky: vi.fn(),
}));
const locationMarker = vi.hoisted(() => ({ update: vi.fn(), destroy: vi.fn() }));
vi.mock('./locationMarkerMapbox', () => ({
attachLocationMarker: vi.fn(() => locationMarker),
}));
const reservationOverlay = vi.hoisted(() => ({
update: vi.fn((_reservations: unknown, _opts: unknown, _routes: unknown) => {}),
destroy: vi.fn(),
}));
vi.mock('./reservationsMapbox', () => ({
ReservationMapboxOverlay: vi.fn(function () {
return reservationOverlay;
}),
}));
const geoStub = vi.hoisted(() => ({
position: null as GeoPosition | null,
mode: 'off' as TrackingMode,
error: null as string | null,
errorCode: null as string | null,
cycleMode: vi.fn(async () => {}),
setMode: vi.fn((_m: TrackingMode | ((prev: TrackingMode) => TrackingMode)) => {}),
}));
vi.mock('../../hooks/useGeolocation', () => ({
useGeolocation: vi.fn(() => geoStub),
}));
vi.mock('../../services/photoService', () => ({
getCached: vi.fn(() => null),
isLoading: vi.fn(() => false),
fetchPhoto: vi.fn(),
onThumbReady: vi.fn(() => () => {}),
getAllThumbs: vi.fn(() => ({})),
}));
import mapboxgl from 'mapbox-gl';
import * as photoService from '../../services/photoService';
import { groupFerratas } from '../Ferratas/ferrataGroups';
import { MapViewGL as MapViewGLWithEngine } from './MapViewGL';
import * as mapboxSetup from './mapboxSetup';
// The engine is a prop, not a module import (see MapViewGL.test.tsx). This shim makes
// the same choice glLazy.tsx makes in production.
function MapViewGL(props: Omit<React.ComponentProps<typeof MapViewGLWithEngine>, 'gl'>) {
return <MapViewGLWithEngine {...props} gl={props.glProvider === 'maplibre-gl' ? maplibregl : mapboxgl} />;
}
function pointer(type: string, x: number, y: number): Event {
const event = new Event(type, { bubbles: true, cancelable: true });
Object.defineProperties(event, {
button: { value: 0 },
clientX: { value: x },
clientY: { value: y },
pointerId: { value: 1 },
});
return event;
}
beforeEach(() => {
glMap.on.mockImplementation(() => glMap);
glMap.off.mockImplementation(() => glMap);
glMap.once.mockImplementation(() => glMap);
glMap.loaded.mockReturnValue(true);
glMap.getSource.mockReturnValue(null);
glMap.getLayer.mockReturnValue(null);
glMap.queryRenderedFeatures.mockReturnValue([]);
glMap.querySourceFeatures.mockReturnValue([]);
glMap.getCanvas.mockImplementation(() => document.createElement('canvas'));
glMap.getBearing.mockReturnValue(0);
glMap.queryTerrainElevation.mockReturnValue(null);
// A busy style, a refused source and a custom layer list are each set by one test
// for the case it covers. Put back here, or every test after it would silently run
// against a map that never settles.
glMap.isStyleLoaded.mockReturnValue(true);
glMap.getStyle.mockReturnValue({ layers: [] });
glMap.addSource.mockImplementation(() => undefined);
glMarkers.clear();
// clearAllMocks() wipes call history but keeps implementations, so anything a
// test overrides with mockReturnValue has to be put back here.
vi.mocked(mapboxSetup.isStandardFamily).mockReturnValue(false);
vi.mocked(mapboxSetup.supportsCustom3d).mockReturnValue(false);
vi.mocked(mapboxSetup.wantsTerrain).mockReturnValue(false);
vi.mocked(photoService.getCached).mockReturnValue(undefined);
vi.mocked(photoService.isLoading).mockReturnValue(false);
vi.mocked(photoService.onThumbReady).mockReturnValue(() => {});
vi.mocked(photoService.getAllThumbs).mockReturnValue({});
geoStub.position = null;
geoStub.mode = 'off';
geoStub.error = null;
useSettingsStore.setState({
settings: {
...useSettingsStore.getState().settings,
map_provider: 'mapbox-gl',
mapbox_access_token: 'pk.test_token',
mapbox_style: 'mapbox://styles/mapbox/streets-v12',
mapbox_3d_enabled: false,
},
});
});
afterEach(() => {
vi.clearAllMocks();
glBounds.clear();
resetAllStores();
});
describe('MapViewGL', () => {
function loadOnAttach() {
glMap.on.mockImplementation((event: string, handlerOrLayer: unknown) => {
if (event === 'load' && typeof handlerOrLayer === 'function') (handlerOrLayer as () => void)();
return glMap;
});
}
it('honors a location-search camera intent and preserves it through later route updates', async () => {
loadOnAttach();
const searchPoint: [number, number] = [35.0116, 135.7681];
const { rerender } = render(
<MapViewGL
places={[]}
route={null}
followSelection={false}
focusKey="tour:0:search:1"
focusPoints={[searchPoint]}
glProvider="maplibre-gl"
/>
);
await act(async () => {});
expect(glMap.fitBounds).toHaveBeenCalledOnce();
expect(glMap.fitBounds).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ maxZoom: 15 }));
const mapConstructions = vi.mocked(maplibregl.Map).mock.calls.length;
glMap.fitBounds.mockClear();
rerender(
<MapViewGL
places={[]}
route={[[searchPoint, [35.02, 135.77]]]}
followSelection={false}
focusKey="tour:0:search:1"
focusPoints={[searchPoint, [35.02, 135.77]]}
glProvider="maplibre-gl"
/>
);
await act(async () => {});
expect(glMap.fitBounds).not.toHaveBeenCalled();
expect(vi.mocked(maplibregl.Map).mock.calls).toHaveLength(mapConstructions);
rerender(
<MapViewGL
places={[]}
followSelection={false}
focusKey="tour:1"
focusPoints={[
[46.8, 9.5],
[47.1, 10.1],
]}
glProvider="maplibre-gl"
/>
);
await act(async () => {});
expect(glMap.fitBounds).toHaveBeenCalledOnce();
});
it('frames handed-over points across the antimeridian the short way, as the opening camera does', async () => {
loadOnAttach();
// Fiji, Tonga and Samoa, a collection's list: a box from plain min and max would run
// from -175 to 178, round the far side of the world, with each pin on an edge.
render(
<MapViewGL
places={[]}
followSelection={false}
focusKey="1,2,3"
focusPoints={[
[-18.14, 178.44],
[-21.14, -175.2],
[-13.83, -171.76],
]}
glProvider="maplibre-gl"
/>
);
await act(async () => {});
expect(glMap.fitBounds).toHaveBeenCalledOnce();
const framed = glBounds.instances.find((bounds) => bounds === glMap.fitBounds.mock.calls[0][0]);
const lngs = framed?.extend.mock.calls.map(([lngLat]) => Math.round(lngLat[0] * 100) / 100);
expect(lngs).toEqual([178.44, 184.8, 188.24]);
});
it.each(['maplibre-gl', 'mapbox-gl'] as const)(
'RC-08: %s previews waypoint drags locally and commits only on pointer up without changing the camera',
async (provider) => {
loadOnAttach();
glMap.project.mockImplementation((lngLat: [number, number]) => ({ x: lngLat[0] * 10, y: lngLat[1] * 10 }));
glMap.unproject.mockReturnValue({ lng: 2.3522, lat: 48.8566 });
glMap.getContainer.mockReturnValue(glCanvasContainer);
const waypoint = { id: 'via-1', lat: 48, lng: 11, role: 'via' as const };
const waypoints = [waypoint];
const onMove = vi.fn(() => true);
const onSelect = vi.fn();
const onMapClick = vi.fn();
const view = render(
<MapViewGL
places={[]}
plannerWaypoints={waypoints}
onPlannerWaypointClick={onSelect}
onPlannerWaypointMove={onMove}
onMapClick={onMapClick}
focusKey="tour:1"
focusPoints={[[waypoint.lat, waypoint.lng]]}
routeProfileFocus={null}
glProvider={provider}
/>
);
await act(async () => {});
glMap.fitBounds.mockClear();
const pin =
provider === 'maplibre-gl'
? (glCanvasContainer.querySelector('[aria-label="Waypoint 1"]') as HTMLButtonElement)
: (glMarkers.created.find((marker) => marker.element.getAttribute('aria-label') === 'Waypoint 1')
?.element as HTMLButtonElement);
const startTransform = pin.style.transform;
const libraryMarker =
provider === 'mapbox-gl' ? glMarkers.created.find((marker) => marker.element === pin) : undefined;
const startLngLat = libraryMarker?.lngLat;
act(() => {
pin.dispatchEvent(pointer('pointerdown', 10, 10));
pin.dispatchEvent(pointer('pointermove', 30, 40));
});
if (provider === 'maplibre-gl') expect(pin.style.transform).not.toBe(startTransform);
else expect(libraryMarker?.lngLat).not.toEqual(startLngLat);
expect(onMove).not.toHaveBeenCalled();
expect(waypoints[0]).toEqual(waypoint);
view.rerender(
<MapViewGL
places={[]}
plannerWaypoints={waypoints}
onPlannerWaypointClick={onSelect}
onPlannerWaypointMove={onMove}
onMapClick={onMapClick}
focusKey="tour:1"
focusPoints={[[waypoint.lat, waypoint.lng]]}
routeProfileFocus={{ distanceMeters: 100, elevationMeters: 0, lat: 48.1, lng: 11.1, sampleIndex: 0 }}
glProvider={provider}
/>
);
if (provider === 'maplibre-gl') expect(pin.style.transform).not.toBe(startTransform);
else expect(libraryMarker?.lngLat).not.toEqual(startLngLat);
act(() => {
pin.dispatchEvent(pointer('pointerup', 30, 40));
pin.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
});
expect(onMove).toHaveBeenCalledOnce();
expect(onMove).toHaveBeenCalledWith(waypoint.id, 48.8566, 2.3522);
expect(onSelect).not.toHaveBeenCalled();
expect(onMapClick).not.toHaveBeenCalled();
view.rerender(
<MapViewGL
places={[]}
plannerWaypoints={[{ ...waypoint, lat: 48.4, lng: 11.3 }]}
onPlannerWaypointClick={onSelect}
onPlannerWaypointMove={onMove}
onMapClick={onMapClick}
focusKey="tour:1"
focusPoints={[[48.4, 11.3]]}
routeProfileFocus={{ distanceMeters: 100, elevationMeters: 0, lat: 48.1, lng: 11.1, sampleIndex: 0 }}
glProvider={provider}
/>
);
expect(glMap.fitBounds).not.toHaveBeenCalled();
expect(glMap.flyTo).not.toHaveBeenCalled();
expect(glMap.jumpTo).not.toHaveBeenCalled();
}
);
it('RC-08: pointer cancellation restores the MapLibre pin and plain clicks still select and add separately', async () => {
loadOnAttach();
const waypoint = { id: 'start', lat: 48, lng: 11, role: 'start' as const };
const onMove = vi.fn(() => true);
const onSelect = vi.fn();
const onMapClick = vi.fn();
render(
<MapViewGL
places={[]}
plannerWaypoints={[waypoint]}
onPlannerWaypointClick={onSelect}
onPlannerWaypointMove={onMove}
onMapClick={onMapClick}
glProvider="maplibre-gl"
/>
);
await act(async () => {});
const pin = glCanvasContainer.querySelector('[aria-label="Waypoint 1"]') as HTMLButtonElement;
const initialTransform = pin.style.transform;
act(() => {
pin.dispatchEvent(pointer('pointerdown', 10, 10));
pin.dispatchEvent(pointer('pointermove', 30, 40));
pin.dispatchEvent(pointer('pointercancel', 30, 40));
});
expect(pin.style.transform).toBe(initialTransform);
expect(onMove).not.toHaveBeenCalled();
act(() => {
pin.dispatchEvent(pointer('pointerdown', 10, 10));
pin.dispatchEvent(pointer('pointerup', 10, 10));
pin.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
});
expect(onSelect).toHaveBeenCalledOnce();
expect(onSelect).toHaveBeenCalledWith(waypoint.id);
expect(onMapClick).not.toHaveBeenCalled();
});
const FERRATA = {
id: 'way/42',
name: 'Via delle Trincee',
grade: { raw: '4', level: 4, plus: null },
routeName: null,
geometry: [
[46.52, 11.8],
[46.53, 11.81],
] as [number, number][],
osmUrl: 'https://www.openstreetmap.org/way/42',
};
const FERRATA_GROUPS = groupFerratas([FERRATA]);
const ferrataLayer = (active: boolean) => ({
active,
onToggle: vi.fn(),
status: active ? ('ready' as const) : ('idle' as const),
count: active ? 1 : 0,
groups: FERRATA_GROUPS,
selectedId: null,
onSelect: vi.fn(),
});
const addedFerratas = () => glMap.addSource.mock.calls.filter(([id]) => id === 'trek-ferratas');
it('RC-10: the via ferrata layer is drawn on the ready map only while it is on, its switch in the tour pill', async () => {
loadOnAttach();
const off = ferrataLayer(false);
const view = render(
<MapViewGL
places={[]}
viewBaseLayer="topo"
onViewBaseLayerChange={vi.fn()}
ferrataLayer={off}
glProvider="maplibre-gl"
/>
);
await act(async () => {});
expect(addedFerratas()).toHaveLength(0);
const toggle = view.getByRole('button', { name: 'Via ferratas' });
expect(toggle).toHaveAttribute('aria-pressed', 'false');
act(() => toggle.click());
expect(off.onToggle).toHaveBeenCalledOnce();
view.rerender(
<MapViewGL
places={[]}
viewBaseLayer="topo"
onViewBaseLayerChange={vi.fn()}
ferrataLayer={ferrataLayer(true)}
glProvider="maplibre-gl"
/>
);
await act(async () => {});
expect(addedFerratas()).toHaveLength(1);
expect(view.getByRole('button', { name: 'Via ferratas' })).toHaveAttribute('aria-pressed', 'true');
expect(view.getByTestId('ferrata-count-badge')).toHaveTextContent('1');
});
it('RC-10: a click on a drawn ferrata opens it and is not a map click, so no control point lands under it', async () => {
loadOnAttach();
glMap.getLayer.mockImplementation((id: string) => (id === 'trek-ferratas-hit' ? { id } : null));
glMap.queryRenderedFeatures.mockImplementation((_point: unknown, options?: { layers?: string[] }) =>
options?.layers?.includes('trek-ferratas-hit') ? [{ properties: { id: FERRATA.id } }] : []
);
const layer = ferrataLayer(true);
const onMapClick = vi.fn();
render(
<MapViewGL
places={[]}
viewBaseLayer="topo"
onViewBaseLayerChange={vi.fn()}
ferrataLayer={layer}
onMapClick={onMapClick}
glProvider="maplibre-gl"
/>
);
await act(async () => {});
const mapClicks = glMap.on.mock.calls
.filter(([event, handler]) => event === 'click' && typeof handler === 'function')
.map(([, handler]) => handler as (event: unknown) => void);
expect(mapClicks.length).toBeGreaterThan(0);
const click = {
point: { x: 5, y: 5 },
lngLat: { lat: 46.52, lng: 11.8 },
originalEvent: { target: document.createElement('div') },
};
act(() => mapClicks.forEach((handler) => handler(click)));
expect(onMapClick).not.toHaveBeenCalled();
expect(layer.onSelect).toHaveBeenCalledWith(FERRATA_GROUPS[0], FERRATA, { lat: 46.52, lng: 11.8 });
});
});
+253 -21
View File
@@ -8,12 +8,14 @@ import { buildPlace } from '../../../tests/helpers/factories'
import { server } from '../../../tests/helpers/msw/server'
import { useSettingsStore } from '../../store/settingsStore'
import { useAuthStore } from '../../store/authStore'
import maplibregl from 'maplibre-gl'
import * as maplibregl from 'maplibre-gl'
import { DEFAULT_MAP_ZOOM } from '../../constants/mapDefaults'
import { MAP_LAYER_SWITCHER_INSET } from './MapLayerSwitcher'
import type { GeoPosition, TrackingMode } from '../../hooks/useGeolocation'
import type { PluginMapLayer, PluginMapLayerFeature, PluginMapMarker } from '../../api/client'
import type { Poi } from './poiCategories'
import { Coffee, type LucideIcon } from 'lucide-react'
import { renderIconMarkup } from '../../utils/iconMarkup'
import type { RouteVia } from '../../types'
// Stable fake map so fitBounds call counts survive re-renders. The canvas
@@ -29,6 +31,7 @@ const glMap = vi.hoisted(() => ({
flyTo: vi.fn(),
jumpTo: vi.fn(),
getZoom: vi.fn().mockReturnValue(10),
getCenter: vi.fn(() => ({ lng: 0, lat: 0 })),
addControl: vi.fn(),
removeControl: vi.fn(),
remove: vi.fn(),
@@ -153,22 +156,21 @@ vi.mock('mapbox-gl', () => ({
}))
vi.mock('mapbox-gl/dist/mapbox-gl.css', () => ({}))
// maplibre-gl 6 has no default export, so the fakes are named exports.
vi.mock('maplibre-gl', () => ({
default: {
Map: vi.fn(function () {
return glMap
}),
Marker: vi.fn(function (opts?: { element?: HTMLElement }) {
return glMarkers.make(opts)
}),
LngLatBounds: vi.fn(function () {
return glBounds.create()
}),
NavigationControl: vi.fn(),
Popup: vi.fn(function () {
return glPopup
}),
},
Map: vi.fn(function () {
return glMap
}),
Marker: vi.fn(function (opts?: { element?: HTMLElement }) {
return glMarkers.make(opts)
}),
LngLatBounds: vi.fn(function () {
return glBounds.create()
}),
NavigationControl: vi.fn(),
Popup: vi.fn(function () {
return glPopup
}),
}))
vi.mock('maplibre-gl/dist/maplibre-gl.css', () => ({}))
@@ -254,6 +256,7 @@ beforeEach(() => {
glMap.querySourceFeatures.mockReturnValue([])
glMap.getCanvas.mockImplementation(() => document.createElement('canvas'))
glMap.getBearing.mockReturnValue(0)
glMap.getZoom.mockReturnValue(10)
glMap.queryTerrainElevation.mockReturnValue(null)
// A busy style, a refused source and a custom layer list are each set by one test
// for the case it covers. Put back here, or every test after it would silently run
@@ -348,7 +351,7 @@ describe('MapViewGL', () => {
it('FE-COMP-MAPVIEWGL-004: renders with the MapLibre provider and no token', async () => {
const mapboxgl = (await import('mapbox-gl')).default
const maplibregl = (await import('maplibre-gl')).default
const maplibregl = await import('maplibre-gl')
useSettingsStore.setState({
settings: {
...useSettingsStore.getState().settings,
@@ -369,7 +372,7 @@ describe('MapViewGL', () => {
it('FE-COMP-MAPVIEWGL-014: MapLibre maps disable the around-center mouse rotate (#1545)', async () => {
const mapboxgl = (await import('mapbox-gl')).default
const maplibregl = (await import('maplibre-gl')).default
const maplibregl = await import('maplibre-gl')
useSettingsStore.setState({
settings: {
...useSettingsStore.getState().settings,
@@ -887,6 +890,116 @@ describe('MapViewGL', () => {
return calls[calls.length - 1][0] as { features: GeoFeature[] }
}
it('moves a passive semantic profile focus pin without changing the map camera', async () => {
loadOnAttach()
const focus = { distanceMeters: 120, elevationMeters: 340, lat: 48.123, lng: 11.456, sampleIndex: 3 }
const focusPoints: [number, number][] = [[48.1, 11.4], [48.2, 11.5]]
const route: [number, number][][] = [[[48.1, 11.4], [48.2, 11.5]]]
const { rerender } = render(<MapViewGL places={[]} route={route} fitKey={1} focusPoints={focusPoints} glProvider="maplibre-gl" routeProfileFocus={focus} />)
await act(async () => {})
const marker = glCanvasContainer.querySelector<HTMLElement>('[data-tour-profile-focus="true"]')
expect(marker).not.toBeNull()
const projected = glMap.project([focus.lng, focus.lat])
expect(marker?.style.transform).toContain(`translate(${projected.x}px, ${projected.y}px)`)
expect(marker?.style.pointerEvents).toBe('none')
expect(marker?.style.background).toBe('var(--text-muted)')
expect(marker?.style.border).toBe('3px solid var(--bg-card)')
expect(glCanvasContainer.contains(marker)).toBe(true)
glMap.fitBounds.mockClear()
glMap.flyTo.mockClear()
glMap.jumpTo.mockClear()
glMap.easeTo.mockClear()
const movedFocus = { ...focus, lat: 48.16, lng: 11.47 }
rerender(<MapViewGL places={[]} route={route} fitKey={1} focusPoints={focusPoints} glProvider="maplibre-gl" routeProfileFocus={movedFocus} />)
await act(async () => {})
const movedMarker = glCanvasContainer.querySelector<HTMLElement>('[data-tour-profile-focus="true"]')
expect(movedMarker).toBe(marker)
expect(movedMarker?.style.transform).toContain(`translate(${glMap.project([movedFocus.lng, movedFocus.lat]).x}px, ${glMap.project([movedFocus.lng, movedFocus.lat]).y}px)`)
expect(glMap.fitBounds).not.toHaveBeenCalled()
expect(glMap.flyTo).not.toHaveBeenCalled()
expect(glMap.jumpTo).not.toHaveBeenCalled()
expect(glMap.easeTo).not.toHaveBeenCalled()
rerender(<MapViewGL places={[]} route={route} fitKey={1} focusPoints={focusPoints} glProvider="maplibre-gl" routeProfileFocus={null} />)
await act(async () => {})
expect(glCanvasContainer.contains(marker)).toBe(false)
expect(glMap.fitBounds).not.toHaveBeenCalled()
expect(glMap.flyTo).not.toHaveBeenCalled()
expect(glMap.jumpTo).not.toHaveBeenCalled()
expect(glMap.easeTo).not.toHaveBeenCalled()
})
it('frames Tour focus once, ignores waypoint and route updates, then honors a new focus intent', async () => {
loadOnAttach()
const { rerender } = render(
<MapViewGL
places={[]}
route={null}
followSelection={false}
focusKey={1}
focusPoints={[[48, 11], [48.2, 11.3]]}
glProvider="maplibre-gl"
/>,
)
await act(async () => {})
expect(glMap.fitBounds.mock.calls).toEqual([[expect.anything(), expect.objectContaining({ duration: 0 })]])
glMap.fitBounds.mockClear()
const mapConstructions = (maplibregl.Map as any).mock.calls.length
const retainedCenter = { lng: 135.8, lat: 35.2 }
glMap.getCenter.mockReturnValue(retainedCenter)
glMap.getZoom.mockReturnValue(12)
rerender(
<MapViewGL
places={[]}
followSelection={false}
focusKey={2}
focusPoints={[]}
glProvider="maplibre-gl"
/>,
)
await act(async () => {})
expect(glMap.fitBounds).not.toHaveBeenCalled()
expect(glMap.flyTo).not.toHaveBeenCalled()
expect(glMap.jumpTo).not.toHaveBeenCalled()
expect(glMap.easeTo).not.toHaveBeenCalled()
expect((maplibregl.Map as any).mock.calls).toHaveLength(mapConstructions)
expect(glMap.getCenter()).toEqual(retainedCenter)
expect(glMap.getZoom()).toBe(12)
rerender(
<MapViewGL
places={[]}
followSelection={false}
focusKey={2}
focusPoints={[[35.01, 135.76]]}
glProvider="maplibre-gl"
/>,
)
await act(async () => {})
expect(glMap.fitBounds.mock.calls).toEqual([[expect.anything(), expect.objectContaining({ duration: 400 })]])
})
it('keeps selection fit and the pending route-arrival refit for semantic changes', async () => {
loadOnAttach()
const selectedPlace = buildPlace({ id: 902, lat: 48, lng: 11 })
const route: [number, number][][] = [[[48, 11], [48.2, 11.3]]]
const { rerender } = render(<MapViewGL places={[]} route={null} fitKey={0} glProvider="maplibre-gl" />)
await act(async () => {})
glMap.fitBounds.mockClear()
rerender(<MapViewGL places={[selectedPlace]} route={null} fitKey={1} glProvider="maplibre-gl" />)
await act(async () => {})
expect(glMap.fitBounds).toHaveBeenCalled()
glMap.fitBounds.mockClear()
rerender(<MapViewGL places={[selectedPlace]} route={route} fitKey={2} glProvider="maplibre-gl" />)
await act(async () => {})
expect(glMap.fitBounds).toHaveBeenCalled()
})
// jsdom drives requestAnimationFrame off a timer, so the marker reconcile and
// the batched photo updates only land after a short tick.
const flushFrames = () => act(async () => { await new Promise(resolve => setTimeout(resolve, 40)) })
@@ -1462,7 +1575,58 @@ describe('MapViewGL', () => {
const list = calls[calls.length - 1][0]
act(() => { list.querySelectorAll('button')[1].click() })
expect(onPoiClick).toHaveBeenCalledWith(other)
vi.mocked(glMap.getZoom).mockReturnValue(10)
})
const pinGlyph = (Icon: LucideIcon) => renderIconMarkup(React.createElement(Icon, { size: 13, color: 'white', strokeWidth: 2.5 }))
const explorePoi = (overrides: Partial<Poi>): Poi => ({
osm_id: 'n1', name: 'Café de Flore', lat: 48.854, lng: 2.332, category: 'cafe',
poi_type: 'cafe', address: null, website: null, phone: null, opening_hours: null,
cuisine: null, source: 'openstreetmap', ...overrides,
})
it('FE-COMP-MAPVIEWGL-104: a core POI pin is the disc it always was', async () => {
loadOnAttach()
render(<MapViewGL places={[]} fitKey={1} pois={[explorePoi({})]} />)
await act(async () => {})
// Parsed the same way the element's own markup was, so only a real change shows up.
const expected = document.createElement('div')
expected.innerHTML = '<div style="position:relative;width:26px;height:26px;border-radius:50%;background:#B45309;border:2px solid #fff;box-shadow:0 1px 5px rgba(0,0,0,0.3);display:flex;align-items:center;justify-content:center;box-sizing:border-box;overflow:hidden;">'
+ `${pinGlyph(Coffee)}</div>`
expect(glMarkers.created[0].element.innerHTML).toBe(expected.innerHTML)
})
it('FE-COMP-MAPVIEWGL-105: a plugin POI pin and its hover card use its checked colour and icon, and its details stay text', async () => {
loadOnAttach()
const plugin = explorePoi({
osm_id: 'plugin:trail-finder:1', name: '<img src=x onerror=alert(1)>', category: 'plugin:trail-finder/trailheads',
source: 'plugin:trail-finder', pluginId: 'trail-finder', color: '#2f855a', icon: 'Signpost',
details: [{ label: 'Length', value: '12.4 km' }, { label: '<b>Fee</b>', value: '"><svg onload=alert(2)>' }],
})
const bad = explorePoi({
osm_id: 'plugin:trail-finder:2', category: 'plugin:trail-finder/trailheads',
color: 'red;background:url(https://evil.example/x)', icon: '<img src=x onerror=alert(3)>',
})
render(<MapViewGL places={[]} fitKey={1} pois={[plugin, bad]} />)
await act(async () => {})
const [good, fallback] = glMarkers.created.map(pin => pin.element)
expect(good.innerHTML).toContain('background:#2f855a;')
expect(good.querySelectorAll('svg')).toHaveLength(1)
expect(good.querySelector('svg.lucide-signpost')).not.toBeNull()
expect(fallback.innerHTML).toContain('background:#6b7280;')
expect(fallback.innerHTML).not.toContain('evil.example')
expect(fallback.querySelectorAll('img')).toHaveLength(0)
expect(fallback.querySelector('svg.lucide-map-pin')).not.toBeNull()
act(() => { good.dispatchEvent(new MouseEvent('mouseenter')) })
const card = document.createElement('div')
card.innerHTML = vi.mocked(glPopup.setHTML).mock.lastCall![0]
expect(card.querySelectorAll('img, b')).toHaveLength(0)
expect(card.querySelectorAll('svg')).toHaveLength(1)
expect(card.textContent).toContain('<img src=x onerror=alert(1)>')
expect([...card.querySelectorAll('div[style*="grid-template-columns"] > span')].map(el => el.textContent)).toEqual([
'Length', '12.4 km', '<b>Fee</b>', '"><svg onload=alert(2)>',
])
})
it('FE-COMP-MAPVIEWGL-043: plugin markers render as tone dots with a text-only popup', async () => {
@@ -1728,6 +1892,33 @@ describe('MapViewGL', () => {
expect(features[1].properties.color).toBeNull()
})
it('uses view-local Topo tiles and controls without writing settings or moving the camera', async () => {
glMap.on.mockImplementation((event, handlerOrLayer) => {
if (event === 'load' && typeof handlerOrLayer === 'function') handlerOrLayer()
return glMap
})
const onChange = vi.fn()
const settings = useSettingsStore.getState().settings.map_base_layer
const { container, rerender } = render(<MapViewGL places={[]} fitKey={1} glProvider="maplibre-gl" viewBaseLayer="topo" onViewBaseLayerChange={onChange} />)
await act(async () => {})
expect(glMap.addSource).toHaveBeenCalledWith('trip-topo', expect.objectContaining({
type: 'raster', tiles: ['a', 'b', 'c'].map(subdomain => `https://${subdomain}.tile.opentopomap.org/{z}/{x}/{y}.png`),
}))
const button = Array.from(container.querySelectorAll('button')).find(element => element.textContent === 'Topo')!
expect(button).toHaveAttribute('aria-pressed', 'true')
fireEvent.click(button)
expect(onChange).toHaveBeenCalledWith('topo')
expect(useSettingsStore.getState().settings.map_base_layer).toBe(settings)
glMap.fitBounds.mockClear()
glMap.flyTo.mockClear()
glMap.jumpTo.mockClear()
rerender(<MapViewGL places={[]} fitKey={1} glProvider="maplibre-gl" viewBaseLayer="default" onViewBaseLayerChange={onChange} />)
await act(async () => {})
expect(glMap.fitBounds).not.toHaveBeenCalled()
expect(glMap.flyTo).not.toHaveBeenCalled()
expect(glMap.jumpTo).not.toHaveBeenCalled()
})
it('FE-COMP-MAPVIEWGL-049: unusable GPX geometry is skipped instead of breaking the layer', async () => {
const gpxSource = geoSource()
glMap.getSource.mockImplementation((id: string) => (id === 'trip-gpx' ? gpxSource : null))
@@ -1746,6 +1937,47 @@ describe('MapViewGL', () => {
expect(features[0].properties.place_id).toBe(74)
})
it.each([
['two-point', [[48, 2], [49, 3]]],
['elevation', [[48, 2, 12.5], [49, 3, 22.75]]],
['long track', Array.from({ length: 1200 }, (_, index) => [48 + index / 100000, 2 + index / 100000])],
['loop', [[48, 2], [48.1, 2.1], [48, 2]]],
['point-to-point Tour', [[48, 2], [48.5, 2.5], [49, 3]]],
])('renders valid %s geometry with MapLibre coordinate order', async (_label, geometry) => {
const features = gpxFeatures()
render(<MapViewGL places={[buildMapPlace({ route_geometry: JSON.stringify(geometry) })]} fitKey={1} />)
await act(async () => {})
expect(features()).toHaveLength(1)
expect(features()[0].geometry.coordinates).toEqual(geometry.map(([lat, lng]) => [lng, lat]))
})
it.each([
['malformed JSON', 'not json'],
['non-array JSON', '{"coordinates":[]}'],
['one point', '[[48,2]]'],
['missing coordinate dimension', '[[48],[49,3]]'],
['string coordinates', '[[48,"2"],[49,3]]'],
['NaN token', '[[48,2],[NaN,3]]'],
['Infinity token', '[[48,2],[49,Infinity]]'],
['out-of-range latitude', '[[48,2],[91,3]]'],
['out-of-range longitude', '[[48,2],[49,181]]'],
['all-invalid coordinates', '[[91,2],[49,181]]'],
])('omits %s geometry from the MapLibre source', async (_label, geometry) => {
const features = gpxFeatures()
expect(() => render(<MapViewGL places={[buildMapPlace({ route_geometry: geometry })]} fitKey={1} />)).not.toThrow()
await act(async () => {})
expect(features()).toHaveLength(0)
})
it('filters invalid points and preserves valid order in the MapLibre source', async () => {
const features = gpxFeatures()
const geometry = '[[48,2],null,[91,4],[48.5,2.5],[49,3]]'
render(<MapViewGL places={[buildMapPlace({ route_geometry: geometry })]} fitKey={1} />)
await act(async () => {})
expect(features()).toHaveLength(1)
expect(features()[0].geometry.coordinates).toEqual([[2, 48], [2.5, 48.5], [3, 49]])
})
it('FE-COMP-MAPVIEWGL-050: without a Mapbox token it shows the settings hint and touches no camera', async () => {
const mapboxgl = (await import('mapbox-gl')).default
useSettingsStore.setState({
@@ -1982,13 +2214,13 @@ describe('MapViewGL', () => {
expect((window as any).__trek_map).toBeUndefined()
})
it('FE-COMP-MAPVIEWGL-059: pan and zoom report the visible bbox for the POI explore pill', async () => {
it('FE-COMP-MAPVIEWGL-059: pan and zoom report the visible bbox and tile zoom for the POI explore pill', async () => {
const onViewportChange = vi.fn()
render(<MapViewGL places={[]} fitKey={1} onViewportChange={onViewportChange} />)
await act(async () => {})
act(() => { mapHandler('moveend')() })
expect(onViewportChange).toHaveBeenCalledWith({ south: 0, west: 0, north: 1, east: 1 })
expect(onViewportChange).toHaveBeenCalledWith({ south: 0, west: 0, north: 1, east: 1 }, 11)
})
it('FE-COMP-MAPVIEWGL-060: a new POI or via set replaces the previous overlay markers', async () => {
+169 -368
View File
@@ -1,19 +1,22 @@
import { useEffect, useRef, useMemo, useState, createElement, useCallback } from 'react'
import { useEffect, useRef, useMemo, useState, useCallback } from 'react'
import { makeMarkerDraggable, makePoiDraggable, draggedPoiId } from './markerDrag'
import type { DawarichTrack, RoadtripVia } from '@trek/shared'
import { useStableVias } from './viaMarkerState'
import { usePlannerWaypointMarkersGL } from './usePlannerWaypointMarkersGL'
import { carryAssistantMarks, useAssistantMapGL } from './useAssistantMapGL'
import { ALT_CASING, ALT_LABEL_TEXT } from '../Roadtrip/alternativeColors'
import type { AlternativeOverlay } from '../Roadtrip/alternativeOverlays'
import { serviceMarkerHtml, serviceMarkerOuter } from '../Roadtrip/serviceMarker'
import { renderIconMarkup } from '../../utils/iconMarkup'
import { categoryIconSvg } from './categoryIconSvg'
import type mapboxgl from 'mapbox-gl'
import { useSettingsStore } from '../../store/settingsStore'
import { useTranslation } from '../../i18n/TranslationContext'
import { MapLayerSwitcher, MAP_LAYER_SWITCHER_INSET, type BaseLayer } from './MapLayerSwitcher'
import { useAuthStore } from '../../store/authStore'
import { getCached, isLoading, fetchPhoto, onThumbReady, getAllThumbs } from '../../services/photoService'
import { isCustomPlaceImage, markerPhotoHtml, photoCacheKey, photoSourcesKey } from './placePhoto'
import { CATEGORY_ICON_MAP } from '../shared/categoryIcons'
import { applyBaseLayer } from './glRasterLayers'
import { reportGlViewport } from './glViewport'
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'
import { placeMarkerLook, type PlaceMarkerFlags } from './markerLook'
import { markerPhotoHtml, placePhotoFull, placePhotoUrl } from './placePhoto'
import { isStandardFamily, supportsCustom3d, wantsTerrain, addCustom3dBuildings, addTerrainAndSky } from './mapboxSetup'
import { attachLocationMarker, type LocationMarkerHandle } from './locationMarkerMapbox'
import { ReservationMapboxOverlay } from './reservationsMapbox'
@@ -21,36 +24,33 @@ import { useTransportRoutes } from '../../hooks/useTransportRoutes'
import { visibleRouteReservations } from '../../utils/reservationRoutes'
import { safeHexColor } from '../../utils/safeColor'
import { MAPBOX_DEFAULT_STYLE, styleForActiveProvider, basemapLanguage, type GlMapProvider } from './glProviders'
import { buildGlMap, initialMapStyle } from './glSupport'
import LocationButton from './LocationButton'
import { useIsPhone } from '../../mobile/useIsPhone'
import { useGeolocation } from '../../hooks/useGeolocation'
import type { Day, Place, Reservation, RouteVia } from '../../types'
import type { MapHoverInfo } from './mapHover'
import type { MapViewProps, RouteSegment } from './mapViewContract'
import { nightPauseMarker, NIGHT_PAUSE_MIN_ZOOM } from './nightPauseMarker'
import { clusterPois, poiClusterMarkup, poiClusterList, POI_CLUSTER_DETAIL_ZOOM } from './poiClusters'
import { groupCoincidentPlaces } from './coincidentPlaces'
import type { RoadtripHazard } from '@trek/shared'
import { useHazardLayerGL } from './useHazardLayerGL'
import type { FerrataGlMap } from '../Ferratas/useFerrataLayerGL'
import { formatViaDwell } from './routeViaDwell'
import { useDawarichTrailGL } from './useDawarichTrailGL'
import { bindDayBoundaryDrag, type DayBoundaryControls } from './dayBoundaryDrag'
import { bindDayBoundaryDrag } from './dayBoundaryDrag'
import NightPauseTooltip from './NightPauseTooltip'
import PlaceHoverCard from './PlaceHoverCard'
import { ratingBadgeHtml } from './ratingBadge'
import { POI_CATEGORY_BY_KEY, type Poi } from './poiCategories'
import { resolveTrackColor, hasManualTrackColor } from './trackColors'
import type { Poi } from './poiCategories'
import { poiPinParts } from './poiMarker'
import { addGpxTrackLayers, GPX_HIT_LAYER_ID, hasGpxTrackLayers, selectGpxTrack, setGpxTracks } from './gpxTrackLayers'
import { buildPoiPopupHtml } from './placePopup'
import { pluginsApi, type PluginMapMarker, type PluginMapLayer } from '../../api/client'
import { DEFAULT_MAP_CENTER, DEFAULT_MAP_ZOOM, SATELLITE_TILE_URL, SATELLITE_TILE_ATTRIBUTION, SATELLITE_TILE_MAXZOOM } from '../../constants/mapDefaults'
import { computeMapViewport, TILE_SIZE_GL, type ViewportPadding } from '../../utils/mapViewport'
import { DEFAULT_MAP_CENTER, DEFAULT_MAP_ZOOM } from '../../constants/mapDefaults'
import { alongShortestArc, computeMapViewport, TILE_SIZE_GL } from '../../utils/mapViewport'
import { selectedPlaceTarget } from './selectedPlaceTarget'
import { offlineStyle } from '../../native/offlineTiles'
function categoryIconSvg(iconName: string | null | undefined, size: number): string {
const IconComponent = (iconName && CATEGORY_ICON_MAP[iconName]) || CATEGORY_ICON_MAP['MapPin']
try {
return renderIconMarkup(createElement(IconComponent, { size, color: 'white', strokeWidth: 2.5 }))
} catch { return '' }
}
import { PLACE_CLUSTER_CIRCLE_LAYER_ID, PLACE_CLUSTER_COUNT_LAYER_ID } from './placeClusterLayers'
// Marker grouping for the GL map (#1385): MapLibre/Mapbox can't show the rich
// HTML photo markers *and* cluster them natively, so we feed the place points
@@ -59,29 +59,7 @@ function categoryIconSvg(iconName: string | null | undefined, size: number): str
// points the source reports as currently unclustered. Grouping is always on,
// matching the Leaflet map's MarkerClusterGroup.
const PLACE_CLUSTER_SOURCE_ID = 'trip-place-clusters'
const PLACE_CLUSTER_CIRCLE_LAYER_ID = 'trip-place-clusters-circle'
const PLACE_CLUSTER_COUNT_LAYER_ID = 'trip-place-clusters-count'
const PLACE_UNCLUSTERED_LAYER_ID = 'trip-place-unclustered-hit'
const GPX_HIT_LAYER_ID = 'trip-gpx-hit'
/**
* The satellite base layer, the GL twin of the Leaflet one.
*
* Leaflet swaps its whole tile layer for the imagery; a GL map cannot, because the
* basemap is a style with dozens of layers in it. So the imagery goes on as a raster
* layer of its own, drawn over the style and under everything TREK adds — the route,
* the pins and the tracks stay on top and stay legible, which is the same order the
* Leaflet map ends up with.
*
* Same tokenless ESRI source as Leaflet, so the two look alike and neither needs a key.
*/
const SATELLITE_SOURCE_ID = 'trip-satellite'
const SATELLITE_LAYER_ID = 'trip-satellite-raster'
/** Everything TREK draws is prefixed; the imagery is inserted before the first of them. */
// Everything TREK draws on a GL map, so the satellite raster can be slipped underneath all
// of it. `route-alt-` earns its place here: the roads offered for a leg are added before the
// route source so they sit under the current route, which also puts them before the first
// `trip-` layer, and anchoring the imagery there painted right over them.
const OWN_LAYER_PREFIXES = ['trip-', 'trek-', 'route-alt-']
type PlaceWithCoords = Place & { lat: number; lng: number }
@@ -104,13 +82,6 @@ function buildPlaceClusterData(places: Place[]) {
}
}
interface RouteSegment {
mid: [number, number]
from: [number, number]
to: [number, number]
walkingText?: string
drivingText?: string
}
// Stable identities for the omitted collection props. An inline `= []` / `= {}`
// default allocates a fresh object on every render, and these props sit in the
@@ -129,105 +100,8 @@ const NO_CONNECTION_IDS: number[] = []
const NO_POIS: Poi[] = []
const NO_DAYS: Day[] = []
interface Props {
places: Place[]
dayPlaces?: Place[]
// Enables the plugin map contributions (markers + layers). Absent on surfaces
// without a trip (CollectionMap), which naturally excludes them — same rule as
// the Leaflet MapPluginMarkers.
tripId?: number | string
// Charging stops / rest areas a plugin route places on the drawn day route.
routeVias?: RouteVia[]
dayBoundaryControls?: DayBoundaryControls
/** The dashed last bit to a place the road network does not reach. */
accessLines?: { line: [[number, number], [number, number]]; meters: number }[]
route?: [number, number][][] | null
/**
* One colour pair per entry of `route`, or absent for the blue the route has always
* been. Only the road trip passes these, and only while colouring by day is on.
*/
routeColors?: ({ line: string; casing: string } | undefined)[] | null
routeSegments?: RouteSegment[]
selectedPlaceId?: number | null
/** The selected place itself, for when no pin on this map stands for it. */
selectedPlace?: Place | null
onMarkerClick?: (id: number) => void
hoverDisabled?: boolean
onMapClick?: (info: { latlng: { lat: number; lng: number } }) => void
onMapContextMenu?: ((e: { latlng: { lat: number; lng: number }; originalEvent: MouseEvent | TouchEvent }) => void) | null
center?: [number, number]
zoom?: number
fitKey?: number | null
dayOrderMap?: Record<number, number[] | null>
leftWidth?: number
rightWidth?: number
hasInspector?: boolean
hasDayDetail?: boolean
reservations?: Reservation[]
visibleConnectionIds?: number[]
showTransitRoutes?: boolean
days?: Day[]
selectedDayId?: number | null
/**
* Whether a booking switched on by hand also has to run on the selected day to be
* drawn. Only the phone's plan map asks for it; see RouteVisibilityOptions.
*/
scopeConnectionsToDay?: boolean
showReservationStats?: boolean
onReservationClick?: (reservationId: number) => void
pois?: Poi[]
onPoiClick?: (poi: Poi) => void
/**
* A corridor hit dropped somewhere on the map, with the coordinate it landed on.
* The caller decides whether that point is near enough to the drive to mean anything.
*/
onPoiDropOnRoute?: (osmId: string, lat: number, lng: number) => void
/** A click on the drawn route, for putting a via point there (#1797). */
onRouteClick?: (lat: number, lng: number) => void
/** The ways of driving one leg, drawn while the picker is open. */
alternativeRoutes?: AlternativeOverlay[]
/** Which option is being considered, so it can be lit up in its own colour. */
activeAlternative?: number | null
onChooseAlternative?: (index: number) => void
/** Reports which option the pointer is over, so the list and the map agree. */
onHighlightAlternative?: (index: number | null) => void
/**
* An explicit stretch of map to frame, independent of the day being shown.
*
* `fitKey` cannot express this: it carries no coordinates, and each renderer decides
* for itself that it means "the selected day". Weighing the ways of driving one leg
* needs that leg on screen, which is neither the day nor the trip.
*/
focusPoints?: [number, number][]
/**
* What the caller's own chrome covers while `focusPoints` is framed, in pixels per edge.
*
* The default padding knows this component's panels and nothing else, and on a phone it
* is a flat margin. A shell that lays its own bars over the map passes what they cover,
* so the frame lands in the part still visible. Only the fit on `focusPoints` reads it.
* Compared by value: the same numbers in a new object do not refit, while new numbers
* refit the points already handed over, because the chrome they must clear has moved.
*/
fitPadding?: ViewportPadding
/**
* Let markers stay apart longer than usual.
*
* A road trip is read along a line: two stops fifty kilometres apart on the same
* motorway are the shape of the day, and merging them into one dot hides it.
*/
clusterLoosely?: boolean
hazards?: RoadtripHazard[]
/** The route recorded in Dawarich, already fetched by MapViewAuto (#2279). */
dawarichTrack?: DawarichTrack | null
/** Draw only this local day of the recording. */
dawarichSelectedDate?: string | null
/** Local dates whose day is collapsed in the day plan; their recording is not drawn. */
dawarichHiddenDates?: ReadonlySet<string> | null
/** Via points to draw as draggable handles, keyed by day (#1797). */
roadtripVias?: Record<number, RoadtripVia[]>
onMoveVia?: (dayId: number, id: number, lat: number, lng: number) => void
onRemoveVia?: (dayId: number, id: number) => void
onViewportChange?: (bbox: { south: number; west: number; north: number; east: number }) => void
/** The GL renderer: the shared map contract plus the engine it is bound to. */
interface Props extends MapViewProps {
glProvider?: GlMapProvider
/**
* The GL engine, injected instead of imported. Both SDKs used to be pulled in
@@ -236,8 +110,6 @@ interface Props {
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
gl: any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onMapReady?: (map: any | null) => void
}
/**
@@ -305,57 +177,8 @@ function addPlaceClusterLayers(map: any): void {
})
}
/**
* Puts the imagery on the map, or takes it off again.
*
* Built on demand rather than once at load: a style change drops every source the map
* had, and a hot reload does the same. Visibility comes first: a layer that is already
* there only needs flipping, so the usual pass is one call and a tap answers at once.
*
* Deliberately not gated on `isStyleLoaded()`. That reports false for as long as any
* source has tiles or a setData in flight (see useDawarichTrailGL), which on a phone is
* the usual state, and the only retry here is `styledata`, which fires on style edits
* and not when those finish. Behind that gate a stored choice met a busy map on load,
* and a tap on the road trip stage met the sources the same render had just set again,
* so the imagery was never drawn. The gate was also the wrong question: this only runs
* after `load`, and addSource and addLayer refuse only a style document that is not in
* yet. The catch covers that case, and `styledata` brings the pass back once it is in.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function applySatellite(map: any, on: boolean): void {
try {
if (map.getLayer(SATELLITE_LAYER_ID)) {
map.setLayoutProperty(SATELLITE_LAYER_ID, 'visibility', on ? 'visible' : 'none')
return
}
if (!on) return // Nothing to build while it is switched off.
// The layer is what is missing, not necessarily the source: a pass that got the
// source in and then failed on the layer would otherwise leave a source that stops
// every later pass from ever building the layer.
if (!map.getSource(SATELLITE_SOURCE_ID)) {
map.addSource(SATELLITE_SOURCE_ID, {
type: 'raster',
tiles: [SATELLITE_TILE_URL],
tileSize: 256,
maxzoom: SATELLITE_TILE_MAXZOOM,
attribution: SATELLITE_TILE_ATTRIBUTION,
})
}
// Under the first thing TREK draws, over everything the basemap style draws.
// Without the anchor the imagery lands on top and buries the route.
const layers = map.getStyle?.()?.layers ?? []
const firstOwn = layers.find((l: { id: string }) =>
OWN_LAYER_PREFIXES.some(prefix => l.id.startsWith(prefix)))
map.addLayer({
id: SATELLITE_LAYER_ID,
type: 'raster',
source: SATELLITE_SOURCE_ID,
paint: { 'raster-opacity': 1 },
}, firstOwn?.id)
} catch { /* a style that refuses the layer keeps the plain basemap */ }
}
function createMarkerElement(place: Place & { category_color?: string; category_icon?: string }, photoUrl: string | null, orderNumbers: number[] | null, selected: boolean): HTMLDivElement {
function createMarkerElement(place: Place & PlaceMarkerFlags & { category_color?: string; category_icon?: string }, photoUrl: string | null, orderNumbers: number[] | null, selected: boolean): HTMLDivElement {
// A stop that interrupts the drive gets its own small disc, decided before the photo
// branch: the brand logo a fuel search comes back with is exactly what this replaces.
// No number badge either, for the same reason the rail gives it none.
@@ -368,10 +191,10 @@ function createMarkerElement(place: Place & { category_color?: string; category_
return wrap
}
const size = selected ? 44 : 36
const look = placeMarkerLook(place, selected)
const { size, borderWidth } = look
// See MapView: allow-listed rather than escaped, because this is a CSS context.
const borderColor = selected ? '#111827' : safeHexColor(place.category_color, 'white')
const borderWidth = selected ? 3 : 2.5
const shadow = selected
? '0 0 0 3px rgba(17,24,39,0.25), 0 4px 14px rgba(0,0,0,0.3)'
: '0 2px 8px rgba(0,0,0,0.22)'
@@ -386,7 +209,7 @@ function createMarkerElement(place: Place & { category_color?: string; category_
// Same corner, same rule as the Leaflet map: numbers when the place is planned into a
// day, the rating when it is not.
let badgeHtml = ratingBadgeHtml((place as { rating_avg?: number | null }).rating_avg)
let badgeHtml = look.showRating ? ratingBadgeHtml((place as { rating_avg?: number | null }).rating_avg) : ''
if (orderNumbers && orderNumbers.length > 0) {
const label = orderNumbers.join(' · ')
badgeHtml = `<span style="
@@ -413,7 +236,7 @@ function createMarkerElement(place: Place & { category_color?: string; category_
// to its stacked slot, not to the map viewport.
wrap.style.cssText = `width:${outer}px;height:${outer}px;cursor:pointer;`
const hasPhoto = photoUrl && (photoUrl.startsWith('data:') || photoUrl.startsWith('/api/maps/place-photo/') || photoUrl.startsWith('/uploads/'))
const hasPhoto = look.showPhoto && photoUrl && (photoUrl.startsWith('data:') || photoUrl.startsWith('/api/maps/place-photo/') || photoUrl.startsWith('/uploads/'))
if (hasPhoto) {
wrap.innerHTML = `
<div style="
@@ -422,7 +245,7 @@ function createMarkerElement(place: Place & { category_color?: string; category_
border:${borderWidth}px solid ${borderColor};
box-shadow:${shadow};
overflow:hidden;background:${bgColor};
box-sizing:content-box;
box-sizing:content-box;${look.circleCss}
">
${markerPhotoHtml(photoUrl)}
</div>
@@ -437,9 +260,9 @@ function createMarkerElement(place: Place & { category_color?: string; category_
box-shadow:${shadow};
background:${bgColor};
display:flex;align-items:center;justify-content:center;
box-sizing:content-box;
box-sizing:content-box;${look.circleCss}
">
${categoryIconSvg(place.category_icon, selected ? 18 : 15)}
${categoryIconSvg(place.category_icon, look.iconSize)}
</div>
${badgeHtml}
`
@@ -519,12 +342,6 @@ function buildPluginLayerData(layers: PluginMapLayer[]) {
return { type: 'FeatureCollection' as const, features }
}
function formatViaDwellGl(seconds: number): string {
const h = Math.floor(seconds / 3600)
const m = Math.round((seconds % 3600) / 60)
return h > 0 ? `${h} h ${m} min` : `${m} min`
}
/**
* A place pin on the map, whatever is carrying it.
*
@@ -647,10 +464,10 @@ function buildPluginMarkerPopup(mk: PluginMapMarker): HTMLDivElement {
// A chain shows its logo instead of the category icon: on a corridor full of petrol
// stations the brand is what the eye is looking for, and the server proxies it so the
// browser never asks Wikimedia which ones are on screen.
function createPoiMarkerElement(category: string, brandWikidata?: string | null): HTMLDivElement {
const cat = POI_CATEGORY_BY_KEY[category]
const color = cat?.color || '#6b7280'
const svg = cat ? renderIconMarkup(createElement(cat.Icon, { size: 13, color: 'white', strokeWidth: 2.5 })) : ''
function createPoiMarkerElement(poi: Pick<Poi, 'category' | 'icon' | 'color'>, brandWikidata?: string | null): HTMLDivElement {
// The same parts the Leaflet pin is built from: a plugin POI's own colour and icon,
// both checked before they get anywhere near innerHTML.
const { color, svg } = poiPinParts(poi)
const el = document.createElement('div')
el.style.cssText = 'width:26px;height:26px;cursor:pointer;will-change:transform;'
el.innerHTML = `<div style="position:relative;width:26px;height:26px;border-radius:50%;background:${color};border:2px solid #fff;box-shadow:0 1px 5px rgba(0,0,0,0.3);display:flex;align-items:center;justify-content:center;box-sizing:border-box;overflow:hidden;">${svg}${brandLogoMarkup(brandWikidata)}</div>`
@@ -669,6 +486,11 @@ export function brandLogoMarkup(_brandWikidata?: string | null): string {
return ''
}
/** The look of a planner control point, drawn by usePlannerWaypointMarkersGL. */
function plannerWaypointPinCss(size: number, selected: boolean): string {
return `display:flex;width:${size}px;height:${size}px;align-items:center;justify-content:center;border-radius:9999px;background:#0a84ff;color:white;border:${selected ? 3 : 2}px solid white;box-shadow:0 2px 7px rgba(0,0,0,.4);font:700 11px system-ui`
}
export function MapViewGL({
places = NO_PLACES,
dayPlaces = NO_PLACES,
@@ -678,6 +500,9 @@ export function MapViewGL({
accessLines = NO_ACCESS_LINES,
route = null,
routeColors = null,
routeWalking = null,
followSelection = true,
onToggleFollow,
routeSegments = NO_ROUTE_SEGMENTS,
selectedPlaceId = null,
selectedPlace = null,
@@ -689,6 +514,7 @@ export function MapViewGL({
zoom = DEFAULT_MAP_ZOOM,
fitKey = 0,
focusPoints,
focusKey,
fitPadding,
clusterLoosely = false,
hazards,
@@ -716,6 +542,12 @@ export function MapViewGL({
activeAlternative,
onChooseAlternative,
onHighlightAlternative,
plannerWaypoints = [],
selectedPlannerWaypointId = null,
onPlannerWaypointClick,
onPlannerWaypointMove,
routeProfileFocus = null,
viewBaseLayer, onViewBaseLayerChange, onToggleTerrain3d, ferrataLayer, placeTool, tourLayers,
roadtripVias,
onMoveVia,
onRemoveVia,
@@ -723,13 +555,16 @@ export function MapViewGL({
glProvider = 'mapbox-gl',
gl,
onMapReady,
...assistant
}: Props) {
const { t } = useTranslation()
const rawMapboxStyle = useSettingsStore(s => s.settings.mapbox_style || MAPBOX_DEFAULT_STYLE)
const rawMaplibreStyle = useSettingsStore(s => s.settings.maplibre_style || '')
const mapboxToken = useSettingsStore(s => s.settings.mapbox_access_token || '')
// The same stored choice the Leaflet map reads, so the two renderers agree.
const baseLayer = useSettingsStore(s => s.settings.map_base_layer) || 'default'
const globalBaseLayer = useSettingsStore(s => s.settings.map_base_layer) || 'default'
const baseLayer = viewBaseLayer ?? globalBaseLayer
const hasViewBaseLayer = viewBaseLayer !== undefined && typeof onViewBaseLayerChange === 'function'
const updateSetting = useSettingsStore(s => s.updateSetting)
const isSatellite = baseLayer === 'satellite'
const toggleBaseLayer = useCallback(() => {
@@ -744,9 +579,8 @@ export function MapViewGL({
const isMapLibre = glProvider === 'maplibre-gl'
const glStyle = styleForActiveProvider(glProvider, rawMapboxStyle, rawMaplibreStyle)
const enableMapbox3d = !isMapLibre && mapbox3d
const placesPhotosEnabled = useAuthStore(s => s.placesPhotosEnabled)
const [photoUrls, setPhotoUrls] = useState<Record<string, string>>(getAllThumbs)
const [mapReady, setMapReady] = useState(false)
const [readyMap, setReadyMap] = useState<FerrataGlMap | null>(null) // the ready map, read without touching mapRef
// Hover tooltip — a cursor-following name/category/address card, matching the
// Leaflet map's overlay exactly (no anchored popup, no photo thumbnail).
const [hoverPlace, setHoverPlace] = useState<MapHoverInfo | null>(null)
@@ -773,6 +607,7 @@ export function MapViewGL({
const mapRef = useRef<any | null>(null)
const hazardPopupFactory = useCallback(() => new gl.Popup({ className: 'map-tooltip trek-hazard-popup', maxWidth: '320px' }), [gl])
useHazardLayerGL(mapRef.current, mapReady, hazards, hazardPopupFactory)
useTourMapLayersGL(mapReady ? readyMap : null, ferrataLayer, tourLayers)
// Beneath the planned route's casing, the GL twin of the Leaflet pane order.
useDawarichTrailGL(mapRef.current, mapReady, dawarichTrack, dawarichSelectedDate, 'trip-route-casing', dawarichHiddenDates)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -798,6 +633,9 @@ export function MapViewGL({
const routeViaMarkersRef = useRef<PlacePin[]>([])
/** The road-trip via handles (#1797) — hand-positioned like the rest, so listed here. */
const viaPinsRef = useRef<PlacePin[]>([])
const plannerWaypointPinsRef = useRef<PlacePin[]>([])
const assistantGhostPinsRef = useRef<PlacePin[]>([])
const profileFocusPinRef = useRef<PlacePin | null>(null)
/** The drive-time pills on the offered routes; same treatment. */
const altLabelsRef = useRef<PlacePin[]>([])
// Every hand-positioned pin, whichever set it belongs to. They all have to be written
@@ -808,6 +646,9 @@ export function MapViewGL({
pluginMarkersRef.current.forEach(pin => pin.reposition())
routeViaMarkersRef.current.forEach(pin => pin.reposition())
viaPinsRef.current.forEach(pin => pin.reposition())
plannerWaypointPinsRef.current.forEach(pin => pin.reposition())
assistantGhostPinsRef.current.forEach(pin => pin.reposition())
profileFocusPinRef.current?.reposition()
altLabelsRef.current.forEach(pin => pin.reposition())
}, [])
// Single reusable hover popup for POI markers. Planned places use the
@@ -826,6 +667,42 @@ export function MapViewGL({
* drag is therefore hand-rolled — pointer events on the element, unproject on move.
*/
const viaCleanupRef = useRef<(() => void)[]>([])
const attachPlannerWaypointPin = useCallback(
(el: HTMLElement, lng: number, lat: number) => attachPin(mapRef.current, gl, pinLayerRef.current, el, lng, lat),
[gl],
)
usePlannerWaypointMarkersGL({
mapRef, mapReady, pinsRef: plannerWaypointPinsRef, attachPin: attachPlannerWaypointPin, pinCss: plannerWaypointPinCss,
plannerWaypoints, selectedPlannerWaypointId, onPlannerWaypointClick, onPlannerWaypointMove,
})
useEffect(() => () => {
profileFocusPinRef.current?.remove()
profileFocusPinRef.current = null
}, [gl, mapReady])
useEffect(() => {
const map = mapRef.current
if (!map || !mapReady) return
if (!routeProfileFocus) {
profileFocusPinRef.current?.remove()
profileFocusPinRef.current = null
return
}
let pin = profileFocusPinRef.current
if (!pin) {
const element = document.createElement('div')
element.setAttribute('aria-hidden', 'true')
element.dataset.tourProfileFocus = 'true'
element.style.cssText = 'width:18px;height:18px;border:3px solid var(--bg-card);border-radius:50%;background:var(--text-muted);box-shadow:0 0 0 1px var(--text-secondary);pointer-events:none;box-sizing:border-box;'
pin = attachPin(map, gl, pinLayerRef.current, element, routeProfileFocus.lng, routeProfileFocus.lat)
profileFocusPinRef.current = pin
} else {
pin.setLngLat([routeProfileFocus.lng, routeProfileFocus.lat])
}
pin.el.style.pointerEvents = 'none'
}, [gl, mapReady, routeProfileFocus])
/**
* The list only changes when a via does, and the callbacks are read through a ref.
*
@@ -1220,7 +1097,7 @@ export function MapViewGL({
const mapOptions: Record<string, unknown> = {
container: containerRef.current,
style: isMapLibre ? offlineStyle(glStyle) : glStyle,
style: initialMapStyle(glProvider, glStyle),
center: [initial.center[1], initial.center[0]],
zoom: initial.zoom,
pitch: enableMapbox3d ? 45 : 0,
@@ -1228,13 +1105,12 @@ export function MapViewGL({
antialias: mapboxQuality,
}
if (!isMapLibre) mapOptions.projection = mapboxQuality ? 'globe' : 'mercator'
// MapLibre 5's mouse-rotate inverts its sign at a mid-screen line it gets by
// re-projecting the map center — a line that drifts with the bearing, so a
// right-button drag near mid-screen ping-pongs instead of rotating (#1545).
// aroundCenter: false restores the plain dx-based rotate mapbox-gl uses.
// MapLibre's around-center rotate ping-pongs near mid-screen (#1545); false is mapbox-gl's dx rotate.
if (isMapLibre) mapOptions.aroundCenter = false
const map = new gl.Map(mapOptions as any)
// Null when the GPU refused WebGL2: MapViewAuto has switched to Leaflet by then.
const map = buildGlMap(() => new gl.Map(mapOptions as any))
if (!map) return
mapRef.current = map
popupRef.current = new gl.Popup({
closeButton: false,
@@ -1344,6 +1220,8 @@ export function MapViewGL({
source: 'trip-route',
// Per feature where the caller gave one, else the blue the route has always
// been. `coalesce` rather than a second layer: one source, one stroke.
// A walked stretch has no casing; it is drawn dashed by its own layer (#2532).
filter: ['!=', ['get', 'walks'], true],
paint: { 'line-color': ['coalesce', ['get', 'casing'], '#0a5cc2'], 'line-width': 8 },
layout: { 'line-cap': 'round', 'line-join': 'round' },
})
@@ -1361,9 +1239,18 @@ export function MapViewGL({
id: 'trip-route-line',
type: 'line',
source: 'trip-route',
filter: ['!=', ['get', 'walks'], true],
paint: { 'line-color': ['coalesce', ['get', 'color'], '#0a84ff'], 'line-width': 5 },
layout: { 'line-cap': 'round', 'line-join': 'round' },
})
map.addLayer({
id: 'trip-route-walk',
type: 'line',
source: 'trip-route',
filter: ['==', ['get', 'walks'], true],
paint: { 'line-color': ['coalesce', ['get', 'color'], '#0a84ff'], 'line-width': 4, 'line-dasharray': [0.1, 2.2] },
layout: { 'line-cap': 'round', 'line-join': 'round' },
})
}
// The last bit to a place the road does not reach (#1797). Added after the route
// so it draws over it: it is the one piece of the line that is not driving, and it
@@ -1381,40 +1268,8 @@ export function MapViewGL({
})
}
// gpx geometries source (place.route_geometry)
if (!map.getSource('trip-gpx')) {
map.addSource('trip-gpx', { type: 'geojson', data: { type: 'FeatureCollection', features: [] } })
// Casing under the tracks that carry a picked colour (#776) — keeps them
// legible on satellite and dark styles. Untouched tracks are filtered
// out, so they look exactly as they did before.
map.addLayer({
id: 'trip-gpx-casing',
type: 'line',
source: 'trip-gpx',
filter: ['==', ['get', 'cased'], true],
paint: { 'line-color': '#ffffff', 'line-width': 6.5, 'line-opacity': 0.7 },
layout: { 'line-cap': 'round', 'line-join': 'round' },
})
map.addLayer({
id: 'trip-gpx-line',
type: 'line',
source: 'trip-gpx',
paint: {
'line-color': ['coalesce', ['get', 'color'], '#3b82f6'],
'line-width': 3.5,
'line-opacity': ['case', ['==', ['get', 'cased'], true], 0.9, 0.75],
},
layout: { 'line-cap': 'round', 'line-join': 'round' },
})
// Invisible fat line that catches the click — 3.5px is not a target,
// and the start markers cluster below zoom 11, so without this a track
// is unreachable at the very zoom where you compare walks side by side.
map.addLayer({
id: GPX_HIT_LAYER_ID,
type: 'line',
source: 'trip-gpx',
paint: { 'line-color': '#000', 'line-width': 14, 'line-opacity': 0 },
layout: { 'line-cap': 'round', 'line-join': 'round' },
})
if (!hasGpxTrackLayers(map)) {
addGpxTrackLayers(map)
const selectTrack = (e: any) => { // eslint-disable-line @typescript-eslint/no-explicit-any
// A click on a cluster bubble sitting over a track belongs to the
// cluster (zoom-to-expand), not to the line underneath it.
@@ -1521,6 +1376,7 @@ export function MapViewGL({
// safely add their own sources. Style rebuilds reset this via the
// cleanup below.
setMapReady(true)
setReadyMap(map)
})
// Layer for the hand-positioned place pins, inside the canvas container so it
@@ -1569,14 +1425,11 @@ export function MapViewGL({
&& typeof map.queryRenderedFeatures === 'function'
&& map.queryRenderedFeatures(e.point, { layers: ['trip-route-hit'] }).length > 0
) return
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
// pill can fetch OSM places for the visible area.
const emitViewport = () => {
const b = map.getBounds()
onViewportChangeRef.current?.({ south: b.getSouth(), west: b.getWest(), north: b.getNorth(), east: b.getEast() })
}
// Emit the viewport (pan/zoom + once on first idle) for the POI-explore pill.
const emitViewport = () => reportGlViewport(map, onViewportChangeRef.current)
map.on('moveend', emitViewport)
map.once('idle', emitViewport)
// Clear the hover card (and the anchored POI popup) as soon as the camera
@@ -1764,62 +1617,8 @@ export function MapViewGL({
try { map.setConfigProperty('basemap', 'language', basemapLanguage(mapLang)) } catch { /* style/SDK may not support the basemap language property */ }
}, [mapLang, mapReady, isMapLibre, glStyle])
// Photo loading — mirrors the Leaflet MapView. Updates via RAF to batch
// simultaneous thumb arrivals into one re-render.
const pendingThumbsRef = useRef<Record<string, string>>({})
const thumbRafRef = useRef<number | null>(null)
const photoSources = useMemo(() => photoSourcesKey(places), [places])
useEffect(() => {
if (!places || places.length === 0 || !placesPhotosEnabled) return
const cleanups: (() => void)[] = []
const setThumb = (cacheKey: string, thumb: string) => {
pendingThumbsRef.current[cacheKey] = thumb
if (thumbRafRef.current !== null) return
thumbRafRef.current = requestAnimationFrame(() => {
thumbRafRef.current = null
const pending = pendingThumbsRef.current
pendingThumbsRef.current = {}
setPhotoUrls(prev => {
const hasChange = Object.entries(pending).some(([k, v]) => prev[k] !== v)
return hasChange ? { ...prev, ...pending } : prev
})
})
}
for (const place of places) {
// A custom uploaded image is shown directly — never auto-fetch a provider
// photo for it (that request would 404 for OSM-only places and, worse, the
// fetched thumb would shadow the user's own image). (#1136)
if (isCustomPlaceImage(place.image_url)) continue
const cacheKey = photoCacheKey(place)
if (!cacheKey) continue
const cached = getCached(cacheKey)
if (cached?.thumbDataUrl) {
setThumb(cacheKey, cached.thumbDataUrl)
continue
}
cleanups.push(onThumbReady(cacheKey, thumb => setThumb(cacheKey, thumb)))
if (!cached && !isLoading(cacheKey)) {
const photoId =
(place.image_url?.startsWith('/api/maps/place-photo/') ? place.image_url : null)
|| place.google_place_id
|| place.osm_id
|| place.image_url
if (photoId || (place.lat && place.lng)) {
fetchPhoto(cacheKey, photoId || `coords:${place.lat}:${place.lng}`, place.lat, place.lng, place.name)
}
}
}
return () => {
cleanups.forEach(fn => fn())
if (thumbRafRef.current !== null) {
cancelAnimationFrame(thumbRafRef.current)
thumbRafRef.current = null
}
}
}, [photoSources, placesPhotosEnabled]) // eslint-disable-line react-hooks/exhaustive-deps
// Photo loading, shared with the Leaflet MapView.
const photoUrls = useMarkerThumbs(places)
// Reconcile markers with places + photos. The clustered GeoJSON source decides
// which points are currently unclustered, and we render the existing rich HTML
@@ -1849,15 +1648,13 @@ export function MapViewGL({
visiblePlaces.forEach(place => {
const orderNumbers = dayOrderMap[place.id] ?? null
const pck = photoCacheKey(place)
// A custom image wins over the auto-fetched thumb; otherwise fall back to it.
const photoUrl = isCustomPlaceImage(place.image_url) ? place.image_url! : ((pck && photoUrls[pck]) || place.image_url || null)
const photoUrl = placePhotoUrl(place, photoUrls)
const selected = place.id === selectedPlaceId
const el = createMarkerElement(place as Place & { category_color?: string; category_icon?: string }, photoUrl, orderNumbers, selected)
const el = createMarkerElement(place as Place & PlaceMarkerFlags & { category_color?: string; category_icon?: string }, photoUrl, orderNumbers, selected)
// Drag onto a day in the plan (#891). Markers are rebuilt from scratch
// on every reconcile, so the listeners go with the element and need no
// teardown of their own.
if (markersDraggableRef.current) makeMarkerDraggable(el, place.id)
if (markersDraggableRef.current && !assistant.markersLocked) makeMarkerDraggable(el, place.id)
el.addEventListener('click', (ev) => {
ev.stopPropagation()
// Clear the card right away — the flyTo that follows moves the marker
@@ -1870,7 +1667,7 @@ export function MapViewGL({
el.addEventListener('mouseenter', (ev) => {
if (hoverDisabledRef.current || camMovingRef.current) return
hoverIdRef.current = place.id
setHoverPlace(place as Place & { category_color?: string; category_icon?: string; category_name?: string })
setHoverPlace({ ...(place as Place & { category_color?: string; category_icon?: string; category_name?: string }), photo: placePhotoFull(place) })
setHoverPos({ x: (ev as MouseEvent).clientX, y: (ev as MouseEvent).clientY })
})
el.addEventListener('mousemove', (ev) => {
@@ -1886,7 +1683,7 @@ export function MapViewGL({
// Recreate marker each time rather than patching internal state —
// mapbox-gl's internal _element bookkeeping breaks under DOM swaps.
const existing = markersRef.current.get(place.id)
if (existing) existing.remove()
if (existing) { carryAssistantMarks(existing.el, el); existing.remove() }
// Default (viewport-aligned) anchors keep the marker parallel to the
// screen so its pixel centre lines up with the route line at any
// pitch. Tried `pitchAlignment: 'map'` to snap markers onto terrain,
@@ -1959,7 +1756,7 @@ export function MapViewGL({
map.off('zoomend', scheduleReconcile)
map.off('idle', scheduleReconcile)
}
}, [places, selectedPlaceId, dayOrderMap, photoUrls, mapReady, glProvider, clusterLoosely])
}, [places, selectedPlaceId, dayOrderMap, photoUrls, mapReady, glProvider, clusterLoosely, assistant.markersLocked])
// Search results stay separate from the planned itinerary.
useEffect(() => {
@@ -1995,7 +1792,7 @@ export function MapViewGL({
continue
}
const poi = group.pois[0]
const el = createPoiMarkerElement(poi.category, poi.brand_wikidata)
const el = createPoiMarkerElement(poi, poi.brand_wikidata)
el.addEventListener('mouseenter', () => {
popupRef.current?.setLngLat([poi.lng, poi.lat]).setHTML(buildPoiPopupHtml(poi)).addTo(map)
})
@@ -2074,7 +1871,7 @@ export function MapViewGL({
el.addEventListener('mouseleave', () => { setHoverPlace(null); setHoverPos(null) })
}
if (v.label || v.dwellSeconds != null) {
const text = [v.label, v.dwellSeconds != null ? formatViaDwellGl(v.dwellSeconds) : null].filter(Boolean).join(' · ')
const text = [v.label, v.dwellSeconds != null ? formatViaDwell(v.dwellSeconds) : null].filter(Boolean).join(' · ')
el.addEventListener('click', (ev) => {
ev.stopPropagation()
popupRef.current?.setLngLat([v.lng, v.lat]).setText(text).addTo(map)
@@ -2131,17 +1928,17 @@ export function MapViewGL({
const src = map.getSource('trip-route') as mapboxgl.GeoJSONSource | undefined
if (!src) return
const features = (route || [])
.map((seg, i) => ({ seg, colors: routeColors?.[i] }))
.map((seg, i) => ({ seg, colors: routeColors?.[i], walks: !!routeWalking?.[i] }))
.filter(({ seg }) => seg && seg.length > 1)
.map(({ seg, colors }) => ({
.map(({ seg, colors, walks }) => ({
type: 'Feature' as const,
// Null rather than absent: `coalesce` in the paint expression falls through on
// null, and an absent property would make every line the default colour.
properties: { color: colors?.line ?? null, casing: colors?.casing ?? null },
properties: { color: colors?.line ?? null, casing: colors?.casing ?? null, walks },
geometry: { type: 'LineString' as const, coordinates: seg.map(([lat, lng]) => [lng, lat]) },
}))
src.setData({ type: 'FeatureCollection', features })
}, [route, routeColors, mapReady])
}, [route, routeColors, routeWalking, mapReady])
// Update access-spur geojson
useEffect(() => {
@@ -2165,27 +1962,15 @@ export function MapViewGL({
useEffect(() => {
const map = mapRef.current
if (!map) return
const src = map.getSource('trip-gpx') as mapboxgl.GeoJSONSource | undefined
if (!src) return
const features = places.flatMap(place => {
if (!place.route_geometry) return []
try {
const coords = JSON.parse(place.route_geometry) as [number, number][]
if (!coords || coords.length < 2) return []
return [{
type: 'Feature' as const,
properties: {
color: resolveTrackColor(place),
cased: hasManualTrackColor(place),
place_id: place.id,
},
geometry: { type: 'LineString' as const, coordinates: coords.map(([lat, lng]) => [lng, lat]) },
}]
} catch { return [] }
})
src.setData({ type: 'FeatureCollection', features })
setGpxTracks(map, places)
}, [places, mapReady])
// The picked tour's track stands out (PR1-08).
useEffect(() => {
const map = mapRef.current
if (map && mapReady) selectGpxTrack(map, selectedPlaceId)
}, [selectedPlaceId, mapReady])
// Reservation overlay — mirrors the Leaflet ReservationOverlay: great-
// circle arcs for flights/cruises, straight lines for trains/cars,
// clickable endpoint badges, rotating mid-arc stats label for flights.
@@ -2223,12 +2008,12 @@ export function MapViewGL({
// Fit bounds on fitKey change — matches the Leaflet BoundsController
const paddingOpts = useMemo(() => {
const isMobile = typeof window !== 'undefined' && window.innerWidth < 768
if (isMobile) return { top: 40, right: 20, bottom: 40, left: 20 }
const top = 60
const bottom = hasInspector ? 320 : hasDayDetail ? 280 : 60
return { top, right: rightWidth + 40, bottom, left: leftWidth + 40 }
}, [leftWidth, rightWidth, hasInspector, hasDayDetail])
}, [isMobile, leftWidth, rightWidth, hasInspector, hasDayDetail])
useAssistantMapGL({ mapRef, mapReady, gl, pinsRef: assistantGhostPinsRef, attachPin: attachPlannerWaypointPin, markersRef, padding: paddingOpts, assistant })
const prevFitKey = useRef<number | null>(-1)
const pendingRouteFitRef = useRef<{ fitKey: number | null; routeKey: string } | null>(null)
@@ -2241,6 +2026,8 @@ export function MapViewGL({
&& !!routeFitKey
&& routeFitKey !== pendingRouteFitRef.current.routeKey
if (!fitKeyChanged && !routeArrivedForPendingFit) return
// Locked since the last fit (#2010): the day's route arriving must not move the view.
if (!fitKeyChanged && !followSelection) { pendingRouteFitRef.current = null; return }
const map = mapRef.current
if (!map) return
@@ -2289,14 +2076,22 @@ export function MapViewGL({
// The caller's padding as a value, so a parent that builds the object inline on every
// render does not move the camera each time it renders.
const fitPaddingKey = fitPadding ? [fitPadding.top, fitPadding.right, fitPadding.bottom, fitPadding.left].join(' ') : ''
const didInitialFocusRef = useRef(false)
const prevFocusKeyRef = useRef(focusKey)
// Frame whatever was handed over. Nothing happens when it empties, so closing the
// picker leaves the map where the user left it rather than snapping back.
useEffect(() => {
const map = mapRef.current
if (!map || !focusPoints?.length) return
if (focusKey !== undefined) {
const shouldFit = !didInitialFocusRef.current || focusKey !== prevFocusKeyRef.current
prevFocusKeyRef.current = focusKey
if (!shouldFit) return
didInitialFocusRef.current = true
}
const bounds = new gl.LngLatBounds()
focusPoints.forEach(([lat, lng]) => bounds.extend([lng, lat]))
alongShortestArc(focusPoints).forEach(([lat, lng]) => bounds.extend([lng, lat]))
// A day fit still waiting on its route must not overwrite this a moment later.
pendingRouteFitRef.current = null
try {
@@ -2304,15 +2099,15 @@ export function MapViewGL({
padding: fitPadding ?? paddingOpts,
maxZoom: 15,
pitch: enableMapbox3d ? 45 : 0,
duration: 400,
duration: mapReady ? 400 : 0, // handed over while the map is built: it opens there, no flight in
})
} catch { /* noop */ }
}, [focusPoints, fitPaddingKey]) // eslint-disable-line react-hooks/exhaustive-deps
}, [focusPoints, focusKey, fitPaddingKey]) // eslint-disable-line react-hooks/exhaustive-deps
// flyTo selected place
useEffect(() => {
const map = mapRef.current
if (!map || !selectedPlaceId) return
if (!map || !selectedPlaceId || !followSelection) return
const target = selectedPlaceTarget(selectedPlaceId, places, dayPlaces, selectedPlace)
if (!target?.lat || !target?.lng) return
try {
@@ -2383,11 +2178,11 @@ export function MapViewGL({
useEffect(() => {
const map = mapRef.current
if (!map || !mapReady) return
const apply = () => applySatellite(map, isSatellite)
const apply = () => applyBaseLayer(map, baseLayer)
apply()
map.on('styledata', apply)
return () => { map.off('styledata', apply) }
}, [isSatellite, mapReady, glProvider])
}, [baseLayer, mapReady, glProvider])
if (!isMapLibre && !mapboxToken) {
return (
@@ -2427,11 +2222,16 @@ export function MapViewGL({
covers. */}
<div style={{
position: 'absolute', left: leftWidth + MAP_LAYER_SWITCHER_INSET, zIndex: 1000, pointerEvents: 'none',
display: 'flex', flexDirection: 'column', gap: 8,
bottom: isMobile && hasDayDetail
? 'calc(var(--bottom-nav-h, 0px) + 20px + var(--day-panel-h, 0px) + 12px)'
: 'calc(var(--bottom-nav-h, 0px) + 12px)',
}}>
<MapLayerSwitcher active={baseLayer as BaseLayer} onToggle={toggleBaseLayer} />
{onToggleFollow && <MapLockPill locked={!followSelection} onToggle={onToggleFollow} />}
{hasViewBaseLayer
? <TourMapLayerSwitcher active={baseLayer as TourBaseLayer} onChange={onViewBaseLayerChange}
onToggleTerrain={onToggleTerrain3d} ferrataLayer={ferrataLayer} placeTool={placeTool} layers={tourLayers} />
: <MapLayerSwitcher active={globalBaseLayer as BaseLayer} onToggle={toggleBaseLayer} />}
</div>
{/* Hover tooltip — cursor-following name/category/address card, identical to
the Leaflet map's overlay (no anchored popup, no photo). */}
@@ -2447,7 +2247,8 @@ export function MapViewGL({
categoryIcon={hoverPlace.category_icon}
categoryColor={hoverPlace.category_color}
address={hoverPlace.address}
rating={hoverPlace.rating_avg}
rating={hoverPlace.rating_avg}
photo={hoverPlace.photo}
/>
)}
</div>
+33 -38
View File
@@ -1,6 +1,8 @@
import React from 'react'
import { Star } from 'lucide-react'
import { MapPin, Star } from 'lucide-react'
import { getCategoryIcon } from '../shared/categoryIcons'
import { fs } from '../shared/DialogShell'
import { tintOf } from '../Planner/planParts'
/**
* What a place is, shown at the cursor while the pointer rests on its marker.
@@ -24,48 +26,41 @@ export interface PlaceHoverCardProps {
address?: string | null
/** Average across everyone who rated it, when the surface tracks ratings. */
rating?: number | null
/** The picture its marker wears; the card shows it in place of the category tile. */
photo?: string | null
}
export default function PlaceHoverCard({ x, y, name, categoryName, categoryIcon, categoryColor, address, rating }: PlaceHoverCardProps): React.ReactElement {
const CatIcon = categoryName ? getCategoryIcon(categoryIcon) : null
export default function PlaceHoverCard({ x, y, name, categoryName, categoryIcon, categoryColor, address, rating, photo }: PlaceHoverCardProps): React.ReactElement {
// The tile wears the category the way the planner's rows do; without one it is a quiet pin.
const CatIcon = categoryName ? getCategoryIcon(categoryIcon) : MapPin
const tone = categoryName ? categoryColor || 'var(--text-muted)' : null
return (
<div data-testid="tooltip" style={{
position: 'fixed',
left: x + 14,
top: y - 10,
zIndex: 9999,
pointerEvents: 'none',
background: 'white',
borderRadius: 8,
boxShadow: '0 2px 10px rgba(0,0,0,0.15)',
padding: '6px 10px',
fontFamily: 'var(--font-system)',
maxWidth: 220,
whiteSpace: 'nowrap',
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<div style={{ fontWeight: 600, fontSize: 12, color: '#111827', overflow: 'hidden', textOverflow: 'ellipsis' }}>
{name}
<div data-testid="tooltip"
className="flex max-w-[300px] items-center gap-3 rounded-[18px] border border-edge-faint bg-surface-card p-1.5 pe-4 font-system shadow-popover"
style={{ position: 'fixed', left: x + 14, top: y - 10, zIndex: 9999, pointerEvents: 'none' }}>
{/* Twelve inside eighteen with six of padding: the picture's corners follow the card's. */}
{photo ? (
<img src={photo} alt="" className="block h-14 w-14 flex-none rounded-[12px] bg-surface-tertiary object-cover" />
) : (
<span className="grid h-14 w-14 flex-none place-items-center rounded-[12px]"
style={{ background: tone ? tintOf(tone, 14) : 'var(--bg-tertiary)' }}>
<CatIcon size={18} strokeWidth={2} style={{ color: tone || 'var(--text-faint)' }} />
</span>
)}
<div className="flex min-w-0 flex-col">
<div className="flex min-w-0 items-center gap-1.5">
<span className="min-w-0 truncate font-semibold text-content" style={fs(13, 'body')}>{name}</span>
{typeof rating === 'number' && rating > 0 && (
<span className="inline-flex flex-none items-center gap-0.5 font-geist tabular-nums text-content-secondary" style={fs(11)}>
<Star size={10} strokeWidth={2} className="fill-current text-warning" aria-hidden />
{/* One decimal only when it earns it: "4" reads faster than "4.0". */}
{Number.isInteger(rating) ? rating : rating.toFixed(1)}
</span>
)}
</div>
{typeof rating === 'number' && rating > 0 && (
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 2, flexShrink: 0, fontSize: 11, fontWeight: 600, color: '#111827' }}>
<Star size={10} style={{ fill: '#f59e0b', color: '#f59e0b' }} aria-hidden />
{/* One decimal only when it earns it: "4" reads faster than "4.0". */}
{Number.isInteger(rating) ? rating : rating.toFixed(1)}
</span>
)}
{categoryName && <span className="truncate text-content-muted" style={fs(11)}>{categoryName}</span>}
{address && <span className="truncate text-content-faint" style={fs(11)}>{address}</span>}
</div>
{categoryName && CatIcon && (
<div style={{ display: 'flex', alignItems: 'center', gap: 3, marginTop: 1 }}>
<CatIcon size={10} style={{ color: categoryColor || '#6b7280', flexShrink: 0 }} />
<span style={{ fontSize: 11, color: '#6b7280' }}>{categoryName}</span>
</div>
)}
{address && (
<div style={{ fontSize: 11, color: '#9ca3af', marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis' }}>
{address}
</div>
)}
</div>
)
}
@@ -0,0 +1,97 @@
import L from 'leaflet';
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { Marker, Tooltip, useMap } from 'react-leaflet';
import { MAP_LABEL_BADGE_CLASS } from './mapHoverLabel';
import { plannerPinBadge, plannerPinShape, type PlannerPinPoint } from './plannerPinShape';
import { wirePlannerWaypointDrag } from './plannerWaypointDrag';
/** The pin's inline style for a size and selection; the renderer owns the colour. */
export type PinCss = (size: number, selected: boolean) => string;
function plannerWaypointIcon(
pinCss: PinCss,
point: PlannerPinPoint,
index: number,
selected: boolean,
draggable: boolean
): L.DivIcon {
const { size, text } = plannerPinShape(point, index, selected);
return L.divIcon({
className: 'tour-planner-waypoint-marker',
iconSize: [size, size],
iconAnchor: [size / 2, size / 2],
html: `<span style="${pinCss(size, selected)};cursor:${draggable ? 'grab' : 'pointer'};touch-action:${draggable ? 'none' : 'auto'};user-select:none">${text}</span>${plannerPinBadge(point)}`,
});
}
export default function PlannerWaypointMarker({
point,
index,
selected,
onClick,
onMove,
pinCss,
}: {
point: { id: string; lat: number; lng: number; name?: string; detail?: string } & PlannerPinPoint;
index: number;
selected: boolean;
onClick?: (id: string) => void;
onMove?: (id: string, lat: number, lng: number) => boolean;
pinCss: PinCss;
}) {
const map = useMap();
const [marker, setMarker] = useState<L.Marker | null>(null);
const handlersRef = useRef({ onClick, onMove });
useLayoutEffect(() => {
handlersRef.current = { onClick, onMove };
}, [onClick, onMove]);
const position = useMemo(() => [point.lat, point.lng] as [number, number], [point.lat, point.lng]);
const { label, shaping, stageEnd } = point;
const icon = useMemo(
() => plannerWaypointIcon(pinCss, { label, shaping, stageEnd }, index, selected, !!onMove),
[index, label, onMove, pinCss, selected, shaping, stageEnd]
);
const eventHandlers = useMemo(
() => ({
click: (event: { originalEvent: MouseEvent }) => {
event.originalEvent.stopPropagation();
handlersRef.current.onClick?.(point.id);
},
}),
[point.id]
);
useEffect(() => {
if (!marker || !onMove) return;
const element = marker.getElement();
if (!element) return;
return wirePlannerWaypointDrag({
element,
initial: { lat: point.lat, lng: point.lng },
coordinateAt: (clientX, clientY) => {
const rect = map.getContainer().getBoundingClientRect();
const at = map.containerPointToLatLng([clientX - rect.left, clientY - rect.top]);
return { lat: at.lat, lng: at.lng };
},
setPosition: ({ lat, lng }) => {
marker.setLatLng([lat, lng]);
},
onCommit: ({ lat, lng }) => handlersRef.current.onMove?.(point.id, lat, lng) ?? false,
});
}, [map, marker, onMove, point.id, point.lat, point.lng]);
return (
<Marker
ref={setMarker}
position={position}
icon={icon}
zIndexOffset={selected ? 1200 : 1100}
eventHandlers={eventHandlers}
>
<Tooltip direction="top" offset={[0, -12]} opacity={1} className="map-tooltip">
<span className="font-medium">{point.name ?? index + 1}</span>
{point.detail && <span className={MAP_LABEL_BADGE_CLASS}>{point.detail}</span>}
</Tooltip>
</Marker>
);
}
@@ -1,17 +1,37 @@
// FE-COMP-POIPILL-001 to FE-COMP-POIPILL-008
// FE-COMP-POIPILL-001 to FE-COMP-POIPILL-018
import React from 'react'
import { describe, it, expect, vi } from 'vitest'
import { render, screen } from '../../../tests/helpers/render'
import { fireEvent } from '@testing-library/react'
import PoiCategoryPill from './PoiCategoryPill'
import { POI_CATEGORIES } from './poiCategories'
import { corePoiCategories, pluginPoiCategories, type PoiCategoryGroups } from './usePoiCategories'
const CAFE = POI_CATEGORIES.find(c => c.key === 'cafe')!
const BAR = POI_CATEGORIES.find(c => c.key === 'bar')!
// The labels the English UI gives the core chips, as usePoiCategories hands them over.
const EN: Record<string, string> = {
'poi.cat.restaurants': 'Restaurants', 'poi.cat.cafes': 'Cafés', 'poi.cat.bars': 'Bars & nightlife',
'poi.cat.hotels': 'Accommodation', 'poi.cat.sights': 'Sights', 'poi.cat.museums': 'Museums & culture',
'poi.cat.nature': 'Nature & parks', 'poi.cat.activities': 'Activities',
}
const CORE_ONLY: PoiCategoryGroups = { core: corePoiCategories(key => EN[key] ?? key), plugin: [] }
const WITH_PLUGINS: PoiCategoryGroups = {
core: CORE_ONLY.core,
plugin: pluginPoiCategories([{
id: 'trail-finder', name: 'Trail finder', type: 'integration', icon: null,
poiCategories: [
{ id: 'trailheads', label: 'Trailheads', icon: 'Signpost', color: '#2f855a' },
{ id: 'water', label: 'Drinking water', icon: 'Droplet', color: '#0369a1' },
],
}], 'en'),
}
const TRAILHEADS = 'plugin:trail-finder/trailheads'
function pill(props: Partial<React.ComponentProps<typeof PoiCategoryPill>> = {}) {
return render(
<PoiCategoryPill active={new Set()} onToggle={vi.fn()} {...props} />,
<PoiCategoryPill categories={CORE_ONLY} active={new Set()} onToggle={vi.fn()} {...props} />,
)
}
@@ -21,6 +41,8 @@ const spinning = () => screen.getAllByRole('button')
.filter(b => b.querySelector('.animate-spin'))
.map(b => b.getAttribute('aria-label'))
const labels = () => screen.getAllByRole('button').map(b => b.getAttribute('aria-label'))
describe('PoiCategoryPill', () => {
it('FE-COMP-POIPILL-001: renders one segment per category, none pressed', () => {
pill()
@@ -75,4 +97,121 @@ describe('PoiCategoryPill', () => {
expect(button.style.width).toBe('34px')
expect((button.parentElement as HTMLElement).style.display).toBe('inline-flex')
})
it('FE-COMP-POIPILL-009: without plugin categories there is no divider and every segment sits in the bar', () => {
pill()
expect(screen.queryByRole('separator')).toBeNull()
const bar = screen.getAllByRole('button')[0].parentElement as HTMLElement
expect(bar.children).toHaveLength(POI_CATEGORIES.length)
})
it('FE-COMP-POIPILL-010: plugin categories follow the core ones after a labelled divider', () => {
pill({ categories: WITH_PLUGINS })
expect(labels()).toEqual([...CORE_ONLY.core.map(c => c.label), 'Trailheads', 'Drinking water'])
const divider = screen.getByRole('separator', { name: 'Categories from plugins' })
const bar = divider.parentElement as HTMLElement
// In the same bar, straight after the last core segment.
expect(Array.from(bar.children).indexOf(divider)).toBe(POI_CATEGORIES.length)
expect(divider.getAttribute('aria-orientation')).toBe('vertical')
})
it('FE-COMP-POIPILL-011: a plugin segment toggles its namespaced key and fills with its own colour', () => {
const onToggle = vi.fn()
const { rerender } = pill({ categories: WITH_PLUGINS, onToggle })
fireEvent.click(screen.getByRole('button', { name: 'Trailheads' }))
expect(onToggle).toHaveBeenCalledWith(TRAILHEADS)
rerender(<PoiCategoryPill categories={WITH_PLUGINS} active={new Set([TRAILHEADS])} onToggle={onToggle} errorKeys={new Set([TRAILHEADS])} />)
const segment = screen.getByRole('button', { name: 'Trailheads' })
expect(segment.getAttribute('aria-pressed')).toBe('true')
expect(segment.style.background).toBe('rgb(47, 133, 90)')
// A failing plugin category offers the same retry a core one does.
expect(screen.getByText('Search this area')).toBeInTheDocument()
})
it('FE-COMP-POIPILL-012: the bar scrolls sideways once it runs out of room', () => {
pill({ categories: WITH_PLUGINS, fullWidth: true })
const bar = screen.getAllByRole('button')[0].parentElement as HTMLElement
expect(bar.style.overflowX).toBe('auto')
expect(bar.style.maxWidth).toBe('100%')
// The column around it may shrink, or the bar would push past its container instead.
expect((bar.parentElement as HTMLElement).style.minWidth).toBe('0px')
})
it('FE-COMP-POIPILL-013: a phone segment never shrinks below the 34px touch target', () => {
pill({ categories: WITH_PLUGINS, fullWidth: true })
for (const button of screen.getAllByRole('button')) {
expect(button.style.minWidth).toBe('34px')
expect(button.style.height).toBe('34px')
}
})
it('FE-COMP-POIPILL-014: a desktop segment keeps its 34px instead of shrinking in a narrow corridor', () => {
pill({ categories: WITH_PLUGINS })
for (const button of screen.getAllByRole('button')) {
expect(button.style.flexShrink).toBe('0')
expect(button.style.minWidth).toBe('34px')
}
expect((screen.getByRole('separator').style.flexShrink)).toBe('0')
})
it('FE-COMP-POIPILL-015: hovering highlights an idle segment and leaves an active one its colour', () => {
pill({ categories: WITH_PLUGINS, active: new Set([TRAILHEADS]) })
const idle = screen.getByRole('button', { name: 'Drinking water' })
fireEvent.mouseEnter(idle)
expect(idle.style.background).toBe('var(--bg-hover)')
fireEvent.mouseLeave(idle)
expect(idle.style.background).toBe('transparent')
const on = screen.getByRole('button', { name: 'Trailheads' })
fireEvent.mouseEnter(on)
fireEvent.mouseLeave(on)
expect(on.style.background).toBe('rgb(47, 133, 90)')
})
// jsdom lays nothing out, so the bar is given the widths a narrow desktop corridor would.
const barOf = (clientWidth: number, scrollWidth: number) => {
const bar = screen.getByRole('separator').parentElement as HTMLElement
Object.defineProperty(bar, 'clientWidth', { configurable: true, value: clientWidth })
Object.defineProperty(bar, 'scrollWidth', { configurable: true, value: scrollWidth })
return bar
}
it('FE-COMP-POIPILL-016: a mouse wheel scrolls an overflowing desktop bar sideways, in pixels, lines or pages', () => {
pill({ categories: WITH_PLUGINS })
const bar = barOf(300, 450)
fireEvent.wheel(bar, { deltaY: 100 })
expect(bar.scrollLeft).toBe(100)
fireEvent.wheel(bar, { deltaY: 1, deltaMode: WheelEvent.DOM_DELTA_LINE })
expect(bar.scrollLeft).toBe(134)
fireEvent.wheel(bar, { deltaY: 0.5, deltaMode: WheelEvent.DOM_DELTA_PAGE })
expect(bar.scrollLeft).toBe(284)
})
it('FE-COMP-POIPILL-017: the wheel is left alone when the bar fits or the turn is already sideways', () => {
pill({ categories: WITH_PLUGINS })
const bar = barOf(450, 450)
fireEvent.wheel(bar, { deltaY: 100 })
expect(bar.scrollLeft).toBe(0)
// A trackpad swipe or Shift+wheel scrolls the bar natively; adding to it would double it.
barOf(300, 450)
fireEvent.wheel(bar, { deltaX: 40, deltaY: 10 })
expect(bar.scrollLeft).toBe(0)
})
it('FE-COMP-POIPILL-018: in a right-to-left language a wheel-down still moves toward the plugin chips', () => {
// The app sets the page direction from the language (TranslationContext) and the bar
// inherits it. The test provider renders in English, so a wrapper stands in for Arabic.
render(
<div dir="rtl">
<PoiCategoryPill categories={WITH_PLUGINS} active={new Set()} onToggle={vi.fn()} />
</div>,
)
const bar = barOf(300, 450)
// An RTL scroller counts scrollLeft from 0 at the start down to negative at the end.
fireEvent.wheel(bar, { deltaY: 100 })
expect(bar.scrollLeft).toBe(-100)
fireEvent.wheel(bar, { deltaY: -40 })
expect(bar.scrollLeft).toBe(-60)
})
})
+121 -56
View File
@@ -1,9 +1,11 @@
import { RotateCw, AlertTriangle } from 'lucide-react'
import { useTranslation } from '../../i18n'
import { Tooltip } from '../shared/Tooltip'
import { POI_CATEGORIES } from './poiCategories'
import type { ExplorePoiCategory, PoiCategoryGroups } from './usePoiCategories'
interface Props {
/** The chips to offer, from usePoiCategories by way of usePoiExplore. */
categories: PoiCategoryGroups
active: Set<string>
onToggle: (key: string) => void
loadingKeys?: Set<string>
@@ -18,10 +20,95 @@ interface Props {
fullWidth?: boolean
}
// The touch target every segment keeps, however many categories there are.
const SEGMENT = 34
// How far one wheel step moves the bar. Firefox counts a mouse wheel in lines and
// some drivers in pages; a line moves about one segment, a page one bar width.
function wheelPixels(e: React.WheelEvent, barWidth: number): number {
if (e.deltaMode === WheelEvent.DOM_DELTA_LINE) return e.deltaY * SEGMENT
if (e.deltaMode === WheelEvent.DOM_DELTA_PAGE) return e.deltaY * barWidth
return e.deltaY
}
// The bar only ever overflows sideways and a plain mouse wheel only turns vertically,
// so on desktop the chips past the corridor edge (the plugin ones first) were out of
// reach without a trackpad. While the bar overflows, a mostly vertical turn scrolls it
// sideways. A sideways swipe or Shift+wheel already scrolls it natively and is left alone.
// In a right-to-left language the chips overflow to the left and scrollLeft runs from 0
// down into negative numbers, so the same turn has to count the other way to reach them.
function wheelSideways(e: React.WheelEvent<HTMLDivElement>) {
const bar = e.currentTarget
if (bar.scrollWidth <= bar.clientWidth || Math.abs(e.deltaY) <= Math.abs(e.deltaX)) return
const towardEnd = getComputedStyle(bar).direction === 'rtl' ? -1 : 1
bar.scrollLeft += towardEnd * wheelPixels(e, bar.clientWidth)
}
interface SegmentProps {
cat: ExplorePoiCategory
on: boolean
loading: boolean
failed: boolean
fullWidth?: boolean
onToggle: (key: string) => void
}
function Segment({ cat, on, loading, failed, fullWidth, onToggle }: Readonly<SegmentProps>) {
return (
<Tooltip label={cat.label} placement="bottom">
<button
type="button"
onClick={() => onToggle(cat.key)}
aria-pressed={on}
aria-label={cat.label}
className={on ? '' : 'text-content-muted'}
style={{
position: 'relative',
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
flexGrow: fullWidth ? 1 : undefined,
// Spread on the phone, fixed on desktop, and never narrower than the touch
// target either way: past that the bar scrolls instead of squeezing.
flexShrink: fullWidth ? 1 : 0,
flexBasis: fullWidth ? 0 : undefined,
minWidth: SEGMENT,
width: fullWidth ? 'auto' : SEGMENT, height: SEGMENT, borderRadius: 999, border: 'none', cursor: 'pointer',
background: on ? cat.color : 'transparent',
color: on ? '#fff' : undefined,
transition: 'background 0.14s, color 0.14s',
}}
onMouseEnter={e => { if (!on) e.currentTarget.style.background = 'var(--bg-hover)' }}
onMouseLeave={e => { if (!on) e.currentTarget.style.background = 'transparent' }}
>
{loading ? (
<span
className="animate-spin"
style={{
width: 14, height: 14, borderRadius: 999, display: 'inline-block',
border: '2px solid', borderColor: on ? 'rgba(255,255,255,0.45)' : 'var(--border-primary)',
borderTopColor: on ? '#fff' : 'var(--text-muted)',
}}
/>
) : (
<cat.Icon size={16} strokeWidth={2} />
)}
{on && !loading && failed && (
<span style={{
position: 'absolute', top: 2, right: 2, width: 8, height: 8,
borderRadius: 999, background: 'var(--danger)', border: '1.5px solid var(--sidebar-bg)',
}} />
)}
</button>
</Tooltip>
)
}
// Frosted, icon-only segmented control that floats over the map. Active segments
// fill with the category colour (matching their markers); the label shows in a
// custom tooltip on hover so the pill stays compact and never needs to scroll.
export default function PoiCategoryPill({ active, onToggle, loadingKeys, errorKeys, moved, onSearchArea, fullWidth }: Props) {
// custom tooltip on hover so the pill stays compact. The core categories come first
// and whatever plugins add follows a thin divider (#1781); once that is more than the
// width holds, the bar scrolls sideways (by swipe, trackpad or mouse wheel) rather than
// shrinking a segment below the touch target.
export default function PoiCategoryPill({ categories, active, onToggle, loadingKeys, errorKeys, moved, onSearchArea, fullWidth }: Readonly<Props>) {
const { t } = useTranslation()
const anyError = !!errorKeys && Array.from(active).some(k => errorKeys.has(k))
@@ -32,63 +119,41 @@ export default function PoiCategoryPill({ active, onToggle, loadingKeys, errorKe
boxShadow: 'var(--sidebar-shadow, 0 4px 16px rgba(0,0,0,0.14))',
}
const segment = (cat: ExplorePoiCategory) => {
const on = active.has(cat.key)
// Only an active category can be loading: a deselected one whose fetch
// is still winding down must not keep spinning.
const loading = on && !!loadingKeys?.has(cat.key)
return (
<Segment
key={cat.key}
cat={cat}
on={on}
loading={loading}
failed={!!errorKeys?.has(cat.key)}
fullWidth={fullWidth}
onToggle={onToggle}
/>
)
}
return (
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, width: fullWidth ? '100%' : undefined }}>
<div style={{
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, width: fullWidth ? '100%' : undefined, maxWidth: '100%', minWidth: 0 }}>
<div onWheel={wheelSideways} style={{
display: fullWidth ? 'flex' : 'inline-flex',
alignSelf: fullWidth ? 'stretch' : undefined,
alignItems: 'center', gap: 2, padding: 4, borderRadius: 999, pointerEvents: 'auto', ...frosted,
maxWidth: '100%', overflowX: 'auto', scrollbarWidth: 'none',
}}>
{POI_CATEGORIES.map(cat => {
const on = active.has(cat.key)
// Only an active category can be loading — a deselected one whose fetch
// is still winding down must not keep spinning.
const loading = on && !!loadingKeys?.has(cat.key)
return (
<Tooltip key={cat.key} label={t(cat.labelKey)} placement="bottom">
<button
type="button"
onClick={() => onToggle(cat.key)}
aria-pressed={on}
aria-label={t(cat.labelKey)}
className={on ? '' : 'text-content-muted'}
style={{
position: 'relative',
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
flexGrow: fullWidth ? 1 : undefined,
flexShrink: fullWidth ? 1 : undefined,
flexBasis: fullWidth ? 0 : undefined,
minWidth: fullWidth ? 0 : undefined,
width: fullWidth ? 'auto' : 34, height: 34, borderRadius: 999, border: 'none', cursor: 'pointer',
background: on ? cat.color : 'transparent',
color: on ? '#fff' : undefined,
transition: 'background 0.14s, color 0.14s',
}}
onMouseEnter={e => { if (!on) e.currentTarget.style.background = 'var(--bg-hover)' }}
onMouseLeave={e => { if (!on) e.currentTarget.style.background = 'transparent' }}
>
{loading ? (
<span
className="animate-spin"
style={{
width: 14, height: 14, borderRadius: 999, display: 'inline-block',
border: '2px solid', borderColor: on ? 'rgba(255,255,255,0.45)' : 'var(--border-primary)',
borderTopColor: on ? '#fff' : 'var(--text-muted)',
}}
/>
) : (
<cat.Icon size={16} strokeWidth={2} />
)}
{on && !loading && errorKeys?.has(cat.key) && (
<span style={{
position: 'absolute', top: 2, right: 2, width: 8, height: 8,
borderRadius: 999, background: '#ef4444', border: '1.5px solid var(--sidebar-bg)',
}} />
)}
</button>
</Tooltip>
)
})}
{categories.core.map(segment)}
{categories.plugin.length > 0 && (
<hr
aria-orientation="vertical"
aria-label={t('poi.pluginCategories')}
style={{ flexShrink: 0, width: 1, height: 20, margin: '0 3px', border: 'none', background: 'var(--border-primary)' }}
/>
)}
{categories.plugin.map(segment)}
</div>
{(moved || anyError) && active.size > 0 && (
@@ -99,7 +164,7 @@ export default function PoiCategoryPill({ active, onToggle, loadingKeys, errorKe
style={{
display: 'inline-flex', alignItems: 'center', gap: 6,
padding: '6px 13px', borderRadius: 999, border: 'none', cursor: 'pointer',
fontSize: 12, fontWeight: 600, fontFamily: 'inherit', pointerEvents: 'auto',
fontSize: 'calc(12px * var(--fs-scale-caption, 1))', fontWeight: 600, fontFamily: 'inherit', pointerEvents: 'auto',
color: anyError ? '#ef4444' : undefined,
...frosted,
}}
@@ -0,0 +1,52 @@
import { TileLayer } from 'react-leaflet';
import { FerrataMapLayerLeaflet } from '../Ferratas/FerrataLayerLeaflet';
import type { FerrataMapLayer } from '../Ferratas/useFerrataMapLayer';
import { PaddleLayerLeaflet } from '../Tours/paddle/PaddleLayerLeaflet';
import type { PaddleMapLayer } from '../Tours/paddle/paddleMapLayer';
import type { MapRasterOverlay } from './mapRasterOverlay';
/** Over the basemap's tiles (z-index 1) and every basemap raster, under the route's own panes. */
const OVERLAY_Z_INDEX = 300;
/** The overlays on the Leaflet map: a tile layer each while it is on, nothing while it is off. */
function RasterOverlaysLeaflet({ overlays }: { overlays?: readonly MapRasterOverlay[] }) {
return (
<>
{overlays
?.filter((overlay) => overlay.active)
.map((overlay) => (
<TileLayer
key={overlay.id}
url={overlay.url}
attribution={overlay.attribution}
minZoom={overlay.minZoom}
maxNativeZoom={overlay.maxZoom}
maxZoom={22}
zIndex={OVERLAY_Z_INDEX}
// The page's origin as the referer, which the overlays' operators ask for (OpenSnowMap names it).
referrerPolicy="strict-origin-when-cross-origin"
eventHandlers={{ tileerror: overlay.onTileError, tileload: overlay.onTileLoad }}
/>
))}
</>
);
}
/** The tour planner's layers on the Leaflet map: the via ferratas, the raster overlays its type offers and the paddle obstacles. */
export function TourMapLayersLeaflet({
ferrataLayer,
overlays,
paddle,
}: {
ferrataLayer?: FerrataMapLayer;
overlays?: readonly MapRasterOverlay[];
paddle?: PaddleMapLayer;
}) {
return (
<>
<FerrataMapLayerLeaflet layer={ferrataLayer} />
<RasterOverlaysLeaflet overlays={overlays} />
<PaddleLayerLeaflet layer={paddle} />
</>
);
}
+10 -130
View File
@@ -2,35 +2,16 @@ import { Fragment, createElement, useMemo, useState } from 'react'
import { renderIconMarkup } from '../../utils/iconMarkup'
import { Marker, Polyline, Tooltip, useMap, useMapEvents } from 'react-leaflet'
import L from 'leaflet'
import { Plane, Train, Ship, Car, Bus, Sailboat, Bike, CarTaxiFront, Route, TramFront } from 'lucide-react'
import { escapeHtml } from '@trek/shared'
import { getTransitMapSegments, type TransitMapSegment } from './transitGeometry'
import { geodesicArcs } from './flightGeodesy'
import { cleanEndpointName } from './reservationName'
import { useSettingsStore } from '../../store/settingsStore'
import { hopIsVisible, labelFloorPx } from '../../utils/reservationRoutes'
import type { Reservation, ReservationEndpoint } from '../../types'
import { TRANSPORT_COLOR, TRANSPORT_META, transportHop, type TransportHop, type TransportType } from './transportHops'
import type { Reservation } from '../../types'
const ENDPOINT_PANE = 'reservation-endpoints'
type TransportType = 'flight' | 'train' | 'cruise' | 'car' | 'bus' | 'taxi' | 'bicycle' | 'ferry' | 'transit' | 'transport_other'
const TRANSPORT_TYPES: TransportType[] = ['flight', 'train', 'cruise', 'car', 'bus', 'taxi', 'bicycle', 'ferry', 'transit', 'transport_other']
const TRANSPORT_COLOR = '#3b82f6'
const TYPE_META: Record<TransportType, { color: string; icon: typeof Plane; geodesic: boolean }> = {
flight: { color: TRANSPORT_COLOR, icon: Plane, geodesic: true },
train: { color: TRANSPORT_COLOR, icon: Train, geodesic: false },
cruise: { color: TRANSPORT_COLOR, icon: Ship, geodesic: true },
car: { color: TRANSPORT_COLOR, icon: Car, geodesic: false },
bus: { color: TRANSPORT_COLOR, icon: Bus, geodesic: false },
taxi: { color: TRANSPORT_COLOR, icon: CarTaxiFront, geodesic: false },
bicycle: { color: TRANSPORT_COLOR, icon: Bike, geodesic: false },
ferry: { color: TRANSPORT_COLOR, icon: Sailboat, geodesic: true },
transit: { color: TRANSPORT_COLOR, icon: TramFront, geodesic: false },
transport_other: { color: TRANSPORT_COLOR, icon: Route, geodesic: false },
}
function useEndpointPane() {
const map = useMap()
useMemo(() => {
@@ -44,7 +25,7 @@ function useEndpointPane() {
}
function endpointIcon(type: TransportType, label: string | null): L.DivIcon {
const { icon: IconCmp, color } = TYPE_META[type]
const { icon: IconCmp } = TRANSPORT_META[type]
const svg = renderIconMarkup(createElement(IconCmp, { size: 13, color: 'white', strokeWidth: 2.5 }))
const labelHtml = label ? `<span style="display:inline-flex;align-items:center;line-height:1">${escapeHtml(label)}</span>` : ''
const estWidth = label ? Math.max(40, label.length * 6 + 28) : 26
@@ -53,7 +34,7 @@ function endpointIcon(type: TransportType, label: string | null): L.DivIcon {
html: `<div style="
display:inline-flex;align-items:center;justify-content:center;gap:4px;
padding:0 8px;border-radius:999px;
background:${color};box-shadow:0 2px 6px rgba(0,0,0,0.25);
background:${TRANSPORT_COLOR};box-shadow:0 2px 6px rgba(0,0,0,0.25);
border:1.5px solid #fff;color:#fff;
font-family:var(--font-system);font-size:11px;font-weight:600;letter-spacing:0.3px;line-height:1;
box-sizing:border-box;height:22px;white-space:nowrap;
@@ -64,84 +45,14 @@ function endpointIcon(type: TransportType, label: string | null): L.DivIcon {
})
}
function toRad(d: number) { return d * Math.PI / 180 }
function haversineKm(a: [number, number], b: [number, number]): number {
const R = 6371
const dLat = toRad(b[0] - a[0])
const dLng = toRad(b[1] - a[1])
const h = Math.sin(dLat / 2) ** 2 + Math.cos(toRad(a[0])) * Math.cos(toRad(b[0])) * Math.sin(dLng / 2) ** 2
return 2 * R * Math.asin(Math.sqrt(h))
}
function parseInTz(isoLocal: string, tz: string): number {
const [datePart, timePart] = isoLocal.split('T')
const [y, mo, d] = datePart.split('-').map(Number)
const [h, mi] = (timePart || '00:00').split(':').map(Number)
const guess = Date.UTC(y, mo - 1, d, h, mi)
// A malformed date/time (e.g. an imported booking whose time is missing its
// minutes) makes Date.UTC NaN; bail before formatToParts, which throws on a
// non-finite date and would blank the whole trip. computeDuration's finiteness
// check then drops the duration cleanly.
if (!Number.isFinite(guess)) return Number.NaN
const fmt = new Intl.DateTimeFormat('en-US', {
timeZone: tz, hour12: false,
year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit',
})
const parts = Object.fromEntries(fmt.formatToParts(new Date(guess)).filter(p => p.type !== 'literal').map(p => [p.type, p.value]))
const asUtc = Date.UTC(Number(parts.year), Number(parts.month) - 1, Number(parts.day), Number(parts.hour) % 24, Number(parts.minute), Number(parts.second))
return guess - (asUtc - guess)
}
function computeDuration(from: ReservationEndpoint, to: ReservationEndpoint, fallbackStart: string | null, fallbackEnd: string | null): string | null {
let start = from.local_date && from.local_time ? `${from.local_date}T${from.local_time}` : fallbackStart
let end = to.local_date && to.local_time ? `${to.local_date}T${to.local_time}` : fallbackEnd
if (!start || !end) return null
if (!start.includes('T') && end.includes('T')) start = `${end.split('T')[0]}T${start}`
if (!end.includes('T') && start.includes('T')) end = `${start.split('T')[0]}T${end}`
if (!start.includes('T') || !end.includes('T')) return null
const fromTz = from.timezone || to.timezone
const toTz = to.timezone || fromTz
let startMs: number, endMs: number
if (fromTz && toTz) {
startMs = parseInTz(start, fromTz)
endMs = parseInTz(end, toTz)
} else {
startMs = new Date(start).getTime()
endMs = new Date(end).getTime()
}
if (!Number.isFinite(startMs) || !Number.isFinite(endMs)) return null
if (endMs <= startMs) endMs += 24 * 60 * 60000
const minutes = Math.round((endMs - startMs) / 60000)
if (minutes <= 0 || minutes > 48 * 60) return null
const h = Math.floor(minutes / 60)
const m = minutes % 60
return h > 0 ? `${h}h ${m}m` : `${m}m`
}
/** What a hop will draw: the road it was routed along when there is one, else its arcs. */
function linesFor(item: TransportItem, roadRoutes: Map<number, [number, number][]> | undefined): [number, number][][] {
const road = roadRoutes?.get(item.res.id)
return road && road.length >= 2 ? [road] : item.arcs
}
interface TransportItem {
res: Reservation
from: ReservationEndpoint
to: ReservationEndpoint
waypoints: ReservationEndpoint[]
type: TransportType
arcs: [number, number][][]
interface TransportItem extends TransportHop {
transitSegs: TransitMapSegment[]
// Route ("VIE → LHR") and duration/distance line. Computed on every update but
// not drawn since the stats badge was dropped; computeDuration still guards the
// non-finite date that used to blank the trip (#1620).
mainLabel: string | null
subLabel: string | null
}
interface Props {
@@ -168,40 +79,9 @@ export default function ReservationOverlay({ reservations, showConnections, onEn
const items = useMemo<TransportItem[]>(() => {
const out: TransportItem[] = []
for (const r of reservations) {
if (!TRANSPORT_TYPES.includes(r.type as TransportType)) continue
// Ordered waypoints (from · stops · to). A single-leg booking has exactly two,
// so the arc + markers below are byte-identical to before for it.
const waypoints = (r.endpoints || [])
.filter(e => e.role === 'from' || e.role === 'to' || e.role === 'stop')
.slice()
.sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0))
if (waypoints.length < 2) continue
const from = waypoints[0]
const to = waypoints[waypoints.length - 1]
const type = r.type as TransportType
const isGeo = TYPE_META[type].geodesic
// One arc per leg (between consecutive waypoints), concatenated.
const arcs: [number, number][][] = []
let distanceKm = 0
for (let i = 0; i < waypoints.length - 1; i++) {
const a = waypoints[i]
const b = waypoints[i + 1]
const segArcs = isGeo
? geodesicArcs([a.lat, a.lng], [b.lat, b.lng], true)
: [[[a.lat, a.lng], [b.lat, b.lng]] as [number, number][]]
arcs.push(...segArcs)
distanceKm += haversineKm([a.lat, a.lng], [b.lat, b.lng])
}
const duration = computeDuration(from, to, r.reservation_time || null, r.reservation_end_time || null)
const distance = `${Math.round(distanceKm)} km`
// Show the full route (FRA → BER → HND) when every waypoint has a code.
const mainLabel = waypoints.every(w => w.code)
? waypoints.map(w => w.code).join(' → ')
: (from.code && to.code ? `${from.code} → ${to.code}` : null)
const subParts = [duration, distance].filter(Boolean) as string[]
const subLabel = subParts.length > 0 ? subParts.join(' · ') : null
out.push({ res: r, from, to, waypoints, type, arcs, transitSegs: type === 'transit' ? getTransitMapSegments(r) : [], mainLabel, subLabel })
const hop = transportHop(r, true)
if (!hop) continue
out.push({ ...hop, transitSegs: hop.type === 'transit' ? getTransitMapSegments(r) : [] })
}
return out
}, [reservations])
@@ -248,7 +128,7 @@ export default function ReservationOverlay({ reservations, showConnections, onEn
positions={seg.coords}
pathOptions={seg.walk
? { color: '#64748b', weight: 3, opacity: 0.8, dashArray: '1, 7', lineCap: 'round' }
: { color: seg.color || TYPE_META.transit.color, weight: 3.5, opacity: 0.95, lineCap: 'round', lineJoin: 'round' }}
: { color: seg.color || TRANSPORT_COLOR, weight: 3.5, opacity: 0.95, lineCap: 'round', lineJoin: 'round' }}
/>
</Fragment>
))
@@ -259,7 +139,7 @@ export default function ReservationOverlay({ reservations, showConnections, onEn
key={`line-${item.res.id}-${segIdx}`}
positions={seg}
pathOptions={{
color: TYPE_META[item.type].color,
color: TRANSPORT_COLOR,
weight: 2.5,
opacity: item.res.status === 'confirmed' ? 0.75 : 0.55,
dashArray: item.res.status === 'confirmed' ? undefined : '6, 6',
@@ -15,8 +15,7 @@ import {
calculateAlternatives,
avoidedClasses,
routeEngineFor,
sameRoad,
furthestFrom,
osrmLegSegment,
} from './RouteCalculator'
// Every route now goes to the FOSSGIS per-profile hosts. The car-only project-osrm.org
@@ -1203,37 +1202,6 @@ describe('a trip that avoids something', () => {
expect(plain.avoidance).toBeUndefined()
})
it('FE-COMP-ROUTECALCULATOR-064: a road that runs the whole of another and turns off to a point and back is not that road', () => {
// The shape of a leg bent by a via: every point of the plain road lies on it, so
// asked only one way round the two read as one.
const plainRoad = { coordinates: [[61, 10], [61, 11], [61, 12]] as [number, number][], distance: 100_000, duration: 3600 }
const spur = { coordinates: [[61, 10], [61, 11], [61.3, 11], [61, 11], [61, 12]] as [number, number][], distance: 166_000, duration: 5400 }
expect(sameRoad(plainRoad, spur)).toBe(false)
expect(sameRoad(spur, plainRoad)).toBe(false)
expect(sameRoad(plainRoad, { ...plainRoad, distance: 104_000, duration: 3900 })).toBe(true)
})
it('FE-COMP-ROUTECALCULATOR-065: one road drawn with a different spacing of points is still one road', () => {
// Two engines' lines of one long road share almost no vertex. Measured to the nearest
// sampled vertex, a point on the same road sat half a sample off it: kilometres here.
// The dense line is sampled every tenth vertex, 0.05 degrees apart; the sparse one sits
// exactly between those samples, 1.8 km from the nearest, on the very same road.
const dense = Array.from({ length: 2001 }, (_, i) => [50, i * 0.005] as [number, number])
const sparse: [number, number][] = [
[50, 0],
...Array.from({ length: 200 }, (_, i) => [50, 0.025 + i * 0.05] as [number, number]),
[50, 10],
]
const a = { coordinates: dense, distance: 700_000, duration: 25_000 }
const b = { coordinates: sparse, distance: 712_000, duration: 27_000 }
expect(sameRoad(a, b)).toBe(true)
const off = furthestFrom([[50.02, 5]], dense)
expect(off?.index).toBe(0)
expect(off?.km).toBeCloseTo(2.22, 1)
})
it('FE-COMP-ROUTECALCULATOR-066: the avoidance offer beside an OSRM leg says when it crosses by ferry', async () => {
server.use(
http.get(`${FOSSGIS.driving}/:coords`, () => HttpResponse.json({ code: 'Ok', routes: [{ geometry: { coordinates: [[10, 63], [11, 63], [12, 63]] }, distance: 100000, duration: 3600 }] })),
@@ -1246,3 +1214,28 @@ describe('a trip that avoids something', () => {
expect(routes[1]).toMatchObject({ avoids: 'motorway', engine: 'valhalla', hasFerry: true })
})
})
describe('osrmLegSegment', () => {
const waypoints = [{ lat: 48, lng: 2 }, { lat: 50, lng: 4 }, { lat: 52, lng: 6 }]
it('spans waypoint i to i + 1 with the label at the midpoint', () => {
const seg = osrmLegSegment({ distance: 1500, duration: 600 }, 1, waypoints)
expect(seg.from).toEqual([50, 4])
expect(seg.to).toEqual([52, 6])
expect(seg.mid).toEqual([51, 5])
expect(seg.distance).toBe(1500)
expect(seg.duration).toBe(600)
})
it('formats driving as measured and walking at 5 km/h', () => {
const seg = osrmLegSegment({ distance: 5000, duration: 600 }, 0, waypoints)
expect(seg.drivingText).toBe('10 min')
expect(seg.walkingText).toBe('1 h 0 min')
expect(seg.durationText).toBeUndefined()
})
it('writes short metric distances in metres', () => {
useSettingsStore.setState({ settings: { ...useSettingsStore.getState().settings, distance_unit: 'metric' } })
expect(osrmLegSegment({ distance: 420.4, duration: 60 }, 0, waypoints).distanceText).toBe('420 m')
})
})
+29 -149
View File
@@ -5,7 +5,7 @@ import { haversineKm } from '../../utils/geo'
import { formatDistance } from '../../utils/units'
import { countRoute } from './routeUsageCounter'
import { valhallaRouteAvoiding, valhallaRun, valhallaAvailable, valhallaAlternates, valhallaSpacing, legAvoids, type AvoidClass, type ValhallaLeg } from './valhallaRoute'
import type { RouteUsageSurface } from '@trek/shared'
import { furthestFrom, sameRoad, type RouteUsageSurface } from '@trek/shared'
// FOSSGIS hosts OSRM with real per-profile routing (car/foot/bike) — the
// project-osrm.org demo is car-only (it ignores the profile in the URL). Use
@@ -470,20 +470,29 @@ export async function calculateSegments(
if (data.code !== 'Ok' || !data.routes?.[0]) throw new Error('No route found')
const legs = data.routes[0].legs
return legs.map((leg: { distance: number; duration: number }, i: number): RouteSegment => {
const from: [number, number] = [waypoints[i].lat, waypoints[i].lng]
const to: [number, number] = [waypoints[i + 1].lat, waypoints[i + 1].lng]
const mid: [number, number] = [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2]
const walkingDuration = leg.distance / (5000 / 3600)
return {
mid, from, to,
distance: leg.distance,
duration: leg.duration,
walkingText: formatDuration(walkingDuration),
drivingText: formatDuration(leg.duration),
distanceText: formatRouteDistance(leg.distance),
}
})
return legs.map((leg: OsrmLeg, i: number): RouteSegment => osrmLegSegment(leg, i, waypoints))
}
interface OsrmLeg { distance: number; duration: number }
/**
* The connector data for OSRM leg i, which runs from waypoint i to waypoint i + 1:
* both ends, the midpoint the label sits on, and the walking time at 5 km/h next to
* the driving time OSRM measured.
*/
export function osrmLegSegment(leg: OsrmLeg, i: number, waypoints: Waypoint[]): RouteSegment {
const from: [number, number] = [waypoints[i].lat, waypoints[i].lng]
const to: [number, number] = [waypoints[i + 1].lat, waypoints[i + 1].lng]
const mid: [number, number] = [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2]
const walkingDuration = leg.distance / (5000 / 3600)
return {
mid, from, to,
distance: leg.distance,
duration: leg.duration,
walkingText: formatDuration(walkingDuration),
drivingText: formatDuration(leg.duration),
distanceText: formatRouteDistance(leg.distance),
}
}
/**
@@ -617,22 +626,12 @@ async function osrmWithLegs(
const coordinates: [number, number][] = route.geometry.coordinates.map(
([lng, lat]: [number, number]) => [lat, lng]
)
// The day plan's connectors also show the leg's own duration line.
const legs: RouteSegment[] = (route.legs || []).map(
(leg: { distance: number; duration: number }, i: number): RouteSegment => {
const from: [number, number] = [waypoints[i].lat, waypoints[i].lng]
const to: [number, number] = [waypoints[i + 1].lat, waypoints[i + 1].lng]
const mid: [number, number] = [(from[0] + to[0]) / 2, (from[1] + to[1]) / 2]
const walkingDuration = leg.distance / (5000 / 3600)
return {
mid, from, to,
distance: leg.distance,
duration: leg.duration,
walkingText: formatDuration(walkingDuration),
drivingText: formatDuration(leg.duration),
distanceText: formatRouteDistance(leg.distance),
durationText: formatDuration(leg.duration),
}
}
(leg: OsrmLeg, i: number): RouteSegment => ({
...osrmLegSegment(leg, i, waypoints),
durationText: formatDuration(leg.duration),
})
)
const snapped = readSnapped(data, waypoints)
@@ -804,41 +803,6 @@ export type RoadLine = Pick<RouteAlternative, 'coordinates' | 'distance' | 'dura
*/
const EXCLUDABLE_CLASSES = ['motorway', 'toll', 'ferry'] as const
/**
* How far two lines may stray from each other and still be the same road, in kilometres.
*
* Parallel carriageways, a different slip road onto the same motorway and the noise
* between two engines' idea of where a road is all sit well under this. A way somebody
* would call an alternative leaves it by kilometres: the ferry-free run from Hamburg to
* Copenhagen, which is a genuinely different road, peaks 2.3 km off the default.
*/
const SAME_ROAD_KM = 0.5
/**
* Two lines are the same road.
*
* Length and duration used to decide this, and stopped being enough when a second engine
* started answering. Valhalla prices roads differently: measured over twelve European
* legs its distances ran 1.8 % above OSRM's, so on a 470 km leg the same road comes back
* thirteen kilometres apart and a 200 m tolerance calls it a discovery. Two identical
* blue lines on the map is exactly what that looks like. Duration is the worse of the
* two to lean on: over the same twelve legs it ranged from 14.7 % under OSRM's to 13.2 %
* over, with the sign set by the region rather than by the road.
*
* The geometry does not care which engine drew it, so it decides whenever there is one.
* The numbers stay as the fallback for a line with no shape to compare.
*
* Measured both ways round. Asked only whether `b` stays near `a`, a road that runs the
* whole of `b` and then turns off to a point and back passed as `b`, because every point
* of `b` is on it; that is exactly the shape of a leg bent by a via, and the picker and
* the check behind a choice both have to tell it from the plain road.
*/
export function sameRoad(a: RoadLine, b: RoadLine): boolean {
const there = furthestFrom(b.coordinates, a.coordinates)
const back = furthestFrom(a.coordinates, b.coordinates)
if (there && back) return Math.max(there.km, back.km) < SAME_ROAD_KM
return Math.abs(a.distance - b.distance) < 200 && Math.abs(a.duration - b.duration) < 60
}
/**
* Hosts that have already answered "I do not do exclude", by base URL.
@@ -1104,87 +1068,3 @@ function furthestPointFrom(line: [number, number][], reference: [number, number]
const furthest = furthestFrom(line, reference)
return furthest ? { lat: furthest.lat, lng: furthest.lng } : null
}
/**
* The same point, plus how far off it actually is.
*
* The search itself stays in squared degrees with a cosine on the longitude: it only has
* to ORDER the candidates, and a haversine per pair of a 200-by-200 comparison buys
* nothing for it. The winner is converted once at the end, because `sameRoad` needs a
* real distance rather than a rank, and half a degree is a different number of metres in
* Andalusia than in Lapland.
*
* `index` is where on `line` the point sits, so points taken off one line can be put back
* in the order that line drives through them.
*/
export function furthestFrom(
line: [number, number][],
reference: [number, number][],
): { index: number; lat: number; lng: number; km: number } | null {
if (!line.length || !reference.length) return null
// Every tenth vertex is plenty: alternatives differ over kilometres, not metres, and a
// full cross product of two thousand-point lines is not worth the milliseconds.
const step = Math.max(1, Math.floor(reference.length / 200))
let bestIndex = -1
let bestNeighbour: [number, number] | null = null
let bestDist = -1
for (let i = 0; i < line.length; i += Math.max(1, Math.floor(line.length / 200))) {
const near = nearestOn(line[i], reference, step)
if (near.d > bestDist) { bestDist = near.d; bestIndex = i; bestNeighbour = near.at }
}
if (bestIndex < 0) return null
const [lat, lng] = line[bestIndex]
const km = bestNeighbour ? haversineKm({ lat, lng }, { lat: bestNeighbour[0], lng: bestNeighbour[1] }) : 0
return { index: bestIndex, lat, lng, km }
}
/**
* Where `reference` passes closest to `point`, as a squared distance in the same scaled
* degrees and the spot on the line it was measured to.
*
* Coarse, then fine. The sampled vertices find the stretch, and the segments either side
* of the nearest one find the road itself. Measured to the sampled vertex alone, a point
* on the very same road sat up to half a sample apart from it, which on a thousand
* kilometre leg is kilometres: two engines' lines of one motorway then read as two roads.
*/
function nearestOn(
point: [number, number],
reference: [number, number][],
step: number,
): { d: number; at: [number, number] } {
const cos = Math.cos((point[0] * Math.PI) / 180)
const squared = (p: [number, number]): number => {
const dLat = point[0] - p[0]
const dLng = (point[1] - p[1]) * cos
return dLat * dLat + dLng * dLng
}
let nearestIndex = 0
let nearest = Infinity
for (let j = 0; j < reference.length; j += step) {
const d = squared(reference[j])
if (d < nearest) { nearest = d; nearestIndex = j }
}
let at = reference[nearestIndex]
const last = Math.min(reference.length - 1, nearestIndex + step)
for (let k = Math.max(0, nearestIndex - step); k < last; k++) {
const on = closestOnSegment(point, reference[k], reference[k + 1], cos)
const d = squared(on)
if (d < nearest) { nearest = d; at = on }
}
return { d: nearest, at }
}
/** The point of segment a-b closest to `p`, with longitude scaled by `cos` so the plane is fair. */
function closestOnSegment(
p: [number, number],
a: [number, number],
b: [number, number],
cos: number,
): [number, number] {
const dx = (b[1] - a[1]) * cos
const dy = b[0] - a[0]
const length = dx * dx + dy * dy
if (length === 0) return a
const t = Math.max(0, Math.min(1, (((p[1] - a[1]) * cos) * dx + (p[0] - a[0]) * dy) / length))
return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]
}
@@ -0,0 +1,53 @@
import { fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { RouteHitBand } from './RouteHitBand';
// jsdom cannot reproduce Leaflet's event propagation, so the mock surfaces the
// option that governs it and hands the click on with a position.
vi.mock('react-leaflet', () => ({
Polyline: ({
eventHandlers,
bubblingMouseEvents,
}: {
eventHandlers?: { click?: (e: unknown) => void };
bubblingMouseEvents?: boolean;
}) => (
<div
data-testid="band"
data-bubbling={String(bubblingMouseEvents)}
onClick={() =>
eventHandlers?.click?.({ latlng: { lat: 46.58, lng: 11.75 }, originalEvent: new MouseEvent('click') })
}
/>
),
}));
describe('RouteHitBand', () => {
it('keeps its click from the map, which would add a point at the end of the tour', () => {
render(
<RouteHitBand
positions={[
[46.5, 11.7],
[46.6, 11.8],
]}
onRouteClick={vi.fn()}
/>
);
expect(screen.getByTestId('band')).toHaveAttribute('data-bubbling', 'false');
});
it('hands the clicked position to the route', () => {
const onRouteClick = vi.fn();
render(
<RouteHitBand
positions={[
[46.5, 11.7],
[46.6, 11.8],
]}
onRouteClick={onRouteClick}
/>
);
fireEvent.click(screen.getByTestId('band'));
expect(onRouteClick).toHaveBeenCalledWith(46.58, 11.75);
});
});
@@ -0,0 +1,39 @@
import { Polyline } from 'react-leaflet';
/**
* P2A-03: an invisible band along a route segment on the Leaflet map, wider
* than the drawn line, that takes the click which reshapes the route, as the
* GL renderer's hit layer does: an 8 px line is too thin to aim at.
*/
export function RouteHitBand({
positions,
onRouteClick,
}: {
positions: [number, number][];
onRouteClick: (lat: number, lng: number) => void;
}) {
return (
<Polyline
positions={positions}
// Leaflet hands a path's click to the map as well unless the path says not to;
// stopping the DOM event does not reach that, and the map's click would add a
// point at the end of the tour under the shaping point (as TrackLines does).
bubblingMouseEvents={false}
pathOptions={{
color: 'transparent',
weight: 20,
opacity: 0,
lineCap: 'round',
lineJoin: 'round',
className: 'cursor-copy',
}}
eventHandlers={{
click: (e: { latlng: { lat: number; lng: number }; originalEvent: MouseEvent }) => {
// Stops the map's own click, which would otherwise open the add-place menu underneath the new via.
e.originalEvent.stopPropagation();
onRouteClick(e.latlng.lat, e.latlng.lng);
},
}}
/>
);
}
+109
View File
@@ -0,0 +1,109 @@
import { memo, type RefObject } from 'react';
import { Polyline } from 'react-leaflet';
import type { Place } from '../../types';
import { TRACK_CASING_COLOR } from './trackColors';
/** A place's track as the Leaflet map draws it: its points, its colour, and whether it carries a rim. */
export interface TrackLine {
place: Place;
coords: [number, number][];
cased: boolean;
color: string;
}
interface TrackLinesProps {
tracks: readonly TrackLine[];
/** The pane the rims go into, below the lines; none while the map has not made it yet. */
casingPane?: string;
/** Read on click, so a new selection handler never redraws every track. */
selectRef: RefObject<(placeId: number) => void>;
}
/**
* Every track of the map: the rims, the lines and an invisible fat line on top
* that takes the click. Memoised on the tracks alone; a selection changes
* nothing here, the picked track is drawn by {@link SelectedTrackLine}.
*/
export const TrackLines = memo(function TrackLines({ tracks, casingPane, selectRef }: TrackLinesProps) {
return (
<>
{/* Casings live in their own pane below the lines. Leaflet stacks paths by
insertion order, so drawing them inline would put the casing of a track
added later — or of one just given a colour — on top of an earlier
track's line. Always rendered, hidden via opacity when there is no
colour, so toggling one never remounts the path. */}
{tracks.map(({ place, coords, cased }) => (
<Polyline
key={`gpx-${place.id}-casing`}
positions={coords}
pane={casingPane}
pathOptions={{
color: TRACK_CASING_COLOR,
weight: 6.5,
opacity: cased ? 0.7 : 0,
lineCap: 'round',
lineJoin: 'round',
}}
interactive={false}
/>
))}
{/* pathOptions, not bare color/weight props: react-leaflet only calls
setStyle when the pathOptions reference changes, so bare props would
stick at their mount-time colour and a repaint would never arrive. */}
{tracks.map(({ place, coords, cased, color }) => (
<Polyline
key={`gpx-${place.id}`}
positions={coords}
pathOptions={{ color, weight: 3.5, opacity: cased ? 0.9 : 0.75 }}
interactive={false}
/>
))}
{/* Invisible fat line on top so the track can actually be hit — 3.5px is
not a target, least of all on touch, and the start markers cluster below
zoom 11. bubblingMouseEvents is essential: paths bubble to the map by
default (markers do not), and the map's own click handler clears the
selection this one just made. */}
{tracks.map(({ place, coords }) => (
<Polyline
key={`gpx-${place.id}-hit`}
positions={coords}
pathOptions={{ color: TRACK_CASING_COLOR, weight: 14, opacity: 0, lineCap: 'round', lineJoin: 'round' }}
bubblingMouseEvents={false}
eventHandlers={{ click: () => selectRef.current?.(place.id) }}
/>
))}
</>
);
});
/**
* PR1-08: the track of the picked tour, wider and with a light rim on top of
* the others, so the line and the list's row read as one. It takes no click:
* the hit line below still does.
*/
export function SelectedTrackLine({
tracks,
selectedPlaceId,
}: {
tracks: readonly TrackLine[];
selectedPlaceId: number | null;
}) {
const track = selectedPlaceId == null ? null : tracks.find((item) => item.place.id === selectedPlaceId);
if (!track) return null;
return (
<>
<Polyline
key={`gpx-selected-${track.place.id}-casing`}
positions={track.coords}
pathOptions={{ color: TRACK_CASING_COLOR, weight: 9, opacity: 0.95, lineCap: 'round', lineJoin: 'round' }}
interactive={false}
/>
<Polyline
key={`gpx-selected-${track.place.id}`}
positions={track.coords}
pathOptions={{ color: track.color, weight: 5.5, opacity: 1, lineCap: 'round', lineJoin: 'round' }}
interactive={false}
/>
</>
);
}
+11 -38
View File
@@ -1,9 +1,8 @@
import { AlertTriangle, Route } from 'lucide-react'
import { useTranslation } from '../../i18n'
import { Tooltip } from '../shared/Tooltip'
import { profileIcon } from '../Planner/DayPlanSidebarRouteConnector'
import { MapTogglePill } from './MapTogglePill'
import { routeModeIcon } from '../Planner/routeModes'
import { formatDistance } from '../../utils/units'
import { MAP_CONTROL_SHADOW } from './mapControlShadow'
import type { TripRouteOverview as Overview } from './useTripRouteOverview'
import type { DistanceUnit } from '../../types'
@@ -13,40 +12,14 @@ import type { DistanceUnit } from '../../types'
*/
export function TripRouteOverviewPill({ active, onToggle }: { active: boolean; onToggle: () => void }) {
const { t } = useTranslation()
const label = active ? t('map.overview.hide') : t('map.overview.show')
return (
<div style={{
display: 'inline-flex', alignItems: 'center', padding: 4, borderRadius: 999, pointerEvents: 'auto',
background: 'var(--sidebar-bg)',
backdropFilter: 'blur(20px) saturate(180%)',
WebkitBackdropFilter: 'blur(20px) saturate(180%)',
boxShadow: MAP_CONTROL_SHADOW,
}}>
{/* TREK's own tooltip, not the browser's — the native one ignores the
colour scheme, waits a second and a half, and cannot be read on a touch
device at all. `left`, because these controls hug the right edge of the
map and a tooltip to the right would hang off it. */}
<Tooltip label={label} placement="left">
<button
type="button"
onClick={onToggle}
aria-label={label}
aria-pressed={active}
data-testid="trip-overview-pill"
className={active ? 'text-accent' : 'text-content-muted'}
style={{
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
width: 34, height: 34, borderRadius: 999, border: 'none', cursor: 'pointer',
background: 'transparent', padding: 0,
transition: 'background 0.14s, color 0.14s',
}}
onMouseEnter={e => { e.currentTarget.style.background = 'var(--bg-hover)' }}
onMouseLeave={e => { e.currentTarget.style.background = 'transparent' }}
>
<Route size={17} strokeWidth={2} />
</button>
</Tooltip>
</div>
<MapTogglePill
active={active}
onToggle={onToggle}
label={active ? t('map.overview.hide') : t('map.overview.show')}
testId="trip-overview-pill"
icon={<Route size={17} strokeWidth={2} />}
/>
)
}
@@ -123,7 +96,7 @@ export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelect
</span>
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 3, flexShrink: 0 }} className="text-content-muted">
{day.modes.map(mode => {
const Icon = profileIcon(mode)
const Icon = routeModeIcon(mode)
return <Icon key={mode} size={12} strokeWidth={2} aria-hidden />
})}
</span>
@@ -145,7 +118,7 @@ export function TripRouteOverviewPanel({ overview, unit, selectedDayId, onSelect
)
const style = {
display: 'flex', alignItems: 'center', gap: 8, width: '100%',
padding: '7px 14px', textAlign: 'left' as const,
padding: '7px 14px', textAlign: 'start' as const,
fontSize: 'calc(12px * var(--fs-scale-body, 1))',
background: day.dayId === selectedDayId ? 'var(--bg-hover)' : 'transparent',
border: 'none',
+4 -1
View File
@@ -7,7 +7,8 @@ import {
RASTER_FALLBACK_TILE_URL,
attributionForTile,
} from '../../constants/mapDefaults'
import { hasWebGL } from '../../utils/webgl'
import { hasWebGL, reportWebGLFailure } from '../../utils/webgl'
import { isGpuInitFailure } from './glSupport'
import { isChunkLoadError, reloadOnceForChunk } from '../../utils/chunkReload'
import { offlineStyle } from '../../native/offlineTiles'
@@ -97,6 +98,8 @@ function attachGlLayer(map: L.Map, layer: GlLeafletLayer, style: string): boolea
layer.addTo(map)
} catch (err) {
console.warn('[basemap] no WebGL context for the vector basemap, drawing raster tiles', err)
// The GPU, not a context budget: the GL maps elsewhere in the app switch to Leaflet too.
if (isGpuInitFailure(err)) reportWebGLFailure()
detachBasemapLayer(layer)
return false
}
@@ -0,0 +1,73 @@
// FE-MAP-ASSIST-CAMERA-001 to 004: what both renderers share when the assistant moves the map or marks a pin.
import { act, renderHook } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { centreOf, coverPadding, useAssistantMarkerClasses } from './assistantCamera';
import { carryAssistantMarks } from './useAssistantMapGL';
describe('assistantCamera', () => {
it('FE-MAP-ASSIST-CAMERA-001: the window widens the padding on its side only, never narrows it', () => {
const base = { top: 60, right: 340, bottom: 60, left: 40 };
expect(coverPadding(base, null)).toBe(base);
expect(coverPadding(base, { side: 'left', px: 400 })).toEqual({ ...base, left: 400 });
expect(coverPadding(base, { side: 'right', px: 100 })).toEqual(base);
});
it('FE-MAP-ASSIST-CAMERA-002: the centre is the middle of the box the points span', () => {
expect(
centreOf([
[40, 10],
[44, 12],
[42, 14],
])
).toEqual([42, 12]);
});
it('FE-MAP-ASSIST-CAMERA-003: a popped pin is marked for a moment, a pulsing one while it is hovered', async () => {
const pins = new Map([
[1, document.createElement('div')],
[2, document.createElement('div')],
]);
const markerEl = (id: number) => pins.get(id) ?? null;
const popped: readonly number[] = [1];
const { rerender } = renderHook(({ pulse }) => useAssistantMarkerClasses(markerEl, popped, pulse), {
initialProps: { pulse: 2 as number | null },
});
await act(() => new Promise((resolve) => requestAnimationFrame(resolve)));
expect(pins.get(1)?.classList.contains('trek-place-pop')).toBe(true);
expect(pins.get(2)?.classList.contains('trek-place-pulse')).toBe(true);
await act(() => new Promise((resolve) => setTimeout(resolve, 450)));
expect(pins.get(1)?.classList.contains('trek-place-pop')).toBe(false);
rerender({ pulse: null });
expect(pins.get(2)?.classList.contains('trek-place-pulse')).toBe(false);
});
it('FE-MAP-ASSIST-CAMERA-004: a pin the GL map rebuilds keeps its marks, and they end on the new pin', async () => {
const pins = new Map([
[1, document.createElement('div')],
[2, document.createElement('div')],
]);
const markerEl = (id: number) => pins.get(id) ?? null;
const popped: readonly number[] = [1];
const { rerender } = renderHook(({ pulse }) => useAssistantMarkerClasses(markerEl, popped, pulse), {
initialProps: { pulse: 2 as number | null },
});
await act(() => new Promise((resolve) => requestAnimationFrame(resolve)));
// A pan rebuilds both pins.
for (const id of [1, 2]) {
const rebuilt = document.createElement('div');
carryAssistantMarks(pins.get(id) as HTMLElement, rebuilt);
pins.set(id, rebuilt);
}
expect(pins.get(1)?.classList.contains('trek-place-pop')).toBe(true);
expect(pins.get(2)?.classList.contains('trek-place-pulse')).toBe(true);
expect(pins.get(2)?.classList.contains('trek-place-pop')).toBe(false);
await act(() => new Promise((resolve) => setTimeout(resolve, 450)));
expect(pins.get(1)?.classList.contains('trek-place-pop')).toBe(false);
rerender({ pulse: null });
expect(pins.get(2)?.classList.contains('trek-place-pulse')).toBe(false);
});
});
@@ -0,0 +1,126 @@
import { useEffect, useRef } from 'react';
import type { ViewportPadding } from '../../utils/mapViewport';
import { PLACE_POP_CLASS, PLACE_PULSE_CLASS } from './assistantGhostMarker';
import type { AssistantCamera } from './mapViewContract';
/**
* What both renderers share when the assistant moves their camera or marks a
* pin: the padding around what the assistant's window hides, the centre of
* a set of points, whether the user is busy moving the map, and the classes
* on the real pins. The renderer keeps only its own camera calls.
*/
/** How long a move the assistant asks for takes, when it animates. */
export const ASSISTANT_CAMERA_MS = 600;
/** After the user touched the map, moves they did not ask for wait this long. */
const USER_MOVE_QUIET_MS = 5000;
/** How long a pin that just arrived keeps its pop class; the animation itself is shorter. */
const POP_HOLD_MS = 400;
/** A request this young when the map mounts was meant for this map: the chat switched to it to show something. */
const FRESH_REQUEST_MS = 5000;
/** The renderer's padding, widened on the side the assistant's window covers. */
export function coverPadding(base: ViewportPadding, cover: AssistantCamera['cover']): ViewportPadding {
if (!cover) return base;
return { ...base, [cover.side]: Math.max(base[cover.side], cover.px) };
}
/** The middle of the points' box, [lat, lng]. */
export function centreOf(points: readonly [number, number][]): [number, number] {
const lats = points.map(([lat]) => lat);
const lngs = points.map(([, lng]) => lng);
return [(Math.min(...lats) + Math.max(...lats)) / 2, (Math.min(...lngs) + Math.max(...lngs)) / 2];
}
/**
* When the user last pressed, scrolled or touched the map. Read from the
* input itself rather than from the map's move events, which fire for the
* assistant's own moves just the same.
*/
export function useUserMoveClock(getContainer: () => HTMLElement | null, ready: boolean): { readonly current: number } {
const last = useRef(0);
useEffect(() => {
const container = ready ? getContainer() : null;
if (!container) return;
const mark = () => {
last.current = Date.now();
};
const events = ['pointerdown', 'wheel', 'touchstart'] as const;
events.forEach((type) => container.addEventListener(type, mark, { passive: true }));
return () => events.forEach((type) => container.removeEventListener(type, mark));
}, [getContainer, ready]);
return last;
}
/**
* The request the camera should carry out now, or null. The one present when
* the map mounts is skipped (it was meant for a map that is gone) unless it
* was asked for a moment ago (the chat switched to the map to show it), as is a
* repeated key, and a move the user did not ask for while they are moving
* the map themselves.
*/
export function useCameraRequest(
camera: AssistantCamera | null | undefined,
userMovedAt: { readonly current: number }
): (run: (camera: AssistantCamera) => void) => void {
// The request on screen when the map mounted, judged on the first run: young enough, it was meant for this map.
const mounted = useRef(camera ?? null);
const seen = useRef<string | null>(null);
return (run) => {
const first = mounted.current;
if (first) {
mounted.current = null;
if (!(first.at && Date.now() - first.at < FRESH_REQUEST_MS)) seen.current = first.key;
}
if (!camera || camera.key === seen.current) return;
seen.current = camera.key;
if (camera.auto && Date.now() - userMovedAt.current < USER_MOVE_QUIET_MS) return;
if (camera.points.length > 0) run(camera);
};
}
/**
* Puts the pop class on the pins of places that just arrived and the pulse
* class on the pin the hovered suggestion is about. A frame late on purpose:
* the GL map rebuilds its pins in the next frame after the places change.
* A mark ends on the pin the place has then, which on the GL map may be a
* newer element than the one marked (`carryAssistantMarks` in useAssistantMapGL).
*/
export function useAssistantMarkerClasses(
markerEl: (placeId: number) => HTMLElement | null,
poppedPlaceIds: readonly number[] | undefined,
pulsePlaceId: number | null | undefined
): void {
useEffect(() => {
if (!poppedPlaceIds?.length) return;
let marked: HTMLElement[] = [];
const unmark = () =>
[...marked, ...poppedPlaceIds.flatMap((id) => markerEl(id) ?? [])].forEach((el) =>
el.classList.remove(PLACE_POP_CLASS)
);
const frame = requestAnimationFrame(() => {
marked = poppedPlaceIds.flatMap((id) => markerEl(id) ?? []);
marked.forEach((el) => el.classList.add(PLACE_POP_CLASS));
});
const timer = window.setTimeout(unmark, POP_HOLD_MS);
return () => {
cancelAnimationFrame(frame);
window.clearTimeout(timer);
unmark();
};
}, [markerEl, poppedPlaceIds]);
useEffect(() => {
if (pulsePlaceId == null) return;
let marked: HTMLElement | null = null;
const frame = requestAnimationFrame(() => {
marked = markerEl(pulsePlaceId);
marked?.classList.add(PLACE_PULSE_CLASS);
});
return () => {
cancelAnimationFrame(frame);
marked?.classList.remove(PLACE_PULSE_CLASS);
markerEl(pulsePlaceId)?.classList.remove(PLACE_PULSE_CLASS);
};
}, [markerEl, pulsePlaceId]);
}
@@ -0,0 +1,119 @@
/*
* The assistant on the map: a suggested place drawn before it exists (a ghost),
* the pulse when its row or pin is under the pointer, and the pop of a place
* that just arrived. Both renderers position the outer element themselves (a
* transform), so every animation runs on its first child and never fights
* the position.
*/
@keyframes trek-ghost-enter {
from {
opacity: 0;
transform: scale(0.8);
}
to {
opacity: 1;
transform: scale(1);
}
}
@keyframes trek-ghost-pulse {
0% {
box-shadow: 0 0 0 0 color-mix(in srgb, var(--accent) 45%, transparent);
}
100% {
box-shadow: 0 0 0 12px color-mix(in srgb, var(--accent) 0%, transparent);
}
}
@keyframes trek-place-pop {
0% {
transform: scale(0.6);
}
65% {
transform: scale(1.08);
}
100% {
transform: scale(1);
}
}
.trek-ghost-pin {
background: none;
border: none;
}
.trek-ghost {
width: 30px;
height: 30px;
cursor: pointer;
}
.trek-ghost-face {
display: flex;
box-sizing: border-box;
width: 100%;
height: 100%;
align-items: center;
justify-content: center;
border: 2px dashed var(--accent);
border-radius: 9999px;
background: color-mix(in srgb, var(--bg-card) 60%, transparent);
color: var(--ghost-color, var(--text-secondary));
box-shadow: var(--shadow-sm);
animation: trek-ghost-enter 180ms var(--ease-out-quint) both;
}
/* A spot a card marks (a via of a drive): a small dashed dot in the middle of the ghost's box, no icon. */
.trek-ghost--point {
display: flex;
align-items: center;
justify-content: center;
}
.trek-ghost--point .trek-ghost-face {
width: 12px;
height: 12px;
border-width: 2px;
}
.trek-ghost.is-hot .trek-ghost-face {
border-style: solid;
animation:
trek-ghost-enter 180ms var(--ease-out-quint) both,
trek-ghost-pulse 900ms var(--ease-out-quint) 2;
}
.trek-place-pulse > :first-child {
animation: trek-ghost-pulse 900ms var(--ease-out-quint) 2;
}
.trek-place-pop > :first-child {
animation: trek-place-pop 220ms var(--ease-out-quint);
}
@media (prefers-reduced-motion: reduce) {
.trek-ghost-face {
animation: trek-ghost-enter 120ms ease-out both;
}
.trek-ghost.is-hot .trek-ghost-face,
.trek-place-pulse > :first-child {
animation: none;
box-shadow: 0 0 0 3px var(--accent);
}
.trek-place-pop > :first-child {
animation: trek-backdrop-enter 120ms ease-out;
}
}
[data-reduce-motion] .trek-ghost-face {
animation: trek-ghost-enter 120ms ease-out both;
}
[data-reduce-motion] .trek-ghost.is-hot .trek-ghost-face,
[data-reduce-motion] .trek-place-pulse > :first-child {
animation: none;
box-shadow: 0 0 0 3px var(--accent);
}
[data-reduce-motion] .trek-place-pop > :first-child {
animation: trek-backdrop-enter 120ms ease-out;
}
@@ -0,0 +1,81 @@
// FE-MAP-GHOST-001 to 004: the assistant's suggested places as map pins, built once for both renderers.
import { describe, expect, it, vi } from 'vitest';
import { GHOST_HOT_CLASS, buildGhostElement, mountGhosts, setGhostHot } from './assistantGhostMarker';
const GHOST = { id: 'c1', lat: 41.9, lng: 12.48, name: 'Pantheon', color: '#ff0000', icon: 'Landmark' };
describe('assistantGhostMarker', () => {
it('FE-MAP-GHOST-001: a name never becomes markup, and the colour goes in as a CSS variable', () => {
const el = buildGhostElement({ ...GHOST, name: '<img src=x onerror=alert(1)>' });
expect(el.querySelector('img')).toBeNull();
expect(el.getAttribute('aria-label')).toBe('<img src=x onerror=alert(1)>');
expect(el.style.getPropertyValue('--ghost-color')).toBe('#ff0000');
expect(el.querySelector('.trek-ghost-face svg')).not.toBeNull();
});
it('FE-MAP-GHOST-002: the pointer reports the hover, a click or Enter reports the ghost without reaching the map', () => {
const onHover = vi.fn();
const onClick = vi.fn();
const removed = vi.fn();
const map = document.createElement('div');
const mapClick = vi.fn();
map.addEventListener('click', mapClick);
const mounted = mountGhosts(
[GHOST],
(el) => {
map.appendChild(el);
return { remove: removed };
},
{ current: { onHover, onClick } }
);
const el = mounted.elements.get('c1');
el?.dispatchEvent(new Event('pointerenter'));
el?.dispatchEvent(new Event('pointerleave'));
el?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
el?.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
expect(onHover.mock.calls).toEqual([['c1'], [null]]);
expect(onClick).toHaveBeenCalledTimes(2);
expect(mapClick).not.toHaveBeenCalled();
mounted.dispose();
expect(removed).toHaveBeenCalledOnce();
expect(mounted.elements.size).toBe(0);
});
it('FE-MAP-GHOST-003: only the hovered ghost is marked', () => {
const a = document.createElement('div');
const b = document.createElement('div');
const elements = new Map([
['a', a],
['b', b],
]);
setGhostHot(elements, 'b');
expect([a.classList.contains(GHOST_HOT_CLASS), b.classList.contains(GHOST_HOT_CLASS)]).toEqual([false, true]);
setGhostHot(elements, null);
expect(b.classList.contains(GHOST_HOT_CLASS)).toBe(false);
});
it('FE-MAP-GHOST-004: a spot a card marks is a dot without an icon, and every ghost of one change lights by its call', () => {
const point = buildGhostElement({ id: 'c1:via:0', ref: 'c1', lat: 41.9, lng: 12.5, name: 'Via', variant: 'point' });
expect(point.classList.contains('trek-ghost--point')).toBe(true);
expect(point.querySelector('.trek-ghost-face svg')).toBeNull();
const onHover = vi.fn();
const onClick = vi.fn();
const ghosts = [
{ id: 'c1:stop:0', ref: 'c1', lat: 41.9, lng: 12.5, name: 'Stop', variant: 'pin' as const },
{ id: 'c1:via:0', ref: 'c1', lat: 41.91, lng: 12.5, name: 'Via', variant: 'point' as const },
{ id: 'c2', lat: 41.92, lng: 12.5, name: 'Other' },
];
const mounted = mountGhosts(ghosts, () => ({ remove: vi.fn() }), { current: { onHover, onClick } });
mounted.elements.get('c1:via:0')?.dispatchEvent(new Event('pointerenter'));
mounted.elements.get('c1:stop:0')?.dispatchEvent(new MouseEvent('click'));
expect(onHover).toHaveBeenCalledWith('c1');
expect(onClick).toHaveBeenCalledWith('c1');
setGhostHot(mounted.elements, 'c1');
const hot = [...mounted.elements.values()].map((el) => el.classList.contains(GHOST_HOT_CLASS));
expect(hot).toEqual([true, true, false]);
mounted.dispose();
});
});
@@ -0,0 +1,123 @@
import './assistantGhost.css';
import { categoryIconSvg } from './categoryIconSvg';
import type { AssistantGhost } from './mapViewContract';
/**
* The assistant's suggested places on the map, built once for both renderers.
*
* A ghost is a plain element: the Leaflet map hands it to a divIcon, the GL
* map positions it like its other hand-placed pins. Nothing from the ghost's
* data goes in as markup. The name is an attribute and the renderer's own
* label shows it as text, the category colour is a CSS variable set through
* the style API, and the icon is looked up in the app's fixed icon table.
*/
/** The ghost's box in CSS pixels, for the anchor of a Leaflet divIcon. */
export const GHOST_SIZE = 30;
/** On a ghost whose suggestion is under the pointer, here or in the chat. */
export const GHOST_HOT_CLASS = 'is-hot';
/** On a real pin that just arrived from an applied suggestion. */
export const PLACE_POP_CLASS = 'trek-place-pop';
/** On a real pin the hovered suggestion is about. */
export const PLACE_PULSE_CLASS = 'trek-place-pulse';
const iconMarkup = new Map<string, string>();
/** The category's icon in the ghost's colour, rendered once per icon name. */
function ghostIcon(name: string | undefined): string {
const key = name ?? '';
let markup = iconMarkup.get(key);
if (markup === undefined) {
markup = categoryIconSvg(name, 14, 'currentColor');
iconMarkup.set(key, markup);
}
return markup;
}
/**
* A ghost's element: a dashed pin with its category's icon, or for a spot a
* card marks (`point`) a small dashed dot without one.
*/
export function buildGhostElement(ghost: AssistantGhost): HTMLDivElement {
const el = document.createElement('div');
el.className = ghost.variant === 'point' ? 'trek-ghost trek-ghost--point' : 'trek-ghost';
el.dataset.ghostId = ghost.id;
el.dataset.ghostRef = ghost.ref ?? ghost.id;
el.setAttribute('role', 'button');
el.setAttribute('aria-label', ghost.name);
if (ghost.color) el.style.setProperty('--ghost-color', ghost.color);
const face = document.createElement('div');
face.className = 'trek-ghost-face';
// A fixed glyph from the icon table, never anything the ghost carries.
if (ghost.variant !== 'point') face.innerHTML = ghostIcon(ghost.icon);
el.appendChild(face);
return el;
}
export interface GhostHandlers {
onHover?: (id: string | null) => void;
onClick?: (id: string) => void;
}
/** What a renderer gives back for a ghost it put on its map. */
interface GhostPin {
remove: () => void;
}
interface MountedGhosts {
elements: Map<string, HTMLElement>;
dispose: () => void;
}
/**
* Puts every ghost on the map through `place` and wires the pointer: entering
* and leaving report the hover, a click (or Enter) reports the ghost without
* reaching the map underneath. The handlers are read through a ref, so a
* parent passing fresh callbacks does not rebuild the pins.
*/
export function mountGhosts(
ghosts: readonly AssistantGhost[],
place: (el: HTMLElement, ghost: AssistantGhost) => GhostPin,
handlers: { readonly current: GhostHandlers }
): MountedGhosts {
const elements = new Map<string, HTMLElement>();
const cleanups: (() => void)[] = [];
for (const ghost of ghosts) {
const el = buildGhostElement(ghost);
const ref = ghost.ref ?? ghost.id;
const enter = () => handlers.current.onHover?.(ref);
const leave = () => handlers.current.onHover?.(null);
const click = (event: Event) => {
event.stopPropagation();
handlers.current.onClick?.(ref);
};
const key = (event: KeyboardEvent) => {
if (event.key === 'Enter') click(event);
};
el.addEventListener('pointerenter', enter);
el.addEventListener('pointerleave', leave);
el.addEventListener('click', click);
el.addEventListener('keydown', key);
const pin = place(el, ghost);
elements.set(ghost.id, el);
cleanups.push(() => {
el.removeEventListener('pointerenter', enter);
el.removeEventListener('pointerleave', leave);
el.removeEventListener('click', click);
el.removeEventListener('keydown', key);
pin.remove();
});
}
return {
elements,
dispose: () => {
cleanups.forEach((cleanup) => cleanup());
elements.clear();
},
};
}
/** Marks the hovered ghosts (every one of a change lit by its call), and only them, without rebuilding any pin. */
export function setGhostHot(elements: ReadonlyMap<string, HTMLElement>, hoveredId: string | null | undefined): void {
elements.forEach((el, id) => el.classList.toggle(GHOST_HOT_CLASS, (el.dataset.ghostRef ?? id) === hoveredId));
}
@@ -0,0 +1,99 @@
import type { AssistantMapView } from '@trek/shared';
import { useEffect } from 'react';
import { useMap } from 'react-leaflet';
import { useAssistantStore } from '../../store/assistantStore';
import { useTripStore } from '../../store/tripStore';
/**
* The part of the planner's map on screen, told to the assistant after every
* move, so a question about "here" needs no place named. Both renderers report
* through this module; the assistant sends it with the next question only for
* the trip it was taken on.
*/
interface Edges {
south: number;
west: number;
north: number;
east: number;
}
const clamp = (value: number, limit: number) => Math.max(-limit, Math.min(limit, value));
const round = (value: number) => Math.round(value * 1e4) / 1e4;
/** The edges as the contract takes them: inside the globe (a wrapped map runs past ±180) and to about ten metres. */
export function mapViewOf(edges: Edges): AssistantMapView {
return {
south: round(clamp(edges.south, 90)),
west: round(clamp(edges.west, 180)),
north: round(clamp(edges.north, 90)),
east: round(clamp(edges.east, 180)),
};
}
function report(tripId: number | null, edges: Edges | null): void {
const set = useAssistantStore.getState().setMapView;
// A map without a size yet (hidden, or still laying out) has no edges to speak of.
const usable = edges && Object.values(edges).every(Number.isFinite) && edges.north > edges.south;
set(tripId !== null && usable ? { tripId, view: mapViewOf(edges) } : null);
}
/** The trip whose view is reported: only while the assistant can run, so a map without it listens to nothing. */
function useReportedTrip(): number | null {
const available = useAssistantStore((s) => s.status?.available === true);
const tripId = useTripStore((s) => s.trip?.id ?? null);
return available ? tripId : null;
}
/** Leaflet: read from inside the map container, after each move and once on mount. */
export function useReportViewLeaflet(): void {
const map = useMap();
const tripId = useReportedTrip();
useEffect(() => {
if (tripId === null) return;
const read = () => {
const b = map.getBounds();
report(tripId, { south: b.getSouth(), west: b.getWest(), north: b.getNorth(), east: b.getEast() });
};
read();
map.on('moveend', read);
return () => {
map.off('moveend', read);
report(null, null);
};
}, [map, tripId]);
}
/** What the GL map offers for it; mapbox-gl and maplibre-gl alike. */
interface ViewMap {
getBounds: () => {
getSouth: () => number;
getWest: () => number;
getNorth: () => number;
getEast: () => number;
} | null;
on: (type: 'moveend', listener: () => void) => unknown;
off: (type: 'moveend', listener: () => void) => unknown;
}
/** GL: the same, once the map is ready. */
export function useReportViewGL(mapRef: { readonly current: unknown }, mapReady: boolean): void {
const tripId = useReportedTrip();
useEffect(() => {
const map = mapRef.current as Partial<ViewMap> | null;
if (tripId === null || !mapReady || !map?.on || !map.off || !map.getBounds) return;
const { on, off, getBounds } = { on: map.on.bind(map), off: map.off.bind(map), getBounds: map.getBounds.bind(map) };
const read = () => {
const b = getBounds();
if (typeof b?.getSouth !== 'function') return;
report(tripId, { south: b.getSouth(), west: b.getWest(), north: b.getNorth(), east: b.getEast() });
};
read();
on('moveend', read);
return () => {
off('moveend', read);
report(null, null);
};
}, [mapRef, mapReady, tripId]);
}
@@ -0,0 +1,20 @@
import { createElement } from 'react';
import { renderIconMarkup } from '../../utils/iconMarkup';
import { CATEGORY_ICON_MAP } from '../shared/categoryIcons';
/**
* A category's icon as markup for a hand-built map pin, the same on the
* Leaflet and the GL map. The name only picks from the app's own icon table
* (an unknown one falls back to the pin), so nothing it carries reaches the
* markup. Every icon in that table is rendered by iconMarkup.parity.test.ts,
* so a failure here is a bug to surface, not a case to hide.
*/
export function categoryIconSvg(
iconName: string | null | undefined,
size: number,
color = 'white',
strokeWidth = 2.5
): string {
const IconComponent = (iconName && CATEGORY_ICON_MAP[iconName]) || CATEGORY_ICON_MAP['MapPin'];
return renderIconMarkup(createElement(IconComponent, { size, color, strokeWidth }));
}
@@ -0,0 +1,38 @@
import { describe, expect, it } from 'vitest';
import { centredMapCard } from './centredMapCard';
// Resolves the CSS the helper returns for a given container width, so the
// geometry is checked in pixels rather than as strings.
function resolve(css: string, extent: number): number {
const expr = css
.replace(/100%/g, `${extent}px`)
.replace(/px/g, '')
.replace(/calc/g, '')
.replace(/min\(/g, 'Math.min(')
.replace(/max\(/g, 'Math.max(');
return Function(`return (${expr})`)() as number;
}
describe('centredMapCard', () => {
it('keeps the old centred box when there is no pill to clear', () => {
const box = centredMapCard(320, 320);
expect(resolve(box.width, 1280)).toBe(608);
expect(resolve(box.centre, 1280)).toBe(640);
});
it('a narrow desktop map moves the card off the base-layer pill (#2604)', () => {
const box = centredMapCard(350, 310, { clearPill: true });
const width = resolve(box.width, 1280);
const leftEdge = resolve(box.centre, 1280) - width / 2;
// The pill spans 20 to 62 px right of the left panel.
expect(leftEdge).toBeGreaterThanOrEqual(350 + 62);
// And the card still stops 16 px short of the right panel.
expect(leftEdge + width).toBeLessThanOrEqual(1280 - 310 - 16);
});
it('a wide map keeps the card exactly centred and 800 wide', () => {
const box = centredMapCard(320, 320, { clearPill: true });
expect(resolve(box.width, 1920)).toBe(800);
expect(resolve(box.centre, 1920)).toBe(960);
});
});
@@ -0,0 +1,38 @@
import { MAP_LAYER_SWITCHER_INSET, MAP_ROUND_CONTROL_SIZE } from './MapLayerSwitcher';
/** The card's gap to the side panels where nothing else sits at the map's edge. */
const EDGE_GAP = 16;
/** How far the card keeps from the left panel, so it ends short of the base-layer pill. */
const PILL_CLEARANCE = MAP_LAYER_SWITCHER_INSET + MAP_ROUND_CONTROL_SIZE + 8;
/**
* Where a card opened over the map sits (the place inspector, a tour's detail,
* the day panel): centred between the two side panels, at most 800 wide.
*
* On the desktop map the base-layer pill stays put in the bottom-left corner. On
* a map wide enough the centred card never reaches that corner, but on a narrower
* one (both sidebars open in a 1280 window) it ran under the pill, which then
* covered the first button of the card's footer (#2604). With `clearPill` the
* card's left edge never comes closer than the pill: a narrow card moves right of
* it and gives up the few pixels it needs, a wide map keeps it exactly centred.
* The phone shows these cards as sheets with no pill beside them, so it leaves
* `clearPill` off.
*
* `extent` is what the card is placed in: '100%' of the map, or '100vw' for the
* fixed day panel.
*
* `centre` is where the card's middle sits, measured from the map's left edge like
* the panel widths. Each card sets it as its own `left` next to translateX(-50%),
* so lint:rtl counts that physical side where the card is placed.
*/
export function centredMapCard(
leftWidth: number,
rightWidth: number,
{ extent = '100%', clearPill = false }: { extent?: string; clearPill?: boolean } = {}
): { centre: string; width: string } {
const free = `(${extent} - ${leftWidth}px - ${rightWidth}px)`;
const centre = `calc(${leftWidth}px + ${free} / 2)`;
if (!clearPill) return { centre, width: `min(800px, calc(${free} - ${2 * EDGE_GAP}px))` };
const width = `min(800px, calc(${free} - ${PILL_CLEARANCE + EDGE_GAP}px))`;
return { width, centre: `max(${centre}, calc(${leftWidth}px + ${PILL_CLEARANCE}px + ${width} / 2))` };
}
@@ -0,0 +1,99 @@
import type { RoadtripVia } from '@trek/shared';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { buildAssignment, buildPlace } from '../../../tests/helpers/factories';
import type { AssignmentsMap, RouteSegment } from '../../types';
import { dayViaLookup } from '../../utils/dayRouteVias';
import { routeLeg } from './dayRouteLeg';
vi.mock('./RouteCalculator', async (importActual) => {
const actual = await importActual<typeof import('./RouteCalculator')>();
return { ...actual, calculateRouteWithLegs: vi.fn() };
});
const { calculateRouteWithLegs } = await import('./RouteCalculator');
const leg = (distance: number): RouteSegment => ({
mid: [0, 0],
from: [distance, 0],
to: [distance + 1, 0],
distance,
duration: distance / 10,
distanceText: '',
durationText: '',
walkingText: '',
drivingText: '',
});
const via = (dayId: number, afterOrderIndex: number, lat: number, sequence = 0): RoadtripVia =>
({
id: lat,
day_id: dayId,
after_order_index: afterOrderIndex,
sequence,
lat,
lng: 0,
created_at: '',
}) as RoadtripVia;
const stop = (id: number, order: number, extra: Record<string, unknown> = {}) =>
buildAssignment({ id, day_id: 1, order_index: order, place: buildPlace({ lat: 48 + order, lng: 2 }), ...extra });
// Stored order: hotel row, Paris, a place without coordinates, Lille, Brussels.
const STORED: AssignmentsMap = {
'1': [
stop(14, 3),
stop(11, 1),
stop(10, 0, { accommodation_id: 5 }),
buildAssignment({
id: 12,
day_id: 1,
order_index: 2,
place: buildPlace({ lat: null as unknown as number, lng: null as unknown as number }),
}),
stop(13, 2.5),
],
};
beforeEach(() => {
vi.mocked(calculateRouteWithLegs).mockReset();
});
describe('dayRouteLeg (#2580)', () => {
it('FE-MAP-DRV-009: one leg is routed through its vias and read back as one leg in its mode', async () => {
vi.mocked(calculateRouteWithLegs).mockResolvedValue({
coordinates: [],
distance: 0,
duration: 0,
legs: [leg(1000), leg(2000)],
});
const lookup = dayViaLookup(STORED, { 1: [via(1, 1, 49.3)] });
const options = { profile: 'driving', tripId: 7, dayId: 1 };
const seg = await routeLeg(
{ lat: 49, lng: 2, assignmentId: 11 },
{ lat: 50.5, lng: 2, assignmentId: 13 },
lookup,
options,
'metric'
);
expect(vi.mocked(calculateRouteWithLegs).mock.calls[0][0]).toEqual([
{ lat: 49, lng: 2 },
{ lat: 49.3, lng: 0 },
{ lat: 50.5, lng: 2 },
]);
expect(seg?.distance).toBe(3000);
expect(seg?.mode).toBe('driving');
});
it('FE-MAP-DRV-010: a leg the router cannot answer is undefined', async () => {
vi.mocked(calculateRouteWithLegs).mockRejectedValueOnce(new Error('down'));
expect(
await routeLeg({ lat: 1, lng: 1 }, { lat: 2, lng: 2 }, null, { profile: 'driving', dayId: 1 }, 'metric')
).toBeUndefined();
vi.mocked(calculateRouteWithLegs).mockResolvedValueOnce({ coordinates: [], distance: 0, duration: 0, legs: [] });
expect(
await routeLeg({ lat: 1, lng: 1 }, { lat: 2, lng: 2 }, null, { profile: 'driving', dayId: 1 }, 'metric')
).toBeUndefined();
});
});
+29
View File
@@ -0,0 +1,29 @@
import type { DistanceUnit, RouteSegment } from '../../types';
import { foldViaLegs, viasOnDayLeg, type DayViaLookup } from '../../utils/dayRouteVias';
import { calculateRouteWithLegs } from './RouteCalculator';
/** One end of a leg: a planned stop carries its assignment, which the vias are filed against. */
export type LegEnd = { lat: number; lng: number; assignmentId?: number };
/**
* The drive between two points of a day as one leg, bent through the road trip's vias
* between them and tagged with the mode it was routed in. Undefined when the router has
* no road for it.
*/
export async function routeLeg(
from: LegEnd,
to: LegEnd,
lookup: DayViaLookup | null,
options: Parameters<typeof calculateRouteWithLegs>[1] & { profile: string; dayId: number },
unit: DistanceUnit | undefined
): Promise<RouteSegment | undefined> {
const vias = viasOnDayLeg(lookup, options.dayId, options.profile, from, to);
try {
const waypoints = [from, ...vias, to].map((p) => ({ lat: p.lat, lng: p.lng }));
const r = await calculateRouteWithLegs(waypoints, options);
const leg = foldViaLegs(r.legs, [0, vias.length + 1], unit)[0];
return leg ? { ...leg, mode: options.profile } : undefined;
} catch {
return undefined;
}
}
+355 -2
View File
@@ -1,6 +1,9 @@
import { describe, it, expect } from 'vitest'
import { buildDayRouteRuns } from './dayRoutePlan'
import { buildAssignment, buildDay, buildPlace } from '../../../tests/helpers/factories'
import { buildDayRouteRuns, hotelBookendOf } from './dayRoutePlan'
import { projectDayItinerary, tourStageStopsByPlace } from './dayTourProjection'
import { resolveLegMode } from '../Planner/legMode'
import { planTripRoute, assembleTripRoute, emptyAnswers, summariseTripRoute } from './tripRouteGeometry'
import { buildAssignment, buildDay, buildPlace, buildReservation } from '../../../tests/helpers/factories'
import type { Accommodation, AssignmentsMap, Day, Reservation } from '../../types'
const at = (lat: number, lng: number, order: number, extra: Record<string, unknown> = {}) =>
@@ -142,6 +145,30 @@ describe('buildDayRouteRuns', () => {
expect(runs[0].map(p => p.lat)).toEqual([53.5503, 53.5465])
})
it('FE-MAP-DRP-015: the hotel points say which end of the day they are, a stop on the same spot does not (#2501)', () => {
const hotel = { id: 1, trip_id: 1, place_lat: 48.80, place_lng: 2.30, start_day_id: 1, end_day_id: 3 } as unknown as Accommodation
const runs = buildDayRouteRuns(2, inputs({
days: [buildDay({ id: 1, day_number: 1 }), buildDay({ id: 2, day_number: 2 }), buildDay({ id: 3, day_number: 3 })],
assignments: { '2': [at(48.86, 2.35, 0), at(48.80, 2.30, 1), at(48.88, 2.36, 2)] },
accommodations: [hotel],
optimizeFromAccommodation: true,
}))
const legs = runs.flatMap(run => run.slice(1).map((p, i) => hotelBookendOf(run[i], p) ?? null))
// Out of the hotel, three stops (one of them on the hotel's own spot), back to it.
expect(legs).toEqual(['morning', null, null, 'evening'])
})
it('FE-MAP-DRP-016: the one drive of a moving day without stops is its morning leg (#2476)', () => {
const days = [1, 2, 3].map(n => buildDay({ id: n, day_number: n }))
const stays = [
{ id: 1, trip_id: 1, place_lat: 48.137, place_lng: 11.575, start_day_id: 1, end_day_id: 2 },
{ id: 2, trip_id: 1, place_lat: 53.551, place_lng: 9.993, start_day_id: 2, end_day_id: 3 },
] as unknown as Accommodation[]
const [run] = buildDayRouteRuns(2, inputs({ days, accommodations: stays, optimizeFromAccommodation: true }))
expect(run.map(p => p.hotel)).toEqual(['morning', 'evening'])
expect(hotelBookendOf(run[0], run[1])).toBe('morning')
})
it('FE-MAP-DRP-008: a day that is not in the trip has no route', () => {
expect(buildDayRouteRuns(99, inputs({ assignments: { '1': [at(48.86, 2.35, 0)] } }))).toEqual([])
})
@@ -200,3 +227,329 @@ describe('buildDayRouteRuns', () => {
})
})
})
describe('Tour day itinerary segments', () => {
const points = {
A: [48.1, 11.1], B: [48.101, 11.101], C: [48.13, 11.13],
S: [48.103, 11.103], E: [48.12, 11.12],
S2: [48.121, 11.121], E2: [48.125, 11.125],
} as const
type Name = keyof typeof points
const tour = (name: Name, end: Name, order: number, geometry?: string) => {
const assignment = at(points[name][0], points[name][1], order)
return { ...assignment, tour_place_id: assignment.place.id,
tour_route_geometry: geometry ?? JSON.stringify([points[name], points[end]]) }
}
const ordinary = (name: Name, order: number) => at(points[name][0], points[name][1], order)
const inspect = (list: AssignmentsMap['1'], enabled = true, profile: 'walking' | 'driving' = 'walking') => {
const input = { ...inputs({ assignments: { '1': list } }), toursEnabled: enabled }
const runs = buildDayRouteRuns(1, input)
const plan = planTripRoute(input, profile)
const lines = assembleTripRoute(plan, emptyAnswers(plan))[0]?.lines ?? []
return { runs: runs.map(run => run.map(p => [p.lat, p.lng])),
chunks: plan.flatMap(day => day.runs.flatMap(run => run.map(chunk => chunk.mode))), lines }
}
it('keeps ordinary A-B-C unchanged with Tours on or off', () => {
const list = [ordinary('A', 0), ordinary('B', 1), ordinary('C', 2)]
expect(inspect(list).runs).toEqual(inspect(list, false).runs)
expect(inspect(list).runs).toEqual([[points.A, points.B, points.C]])
})
it('skips an excluded ordinary activity while preserving the upstream A-C run', () => {
const list = [ordinary('A', 0), { ...ordinary('B', 1), route_excluded: true }, ordinary('C', 2)]
expect(inspect(list).runs).toEqual([[points.A, points.C]])
expect(inspect(list, false).runs).toEqual([[points.A, points.C]])
})
it('retains an excluded Tour and its line but uses no Tour endpoint in routing', () => {
const excluded = { ...tour('S', 'E', 1), route_excluded: true }
const list = [ordinary('A', 0), excluded, ordinary('C', 2)]
expect(projectDayItinerary(list, true)[1]).toMatchObject({
kind: 'tour', assignment: excluded, geometry: [points.S, points.E], valid: true,
})
expect(inspect(list).runs).toEqual([[points.A, points.C]])
expect(inspect(list).lines).toEqual([[points.A, points.C]])
expect(inspect(list, false).runs).toEqual([[points.A, points.C]])
})
it('frames an excluded Tour-only day without generating any calculated route line', () => {
const excluded = { ...tour('S', 'E', 0), route_excluded: true }
const plan = planTripRoute({ ...inputs({ assignments: { '1': [excluded] } }), toursEnabled: true }, 'walking')
expect(plan).toHaveLength(1)
expect(plan[0].runs).toEqual([])
const overview = summariseTripRoute(assembleTripRoute(plan, emptyAnswers(plan)))
expect(overview.lines).toEqual([])
expect(overview.days[0].tourLines).toEqual([[points.S, points.E]])
expect(overview.focusPoints).toEqual([points.S, points.E])
})
it('omits excluded first, last, consecutive and invalid Tours from connector anchors', () => {
const excluded = (start: Name, end: Name, order: number, geometry?: string) => ({
...tour(start, end, order, geometry), route_excluded: true,
})
expect(inspect([excluded('S', 'E', 0), ordinary('A', 1), ordinary('C', 2)]).runs).toEqual([[points.A, points.C]])
expect(inspect([ordinary('A', 0), ordinary('C', 1), excluded('S', 'E', 2)]).runs).toEqual([[points.A, points.C]])
expect(inspect([ordinary('A', 0), excluded('S', 'E', 1), excluded('S2', 'E2', 2), ordinary('C', 3)]).runs).toEqual([[points.A, points.C]])
expect(inspect([ordinary('A', 0), excluded('S', 'E', 1, '{bad'), ordinary('C', 2)]).runs).toEqual([[points.A, points.C]])
})
it.each(['cycling', 'cable_car', 'plugin:custom/walk'])('preserves %s overrides on connectors outside Tours', mode => {
const list = [{ ...ordinary('A', 0), leg_transport_mode: mode }, tour('S', 'E', 1), ordinary('C', 2)]
expect(inspect(list).runs).toEqual([[points.A, points.S], [points.E, points.C]])
expect(inspect(list).chunks).toEqual([mode, 'walking'])
})
it.each(['walking', 'driving'] as const)('uses connectors and authoritative point-to-point geometry in %s', profile => {
const list = [ordinary('A', 0), tour('S', 'E', 1), ordinary('C', 2)]
const projection = projectDayItinerary(list, true)
expect(projection[1]).toMatchObject({ kind: 'tour', valid: true, start: { lat: 48.103, lng: 11.103 }, end: { lat: 48.12, lng: 11.12 }, geometry: [points.S, points.E] })
expect(inspect(list, true, profile).runs).toEqual([[points.A, points.S], [points.E, points.C]])
expect(inspect(list, true, profile).lines).toEqual([[points.A, points.S], [points.E, points.C]])
expect(inspect(list, true, profile).chunks).toEqual([profile, profile])
expect(inspect(list, false, profile).runs).toEqual([[points.A, points.S, points.C]])
})
it('joins a loop at its shared start/end without routing across the Tour', () => {
const list = [ordinary('A', 0), tour('S', 'S', 1, JSON.stringify([points.S, points.E, points.S])), ordinary('C', 2)]
expect(inspect(list).runs).toEqual([[points.A, points.S], [points.S, points.C]])
expect(projectDayItinerary(list, true)[1]).toMatchObject({ kind: 'tour', loop: true })
})
it('handles first, last, single, and consecutive Tours', () => {
expect(inspect([tour('S', 'E', 0), ordinary('C', 1)]).runs).toEqual([[points.E, points.C]])
expect(inspect([ordinary('A', 0), tour('S', 'E', 1)]).runs).toEqual([[points.A, points.S]])
expect(inspect([tour('S', 'E', 0)]).runs).toEqual([])
expect(inspect([ordinary('A', 0), tour('S', 'E', 1), tour('S2', 'E2', 2), ordinary('C', 3)]).runs)
.toEqual([[points.A, points.S], [points.E, points.S2], [points.E2, points.C]])
})
it('bookends a single Tour at start/end and ignores excluded edge Tours for hotel anchors', () => {
const hotel = [48, 11]
const days = [1, 2, 3].map(id => buildDay({ id, day_number: id }))
const accommodations = [{ id: 1, trip_id: 1, start_day_id: 1, end_day_id: 3,
place_lat: hotel[0], place_lng: hotel[1] }] as Accommodation[]
const withHotels = (list: AssignmentsMap['1']) => buildDayRouteRuns(2, {
...inputs({ days, assignments: { '2': list.map(assignment => ({ ...assignment, day_id: 2 })) },
accommodations, optimizeFromAccommodation: true }), toursEnabled: true,
}).map(run => run.map(point => [point.lat, point.lng]))
expect(withHotels([tour('S', 'E', 0)])).toEqual([[hotel, points.S], [points.E, hotel]])
expect(withHotels([
{ ...tour('S', 'E', 0), route_excluded: true }, ordinary('A', 1), ordinary('C', 2),
{ ...tour('S2', 'E2', 3), route_excluded: true },
])).toEqual([[hotel, points.A], [points.A, points.C], [points.C, hotel]])
expect(withHotels([tour('S', 'E', 0, '{bad')])).toEqual([[hotel, points.S]])
})
it('preserves incoming/outgoing Tour modes on hotel connectors and overview chunks', () => {
const hotel = { id: 1, trip_id: 1, start_day_id: 1, end_day_id: 3, place_lat: 48.09, place_lng: 11.09 } as Accommodation
const days = [
buildDay({ id: 1, day_number: 1 }),
buildDay({ id: 2, day_number: 2, default_transport_mode: 'driving' }),
buildDay({ id: 3, day_number: 3 }),
]
const assignedTour = {
...tour('S', 'E', 0),
incoming_leg_transport_mode: 'walking',
leg_transport_mode: 'cycling',
}
const input = {
...inputs({ days, assignments: { '2': [assignedTour] }, accommodations: [hotel], optimizeFromAccommodation: true }),
toursEnabled: true,
}
const runs = buildDayRouteRuns(2, input)
expect(runs.map(run => run.map(point => [point.lat, point.lng]))).toEqual([
[[hotel.place_lat, hotel.place_lng], points.S],
[points.E, [hotel.place_lat, hotel.place_lng]],
])
expect(resolveLegMode(runs[0][0], runs[0][1], 'driving')).toBe('walking')
expect(resolveLegMode(runs[1][0], runs[1][1], 'driving')).toBe('cycling')
expect(runs[0][1].incoming_leg_transport_mode).toBe('walking')
expect(runs[1][0].leg_transport_mode).toBe('cycling')
const overview = planTripRoute(input, 'driving').find(day => day.day.id === 2)!
expect(overview.runs.map(run => run.map(chunk => chunk.mode))).toEqual([['walking'], ['cycling']])
expect(overview.tourLines).toEqual([[points.S, points.E]])
const loopTour = { ...tour('S', 'S', 0, JSON.stringify([points.S, points.E, points.S])),
incoming_leg_transport_mode: 'walking', leg_transport_mode: 'cycling' }
const loopInput = { ...input, assignments: { '2': [loopTour] } }
const loopRuns = buildDayRouteRuns(2, loopInput)
expect(loopRuns.map(run => resolveLegMode(run[0], run[1], 'driving'))).toEqual(['walking', 'cycling'])
expect(planTripRoute(loopInput, 'driving')[0].tourLines).toEqual([[points.S, points.E, points.S]])
const nextTour = { ...tour('S2', 'E2', 1), incoming_leg_transport_mode: 'walking', leg_transport_mode: 'cycling' }
const consecutiveInput = { ...input, assignments: { '2': [assignedTour, nextTour] } }
const consecutiveRuns = buildDayRouteRuns(2, consecutiveInput)
expect(consecutiveRuns.map(run => resolveLegMode(run[0], run[1], 'driving'))).toEqual(['walking', 'cycling', 'cycling'])
expect(planTripRoute(consecutiveInput, 'driving')[0].tourLines).toEqual([[points.S, points.E], [points.S2, points.E2]])
})
it('does not let an unlocated transport after an invalid Tour create an evening hotel connector', () => {
const hotel = { id: 1, trip_id: 1, start_day_id: 1, end_day_id: 3, place_lat: 48.09, place_lng: 11.09 } as Accommodation
const days = [buildDay({ id: 1, day_number: 1 }), buildDay({ id: 2, day_number: 2 }), buildDay({ id: 3, day_number: 3 })]
const invalidTour = tour('S', 'E', 0, '{bad')
const unlocatedTrain = buildReservation({ id: 90, type: 'train', day_id: 2, day_plan_position: 1, endpoints: [] })
const runs = buildDayRouteRuns(2, {
...inputs({ days, assignments: { '2': [invalidTour] }, reservations: [unlocatedTrain], accommodations: [hotel], optimizeFromAccommodation: true }),
toursEnabled: true,
})
expect(runs.map(run => run.map(point => [point.lat, point.lng]))).toEqual([[[hotel.place_lat, hotel.place_lng], points.S]])
})
it('marks malformed Tour geometry invalid without inventing an outgoing end', () => {
const list = [ordinary('A', 0), tour('S', 'E', 1, '{bad'), ordinary('C', 2)]
expect(projectDayItinerary(list, true)[1]).toMatchObject({ kind: 'tour', valid: false, start: { lat: 48.103, lng: 11.103 }, end: null })
expect(inspect(list).runs).toEqual([[points.A, points.S]])
expect(inspect(list, false).runs).toEqual([[points.A, points.S, points.C]])
})
it('uses first and last usable coordinates when Tour geometry contains malformed points', () => {
const malformedPointToPoint = JSON.stringify([
[91, 200], points.S, [Number.NaN, points.E[1]], points.E, [48.2],
])
const list = [ordinary('A', 0), tour('S', 'E', 1, malformedPointToPoint), ordinary('C', 2)]
expect(projectDayItinerary(list, true)[1]).toMatchObject({
kind: 'tour', valid: true, start: { lat: points.S[0], lng: points.S[1] },
end: { lat: points.E[0], lng: points.E[1] }, geometry: [points.S, points.E],
})
expect(inspect(list).runs).toEqual([[points.A, points.S], [points.E, points.C]])
})
it('uses the current Place geometry when a saved Tour changes before assignments refresh', () => {
const assignment = tour('S', 'E', 1)
const updatedEnd: [number, number] = [48.127, 11.127]
const places = [buildPlace({ id: assignment.place.id, lat: points.S[0], lng: points.S[1],
route_geometry: JSON.stringify([points.S, updatedEnd]) })]
const list = [ordinary('A', 0), assignment, ordinary('C', 2)]
expect(projectDayItinerary(list, true, places)[1]).toMatchObject({ end: { lat: 48.127, lng: 11.127 } })
expect(buildDayRouteRuns(1, { ...inputs({ assignments: { '1': list } }), toursEnabled: true, places })
.map(run => run.map(point => [point.lat, point.lng])))
.toEqual([[points.A, points.S], [updatedEnd, points.C]])
})
it('preserves the outgoing Tour mode override for connectors only', () => {
const list = [ordinary('A', 0), { ...tour('S', 'E', 1), leg_transport_mode: 'plugin:custom/walk' }, ordinary('C', 2)]
expect(inspect(list).chunks).toEqual(['walking', 'plugin:custom/walk'])
expect(projectDayItinerary(list, true)[1]).toMatchObject({ geometry: [points.S, points.E] })
})
})
// MDT-02: a day holding one stage of a multi-day tour routes to that stage and draws its stretch.
describe('A stage of a multi-day tour on a day', () => {
const line: [number, number][] = [[48, 11], [48.01, 11], [48.02, 11], [48.03, 11], [48.04, 11]]
const stops = [
{ key: 'stop-start', lat: 48, lng: 11 },
{ key: 'stop-hut', lat: 48.02, lng: 11 },
{ key: 'stop-end', lat: 48.04, lng: 11 },
]
const hutToHut = (order: number, tour_stage_key: string | null) => {
const assignment = at(48, 11, order)
return { ...assignment, tour_place_id: assignment.place.id, tour_route_geometry: JSON.stringify(line), tour_stage_key }
}
it('FE-MAP-DRP-017: draws and routes to the stretch of the stage, the stops telling where it runs', () => {
const second = hutToHut(1, 'stop-hut')
const stageStops = new Map([[second.place.id, stops]])
expect(projectDayItinerary([second], true, [], stageStops)[0]).toMatchObject({
kind: 'tour', valid: true, start: { lat: 48.02, lng: 11 }, end: { lat: 48.04, lng: 11 }, geometry: line.slice(2),
})
const first = hutToHut(1, 'stop-start')
expect(projectDayItinerary([first], true, [], new Map([[first.place.id, stops]]))[0]).toMatchObject({
start: { lat: 48, lng: 11 }, end: { lat: 48.02, lng: 11 },
})
const runs = buildDayRouteRuns(1, {
...inputs({ assignments: { '1': [at(47.99, 11, 0), second, at(48.05, 11, 2)] } }),
toursEnabled: true, tourStageStops: stageStops,
})
expect(runs.map(run => run.map(point => [point.lat, point.lng]))).toEqual([[[47.99, 11], [48.02, 11]], [[48.04, 11], [48.05, 11]]])
})
it('FE-MAP-DRP-018: keeps the whole tour where the stops do not tell the stage', () => {
const whole = hutToHut(1, null)
const unknown = hutToHut(1, 'stop-gone')
const last = hutToHut(1, 'stop-end')
for (const assignment of [whole, unknown, last]) {
expect(projectDayItinerary([assignment], true, [], new Map([[assignment.place.id, stops]]))[0]).toMatchObject({ geometry: line })
}
const noStops = hutToHut(1, 'stop-hut')
expect(projectDayItinerary([noStops], true)[0]).toMatchObject({ geometry: line })
})
it('FE-MAP-DRP-019: reads the stage stops of the multi-day tours off the tour list, none for a day tour', () => {
const stages = tourStageStopsByPlace([{ place_id: 4, stage_stops: stops }, { place_id: 5, stage_stops: null }, { place_id: 6 }])
expect([...stages.keys()]).toEqual([4])
expect(stages.get(4)).toBe(stops)
})
})
// #2600: an imported GPX/KML place sits at its track's first point, so routing it as a
// plain stop drew a second road from the track start to the next stop, alongside the
// track itself. Any assigned place with a track now leaves that stretch to the track.
describe('Imported track places', () => {
const points = {
A: [35.2015, 24.1395], S: [35.201, 24.118], M: [35.199, 24.1], E: [35.1965, 24.079], C: [35.19, 24.07],
} as const
type Name = keyof typeof points
const stop = (name: Name, order: number, placeId: number) =>
buildAssignment({ id: 900 + order, day_id: 1, order_index: order,
place: buildPlace({ id: placeId, lat: points[name][0], lng: points[name][1] }) })
const trackPlace = (id: number, geometry: string | null, at: readonly [number, number] = points.S) =>
buildPlace({ id, lat: at[0], lng: at[1], route_geometry: geometry })
const track = JSON.stringify([points.S, points.M, points.E])
const runsOf = (list: AssignmentsMap['1'], places: ReturnType<typeof buildPlace>[], toursEnabled = false) =>
buildDayRouteRuns(1, { ...inputs({ assignments: { '1': list } }), toursEnabled, places })
.map(run => run.map(point => [point.lat, point.lng]))
it('routes up to the track start and carries on from its end, without the Tours addon', () => {
const list = [stop('A', 0, 1), stop('S', 1, 2), stop('C', 2, 3)]
const places = [buildPlace({ id: 1 }), trackPlace(2, track), buildPlace({ id: 3 })]
expect(runsOf(list, places)).toEqual([[points.A, points.S], [points.E, points.C]])
expect(runsOf(list, places, true)).toEqual([[points.A, points.S], [points.E, points.C]])
expect(projectDayItinerary(list, false, places)[1]).toMatchObject({ kind: 'tour', valid: true, geometry: [points.S, points.M, points.E] })
})
it('routes to the track start even when the marker was moved off it', () => {
const list = [stop('A', 0, 1), stop('C', 1, 2), stop('C', 2, 3)]
const places = [buildPlace({ id: 1 }), trackPlace(2, track, points.C), buildPlace({ id: 3 })]
expect(runsOf(list, places)).toEqual([[points.A, points.S], [points.E, points.C]])
})
it('takes the track as recorded, so one walked the other way still starts at its first point', () => {
const list = [stop('A', 0, 1), stop('E', 1, 2), stop('C', 2, 3)]
const places = [buildPlace({ id: 1 }), trackPlace(2, track, points.E), buildPlace({ id: 3 })]
expect(runsOf(list, places)).toEqual([[points.A, points.S], [points.E, points.C]])
})
it('keeps a place without a usable track as a plain stop, never as an invalid tour', () => {
const list = [stop('A', 0, 1), stop('S', 1, 2), stop('C', 2, 3)]
for (const geometry of [null, '{bad', JSON.stringify([points.S])]) {
const places = [buildPlace({ id: 1 }), trackPlace(2, geometry), buildPlace({ id: 3 })]
expect(runsOf(list, places)).toEqual([[points.A, points.S, points.C]])
expect(projectDayItinerary(list, true, places)[1]).toMatchObject({ kind: 'stop' })
}
// Places not loaded yet: the assignment alone carries no track, so nothing is guessed.
expect(runsOf(list, [])).toEqual([[points.A, points.S, points.C]])
})
it('starts the evening drive back to the hotel at the end of the track', () => {
const hotel = [35.5, 24.0]
const days = [1, 2, 3].map(id => buildDay({ id, day_number: id }))
const accommodations = [{ id: 1, trip_id: 1, start_day_id: 1, end_day_id: 3,
place_lat: hotel[0], place_lng: hotel[1] }] as Accommodation[]
const list = [stop('A', 0, 1), stop('S', 1, 2)].map(assignment => ({ ...assignment, day_id: 2 }))
const places = [buildPlace({ id: 1 }), trackPlace(2, track)]
expect(buildDayRouteRuns(2, { ...inputs({ days, assignments: { '2': list }, accommodations,
optimizeFromAccommodation: true }), places }).map(run => run.map(point => [point.lat, point.lng])))
.toEqual([[hotel, points.A], [points.A, points.S], [points.E, hotel]])
})
it('draws the track as a line in the trip overview and the PDF map', () => {
const list = [stop('A', 0, 1), stop('S', 1, 2), stop('C', 2, 3)]
const places = [buildPlace({ id: 1 }), trackPlace(2, track), buildPlace({ id: 3 })]
const plan = planTripRoute({ ...inputs({ assignments: { '1': list } }), places }, 'driving')
expect(plan[0].tourLines).toEqual([[points.S, points.M, points.E]])
})
})
+66 -16
View File
@@ -2,9 +2,10 @@ import { withHotelBookends } from './RouteCalculator'
import { getTransportRouteEndpoints, getTransportForDay, getMergedItems, isCarrierTransport, hasCarrierEndpointOnDay } from '../../utils/dayMerge'
import { getDayBookendHotels, shouldDrawMorningLeg, shouldDrawEveningLeg, type CarrierEdge } from '../../utils/dayOrder'
import { withinDriveRange } from '@trek/shared/roadtrip'
import type { Accommodation, AssignmentsMap, Day, Reservation } from '../../types'
import type { Accommodation, AssignmentsMap, Day, Place, Reservation } from '../../types'
import { projectedById, type TourStageStops } from './dayTourProjection'
export const TRANSPORT_TYPES = ['flight', 'train', 'bus', 'car', 'taxi', 'bicycle', 'cruise', 'ferry', 'transit', 'transport_other']
export const TRANSPORT_TYPES = ['flight', 'train', 'bus', 'car', 'taxi', 'bicycle', 'cruise', 'ferry', 'cable_car', 'transit', 'transport_other']
/** A waypoint on a day's drive, carrying the per-leg modes `resolveLegMode` reads off it. */
export interface DayRoutePoint {
@@ -13,6 +14,21 @@ export interface DayRoutePoint {
isPlace: boolean
leg_transport_mode?: string | null
incoming_leg_transport_mode?: string | null
/** Only on an accommodation bookend: the stay the day starts from or ends at. */
hotel?: 'morning' | 'evening'
/** Only on a planned stop: its assignment, which the road trip's vias are filed against. */
assignmentId?: number
}
/**
* Which accommodation bookend the leg between two neighbouring run points is, if any.
* A day that is nothing but the drive from one stay to the next counts as its morning
* leg, so it shows once at the top rather than at both ends (#2476).
*/
export function hotelBookendOf(from: DayRoutePoint, to: DayRoutePoint): 'morning' | 'evening' | undefined {
if (from.hotel === 'morning') return 'morning'
if (to.hotel === 'evening') return 'evening'
return undefined
}
/** Everything the plan depends on, passed in rather than read from the store, so the
@@ -23,6 +39,10 @@ export interface DayRouteInputs {
reservations: Reservation[]
accommodations: Accommodation[]
optimizeFromAccommodation: boolean | undefined
toursEnabled?: boolean
places?: Place[]
/** MDT-02: where the stages of the trip's multi-day tours run, so a day holding one routes to it. */
tourStageStops?: TourStageStops
}
/**
@@ -65,16 +85,25 @@ export function buildDayRouteRuns(dayId: number, input: DayRouteInputs): DayRout
days: allDays,
})
const merged = getMergedItems({ dayAssignments: da, dayNotes: [], dayTransports, dayId })
const projected = projectedById(da, input.toursEnabled ?? false, input.places, input.tourStageStops)
type Entry =
| { kind: 'place'; lat: number; lng: number; pos: number; time: string | null; mode: string | null; incoming: string | null }
| { kind: 'place'; id: number; lat: number; lng: number; pos: number; time: string | null; mode: string | null; incoming: string | null }
| { kind: 'tour'; start: { lat: number; lng: number } | null; end: { lat: number; lng: number } | null; pos: number; time: string | null; mode: string | null; incoming: string | null }
| { kind: 'transport'; from: { lat: number; lng: number } | null; to: { lat: number; lng: number } | null; pos: number; carrier: boolean }
const entries: Entry[] = merged.flatMap((item): Entry[] => {
if (item.type === 'place') {
const a = item.data
if (a.route_excluded) return []
const tour = projected.get(a.id)
if (tour?.kind === 'tour') return [{
kind: 'tour', start: tour.start, end: tour.end, pos: item.sortKey,
time: a.place?.place_time ?? null,
mode: a.leg_transport_mode ?? null, incoming: a.incoming_leg_transport_mode ?? null,
}]
if (!a.place?.lat || !a.place?.lng) return []
return [{
kind: 'place', lat: a.place.lat, lng: a.place.lng, pos: item.sortKey, time: a.place?.place_time ?? null,
kind: 'place', id: a.id, lat: a.place.lat, lng: a.place.lng, pos: item.sortKey, time: a.place?.place_time ?? null,
// Per-segment travel mode (#1281): mode of the leg leaving this place.
mode: (a as { leg_transport_mode?: string | null }).leg_transport_mode ?? null,
// Boundary-leg mode (#1281 follow-up): mode of the leg arriving at this place.
@@ -102,12 +131,24 @@ export function buildDayRouteRuns(dayId: number, input: DayRouteInputs): DayRout
runHasPlace = false
}
for (const entry of entries) {
if (entry.kind === 'place') {
if (entry.kind === 'tour') {
if (entry.start) {
const prev = currentRun[currentRun.length - 1]
if (prev && !prev.isPlace && !withinDriveRange(prev, entry.start)) closeRun()
currentRun.push({ ...entry.start, isPlace: true, incoming_leg_transport_mode: entry.incoming })
runHasPlace = true
}
closeRun()
if (entry.end) {
currentRun.push({ ...entry.end, isPlace: true, leg_transport_mode: entry.mode })
runHasPlace = true
}
} else if (entry.kind === 'place') {
const prev = currentRun[currentRun.length - 1]
// The open run may be nothing but a far-away arrival endpoint — break rather
// than draw the ocean.
if (prev && !prev.isPlace && !withinDriveRange(prev, entry)) closeRun()
currentRun.push({ lat: entry.lat, lng: entry.lng, isPlace: true, leg_transport_mode: entry.mode, incoming_leg_transport_mode: entry.incoming })
currentRun.push({ lat: entry.lat, lng: entry.lng, isPlace: true, leg_transport_mode: entry.mode, incoming_leg_transport_mode: entry.incoming, assignmentId: entry.id })
runHasPlace = true
} else if (entry.from || entry.to) {
const prev = currentRun[currentRun.length - 1]
@@ -127,22 +168,31 @@ export function buildDayRouteRuns(dayId: number, input: DayRouteInputs): DayRout
const flatPts: DayRoutePoint[] = []
for (const e of entries) {
if (e.kind === 'place') flatPts.push({ lat: e.lat, lng: e.lng, isPlace: true, leg_transport_mode: e.mode, incoming_leg_transport_mode: e.incoming })
else if (e.kind === 'tour') {
if (e.start) flatPts.push({ ...e.start, isPlace: true, incoming_leg_transport_mode: e.incoming })
if (e.end) flatPts.push({ ...e.end, isPlace: true, leg_transport_mode: e.mode })
}
else { if (e.from) flatPts.push({ ...e.from, isPlace: false }); if (e.to) flatPts.push({ ...e.to, isPlace: false }) }
}
// A hotel bookend point is not a place-assignment, so isPlace: false — resolveLegMode
// falls through to the day default for hotel-adjacent legs unless the place endpoint
// carries its own override.
const hotelPt = (a?: Accommodation): DayRoutePoint | null =>
a && a.place_lat != null && a.place_lng != null ? { lat: a.place_lat, lng: a.place_lng, isPlace: false } : null
// carries its own override. It says which end of the day it is, so the legs routed
// from it can be told apart from a stop planned on the hotel's own spot (#2501).
const hotelPt = (a: Accommodation | undefined, hotel: 'morning' | 'evening'): DayRoutePoint | null =>
a && a.place_lat != null && a.place_lng != null ? { lat: a.place_lat, lng: a.place_lng, isPlace: false, hotel } : null
// Only draw a hotel bookend when the leg is a real drive: a place before check-in
// (#1465), a later "home" stop on the checkout day (#1465), or a transport endpoint on
// an arrival/departure day (#1321, #2133) all draw no bookend.
const contributes = (e: Entry) => e.kind === 'place' || !!e.from || !!e.to
const contributes = (e: Entry) => e.kind === 'place' || e.kind === 'tour' || !!e.from || !!e.to
const firstStop = entries.find(contributes)
const lastStop = [...entries].reverse().find(contributes)
const edgeInfo = (e: Entry | undefined, side: 'first' | 'last') => {
if (!e) return undefined
if (e.kind === 'place') return { isPlace: true, time: e.time, lat: e.lat, lng: e.lng }
if (e.kind === 'tour') {
const point = side === 'first' ? e.start : e.end
return point ? { isPlace: true, time: e.time, ...point } : undefined
}
const role: CarrierEdge = side === 'first'
? (e.from ? 'departure' : 'arrival')
: (e.to ? 'arrival' : 'departure')
@@ -154,11 +204,11 @@ export function buildDayRouteRuns(dayId: number, input: DayRouteInputs): DayRout
const dayHasCarrier = dayTransports.some(r => hasCarrierEndpointOnDay(r, dayId))
const firstWay = flatPts[0]
const lastWay = flatPts[flatPts.length - 1]
const morningHotel = hotelPt(bookends?.morning)
const eveningHotel = hotelPt(bookends?.evening)
const drawMorning = !!bookends && !!day && shouldDrawMorningLeg(bookends, day, edgeInfo(firstStop, 'first'), dayHasCarrier)
const morningHotel = hotelPt(bookends?.morning, 'morning')
const eveningHotel = hotelPt(bookends?.evening, 'evening')
const drawMorning = !!bookends && !!day && !(firstStop?.kind === 'tour' && !firstStop.start) && shouldDrawMorningLeg(bookends, day, edgeInfo(firstStop, 'first'), dayHasCarrier)
&& (!morningHotel || !firstWay || firstWay.isPlace || withinDriveRange(morningHotel, firstWay))
const drawEvening = !!bookends && !!day && shouldDrawEveningLeg(bookends, day, edgeInfo(lastStop, 'last'), dayHasCarrier)
const drawEvening = !!bookends && !!day && !(lastStop?.kind === 'tour' && !lastStop.end) && shouldDrawEveningLeg(bookends, day, edgeInfo(lastStop, 'last'), dayHasCarrier)
&& (!eveningHotel || !lastWay || lastWay.isPlace || withinDriveRange(eveningHotel, lastWay))
const runsWithHotel: DayRoutePoint[][] = withHotelBookends(
runs,
@@ -176,8 +226,8 @@ export function buildDayRouteRuns(dayId: number, input: DayRouteInputs): DayRout
// waypoint behind, so the gates above never see it; no line beats a wrong one.
const dayHasCarrierBooking = dayTransports.some(r => isCarrierTransport(r))
if (runsWithHotel.length === 0 && drawMorning && drawEvening && !dayHasCarrierBooking) {
const m = hotelPt(bookends?.morning)
const e = hotelPt(bookends?.evening)
const m = hotelPt(bookends?.morning, 'morning')
const e = hotelPt(bookends?.evening, 'evening')
if (m && e && (m.lat !== e.lat || m.lng !== e.lng)) runsWithHotel.push([m, e])
}
@@ -0,0 +1,98 @@
import type { TourListItem, TourStageStop } from '@trek/shared'
import { analyzeRouteGeometry } from '../../utils/routeGeometry'
import type { Assignment, Place } from '../../types'
import { vertexIndicesOf } from '../Tours/stages/tourStages'
/** MDT-02: the stops each multi-day tour's stages run between, by the tour's place id. */
export type TourStageStops = ReadonlyMap<number, readonly TourStageStop[]>
/** The stage stops of the trip's multi-day tours, from the tour list; a day tour has none. */
export function tourStageStopsByPlace(tours: readonly Pick<TourListItem, 'place_id' | 'stage_stops'>[]): TourStageStops {
return new Map(tours.flatMap(tour => (tour.stage_stops ? [[tour.place_id, tour.stage_stops] as const] : [])))
}
/**
* MDT-02: the stretch of a tour's line one stage runs, from the stop it starts
* at to the stop the next one starts at; null where the stops do not tell it
* (a stage the tour no longer has, a line that has not reached them yet).
*/
function stageStretch(
line: [number, number][],
stops: readonly TourStageStop[] | undefined,
stageKey: string | null | undefined,
): [number, number][] | null {
if (!stageKey || !stops || line.length < 2) return null
const index = stops.findIndex(stop => stop.key === stageKey)
if (index < 0 || index >= stops.length - 1) return null
const at = vertexIndicesOf(stops, line)
return at[index + 1] > at[index] ? line.slice(at[index], at[index + 1] + 1) : null
}
export type DayItineraryItem =
| { kind: 'stop'; assignment: Assignment }
| {
kind: 'tour'
assignment: Assignment
placeId: number
start: { lat: number; lng: number } | null
end: { lat: number; lng: number } | null
geometry: [number, number][]
loop: boolean
valid: boolean
}
/**
* A day's stops with each tour projected onto its line: the day's route runs
* to where the tour starts and on from where it ends. A day holding one stage
* of a multi-day tour (MDT-02) runs to that stage's start and on from its end,
* and draws that stage's stretch, where `stageStops` tells them.
*/
export function projectDayItinerary(
assignments: Assignment[],
toursEnabled: boolean,
places: readonly Place[] = [],
stageStops?: TourStageStops,
): DayItineraryItem[] {
const placesById = new Map(places.map(place => [place.id, place]))
return assignments.map(assignment => {
const placeId = assignment.place?.id
if (placeId == null) return { kind: 'stop', assignment }
const currentPlace = placesById.get(placeId)
if (!toursEnabled || assignment.tour_place_id !== placeId) {
// Any other place with a track (GPX/KML import) sits at the track's first point,
// so routing it as a plain stop draws a second road alongside the track (#2600).
// It gets the same gap as a Tour; without a usable track it stays a stop and can
// never turn into an invalid Tour.
const track = analyzeRouteGeometry(currentPlace?.route_geometry)?.routeCoordinates ?? []
if (track.length < 2) return { kind: 'stop', assignment }
const start = { lat: track[0][0], lng: track[0][1] }
const end = { lat: track[track.length - 1][0], lng: track[track.length - 1][1] }
return { kind: 'tour', assignment, placeId, start, end, geometry: track,
loop: start.lat === end.lat && start.lng === end.lng, valid: true } as const
}
const analysis = analyzeRouteGeometry(currentPlace ? currentPlace.route_geometry : assignment.tour_route_geometry)
const whole = analysis?.routeCoordinates ?? []
const geometry = stageStretch(whole, stageStops?.get(placeId), assignment.tour_stage_key) ?? whole
const start = geometry.length >= 2
? { lat: geometry[0][0], lng: geometry[0][1] }
: assignment.place?.lat != null && assignment.place?.lng != null
? { lat: assignment.place.lat, lng: assignment.place.lng }
: null
const end = geometry.length >= 2
? { lat: geometry[geometry.length - 1][0], lng: geometry[geometry.length - 1][1] }
: null
return { kind: 'tour', assignment, placeId, start, end, geometry,
loop: !!start && !!end && start.lat === end.lat && start.lng === end.lng,
valid: !!end } as const
})
}
/** The day's stops projected as `projectDayItinerary` does, by assignment id, for the route that runs through them. */
export function projectedById(
assignments: Assignment[],
toursEnabled: boolean,
places?: readonly Place[],
stageStops?: TourStageStops,
): Map<number, DayItineraryItem> {
return new Map(projectDayItinerary(assignments, toursEnabled, places, stageStops).map(item => [item.assignment.id, item]))
}
+19 -6
View File
@@ -1,7 +1,6 @@
import maplibregl from 'maplibre-gl'
import * as maplibregl from 'maplibre-gl'
import 'maplibre-gl/dist/maplibre-gl.css'
import rtlTextPluginUrl from '@mapbox/mapbox-gl-rtl-text/dist/mapbox-gl-rtl-text.js?url'
import { registerRtlTextPlugin } from '../rtlText'
import workerUrl from 'maplibre-gl/dist/maplibre-gl-worker.mjs?worker&url'
import { installOfflineProtocol } from '../../../native/offlineTiles'
/**
@@ -12,10 +11,24 @@ import { installOfflineProtocol } from '../../../native/offlineTiles'
* Popup, LngLatBounds — which is why the components take the engine as a prop and
* stay engine-agnostic. Where the two genuinely differ, the caller already guards
* on the provider (projection, accessToken, aroundCenter).
*
* MapLibre 6 ships as ES modules only and has no default export any more, so the
* namespace is what goes out as this module's default. It is a frozen module
* namespace: nothing may assign to it, which is why the accessToken writes stay
* behind their mapbox-only guard.
*/
// Arabic/Hebrew/Persian labels come out unjoined and reversed without this.
// MapLibre's signature is (url, lazy) and it resolves a promise — see rtlText.ts.
registerRtlTextPlugin(() => maplibregl.setRTLTextPlugin(rtlTextPluginUrl, true))
// MapLibre 6 finds its worker next to its own module, which inside a bundle is a
// chunk in /assets/ with no worker beside it. Vite builds the worker into its own
// file and hands back the URL; set before any Map is constructed, the
// maplibre-gl-leaflet bridge included, since it only ever reaches the engine
// together with this module.
maplibregl.setWorkerUrl(workerUrl)
// No RTL text plugin here, unlike mapbox. MapLibre 6.9 shapes Arabic and orders
// bidirectional text itself; the old plugin would replace that implementation, and
// a v6 worker can only load the plugin's UMD build through eval.
// The iOS app has no service worker to serve pre-downloaded tiles; see native/offlineTiles.ts.
installOfflineProtocol(maplibregl)
@@ -1,29 +1,33 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
/**
* The two lines this fix actually adds. Everything else is a helper: the guard in
* rtlText.ts has its own tests, but a guard nobody calls looks exactly like a
* working fix from the outside. Deleting either registration, swapping an
* argument or dropping the deferred flag left the whole suite green.
* What each engine module does on import. Everything else is a helper: the guard
* in rtlText.ts has its own tests, but a guard nobody calls looks exactly like a
* working fix from the outside. Deleting the mapbox registration, swapping an
* argument or dropping the deferred flag left the whole suite green, and so would
* a maplibre engine that forgot its worker URL.
*
* The engines are mocked because importing them for real builds a worker pool
* under jsdom, and the plugin URL is mocked so the 133 KB payload never loads.
*/
const { mapboxSet, maplibreSet } = vi.hoisted(() => ({
const { mapboxSet, maplibreSet, maplibreWorker } = vi.hoisted(() => ({
mapboxSet: vi.fn(),
maplibreSet: vi.fn(),
maplibreWorker: vi.fn(),
}));
vi.mock('mapbox-gl', () => ({ default: { setRTLTextPlugin: mapboxSet } }));
vi.mock('maplibre-gl', () => ({ default: { setRTLTextPlugin: maplibreSet } }));
vi.mock('maplibre-gl', () => ({ setRTLTextPlugin: maplibreSet, setWorkerUrl: maplibreWorker }));
vi.mock('mapbox-gl/dist/mapbox-gl.css', () => ({}));
vi.mock('maplibre-gl/dist/maplibre-gl.css', () => ({}));
vi.mock('maplibre-gl/dist/maplibre-gl-worker.mjs?worker&url', () => ({ default: '/assets/maplibre-worker.js' }));
vi.mock('@mapbox/mapbox-gl-rtl-text/dist/mapbox-gl-rtl-text.js?url', () => ({ default: '/assets/rtl-plugin.js' }));
beforeEach(() => {
vi.resetModules();
mapboxSet.mockReset();
maplibreSet.mockReset();
maplibreWorker.mockReset();
});
describe('the GL engines register the RTL text plugin (#2235)', () => {
@@ -37,13 +41,12 @@ describe('the GL engines register the RTL text plugin (#2235)', () => {
expect(mapboxSet).toHaveBeenCalledWith(expect.stringContaining('rtl'), null, true);
});
it('FE-MAP-RTL-002: importing the maplibre engine registers it lazily', async () => {
it('FE-MAP-RTL-002: importing the maplibre engine registers no plugin', async () => {
await import('./maplibre');
expect(maplibreSet).toHaveBeenCalledTimes(1);
// MapLibre 5 takes (url, lazy) and returns a promise, which is the reason
// the call stays with each engine instead of going through one wrapper.
expect(maplibreSet).toHaveBeenCalledWith(expect.stringContaining('rtl'), true);
// MapLibre 6.9 shapes right-to-left text itself. The plugin would replace
// that, and a v6 worker could only run its UMD build through eval.
expect(maplibreSet).not.toHaveBeenCalled();
});
it('FE-MAP-RTL-003: an engine still loads when its registration throws', async () => {
@@ -54,13 +57,13 @@ describe('the GL engines register the RTL text plugin (#2235)', () => {
expect(engine.default).toBeDefined();
});
it('FE-MAP-RTL-004: a rejected registration promise does not surface as an unhandled rejection', async () => {
maplibreSet.mockReturnValue(Promise.reject(new Error('already registered')));
it('FE-MAP-RTL-004: importing the maplibre engine points it at the bundled worker', async () => {
const engine = await import('./maplibre');
expect(engine.default).toBeDefined();
// Give the rejection a tick to go unhandled if nothing caught it.
await new Promise((resolve) => setTimeout(resolve, 0));
// MapLibre 6 looks for its worker next to its own module, which in a bundle
// is a chunk with no worker beside it. Without this no map draws a tile.
expect(maplibreWorker).toHaveBeenCalledTimes(1);
expect(maplibreWorker).toHaveBeenCalledWith('/assets/maplibre-worker.js');
expect(engine.default.setWorkerUrl).toBe(maplibreWorker);
});
});
+10 -4
View File
@@ -1,4 +1,10 @@
import type { ComponentType } from 'react'
import { lazyWithRetry } from '../../utils/lazyWithRetry'
import type { GlMapProvider } from './glProviders'
import type { MapViewProps } from './mapViewContract'
/** What a caller hands the GL trip map: the shared map contract and which provider's style to load. */
export type MapViewGLProps = MapViewProps & { glProvider?: GlMapProvider }
/**
* The six ways into a GL map, one chunk per engine.
@@ -21,15 +27,15 @@ import { lazyWithRetry } from '../../utils/lazyWithRetry'
export const MapViewGLMapbox = lazyWithRetry(async () => {
const [component, engine] = await Promise.all([import('./MapViewGL'), import('./engines/mapbox')])
const MapViewGL = component.MapViewGL
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return { default: (props: any) => <MapViewGL {...props} gl={engine.default} /> }
const bound = (props: MapViewGLProps) => <MapViewGL {...props} gl={engine.default} />
return { default: bound satisfies ComponentType<MapViewGLProps> }
})
export const MapViewGLMaplibre = lazyWithRetry(async () => {
const [component, engine] = await Promise.all([import('./MapViewGL'), import('./engines/maplibre')])
const MapViewGL = component.MapViewGL
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return { default: (props: any) => <MapViewGL {...props} gl={engine.default} /> }
const bound = (props: MapViewGLProps) => <MapViewGL {...props} gl={engine.default} />
return { default: bound satisfies ComponentType<MapViewGLProps> }
})
export const JourneyMapGLMapbox = lazyWithRetry(async () => {
@@ -0,0 +1,62 @@
import { describe, expect, it, vi } from 'vitest';
import { applyBaseLayer, rasterTileZoom, tourRasterSourceId } from './glRasterLayers';
/** Enough of a GL map for the base layers: sources, layers with their visibility, and the style's order. */
function fakeMap(styleLayers: Array<{ id: string }> = [{ id: 'water' }, { id: 'trip-route' }]) {
const sources = new Map<string, Record<string, unknown>>();
const layers = new Map<string, string>();
const map = {
getSource: vi.fn((id: string) => sources.get(id)),
addSource: vi.fn((id: string, source: Record<string, unknown>) => sources.set(id, source)),
getLayer: vi.fn((id: string) => (layers.has(id) ? { id } : undefined)),
addLayer: vi.fn((layer: { id: string }, _before?: string) => layers.set(layer.id, 'visible')),
setLayoutProperty: vi.fn((id: string, _key: string, value: string) => layers.set(id, value)),
getStyle: vi.fn(() => ({ layers: styleLayers })),
};
return { map, sources, layers };
}
describe('applyBaseLayer (MAP-01)', () => {
it('lays OpenHikingMap with its credit under the first thing TREK draws', () => {
const { map, sources } = fakeMap();
applyBaseLayer(map, 'hiking');
expect(tourRasterSourceId('hiking')).toBe('trip-hiking');
expect(sources.get('trip-hiking')).toMatchObject({
type: 'raster',
tiles: ['https://tile.openmaps.fr/openhikingmap/{z}/{x}/{y}.png'],
maxzoom: 18,
});
expect(String(sources.get('trip-hiking')?.attribution)).toContain('openmaps.fr/donate');
expect(map.addLayer).toHaveBeenCalledWith(expect.objectContaining({ id: 'trip-hiking-raster' }), 'trip-route');
// Nothing else is built while it is off.
expect(sources.has('trip-topo')).toBe(false);
expect(sources.has('trip-satellite')).toBe(false);
});
it('switching away hides it, and back shows the same layer again without a second source', () => {
const { map, layers } = fakeMap();
applyBaseLayer(map, 'hiking');
applyBaseLayer(map, 'topo');
expect(layers.get('trip-hiking-raster')).toBe('none');
expect(layers.get('trip-topo-raster')).toBe('visible');
applyBaseLayer(map, 'hiking');
expect(layers.get('trip-hiking-raster')).toBe('visible');
expect(layers.get('trip-topo-raster')).toBe('none');
expect(map.addSource).toHaveBeenCalledTimes(2);
});
it("keeps the user's own map when the style refuses the layer", () => {
const { map } = fakeMap();
map.addLayer.mockImplementation(() => {
throw new Error('style not loaded');
});
expect(() => applyBaseLayer(map, 'hiking')).not.toThrow();
});
});
describe('rasterTileZoom', () => {
it('puts a GL zoom on the 256 px tile scale one step further in, where a raster minimum is read', () => {
expect(rasterTileZoom(8)).toBe(9);
expect(rasterTileZoom(7.5)).toBe(8.5);
});
});
+106
View File
@@ -0,0 +1,106 @@
import { SATELLITE_TILE_ATTRIBUTION, SATELLITE_TILE_MAXZOOM, SATELLITE_TILE_URL } from '../../constants/mapDefaults';
import { TOUR_RASTER_BASE_IDS, TOUR_RASTER_BASES, type TourRasterBase } from './tourRasterBases';
/*
* The raster layers a GL map draws between its basemap style and what TREK
* adds on top: the satellite, topo and hiking base layers, and (in mapRasterOverlay.ts)
* the transparent overlays such as the seamarks.
*/
/**
* The satellite base layer, the GL twin of the Leaflet one.
*
* Leaflet swaps its whole tile layer for the imagery; a GL map cannot, because the
* basemap is a style with dozens of layers in it. So the imagery goes on as a raster
* layer of its own, drawn over the style and under everything TREK adds — the route,
* the pins and the tracks stay on top and stay legible, which is the same order the
* Leaflet map ends up with.
*
* Same tokenless ESRI source as Leaflet, so the two look alike and neither needs a key.
*/
const SATELLITE_SOURCE_ID = 'trip-satellite';
const SATELLITE_LAYER_ID = 'trip-satellite-raster';
/** Everything TREK draws is prefixed; the imagery is inserted before the first of them. */
// Everything TREK draws on a GL map, so the satellite raster can be slipped underneath all
// of it. `route-alt-` earns its place here: the roads offered for a leg are added before the
// route source so they sit under the current route, which also puts them before the first
// `trip-` layer, and anchoring the imagery there painted right over them.
export const OWN_LAYER_PREFIXES = ['trip-', 'trek-', 'route-alt-'];
/**
* A GL map's zoom on the 256 px tile scale that raster tile URLs, their
* min and max zoom, and Leaflet count in. The GL engines count on 512 px
* tiles, so the same view is one step further in on that scale, and a 256 px
* raster source is drawn from its tiles one level up.
*/
export function rasterTileZoom(glZoom: number): number {
return glZoom + 1;
}
/**
* Puts the imagery on the map, or takes it off again.
*
* Built on demand rather than once at load: a style change drops every source the map
* had, and a hot reload does the same. Visibility comes first: a layer that is already
* there only needs flipping, so the usual pass is one call and a tap answers at once.
*
* Deliberately not gated on `isStyleLoaded()`. That reports false for as long as any
* source has tiles or a setData in flight (see useDawarichTrailGL), which on a phone is
* the usual state, and the only retry here is `styledata`, which fires on style edits
* and not when those finish. Behind that gate a stored choice met a busy map on load,
* and a tap on the road trip stage met the sources the same render had just set again,
* so the imagery was never drawn. The gate was also the wrong question: this only runs
* after `load`, and addSource and addLayer refuse only a style document that is not in
* yet. The catch covers that case, and `styledata` brings the pass back once it is in.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function applySatellite(map: any, on: boolean, raster?: TourRasterBase): void {
const layerId = raster ? `trip-${raster}-raster` : SATELLITE_LAYER_ID;
const sourceId = raster ? tourRasterSourceId(raster) : SATELLITE_SOURCE_ID;
const source = raster ? TOUR_RASTER_BASES[raster] : null;
try {
if (map.getLayer(layerId)) {
map.setLayoutProperty(layerId, 'visibility', on ? 'visible' : 'none');
return;
}
if (!on) return; // Nothing to build while it is switched off.
// The layer is what is missing, not necessarily the source: a pass that got the
// source in and then failed on the layer would otherwise leave a source that stops
// every later pass from ever building the layer.
if (!map.getSource(sourceId)) {
map.addSource(sourceId, {
type: 'raster',
tiles: source ? source.tiles : [SATELLITE_TILE_URL],
tileSize: 256,
maxzoom: source ? source.maxZoom : SATELLITE_TILE_MAXZOOM,
attribution: source ? source.attribution : SATELLITE_TILE_ATTRIBUTION,
});
}
// Under the first thing TREK draws, over everything the basemap style draws.
// Without the anchor the imagery lands on top and buries the route.
const layers = map.getStyle?.()?.layers ?? [];
const firstOwn = layers.find((l: { id: string }) => OWN_LAYER_PREFIXES.some((prefix) => l.id.startsWith(prefix)));
map.addLayer(
{
id: layerId,
type: 'raster',
source: sourceId,
paint: { 'raster-opacity': 1 },
},
firstOwn?.id
);
} catch {
/* a style that refuses the layer keeps the plain basemap */
}
}
/** The GL source a Tours raster base map is drawn from, which its tile events name. */
export function tourRasterSourceId(raster: TourRasterBase): string {
return `trip-${raster}`;
}
/** The base layer on a GL map: the imagery, a Tours raster map, or neither over the user's own style. */
export function applyBaseLayer(map: Parameters<typeof applySatellite>[0], baseLayer: string): void {
applySatellite(map, baseLayer === 'satellite');
for (const raster of TOUR_RASTER_BASE_IDS) applySatellite(map, baseLayer === raster, raster);
}
+143
View File
@@ -0,0 +1,143 @@
/**
* Whether a map may be drawn with a GL engine (FE-MAP-GLSUP-*).
*
* MapLibre 6 and Mapbox GL 3 throw out of their Map constructor without WebGL2.
* What is under test is the one decision every GL map goes through: the user's
* provider when it can run here, Leaflet otherwise, and Leaflet from the moment a
* GPU that claimed WebGL2 refuses the context after all.
*/
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { hasWebGL, resetWebGLProbe } from '../../utils/webgl';
import { buildGlMap, initialMapStyle, isGpuInitFailure, pickGlRenderer, useGlRenderer, useWebGL2 } from './glSupport';
const realGetContext = HTMLCanvasElement.prototype.getContext;
/** A browser whose canvas hands out a webgl2 context, or none. */
function browserWithWebGL2(available: boolean) {
const ctx = { getExtension: vi.fn(() => ({ loseContext: vi.fn() })) };
const getContext = vi.fn((type: string) => (available && type === 'webgl2' ? ctx : null));
HTMLCanvasElement.prototype.getContext = getContext as unknown as typeof realGetContext;
return getContext;
}
function gpuError(): Error {
const err = new Error('WebGL2 is required to display this map.');
err.name = 'GPUInitializationError';
return err;
}
beforeEach(() => {
resetWebGLProbe();
});
afterEach(() => {
HTMLCanvasElement.prototype.getContext = realGetContext;
resetWebGLProbe();
});
describe('pickGlRenderer', () => {
it('FE-MAP-GLSUP-001: keeps the GL provider the user picked when WebGL2 is there', () => {
expect(pickGlRenderer('maplibre-gl', '', () => true)).toBe('maplibre-gl');
expect(pickGlRenderer('mapbox-gl', 'pk.token', () => true)).toBe('mapbox-gl');
});
it('FE-MAP-GLSUP-002: draws with Leaflet when the browser has no WebGL2', () => {
expect(pickGlRenderer('maplibre-gl', '', () => false)).toBeNull();
expect(pickGlRenderer('mapbox-gl', 'pk.token', () => false)).toBeNull();
});
it('FE-MAP-GLSUP-003: Mapbox without a token stays on Leaflet, MapLibre needs none', () => {
expect(pickGlRenderer('mapbox-gl', '', () => true)).toBeNull();
expect(pickGlRenderer('maplibre-gl', null, () => true)).toBe('maplibre-gl');
});
it('FE-MAP-GLSUP-004: a Leaflet user never pays for the probe', () => {
const webgl2 = vi.fn(() => true);
expect(pickGlRenderer('leaflet', 'pk.token', webgl2)).toBeNull();
expect(pickGlRenderer(undefined, undefined, webgl2)).toBeNull();
expect(webgl2).not.toHaveBeenCalled();
});
});
describe('isGpuInitFailure', () => {
it('FE-MAP-GLSUP-005: knows both engines’ way of saying the GPU refused', () => {
expect(isGpuInitFailure(gpuError())).toBe(true);
expect(isGpuInitFailure(new Error('Failed to initialize WebGL.'))).toBe(true);
});
it('FE-MAP-GLSUP-006: anything else is not a GPU failure', () => {
expect(isGpuInitFailure(new TypeError('container is null'))).toBe(false);
expect(isGpuInitFailure('Failed to initialize WebGL')).toBe(false);
expect(isGpuInitFailure(null)).toBe(false);
});
});
describe('buildGlMap', () => {
it('FE-MAP-GLSUP-007: hands back the map the engine built', () => {
const map = { remove: vi.fn() };
expect(buildGlMap(() => map)).toBe(map);
});
it('FE-MAP-GLSUP-008: a GPU that claimed WebGL2 and refused it gives null and turns the answer to no', () => {
browserWithWebGL2(true);
expect(hasWebGL()).toBe(true);
expect(
buildGlMap(() => {
throw gpuError();
})
).toBeNull();
expect(hasWebGL()).toBe(false);
});
it('FE-MAP-GLSUP-009: any other error is a bug and is thrown on', () => {
browserWithWebGL2(true);
expect(() =>
buildGlMap(() => {
throw new TypeError('style is undefined');
})
).toThrow('style is undefined');
expect(hasWebGL()).toBe(true);
});
});
describe('useGlRenderer', () => {
it('FE-MAP-GLSUP-010: asks the canvas for webgl2 only', () => {
const getContext = browserWithWebGL2(false);
const { result } = renderHook(() => useGlRenderer('maplibre-gl', ''));
expect(result.current).toBeNull();
expect(getContext.mock.calls.map((call) => call[0])).toEqual(['webgl2']);
});
it('FE-MAP-GLSUP-011: switches every mounted map to Leaflet once a GL map fails to build', () => {
browserWithWebGL2(true);
const trip = renderHook(() => useGlRenderer('maplibre-gl', ''));
const terrain = renderHook(() => useWebGL2());
expect(trip.result.current).toBe('maplibre-gl');
expect(terrain.result.current).toBe(true);
act(() => {
buildGlMap(() => {
throw gpuError();
});
});
expect(trip.result.current).toBeNull();
expect(terrain.result.current).toBe(false);
});
});
describe('initialMapStyle', () => {
it('FE-MAP-GLSUP-INIT-001: leaves the style as it is outside the iOS app, and always for Mapbox', () => {
expect(initialMapStyle('maplibre-gl', 'https://tiles.openfreemap.org/styles/liberty')).toBe(
'https://tiles.openfreemap.org/styles/liberty'
);
expect(initialMapStyle('mapbox-gl', 'mapbox://styles/mapbox/standard')).toBe('mapbox://styles/mapbox/standard');
});
});
+84
View File
@@ -0,0 +1,84 @@
import { useSyncExternalStore } from 'react';
import { offlineStyle } from '../../native/offlineTiles';
import { hasWebGL, reportWebGLFailure, subscribeWebGL, webGLFailures } from '../../utils/webgl';
import type { GlMapProvider } from './glProviders';
/*
* Whether a map may be drawn with a GL engine at all, for every place that would
* build one: the trip map, the journey maps, the settings preview and the 3D tour.
*
* MapLibre 6 and Mapbox GL 3 both need WebGL2 and throw out of their Map
* constructor without it. A browser that cannot give it gets the Leaflet map with
* the user's tiles instead, never a map that fails to start. Like the GL
* renderers it guards, this module stays free of both SDKs (`check:gl-split`).
*/
/**
* The GL engine to draw with, or null for Leaflet: the user's provider, as long
* as it can run here. Mapbox also needs a token, MapLibre does not.
*/
export function pickGlRenderer(
provider: string | null | undefined,
mapboxToken: string | null | undefined,
webgl2: () => boolean = hasWebGL
): GlMapProvider | null {
const wanted: GlMapProvider | null =
provider === 'maplibre-gl' ? 'maplibre-gl' : provider === 'mapbox-gl' && mapboxToken ? 'mapbox-gl' : null;
// Asked only for a GL provider: a Leaflet user never pays for the probe's context.
return wanted && webgl2() ? wanted : null;
}
/** Re-renders the caller when a GL map found out that WebGL2 does not work after all. */
function useWebGLFailures(): number {
return useSyncExternalStore(subscribeWebGL, webGLFailures, webGLFailures);
}
/** pickGlRenderer for a component, switching to Leaflet the moment a GL map fails to build. */
export function useGlRenderer(
provider: string | null | undefined,
mapboxToken: string | null | undefined
): GlMapProvider | null {
useWebGLFailures();
return pickGlRenderer(provider, mapboxToken);
}
/** Whether 3D (the GL terrain map) can run here, kept current the same way. */
export function useWebGL2(): boolean {
useWebGLFailures();
return hasWebGL();
}
/**
* The GPU refusing a context, as either engine reports it from its Map
* constructor. Matched on the name and message because the class itself lives in
* the maplibre chunk, and Mapbox throws a plain Error.
*/
export function isGpuInitFailure(err: unknown): boolean {
if (!(err instanceof Error)) return false;
return err.name === 'GPUInitializationError' || /failed to initialize webgl/i.test(err.message);
}
/**
* Builds a GL map, the second line of defence behind the probe: a GPU that
* claims WebGL2 and still fails is reported, so every map switches to Leaflet,
* and the caller gets null instead of a throw. Anything else is a bug and is
* thrown on.
*/
/**
* The style a new GL map is built with. A MapLibre map inside the iOS app reads
* its tiles through the offline protocol (native/offlineTiles.ts); Mapbox has no
* protocol hook, so its style goes in untouched.
*/
export function initialMapStyle(provider: GlMapProvider, style: string): string {
return provider === 'maplibre-gl' ? offlineStyle(style) : style;
}
export function buildGlMap<T>(construct: () => T): T | null {
try {
return construct();
} catch (err) {
if (!isGpuInitFailure(err)) throw err;
reportWebGLFailure();
return null;
}
}
@@ -0,0 +1,35 @@
import { describe, expect, it, vi } from 'vitest';
import { reportGlViewport } from './glViewport';
/** A GL map showing the given box at the given zoom, or no box yet. */
function fakeMap(zoom: number, box: { south: number; west: number; north: number; east: number } | null) {
const bounds = box && {
getSouth: () => box.south,
getWest: () => box.west,
getNorth: () => box.north,
getEast: () => box.east,
};
return { getBounds: () => bounds, getZoom: () => zoom };
}
describe('reportGlViewport', () => {
it('reports the visible box with the zoom on the raster tile scale', () => {
const report = vi.fn();
reportGlViewport(fakeMap(10, { south: 47, west: 11, north: 48, east: 12 }), report);
// The GL engine counts on 512 px tiles; a raster tile's zoom is one step further in.
expect(report).toHaveBeenCalledWith({ south: 47, west: 11, north: 48, east: 12 }, 11);
});
it('says nothing while the map has no bounds yet', () => {
const report = vi.fn();
reportGlViewport(fakeMap(10, null), report);
expect(report).not.toHaveBeenCalled();
});
it('asks nothing of the map when no one listens', () => {
const map = fakeMap(10, { south: 47, west: 11, north: 48, east: 12 });
const getZoom = vi.spyOn(map, 'getZoom');
reportGlViewport(map, undefined);
expect(getZoom).not.toHaveBeenCalled();
});
});
+21
View File
@@ -0,0 +1,21 @@
import { rasterTileZoom } from './glRasterLayers';
import type { MapViewProps } from './mapViewContract';
/** Enough of a GL map to say what it shows: its bounds and its zoom. */
interface ViewportSource {
getBounds(): { getSouth(): number; getWest(): number; getNorth(): number; getEast(): number } | null;
getZoom(): number;
}
/**
* Tells the page what a GL map shows, so the POI explore pill can fetch the
* OSM places of the visible area: its bounds, and its zoom on the raster tile
* scale Leaflet reports too, so both maps ask for the same places at the
* same view. A map without bounds yet says nothing.
*/
export function reportGlViewport(map: ViewportSource, report: MapViewProps['onViewportChange']): void {
const bounds = map.getBounds();
if (!report || !bounds) return;
const bbox = { south: bounds.getSouth(), west: bounds.getWest(), north: bounds.getNorth(), east: bounds.getEast() };
report(bbox, rasterTileZoom(map.getZoom()));
}
@@ -0,0 +1,66 @@
import type mapboxgl from 'mapbox-gl';
import { describe, expect, it, vi } from 'vitest';
import type { Place } from '../../types';
import { addGpxTrackLayers, GPX_HIT_LAYER_ID, hasGpxTrackLayers, selectGpxTrack, setGpxTracks } from './gpxTrackLayers';
function fakeMap() {
const layers = new Map<string, { filter?: unknown }>();
const sources = new Map<string, { setData: ReturnType<typeof vi.fn> }>();
const map = {
addSource: vi.fn((id: string) => sources.set(id, { setData: vi.fn() })),
getSource: (id: string) => sources.get(id),
addLayer: vi.fn((layer: { id: string; filter?: unknown }) => layers.set(layer.id, { filter: layer.filter })),
getLayer: (id: string) => layers.get(id),
setFilter: vi.fn((id: string, filter: unknown) => layers.set(id, { filter })),
};
return { map: map as unknown as mapboxgl.Map, layers, sources, raw: map };
}
describe('gpxTrackLayers (PR1-08)', () => {
it('adds the rim, the line, the picked track and the hit line once, picking nothing yet', () => {
const { map, layers } = fakeMap();
expect(hasGpxTrackLayers(map)).toBe(false);
addGpxTrackLayers(map);
expect(hasGpxTrackLayers(map)).toBe(true);
expect([...layers.keys()]).toEqual([
'trip-gpx-casing',
'trip-gpx-line',
'trip-gpx-selected-casing',
'trip-gpx-selected',
GPX_HIT_LAYER_ID,
]);
expect(layers.get('trip-gpx-selected')?.filter).toEqual(['==', ['get', 'place_id'], -1]);
});
it('puts only places with a drawable track into the source, with their colour and rim', () => {
const { map, sources } = fakeMap();
addGpxTrackLayers(map);
const track = { id: 5, route_geometry: '[[47,11],[47.1,11.1]]', route_color: '#ff0000' } as Place;
const plain = { id: 6, route_geometry: null } as Place;
setGpxTracks(map, [track, plain]);
const data = sources.get('trip-gpx')?.setData.mock.calls[0]?.[0];
expect(data.features).toHaveLength(1);
expect(data.features[0].properties).toEqual({ color: '#ff0000', cased: true, place_id: 5 });
expect(data.features[0].geometry.coordinates).toEqual([
[11, 47],
[11.1, 47.1],
]);
});
it('points the picked layers at the selected place, and at none again when nothing is picked', () => {
const { map, layers } = fakeMap();
addGpxTrackLayers(map);
selectGpxTrack(map, 5);
expect(layers.get('trip-gpx-selected')?.filter).toEqual(['==', ['get', 'place_id'], 5]);
expect(layers.get('trip-gpx-selected-casing')?.filter).toEqual(['==', ['get', 'place_id'], 5]);
selectGpxTrack(map, null);
expect(layers.get('trip-gpx-selected')?.filter).toEqual(['==', ['get', 'place_id'], -1]);
});
it('does nothing before the style has its layers', () => {
const { map, raw } = fakeMap();
selectGpxTrack(map, 5);
setGpxTracks(map, []);
expect(raw.setFilter).not.toHaveBeenCalled();
});
});
+103
View File
@@ -0,0 +1,103 @@
import { TRACK_COLOR_FALLBACK } from '@trek/shared';
import type mapboxgl from 'mapbox-gl';
import type { Place } from '../../types';
import { parseRenderableRouteGeometry } from '../../utils/routeGeometry';
import { hasManualTrackColor, resolveTrackColor, TRACK_CASING_COLOR } from './trackColors';
const SOURCE_ID = 'trip-gpx';
/** The invisible fat line that takes a click on a track. */
export const GPX_HIT_LAYER_ID = 'trip-gpx-hit';
const SELECTED_CASING_LAYER_ID = 'trip-gpx-selected-casing';
const SELECTED_LAYER_ID = 'trip-gpx-selected';
const ROUND = { 'line-cap': 'round', 'line-join': 'round' } as const;
const NO_TRACK = ['==', ['get', 'place_id'], -1] as mapboxgl.FilterSpecification;
/**
* The tracks of the vector map, as the Leaflet map draws them (TrackLines): a
* rim under the tracks that carry a picked colour, the lines, the picked
* track on top wider with a light rim (PR1-08), and an invisible fat line that
* takes the click. Added once with the style; whoever adds it wires the click.
*/
export function addGpxTrackLayers(map: mapboxgl.Map): void {
map.addSource(SOURCE_ID, { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
// Casing under the tracks that carry a picked colour (#776): legible on satellite and dark styles.
// Untouched tracks are filtered out, so they look exactly as they did before.
map.addLayer({
id: 'trip-gpx-casing',
type: 'line',
source: SOURCE_ID,
filter: ['==', ['get', 'cased'], true],
paint: { 'line-color': TRACK_CASING_COLOR, 'line-width': 6.5, 'line-opacity': 0.7 },
layout: ROUND,
});
map.addLayer({
id: 'trip-gpx-line',
type: 'line',
source: SOURCE_ID,
paint: {
'line-color': ['coalesce', ['get', 'color'], TRACK_COLOR_FALLBACK],
'line-width': 3.5,
'line-opacity': ['case', ['==', ['get', 'cased'], true], 0.9, 0.75],
},
layout: ROUND,
});
// The filter follows the selection (selectGpxTrack); until something is picked it matches no track.
map.addLayer({
id: SELECTED_CASING_LAYER_ID,
type: 'line',
source: SOURCE_ID,
filter: NO_TRACK,
paint: { 'line-color': TRACK_CASING_COLOR, 'line-width': 9, 'line-opacity': 0.95 },
layout: ROUND,
});
map.addLayer({
id: SELECTED_LAYER_ID,
type: 'line',
source: SOURCE_ID,
filter: NO_TRACK,
paint: { 'line-color': ['coalesce', ['get', 'color'], TRACK_COLOR_FALLBACK], 'line-width': 5.5 },
layout: ROUND,
});
// 3.5px is not a target, and the start markers cluster below zoom 11, so without this a track
// is unreachable at the very zoom where you compare walks side by side.
map.addLayer({
id: GPX_HIT_LAYER_ID,
type: 'line',
source: SOURCE_ID,
paint: { 'line-color': TRACK_CASING_COLOR, 'line-width': 14, 'line-opacity': 0 },
layout: ROUND,
});
}
/** Whether the track layers are there yet (they come with the style). */
export function hasGpxTrackLayers(map: mapboxgl.Map): boolean {
return !!map.getSource(SOURCE_ID);
}
/** The places' tracks into the source, each with its colour and whether it carries a rim. */
export function setGpxTracks(map: mapboxgl.Map, places: readonly Place[]): void {
const src = map.getSource(SOURCE_ID) as mapboxgl.GeoJSONSource | undefined;
if (!src) return;
const features = places.flatMap((place) => {
const coords = parseRenderableRouteGeometry(place.route_geometry);
if (!coords) return [];
return [
{
type: 'Feature' as const,
properties: { color: resolveTrackColor(place), cased: hasManualTrackColor(place), place_id: place.id },
geometry: { type: 'LineString' as const, coordinates: coords.map(([lat, lng]) => [lng, lat]) },
},
];
});
src.setData({ type: 'FeatureCollection', features });
}
/** PR1-08: the picked place's track stands out; none picked, none does. */
export function selectGpxTrack(map: mapboxgl.Map, placeId: number | null): void {
if (typeof map.getLayer !== 'function') return;
const filter = ['==', ['get', 'place_id'], placeId ?? -1] as mapboxgl.FilterSpecification;
for (const id of [SELECTED_CASING_LAYER_ID, SELECTED_LAYER_ID]) {
if (map.getLayer(id)) map.setFilter(id, filter);
}
}
@@ -1,3 +1,5 @@
import type { CSSProperties } from 'react'
/**
* The drop shadow every floating map control carries.
*
@@ -8,3 +10,28 @@
* 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,
}
/** The frosted round shell the map's control groups sit in. */
export const FROSTED_SHELL = {
display: 'inline-flex', alignItems: 'center', padding: 4, borderRadius: 999, pointerEvents: 'auto' as const,
background: 'var(--sidebar-bg)',
backdropFilter: 'blur(20px) saturate(180%)',
WebkitBackdropFilter: 'blur(20px) saturate(180%)',
boxShadow: MAP_CONTROL_SHADOW,
}
/** A pill segment of a map control group; `filled` lets its class paint the background. */
export const segmentStyle = (filled: boolean): CSSProperties => ({
display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 5,
minHeight: 34, borderRadius: 999, border: 'none', cursor: 'pointer',
background: filled ? undefined : 'transparent', padding: '0 10px',
fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 600,
})
+2
View File
@@ -9,5 +9,7 @@ export interface MapHoverInfo {
/** Everyone's average, where the surface keeps ratings. On the collections map it
* is the one thing a round photo cannot tell you: which of these you liked. */
rating_avg?: number | null
/** The picture its marker wears, so the hover card can show the same one. */
photo?: string | null
routeVia?: RouteVia
}
+134
View File
@@ -0,0 +1,134 @@
/**
* A name and a short detail floating over a GL map (the via ferrata under the
* pointer and its grade, a tour waypoint and its role), the twin of the
* Leaflet `map-tooltip`: the look of the shared Tooltip (card surface, faint
* edge, caption tier), just above the point it is shown for.
*
* Built from the DOM rather than React, because it follows every mouse move:
* a React state per move would render the whole map view each time. The words
* go in as text, never as markup. It lives in the map's own container, so it
* scrolls, hides and goes away with the map.
*/
/** How far above the pointer the label floats, in CSS pixels. */
const POINTER_GAP = 12;
/** The detail beside the name (a role, a grade) as a badge, as the shared pills draw one. */
export const MAP_LABEL_BADGE_CLASS =
'ms-1.5 inline-flex h-[18px] items-center rounded-full bg-surface-secondary px-1.5 font-semibold text-content-secondary ring-1 ring-inset ring-edge-faint';
const LABEL_CLASS =
'pointer-events-none absolute z-20 flex items-center whitespace-nowrap rounded-lg border border-edge-faint bg-surface-card px-2.5 py-1 text-caption font-medium text-content shadow-lg';
/** Just the call the label needs, so the Mapbox and the MapLibre map both fit, and a stand-in without it gets none. */
interface LabelHost {
getContainer?(): HTMLElement;
}
export interface MapHoverLabel {
/** `owner` is what the label is shown for, so a stale hide from another pin leaves it alone. */
show(text: { name: string; detail: string | null }, point: { x: number; y: number }, owner?: object): void;
/** Whether the label is up for this owner. */
shownFor(owner: object): boolean;
hide(): void;
remove(): void;
}
const NO_LABEL: MapHoverLabel = {
show: () => undefined,
shownFor: () => false,
hide: () => undefined,
remove: () => undefined,
};
export function mapHoverLabel(map: LabelHost, testId = 'map-hover-label'): MapHoverLabel {
if (typeof map.getContainer !== 'function' || typeof document === 'undefined') return NO_LABEL;
const container = map.getContainer();
let element: HTMLDivElement | null = null;
let shownOwner: object | null = null;
const ensure = () => {
if (element) return element;
element = document.createElement('div');
element.className = LABEL_CLASS;
element.setAttribute('role', 'tooltip');
element.dataset.testid = testId;
// The pointer's pixel on the map, not a side of the text: placed from the corner either way.
element.style.inset = '0px auto auto 0px';
// The map's own stylesheet sets Helvetica/Arial on its container; the label speaks in the app's face.
element.style.fontFamily = 'var(--font-system)';
container.appendChild(element);
return element;
};
return {
show({ name, detail }, { x, y }, owner) {
const label = ensure();
shownOwner = owner ?? null;
label.replaceChildren(document.createTextNode(name));
if (detail) {
const badge = document.createElement('span');
badge.className = MAP_LABEL_BADGE_CLASS;
badge.textContent = detail;
label.appendChild(badge);
}
label.style.transform = `translate(${x}px, ${y - POINTER_GAP}px) translate(-50%, -100%)`;
// Not the hidden attribute: the label's `flex` class would win over it and keep it on screen.
label.style.display = '';
},
shownFor(owner) {
return !!element && element.style.display !== 'none' && shownOwner === owner;
},
hide() {
shownOwner = null;
if (element) element.style.display = 'none';
},
remove() {
element?.remove();
element = null;
},
};
}
/** What a map pin names on hover: its place and, beside it, its role. */
export interface PinHoverText {
name: string;
detail: string | null;
}
/**
* Shows the label above a pin while the pointer rests on it, and hides it the
* moment the pin is pressed, so it never trails a drag. A map that moves its
* markers every frame (the 3D terrain) can leave a pin without a leave event,
* so a move anywhere else on the map, or off it, hides the label too, as long
* as it is still this pin's. Returns the unwiring.
*/
export function bindPinHoverLabel(
pin: HTMLElement,
label: MapHoverLabel,
container: HTMLElement,
text: PinHoverText
): () => void {
const show = () => {
const box = pin.getBoundingClientRect();
const frame = container.getBoundingClientRect();
label.show(text, { x: box.left + box.width / 2 - frame.left, y: box.top - frame.top }, pin);
};
const hide = () => label.hide();
const away = (event: Event) => {
if (!label.shownFor(pin)) return;
if (event.type === 'pointerleave' || !(event.target instanceof Node && pin.contains(event.target))) label.hide();
};
pin.addEventListener('pointerenter', show);
pin.addEventListener('pointerleave', hide);
pin.addEventListener('pointerdown', hide);
container.addEventListener('pointermove', away);
container.addEventListener('pointerleave', away);
return () => {
pin.removeEventListener('pointerenter', show);
pin.removeEventListener('pointerleave', hide);
pin.removeEventListener('pointerdown', hide);
container.removeEventListener('pointermove', away);
container.removeEventListener('pointerleave', away);
};
}
+49
View File
@@ -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;
}
+116
View File
@@ -0,0 +1,116 @@
// FE-MAP-PRESS-001 to FE-MAP-PRESS-008: only a real click on the map places a point, never a drag or a long hold.
import { describe, expect, it } from 'vitest';
import { createPressTracker, isPlacementTap, TAP_MAX_DURATION_MS, TAP_MAX_TRAVEL_PX } from './mapPress';
function pointer(type: string, x: number, y: number, pointerId = 1): Event {
const event = new Event(type, { bubbles: true, cancelable: true });
Object.defineProperties(event, {
clientX: { value: x },
clientY: { value: y },
pointerId: { value: pointerId },
});
return event;
}
/** A tracker on a fresh element, with a clock the test moves. */
function setup() {
const el = document.createElement('div');
let clock = 0;
const tracker = createPressTracker(el, () => clock);
return {
el,
tracker,
at: (ms: number) => {
clock = ms;
},
send: (type: string, x: number, y: number, id = 1) => el.dispatchEvent(pointer(type, x, y, id)),
};
}
describe('isPlacementTap', () => {
it('FE-MAP-PRESS-001: a short press that barely moved places', () => {
expect(isPlacementTap({ travelPx: 0, durationMs: 80, pointers: 1 })).toBe(true);
expect(
isPlacementTap({ travelPx: TAP_MAX_TRAVEL_PX - 0.5, durationMs: TAP_MAX_DURATION_MS - 1, pointers: 1 })
).toBe(true);
});
it('FE-MAP-PRESS-002: 4 px of travel, 300 ms of hold or a second finger never place', () => {
expect(isPlacementTap({ travelPx: TAP_MAX_TRAVEL_PX, durationMs: 50, pointers: 1 })).toBe(false);
expect(isPlacementTap({ travelPx: 0, durationMs: TAP_MAX_DURATION_MS, pointers: 1 })).toBe(false);
expect(isPlacementTap({ travelPx: 0, durationMs: 50, pointers: 2 })).toBe(false);
});
it("FE-MAP-PRESS-003: a click no press was seen for (keyboard, synthetic) is the map's own call", () => {
expect(isPlacementTap(null)).toBe(true);
});
});
describe('createPressTracker', () => {
it('FE-MAP-PRESS-004: hands out the finished press once, with its travel and length', () => {
const { tracker, at, send } = setup();
at(1000);
send('pointerdown', 10, 10);
at(1100);
send('pointerup', 12, 11);
const press = tracker.take();
expect(press?.durationMs).toBe(100);
expect(press?.travelPx).toBeCloseTo(Math.hypot(2, 1));
expect(press?.pointers).toBe(1);
expect(isPlacementTap(press)).toBe(true);
expect(tracker.take()).toBeNull();
});
it('FE-MAP-PRESS-005: a drag that came back to where it started still counts as a drag', () => {
const { tracker, at, send } = setup();
at(0);
send('pointerdown', 100, 100);
send('pointermove', 140, 100);
at(120);
send('pointerup', 100, 100);
const press = tracker.take();
expect(press?.travelPx).toBe(40);
expect(isPlacementTap(press)).toBe(false);
});
it('FE-MAP-PRESS-006: a pinch or a two-finger rotate is no tap, and ends with the last finger', () => {
const { tracker, at, send } = setup();
at(0);
send('pointerdown', 10, 10, 1);
send('pointerdown', 50, 50, 2);
at(80);
send('pointerup', 50, 50, 2);
expect(tracker.take()).toBeNull();
send('pointerup', 10, 10, 1);
const press = tracker.take();
expect(press?.pointers).toBe(2);
expect(isPlacementTap(press)).toBe(false);
});
it('FE-MAP-PRESS-007: a cancelled press (the browser took it for a gesture) never places', () => {
const { tracker, at, send } = setup();
at(0);
send('pointerdown', 10, 10);
at(50);
send('pointercancel', 10, 10);
expect(isPlacementTap(tracker.take())).toBe(false);
});
it('FE-MAP-PRESS-008: a new press drops the one nobody read, and dispose stops listening', () => {
const { tracker, at, send } = setup();
at(0);
send('pointerdown', 0, 0);
at(500);
send('pointerup', 0, 0);
send('pointerdown', 0, 0);
expect(tracker.take()).toBeNull();
at(550);
send('pointerup', 0, 0);
expect(tracker.take()?.durationMs).toBe(50);
tracker.dispose();
send('pointerdown', 0, 0);
send('pointerup', 0, 0);
expect(tracker.take()).toBeNull();
});
});
+118
View File
@@ -0,0 +1,118 @@
/**
* Telling a click that should put something on the map from the end of a pan,
* a rotation or a tilt. Both map engines fire their click after short drags
* and long holds too, which in 3D, where every look around is a drag, kept
* dropping waypoints nobody meant to set.
*/
/** How far the pointer may travel during a press that still counts as a click. */
export const TAP_MAX_TRAVEL_PX = 4;
/** How long a press that still counts as a click may last. */
export const TAP_MAX_DURATION_MS = 300;
/** One finished press on the map. */
export interface MapPress {
/** The farthest the first pointer got from where it went down. */
travelPx: number;
durationMs: number;
/** The most pointers down at once: two fingers pinch or rotate, they never place. */
pointers: number;
}
/**
* Whether a press places a point. A press that was never seen (a keyboard
* activation, a synthetic click) is left to the map, which only fires a click
* for it on purpose.
*/
export function isPlacementTap(press: MapPress | null): boolean {
if (!press) return true;
return press.pointers <= 1 && press.travelPx < TAP_MAX_TRAVEL_PX && press.durationMs < TAP_MAX_DURATION_MS;
}
export interface PressTracker {
/** The press that ended last, handed out once: the click it caused reads it, the next one does not. */
take: () => MapPress | null;
dispose: () => void;
}
interface Active {
id: number;
x: number;
y: number;
at: number;
travelPx: number;
pointers: Set<number>;
most: number;
cancelled: boolean;
}
/**
* Follows the presses on an element in the capture phase, so neither engine
* can swallow them first, and keeps the last finished one for the click that
* follows it.
*/
export function createPressTracker(target: EventTarget, now: () => number = () => performance.now()): PressTracker {
let active: Active | null = null;
let last: MapPress | null = null;
const down = (event: Event) => {
const e = event as PointerEvent;
if (active) {
active.pointers.add(e.pointerId);
active.most = Math.max(active.most, active.pointers.size);
return;
}
last = null;
active = {
id: e.pointerId,
x: e.clientX,
y: e.clientY,
at: now(),
travelPx: 0,
pointers: new Set([e.pointerId]),
most: 1,
cancelled: false,
};
};
const move = (event: Event) => {
const e = event as PointerEvent;
if (!active || e.pointerId !== active.id) return;
active.travelPx = Math.max(active.travelPx, Math.hypot(e.clientX - active.x, e.clientY - active.y));
};
const up = (event: Event) => {
const e = event as PointerEvent;
if (!active) return;
if (e.pointerId === active.id && !active.cancelled) {
move(e);
}
if (event.type === 'pointercancel') active.cancelled = true;
active.pointers.delete(e.pointerId);
if (active.pointers.size > 0) return;
last = {
travelPx: active.cancelled ? Number.POSITIVE_INFINITY : active.travelPx,
durationMs: now() - active.at,
pointers: active.most,
};
active = null;
};
const options = { capture: true, passive: true } as const;
target.addEventListener('pointerdown', down, options);
target.addEventListener('pointermove', move, options);
target.addEventListener('pointerup', up, options);
target.addEventListener('pointercancel', up, options);
return {
take: () => {
const press = last;
last = null;
return press;
},
dispose: () => {
target.removeEventListener('pointerdown', down, options);
target.removeEventListener('pointermove', move, options);
target.removeEventListener('pointerup', up, options);
target.removeEventListener('pointercancel', up, options);
},
};
}
@@ -0,0 +1,134 @@
import { renderHook } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import {
useRasterOverlaysGL,
useSourceTileHealthGL,
type MapRasterOverlay,
type RasterOverlayGlMap,
} from './mapRasterOverlay';
type Handler = (event: Record<string, unknown>) => void;
/** Enough of a GL map to watch what the overlay hook does with it. */
function fakeMap(styleLayers: Array<{ id: string }> = []) {
const layers = new Map<string, { visibility: string }>();
const sources = new Set<string>();
const handlers = new Map<string, Set<Handler>>();
const map = {
getLayer: vi.fn((id: string) => layers.get(id)),
getSource: vi.fn((id: string) => (sources.has(id) ? {} : undefined)),
addSource: vi.fn((id: string) => sources.add(id)),
addLayer: vi.fn((layer: { id: string }, _before?: string) => layers.set(layer.id, { visibility: 'visible' })),
setLayoutProperty: vi.fn((id: string, _key: string, value: string) => layers.set(id, { visibility: value })),
getStyle: vi.fn(() => ({ layers: styleLayers })),
on: vi.fn((type: string, handler: Handler) => {
if (!handlers.has(type)) handlers.set(type, new Set());
handlers.get(type)?.add(handler);
}),
off: vi.fn((type: string, handler: Handler) => handlers.get(type)?.delete(handler)),
};
const fire = (type: string, event: Record<string, unknown>) =>
handlers.get(type)?.forEach((handler) => handler(event));
return { map, layers, fire, gl: map as unknown as RasterOverlayGlMap };
}
function overlay(active: boolean): MapRasterOverlay {
return {
id: 'seamarks',
url: 'https://tiles.openseamap.org/seamark/{z}/{x}/{y}.png',
attribution: 'OpenSeaMap',
minZoom: 6,
maxZoom: 18,
active,
onTileError: vi.fn(),
onTileLoad: vi.fn(),
};
}
describe('useRasterOverlaysGL', () => {
it('adds a switched-on overlay under the first own layer, so the route stays on top', () => {
const { map, gl } = fakeMap([{ id: 'background' }, { id: 'trek-route-line' }]);
renderHook(() => useRasterOverlaysGL(gl, [overlay(true)]));
expect(map.addSource).toHaveBeenCalledWith(
'trek-overlay-seamarks',
expect.objectContaining({ type: 'raster', minzoom: 6 })
);
expect(map.addLayer).toHaveBeenCalledWith(
expect.objectContaining({ id: 'trek-overlay-seamarks' }),
'trek-route-line'
);
});
it('adds nothing for an overlay that is off, and hides one already there when it is switched off', () => {
const { map, gl, layers } = fakeMap();
const { rerender } = renderHook(({ list }) => useRasterOverlaysGL(gl, list), {
initialProps: { list: [overlay(false)] },
});
expect(map.addLayer).not.toHaveBeenCalled();
rerender({ list: [overlay(true)] });
expect(layers.get('trek-overlay-seamarks')?.visibility).toBe('visible');
rerender({ list: [overlay(false)] });
expect(layers.get('trek-overlay-seamarks')?.visibility).toBe('none');
});
it('puts the overlay back after a basemap change rebuilt the style', () => {
const { map, gl, layers, fire } = fakeMap();
renderHook(() => useRasterOverlaysGL(gl, [overlay(true)]));
layers.clear();
fire('styledata', {});
expect(map.addLayer).toHaveBeenCalledTimes(2);
});
it("reports its own tiles' failures and arrivals, and leaves other sources' events alone", () => {
const { gl, fire } = fakeMap();
const seamarks = overlay(true);
renderHook(() => useRasterOverlaysGL(gl, [seamarks]));
fire('error', { sourceId: 'trek-overlay-seamarks', error: new Error('503') });
fire('error', { sourceId: 'basemap', error: new Error('503') });
fire('sourcedata', { sourceId: 'trek-overlay-seamarks', tile: {} });
fire('sourcedata', { sourceId: 'trek-overlay-seamarks' });
expect(seamarks.onTileError).toHaveBeenCalledTimes(1);
expect(seamarks.onTileLoad).toHaveBeenCalledTimes(1);
});
it('keeps the plain map when the style refuses the layer, and lets go of its listeners on unmount', () => {
const { map, gl } = fakeMap();
map.addLayer.mockImplementation(() => {
throw new Error('style not loaded');
});
const { unmount } = renderHook(() => useRasterOverlaysGL(gl, [overlay(true)]));
unmount();
expect(map.off).toHaveBeenCalledTimes(3);
});
it('does nothing without a map or without overlays', () => {
const { map, gl } = fakeMap();
renderHook(() => useRasterOverlaysGL(null, [overlay(true)]));
renderHook(() => useRasterOverlaysGL(gl, []));
expect(map.on).not.toHaveBeenCalled();
});
});
describe('useSourceTileHealthGL (MAP-01)', () => {
it("reports one source's failed and arrived tiles into its health, nothing else's", () => {
const { gl, fire } = fakeMap();
const health = { down: false, onTileError: vi.fn(), onTileLoad: vi.fn() };
renderHook(() => useSourceTileHealthGL(gl, 'trip-hiking', health));
fire('error', { sourceId: 'trip-hiking', error: new Error('503') });
fire('error', { sourceId: 'trip-topo', error: new Error('503') });
fire('sourcedata', { sourceId: 'trip-hiking', tile: {} });
fire('sourcedata', { sourceId: 'trip-hiking' });
expect(health.onTileError).toHaveBeenCalledTimes(1);
expect(health.onTileLoad).toHaveBeenCalledTimes(1);
});
it('listens to nothing while the map is not shown, and lets go when it goes', () => {
const { map, gl } = fakeMap();
const health = { down: false, onTileError: vi.fn(), onTileLoad: vi.fn() };
renderHook(() => useSourceTileHealthGL(gl, 'trip-hiking', undefined));
expect(map.on).not.toHaveBeenCalled();
const { unmount } = renderHook(() => useSourceTileHealthGL(gl, 'trip-hiking', health));
unmount();
expect(map.off).toHaveBeenCalledTimes(2);
});
});
@@ -0,0 +1,160 @@
import type { Map } from 'mapbox-gl';
import { useEffect } from 'react';
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, tourRasterSourceId } from './glRasterLayers';
import type { BaseMapHealth, TileHealth } from './tourRasterBases';
/**
* A transparent raster layer laid over the basemap and under the route, such
* as OpenSeaMap's seamarks over a paddle tour. Only the tiles in view are
* fetched while it is on: nothing is prefetched or stored for offline use, and
* the browser's own cache follows the answer's headers.
*/
export interface MapRasterOverlay {
id: string;
url: string;
attribution: string;
minZoom: number;
maxZoom: number;
active: boolean;
/** A tile failed to load; the layer's owner decides when that means the source is down. */
onTileError: () => void;
/** A tile arrived; the source answers again. */
onTileLoad: () => void;
}
type RasterOverlayStatus = 'off' | 'on' | 'down';
/** An overlay with its switch: whether it is on, and whether its source stopped answering. */
export interface ToggleableRasterOverlay extends MapRasterOverlay {
status: RasterOverlayStatus;
/** On, but the map is further out than its first tiles, so nothing of it is drawn yet. */
belowMinZoom: boolean;
onToggle: () => void;
}
/** One map type for both engines, as the ferrata layer does: MapLibre answers every call made here. */
export type RasterOverlayGlMap = Map;
/**
* The layer id. It carries TREK's own prefix, so a basemap raster added later
* (satellite, topo) is put under it, and it goes in under the first other own
* layer, so the route and its markers stay on top.
*/
function overlayLayerId(id: string): string {
return `trek-overlay-${id}`;
}
function applyOverlay(map: RasterOverlayGlMap, overlay: MapRasterOverlay): void {
const layerId = overlayLayerId(overlay.id);
try {
if (map.getLayer(layerId)) {
map.setLayoutProperty(layerId, 'visibility', overlay.active ? 'visible' : 'none');
return;
}
if (!overlay.active) return;
if (!map.getSource(layerId)) {
map.addSource(layerId, {
type: 'raster',
tiles: [overlay.url],
tileSize: 256,
minzoom: overlay.minZoom,
maxzoom: overlay.maxZoom,
attribution: overlay.attribution,
});
}
const firstOwn = (map.getStyle()?.layers ?? []).find(
(layer) =>
OWN_LAYER_PREFIXES.some((prefix) => layer.id.startsWith(prefix)) && !layer.id.startsWith('trek-overlay-')
);
map.addLayer({ id: layerId, type: 'raster', source: layerId, paint: { 'raster-opacity': 1 } }, firstOwn?.id);
} catch {
// A style that refuses the layer keeps the plain map; the switch reports nothing loaded.
}
}
/**
* The overlays on a GL map, kept through a basemap change (which rebuilds the
* style and drops them) and reporting their tiles' arrivals and failures.
*/
export function useRasterOverlaysGL(map: RasterOverlayGlMap | null, overlays: readonly MapRasterOverlay[] | undefined) {
useEffect(() => {
if (!map || !overlays?.length) return;
const apply = () => overlays.forEach((overlay) => applyOverlay(map, overlay));
const sourceOf = (event: { sourceId?: string }) =>
overlays.find((overlay) => overlayLayerId(overlay.id) === event.sourceId);
// A tile's failure carries the source it came from; other errors carry none and are not ours.
const failed = (event: { error?: Error; sourceId?: string }) => {
const overlay = sourceOf(event);
if (overlay?.active) overlay.onTileError();
};
const loaded = (event: { sourceId?: string; tile?: unknown }) => {
const overlay = sourceOf(event);
if (overlay?.active && event.tile) overlay.onTileLoad();
};
apply();
map.on('styledata', apply);
map.on('error', failed);
map.on('sourcedata', loaded);
return () => {
map.off('styledata', apply);
map.off('error', failed);
map.off('sourcedata', loaded);
};
}, [map, overlays]);
}
/**
* Reports the tiles of one GL source into its health while `health` is given:
* a failure carries the source it came from, an arrival a tile. The base layer
* itself is drawn by applyBaseLayer.
*/
export function useSourceTileHealthGL(
map: RasterOverlayGlMap | null,
sourceId: string,
health: TileHealth | undefined
) {
const { onTileError, onTileLoad } = health ?? {};
useEffect(() => {
if (!map || !onTileError || !onTileLoad) return;
const failed = (event: { error?: Error; sourceId?: string }) => {
if (event.sourceId === sourceId) onTileError();
};
const loaded = (event: { sourceId?: string; tile?: unknown }) => {
if (event.sourceId === sourceId && event.tile) onTileLoad();
};
map.on('error', failed);
map.on('sourcedata', loaded);
return () => {
map.off('error', failed);
map.off('sourcedata', loaded);
};
}, [map, sourceId, onTileError, onTileLoad]);
}
/**
* The tour planner's layers on a GL map: the via ferratas, the raster overlays its type offers,
* the paddle obstacles, and whether the map on terms (OpenHikingMap, CyclOSM) answers while it is the base map.
*/
export function useTourMapLayersGL(
map: RasterOverlayGlMap | null,
ferrataLayer: FerrataMapLayer | undefined,
layers: { overlays?: readonly MapRasterOverlay[]; paddle?: PaddleMapLayer; baseHealth?: BaseMapHealth } | undefined
) {
useFerrataMapLayerGL(map, ferrataLayer);
useRasterOverlaysGL(map, layers?.overlays);
usePaddleLayerGL(map as unknown as PaddleGlMap | null, layers?.paddle);
useSourceTileHealthGL(map, tourRasterSourceId(layers?.baseHealth?.base ?? 'hiking'), layers?.baseHealth);
}
/**
* 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,284 @@
import type { DawarichTrack, RoadtripHazard, RoadtripVia } from '@trek/shared';
import type { Day, Place, Reservation, RouteVia } from '../../types';
import type { AssistantRouteLine } from '../../types/assistantMap';
import type { ViewportPadding } from '../../utils/mapViewport';
import type { RouteProfileFocus } from '../../utils/routeGeometry';
import type { FerrataMapLayer } from '../Ferratas/useFerrataMapLayer';
import type { AlternativeOverlay } from '../Roadtrip/alternativeOverlays';
import type { DayBoundaryControls } from './dayBoundaryDrag';
import type { CompassMap } from './MapCompassPill';
import type { MapPlaceTool, TourBaseLayer, TourLayerOffer } from './MapLayerSwitcher';
import type { Poi } from './poiCategories';
/*
* The props both trip map renderers take: the Leaflet MapView and the GL
* MapViewGL (Mapbox or MapLibre), between which MapViewAuto picks at runtime.
*
* Callers talk to MapViewAuto, so one prop type has to describe what either
* renderer does with it; before this file each side read `any`, and a prop one
* renderer learned and the other never heard of went unnoticed. Both renderers
* now declare `satisfies ComponentType<...>` against this type.
*
* Types only, on purpose: this module must stay free of leaflet, mapbox-gl and
* maplibre-gl (`check:gl-split`), so every import here is `import type`.
*/
/**
* A pin as the callers of MapViewAuto hand it down. Besides trip places they
* pass the places inside a day's assignments and collection places, and those
* carry no trip_id. Neither renderer reads trip_id, but both type their pins
* as Place, which requires it; see MapViewAutoProps.
*/
export type MapPlace = Omit<Place, 'trip_id'> & { trip_id?: number };
/** A leg label between two consecutive stops: where it sits and what it says. */
export interface RouteSegment {
mid: [number, number];
from: [number, number];
to: [number, number];
walkingText?: string;
drivingText?: string;
}
export interface MapViewProps {
places?: Place[];
dayPlaces?: Place[];
// Enables the plugin map contributions (markers + layers). Absent on surfaces
// without a trip (CollectionMap), which naturally excludes them — same rule as
// the Leaflet MapPluginMarkers.
tripId?: number;
// Charging stops / rest areas a plugin route places on the drawn day route.
routeVias?: RouteVia[];
dayBoundaryControls?: DayBoundaryControls;
/** The dashed last bit to a place the road network does not reach. */
accessLines?: { line: [[number, number], [number, number]]; meters: number }[];
route?: [number, number][][] | null;
/**
* One colour pair per entry of `route`, or absent for the blue the route has always
* been. Only the road trip passes these, and only while colouring by day is on.
*/
routeColors?: ({ line: string; casing: string } | undefined)[] | null;
/** One flag per entry of `route`: true where the stretch is walked, drawn dashed (#2532). */
routeWalking?: boolean[] | null;
/** False while the map is locked (#2010): picking a place leaves the view alone. */
followSelection?: boolean;
/** Given, the lock that sets followSelection sits above the layer switcher. */
onToggleFollow?: () => void;
routeSegments?: RouteSegment[];
selectedPlaceId?: number | null;
/** The selected place itself, for when no pin on this map stands for it. */
selectedPlace?: Place | null;
onMarkerClick?: (id: number) => void;
hoverDisabled?: boolean;
onMapClick?: (info: { latlng: { lat: number; lng: number } }) => void;
onMapContextMenu?:
((e: { latlng: { lat: number; lng: number }; originalEvent: MouseEvent | TouchEvent }) => void) | null;
center?: [number, number];
zoom?: number;
fitKey?: number | null;
dayOrderMap?: Record<number, number[] | null>;
leftWidth?: number;
rightWidth?: number;
hasInspector?: boolean;
hasDayDetail?: boolean;
reservations?: Reservation[];
visibleConnectionIds?: number[];
showTransitRoutes?: boolean;
days?: Day[];
selectedDayId?: number | null;
/**
* Whether a booking switched on by hand also has to run on the selected day to be
* drawn. Only the phone's plan map asks for it; see RouteVisibilityOptions.
*/
scopeConnectionsToDay?: boolean;
showReservationStats?: boolean;
onReservationClick?: (reservationId: number) => void;
pois?: Poi[];
onPoiClick?: (poi: Poi) => void;
/**
* A corridor hit dropped somewhere on the map, with the coordinate it landed on.
* The caller decides whether that point is near enough to the drive to mean anything.
*/
onPoiDropOnRoute?: (osmId: string, lat: number, lng: number) => void;
/** A click on the drawn route, for putting a via point there (#1797). */
onRouteClick?: (lat: number, lng: number) => void;
/** The ways of driving one leg, drawn while the picker is open. */
alternativeRoutes?: AlternativeOverlay[];
/** Which option is being considered, so it can be lit up in its own colour. */
activeAlternative?: number | null;
onChooseAlternative?: (index: number) => void;
/** Reports which option the pointer is over, so the list and the map agree. */
onHighlightAlternative?: (index: number | null) => void;
/** Generic numbered control points for list-first route editors. */
/** `name` and `detail` (its role) show on hover; without a name the pin is named by its number. */
plannerWaypoints?: Array<{
id: string;
lat: number;
lng: number;
name?: string;
detail?: string;
label?: string;
shaping?: boolean;
/** MDT-01: a stage of a multi-day tour ends here; the pin carries a moon at its corner. */
stageEnd?: boolean;
}>;
selectedPlannerWaypointId?: string | null;
onPlannerWaypointClick?: (id: string) => void;
/** Drops a dragged control point; returns false when the move was refused. */
onPlannerWaypointMove?: (id: string, lat: number, lng: number) => boolean;
routeProfileFocus?: RouteProfileFocus | null;
viewBaseLayer?: TourBaseLayer;
onViewBaseLayerChange?: (layer: TourBaseLayer) => void;
/** Offers the 3D terrain switch in the tour layer pill. */
onToggleTerrain3d?: () => void;
/** Offers the "set points" switch in the tour layer pill, while a tour is being edited. */
placeTool?: MapPlaceTool;
/**
* The via ferrata layer (RC-10): its switch, with the count as a badge, joins
* the tour layer pill, and while it is on its lines are drawn and a click on
* one hands the ferrata to `onSelect`. Both renderers mount it through the
* Ferratas modules.
*/
ferrataLayer?: FerrataMapLayer;
/**
* What the tour's type offers in the tour layer pill (P2B-06): its base layers,
* and transparent overlays drawn over the basemap and under the route.
*/
tourLayers?: TourLayerOffer;
/**
* An explicit stretch of map to frame, independent of the day being shown.
*
* `fitKey` cannot express this: it carries no coordinates, and each renderer decides
* for itself that it means "the selected day". Weighing the ways of driving one leg
* needs that leg on screen, which is neither the day nor the trip.
*/
focusPoints?: [number, number][];
/** Changes only when the caller intentionally wants a new initial frame. */
focusKey?: number | string;
/**
* What the caller's own chrome covers while `focusPoints` is framed, in pixels per edge.
*
* The default padding knows this component's panels and nothing else, and on a phone it
* is a flat margin. A shell that lays its own bars over the map passes what they cover,
* so the frame lands in the part still visible. Only the fit on `focusPoints` reads it.
* Compared by value: the same numbers in a new object do not refit, while new numbers
* refit the points already handed over, because the chrome they must clear has moved.
*/
fitPadding?: ViewportPadding;
/**
* Let markers stay apart longer than usual.
*
* A road trip is read along a line: two stops fifty kilometres apart on the same
* motorway are the shape of the day, and merging them into one dot hides it.
*/
clusterLoosely?: boolean;
hazards?: RoadtripHazard[];
/** The route recorded in Dawarich, already fetched by MapViewAuto (#2279). */
dawarichTrack?: DawarichTrack | null;
/** Draw only this local day of the recording. */
dawarichSelectedDate?: string | null;
/** Local dates whose day is collapsed in the day plan; their recording is not drawn. */
dawarichHiddenDates?: ReadonlySet<string> | null;
/** Via points to draw as draggable handles, keyed by day (#1797). */
roadtripVias?: Record<number, RoadtripVia[]>;
onMoveVia?: (dayId: number, id: number, lat: number, lng: number) => void;
onRemoveVia?: (dayId: number, id: number) => void;
/**
* The visible area after every move, and the zoom on the 256 px tile scale
* raster tile URLs count in (a GL map's own zoom is one step lower there).
*/
onViewportChange?: (bbox: { south: number; west: number; north: number; east: number }, zoom: number) => void;
/**
* The raster tile URL template. Only the Leaflet renderer draws raster tiles;
* the GL renderer draws the style of the chosen provider and ignores it.
*/
tileUrl?: string;
/**
* Hands the caller the live map once it is ready. Only the GL renderer calls
* it; the Leaflet renderer takes the prop and never calls it.
*/
onMapReady?: (map: CompassMap | null) => void;
/** The assistant's suggestions that are not on the map yet, drawn as dashed pins outside the clusters. */
assistantGhosts?: AssistantGhost[];
/** The suggestion under the pointer, in the chat or on the map; its ghost pulses. */
assistantHoveredId?: string | null;
onAssistantGhostHover?: (id: string | null) => void;
onAssistantGhostClick?: (id: string) => void;
/** A place already on the map that the hovered suggestion is about; its own pin pulses instead of a ghost. */
assistantPulsePlaceId?: number | null;
/** Where the assistant asks the map to look; a new `key` is a new request. */
assistantCamera?: AssistantCamera | null;
/** Places that just arrived from an applied suggestion; their pins pop once. */
poppedPlaceIds?: readonly number[];
/** The routes the chat shows beside the plan: proposed ways, held changes, the way a change replaces. */
assistantRouteLines?: AssistantRouteLine[];
/** The pointer onto a route line (its `ref`) or off every one; the phone leaves it out, a tap points instead. */
onAssistantRouteHover?: (ref: string | null) => void;
/** The pointer moving along a route line, or a tap on it: where on the map, for the route's profile. */
onAssistantRoutePoint?: (ref: string, lat: number, lng: number) => void;
/** While the map shows the plan before a change, its pins cannot be dragged onto a day. */
markersLocked?: boolean;
}
/** The assistant's part of the contract, which both renderers hand to their assistant modules whole. */
export type AssistantMapProps = Pick<
MapViewProps,
| 'assistantGhosts'
| 'assistantHoveredId'
| 'onAssistantGhostHover'
| 'onAssistantGhostClick'
| 'assistantPulsePlaceId'
| 'assistantCamera'
| 'poppedPlaceIds'
| 'markersLocked'
| 'assistantRouteLines'
| 'onAssistantRouteHover'
| 'onAssistantRoutePoint'
| 'routeProfileFocus'
>;
/**
* A suggested place drawn before it exists. `color` and `icon` are its
* category's. A spot a card marks (a road trip's new via) is a small
* `point` instead of a pin, and lights with its change's row by `ref`.
*/
export interface AssistantGhost {
id: string;
lat: number;
lng: number;
name: string;
color?: string;
icon?: string;
variant?: 'pin' | 'point';
/** The key it lights by, when several ghosts belong to one change; its `id` otherwise. */
ref?: string;
}
/**
* A camera move the assistant asks for. `fit` frames all points, `pan` only
* brings their centre into view when it is outside. `auto` marks a move the
* user did not ask for: the map skips it while the user is moving the map
* themselves. `cover` is what the assistant's window hides of the map.
*/
export interface AssistantCamera {
key: string;
points: [number, number][];
mode: 'fit' | 'pan';
animate: boolean;
auto: boolean;
/** When it was asked for (ms since the epoch): a map that mounts right after still carries it out. */
at?: number;
cover?: { side: 'left' | 'right'; px: number } | null;
}
/**
* What MapViewAuto accepts: the renderer contract with pins as callers really
* pass them (MapPlace, possibly without trip_id). The gap between this and
* MapViewProps is known drift between the callers and the renderers' Place
* type; it is bridged in one place, in MapViewAuto, until the renderers type
* their pins by what they read.
*/
export type MapViewAutoProps = Omit<MapViewProps, 'places' | 'dayPlaces'> & {
places?: MapPlace[];
dayPlaces?: MapPlace[];
};
+20 -4
View File
@@ -18,23 +18,39 @@
* both end up as a real DOM node, which is all HTML5 drag needs.
*/
/**
* Start dragging `placeId` towards the day plan, from any row or marker that holds a
* place (a tour is one too). Every source goes through here, so the day plan cannot
* tell them apart.
*/
export function startPlaceDrag(transfer: DataTransfer | null, placeId: number): void {
transfer?.setData('placeId', String(placeId))
if (transfer) transfer.effectAllowed = 'copy'
window.__dragData = { placeId: String(placeId) }
}
/** The drag `startPlaceDrag` began has ended, dropped or not. */
export function endPlaceDrag(): void {
window.__dragData = null
}
/** Wire a marker element up as a drag source for `placeId`. */
export function makeMarkerDraggable(el: HTMLElement, placeId: number): () => void {
el.setAttribute('draggable', 'true')
const onDragStart = (e: DragEvent) => {
e.dataTransfer?.setData('placeId', String(placeId))
if (e.dataTransfer) e.dataTransfer.effectAllowed = 'copy'
window.__dragData = { placeId: String(placeId) }
startPlaceDrag(e.dataTransfer, placeId)
el.classList.add('marker-dragging')
}
const onDragEnd = () => {
window.__dragData = null
endPlaceDrag()
el.classList.remove('marker-dragging')
}
// The map pans on mousedown anywhere on its surface, and a marker sits on that
// surface. Without this the map slides away under the pointer while the drag
// is starting, which makes the day plan an impossible target to reach.
// The map then never sees the press that starts a click on the marker, which is why the Leaflet
// renderer clears the map's pan flag itself when a pin is pressed (wireDraggablePin, #2504).
const onMouseDown = (e: MouseEvent) => e.stopPropagation()
el.addEventListener('dragstart', onDragStart)
+41
View File
@@ -0,0 +1,41 @@
/**
* Two ways a place marker can be told apart from the rest, set on the place object the
* planner hands to the map. Underscored because they are the map's reading of the plan,
* never fields of a stored place.
*/
export interface PlaceMarkerFlags {
/** Not planned into any day, drawn small and without its photo (#2024). */
_compact?: boolean
/** Its stay's booking still waits for a confirmation (#2281). */
_pending?: boolean
}
export interface PlaceMarkerLook {
size: number
borderWidth: number
showPhoto: boolean
showRating: boolean
iconSize: number
/** Extra CSS for the round marker: a dashed ring and a faded face for a pending stay. */
circleCss: string
/** Part of the icon cache key, so a changed look is never served from the cache. */
key: string
}
/**
* How a place marker is drawn, the same way on the Leaflet and the GL map. A selected
* marker always shows in full: whatever made it quiet, it is the one being looked at.
*/
export function placeMarkerLook(place: PlaceMarkerFlags, selected: boolean): PlaceMarkerLook {
const compact = !!place._compact && !selected
const pending = !!place._pending
return {
size: selected ? 44 : compact ? 24 : 36,
borderWidth: selected ? 3 : compact ? 2 : 2.5,
showPhoto: !compact,
showRating: !compact,
iconSize: selected ? 18 : compact ? 12 : 15,
circleCss: pending ? 'border-style:dashed;opacity:0.62;' : '',
key: `${compact ? 'c' : ''}${pending ? 'p' : ''}`,
}
}
@@ -0,0 +1,7 @@
/**
* The GL map's cluster bubbles for the trip's places (MapViewGL draws them):
* named here so the layers drawn over them, the assistant's route lines among
* them, can leave a tap on a bubble to the bubble.
*/
export const PLACE_CLUSTER_CIRCLE_LAYER_ID = 'trip-place-clusters-circle';
export const PLACE_CLUSTER_COUNT_LAYER_ID = 'trip-place-clusters-count';
+25
View File
@@ -1,4 +1,5 @@
import { escapeHtml } from '@trek/shared'
import { getCached } from '../../services/photoService'
const PHOTO_PROXY_PREFIX = '/api/maps/place-photo/'
@@ -49,6 +50,30 @@ export function photoSourcesKey(places: Array<PhotoSource & { id: number }>): st
return places.map(p => `${p.id}:${isCustomPlaceImage(p.image_url) ? 'own' : photoCacheKey(p)}`).join('|')
}
/**
* The picture a place wears on the map: a custom uploaded image wins over the
* auto-fetched thumb, which wins over whatever image_url says. The marker and the
* hover card both ask this, so they never show two different pictures.
*/
export function placePhotoUrl(place: PhotoSource, thumbs: Record<string, string>): string | null {
if (isCustomPlaceImage(place.image_url)) return place.image_url!
const key = photoCacheKey(place)
return (key && thumbs[key]) || place.image_url || null
}
/**
* The same picture at full size, for the hover card. The marker's thumb is a 48px
* circle cut for a round pin, which blurs and keeps its round cut-out when it is
* shown any larger, so the card asks the photo cache for the picture it came from.
*/
export function placePhotoFull(place: PhotoSource): string | null {
if (isCustomPlaceImage(place.image_url)) return place.image_url!
const key = photoCacheKey(place)
const full = key ? getCached(key)?.photoUrl : null
if (full) return full
return place.image_url?.startsWith(PHOTO_PROXY_PREFIX) ? place.image_url : null
}
/**
* The picture inside a round place marker, for both the Leaflet and the GL map.
*
+86 -1
View File
@@ -1,5 +1,8 @@
// FE-COMP-PLACEPOPUP-001 to FE-COMP-PLACEPOPUP-014
// FE-COMP-PLACEPOPUP-001 to FE-COMP-PLACEPOPUP-021
import { describe, it, expect } from 'vitest'
import { createElement } from 'react'
import { Coffee, MapPin, Signpost, type LucideIcon } from 'lucide-react'
import { renderIconMarkup } from '../../utils/iconMarkup'
import { buildPlacePopupHtml, buildPoiPopupHtml } from './placePopup'
import { buildPlace } from '../../../tests/helpers/factories'
import type { Poi } from './poiCategories'
@@ -47,6 +50,13 @@ describe('buildPlacePopupHtml', () => {
expect(html).not.toContain('<svg')
})
it('FE-COMP-PLACEPOPUP-021: a place without a name keeps an empty name line, never the word undefined', () => {
const html = buildPlacePopupHtml(popupPlace({ name: undefined as never, address: null }), null)
// The name line is there and empty.
expect(html).toContain('white-space:nowrap;"></div>')
expect(html).not.toContain('undefined')
})
it('FE-COMP-PLACEPOPUP-002: escapes HTML metacharacters in the name', () => {
const html = buildPlacePopupHtml(popupPlace({ name: 'Bar & "Grill" <b>x</b>' }), null)
expect(html).toContain('Bar &amp; &quot;Grill&quot; &lt;b&gt;x&lt;/b&gt;')
@@ -130,3 +140,78 @@ describe('buildPoiPopupHtml', () => {
expect(buildPoiPopupHtml(poi({ address: 'Herrengasse 14 & 16' }))).toContain('Herrengasse 14 &amp; 16')
})
})
describe('buildPoiPopupHtml looks and plugin details', () => {
const PLUGIN_KEY = 'plugin:trail-finder/trailheads'
const icon = (Icon: LucideIcon, color: string) => renderIconMarkup(createElement(Icon, { size: 12, color, strokeWidth: 2 }))
const parse = (html: string) => {
const box = document.createElement('div')
box.innerHTML = html
return box
}
it('FE-COMP-PLACEPOPUP-015: a core POI card is the one it always was, with no details block', () => {
const html = buildPoiPopupHtml(poi({ name: 'Café Central', category: 'cafe', address: 'Herrengasse 14' }))
expect(html).toBe(
'<div style="font-family:var(--font-system);max-width:220px;">'
+ `<div style="display:flex;align-items:center;gap:5px;"><span style="flex-shrink:0;display:inline-flex;line-height:0;">${icon(Coffee, '#B45309')}</span>`
+ '<span style="font-weight:600;font-size:12.5px;color:#111827;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">Café Central</span></div>'
+ '<div style="font-size:11px;color:#9ca3af;margin-top:3px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">Herrengasse 14</div></div>',
)
})
it('FE-COMP-PLACEPOPUP-016: shows the icon and colour the POI carries and its detail rows in order', () => {
const html = buildPoiPopupHtml(poi({
category: PLUGIN_KEY, name: 'Trailhead', color: '#2f855a', icon: 'Signpost',
details: [{ label: 'Length', value: '12.4 km' }, { label: 'Step-free', value: 'Yes' }],
}))
expect(html).toContain(icon(Signpost, '#2f855a'))
const cells = [...parse(html).querySelectorAll('div[style*="grid-template-columns"] > span')].map(el => el.textContent)
expect(cells).toEqual(['Length', '12.4 km', 'Step-free', 'Yes'])
})
it('FE-COMP-PLACEPOPUP-017: markup in the name, the address and the details stays text', () => {
const html = buildPoiPopupHtml(poi({
category: PLUGIN_KEY,
name: '<img src=x onerror=alert(1)>',
address: '</div><script>alert(2)</script>',
color: '#2f855a', icon: 'Signpost',
details: [{ label: '<b onclick=alert(3)>Fee</b>', value: '"><svg onload=alert(4)>' }],
}))
const box = parse(html)
expect(box.querySelectorAll('img, script, b')).toHaveLength(0)
// The only svg is the category glyph, never one a value smuggled in.
expect(box.querySelectorAll('svg')).toHaveLength(1)
expect(box.textContent).toContain('<img src=x onerror=alert(1)>')
expect(box.textContent).toContain('<b onclick=alert(3)>Fee</b>')
expect(box.textContent).toContain('"><svg onload=alert(4)>')
})
it('FE-COMP-PLACEPOPUP-018: a colour or icon that fails the checks is drawn grey with a pin', () => {
const html = buildPoiPopupHtml(poi({
category: PLUGIN_KEY, color: 'red;background:url(https://evil.example/x)', icon: '<img src=x onerror=alert(1)>',
}))
expect(html).toContain(icon(MapPin, '#6b7280'))
expect(html).not.toContain('evil.example')
expect(parse(html).querySelectorAll('img')).toHaveLength(0)
})
it('FE-COMP-PLACEPOPUP-019: shows at most the six rows the contract allows', () => {
const details = Array.from({ length: 9 }, (_, i) => ({ label: `Row ${i}`, value: String(i) }))
const html = buildPoiPopupHtml(poi({ category: PLUGIN_KEY, color: '#2f855a', icon: 'Signpost', details }))
expect(parse(html).querySelectorAll('div[style*="grid-template-columns"] > span')).toHaveLength(12)
expect(html).not.toContain('Row 6')
})
it('FE-COMP-PLACEPOPUP-020: a long label wraps inside a capped column and leaves its value the wider share', () => {
const html = buildPoiPopupHtml(poi({
category: PLUGIN_KEY, color: '#2f855a', icon: 'Signpost',
details: [{ label: 'Wheelchair accessible toilet, ground fl', value: 'Step-free via the side door on the left' }],
}))
const grid = parse(html).querySelector<HTMLElement>('div[style*="grid-template-columns"]')!
expect(grid.style.gridTemplateColumns).toBe('fit-content(45%) 1fr')
const [label, value] = [...grid.querySelectorAll<HTMLElement>(':scope > span')]
expect(label.style.overflowWrap).toBe('anywhere')
expect(value.style.overflowWrap).toBe('anywhere')
})
})
+27 -12
View File
@@ -1,7 +1,9 @@
import { createElement } from 'react'
import { escapeHtml } from '@trek/shared'
import { renderIconMarkup } from '../../utils/iconMarkup'
import { CATEGORY_ICON_MAP } from '../shared/categoryIcons'
import { POI_CATEGORY_BY_KEY, type Poi } from './poiCategories'
import { poiAppearance, type Poi } from './poiCategories'
import { poiDetailRows } from './poiMarker'
import type { Place } from '../../types'
// HTML builders for the Mapbox GL hover popup. The Leaflet map already shows a
@@ -16,12 +18,7 @@ type PlaceWithCategory = Place & {
}
function esc(s: string | null | undefined): string {
if (!s) return ''
return String(s)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
return s ? escapeHtml(String(s)) : ''
}
// Render a lucide category icon to an inline SVG string in the given colour.
@@ -43,6 +40,13 @@ function isDisplayablePhoto(url: string | null | undefined): url is string {
const CARD_OPEN = '<div style="font-family:var(--font-system);max-width:220px;">'
const NAME_STYLE = 'font-weight:600;font-size:12.5px;color:#111827;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;'
const ADDR_STYLE = 'font-size:11px;color:#9ca3af;margin-top:3px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;'
// A plugin POI's detail rows: label and value side by side, the value free to wrap so a
// long one grows the card downwards instead of pushing it off the side of the map. The
// label column stops at 45% and wraps too, so a long label cannot squeeze its value
// into a strip a few letters wide.
const DETAILS_STYLE = 'display:grid;grid-template-columns:fit-content(45%) 1fr;gap:1px 6px;margin-top:4px;font-size:11px;line-height:1.35;'
const DETAIL_LABEL_STYLE = 'color:#6b7280;overflow-wrap:anywhere;'
const DETAIL_VALUE_STYLE = 'color:#111827;overflow-wrap:anywhere;'
/** Hover-popup card for a planned place: optional photo, name, category row, address. */
export function buildPlacePopupHtml(place: PlaceWithCategory, photoUrl: string | null): string {
@@ -57,12 +61,23 @@ export function buildPlacePopupHtml(place: PlaceWithCategory, photoUrl: string |
return `${CARD_OPEN}${img}<div style="${NAME_STYLE}">${esc(place.name)}</div>${category}${address}</div>`
}
/** Hover-popup card for an OSM "explore" POI: category-coloured icon, name, address. */
/**
* Hover-popup card for an "explore" POI: category-coloured icon, name, address, and
* for a plugin POI the rows the plugin knows about it. The colour and icon come from
* poiAppearance, so a plugin's are checked before they are written into the card, and
* every piece of text is escaped.
*/
export function buildPoiPopupHtml(poi: Poi): string {
const cat = POI_CATEGORY_BY_KEY[poi.category]
const color = cat?.color || '#6b7280'
const icon = cat ? renderIconMarkup(createElement(cat.Icon, { size: 12, color, strokeWidth: 2 })) : ''
const { color, Icon } = poiAppearance(poi)
const icon = Icon ? renderIconMarkup(createElement(Icon, { size: 12, color, strokeWidth: 2 })) : ''
const head = `<div style="display:flex;align-items:center;gap:5px;"><span style="flex-shrink:0;display:inline-flex;line-height:0;">${icon}</span><span style="${NAME_STYLE}">${esc(poi.name)}</span></div>`
const address = poi.address ? `<div style="${ADDR_STYLE}">${esc(poi.address)}</div>` : ''
return `${CARD_OPEN}${head}${address}</div>`
return `${CARD_OPEN}${head}${address}${poiDetailsHtml(poi)}</div>`
}
function poiDetailsHtml(poi: Poi): string {
const rows = poiDetailRows(poi)
if (!rows.length) return ''
const cells = rows.map(row => `<span style="${DETAIL_LABEL_STYLE}">${esc(row.label)}</span><span style="${DETAIL_VALUE_STYLE}">${esc(row.value)}</span>`)
return `<div style="${DETAILS_STYLE}">${cells.join('')}</div>`
}
@@ -0,0 +1,22 @@
// FE-PLANNER-PIN-001: a stop is a numbered pin, a shaping point a small dot without a number (P2A-03).
// FE-PLANNER-PIN-002: the stop where a stage of a multi-day tour ends carries the moon at its corner (MDT-01).
import { describe, expect, it } from 'vitest';
import { plannerPinBadge, plannerPinShape } from './plannerPinShape';
describe('plannerPinShape', () => {
it('FE-PLANNER-PIN-001: numbers a stop by its label or its place, and leaves a shaping point blank and small', () => {
expect(plannerPinShape({}, 2, false)).toEqual({ size: 26, text: '3' });
expect(plannerPinShape({ label: '2' }, 4, true)).toEqual({ size: 30, text: '2' });
expect(plannerPinShape({ shaping: true, label: '9' }, 1, false)).toEqual({ size: 14, text: '' });
expect(plannerPinShape({ shaping: true }, 1, true)).toEqual({ size: 18, text: '' });
});
it('FE-PLANNER-PIN-002: marks a stage end with the moon at the corner, and nothing else', () => {
const badge = plannerPinBadge({ stageEnd: true, label: '3' });
expect(badge).toContain('data-stage-end="true"');
expect(badge).toContain('<svg');
expect(badge).toContain('inset-inline-end');
expect(plannerPinBadge({ label: '3' })).toBe('');
expect(plannerPinBadge({ stageEnd: true, shaping: true })).toBe('');
});
});
@@ -0,0 +1,34 @@
import { Moon } from 'lucide-react';
import { createElement } from 'react';
import { renderIconMarkup } from '../../utils/iconMarkup';
/** What a planner pin shows: its stop number, or (P2A-03) nothing on a shaping point, which only steers the route. */
export interface PlannerPinPoint {
/** The stop number to print; shaping points do not count, so stops keep their numbers. */
label?: string;
shaping?: boolean;
/** MDT-01: a stage of a multi-day tour ends at this stop. */
stageEnd?: boolean;
}
/** A stop is a numbered pin; a shaping point a small dot of the same colour, without a number. */
export function plannerPinShape(
point: PlannerPinPoint,
index: number,
selected: boolean
): { size: number; text: string } {
if (point.shaping) return { size: selected ? 18 : 14, text: '' };
return { size: selected ? 30 : 26, text: point.label ?? String(index + 1) };
}
const MOON = renderIconMarkup(createElement(Moon, { size: 9, strokeWidth: 2.6, 'aria-hidden': true }));
/**
* MDT-01: the moon at the corner of a pin where a stage ends, the night
* between two days of the tour, as the planner's list marks the stop's number.
* Laid over the pin, so it needs no room of its own and moves with it.
*/
export function plannerPinBadge(point: PlannerPinPoint): string {
if (!point.stageEnd || point.shaping) return '';
return `<span data-stage-end="true" aria-hidden="true" style="position:absolute;bottom:-4px;inset-inline-end:-4px;display:grid;place-items:center;width:15px;height:15px;border-radius:9999px;background:var(--bg-card);color:var(--text-primary);box-shadow:var(--shadow-sm);pointer-events:none">${MOON}</span>`;
}
@@ -0,0 +1,152 @@
import { describe, expect, it, vi } from 'vitest';
import { wirePlannerWaypointDrag } from './plannerWaypointDrag';
function pointer(type: string, x: number, y: number, pointerId = 1, pointerType: 'mouse' | 'touch' = 'mouse'): Event {
const event = new Event(type, { bubbles: true, cancelable: true });
Object.defineProperties(event, {
button: { value: 0 },
clientX: { value: x },
clientY: { value: y },
pointerId: { value: pointerId },
pointerType: { value: pointerType },
});
return event;
}
describe('Tour waypoint marker drag lifecycle', () => {
it('previews during a drag and commits once on pointer up, swallowing only the generated click', () => {
const element = document.createElement('button');
const initial = { lat: 48, lng: 11 };
const preview = vi.fn();
const onCommit = vi.fn(() => true);
const cleanup = wirePlannerWaypointDrag({
element,
initial,
coordinateAt: (clientX, clientY) => ({ lat: clientY / 100, lng: clientX / 100 }),
setPosition: preview,
onCommit,
});
element.dispatchEvent(pointer('pointerdown', 10, 10));
element.dispatchEvent(pointer('pointermove', 11, 11));
expect(preview).not.toHaveBeenCalled();
expect(onCommit).not.toHaveBeenCalled();
element.dispatchEvent(pointer('pointermove', 20, 30));
expect(preview).toHaveBeenLastCalledWith({ lat: 0.3, lng: 0.2 });
expect(onCommit).not.toHaveBeenCalled();
element.dispatchEvent(pointer('pointerup', 30, 40));
expect(preview).toHaveBeenLastCalledWith({ lat: 0.4, lng: 0.3 });
expect(onCommit).toHaveBeenCalledOnce();
expect(onCommit).toHaveBeenCalledWith({ lat: 0.4, lng: 0.3 });
const generatedClick = new MouseEvent('click', { bubbles: true, cancelable: true });
element.dispatchEvent(generatedClick);
expect(generatedClick.defaultPrevented).toBe(true);
const nextClick = new MouseEvent('click', { bubbles: true, cancelable: true });
element.dispatchEvent(nextClick);
expect(nextClick.defaultPrevented).toBe(false);
cleanup();
});
it('restores the starting coordinate on pointer cancellation and does not commit', () => {
const element = document.createElement('button');
const initial = { lat: 48, lng: 11 };
const preview = vi.fn();
const onCommit = vi.fn();
const cleanup = wirePlannerWaypointDrag({
element,
initial,
coordinateAt: (clientX, clientY) => ({ lat: clientY, lng: clientX }),
setPosition: preview,
onCommit,
});
element.dispatchEvent(pointer('pointerdown', 10, 10));
element.dispatchEvent(pointer('pointermove', 20, 30));
element.dispatchEvent(pointer('pointercancel', 20, 30));
expect(preview).toHaveBeenLastCalledWith(initial);
expect(onCommit).not.toHaveBeenCalled();
cleanup();
});
it('restores the preview when the canonical commit is rejected', () => {
const element = document.createElement('button');
const initial = { lat: 48, lng: 11 };
const preview = vi.fn();
const cleanup = wirePlannerWaypointDrag({
element,
initial,
coordinateAt: (clientX, clientY) => ({ lat: clientY, lng: clientX }),
setPosition: preview,
onCommit: () => false,
});
element.dispatchEvent(pointer('pointerdown', 10, 10));
element.dispatchEvent(pointer('pointermove', 20, 30));
element.dispatchEvent(pointer('pointerup', 20, 30));
expect(preview).toHaveBeenLastCalledWith(initial);
cleanup();
});
it('keeps pointer, mouse, and touch starts from bubbling into map pan handlers', () => {
const mapSurface = document.createElement('div');
const element = document.createElement('button');
mapSurface.append(element);
const mapPan = vi.fn();
mapSurface.addEventListener('pointerdown', mapPan);
mapSurface.addEventListener('mousedown', mapPan);
mapSurface.addEventListener('touchstart', mapPan);
const cleanup = wirePlannerWaypointDrag({
element,
initial: { lat: 48, lng: 11 },
coordinateAt: () => ({ lat: 48, lng: 11 }),
setPosition: vi.fn(),
onCommit: vi.fn(),
});
element.dispatchEvent(pointer('pointerdown', 10, 10));
element.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button: 0 }));
element.dispatchEvent(new Event('touchstart', { bubbles: true, cancelable: true }));
expect(mapPan).not.toHaveBeenCalled();
cleanup();
});
it('commits a touch-pointer drag once at release', () => {
const element = document.createElement('button');
const onCommit = vi.fn(() => true);
const cleanup = wirePlannerWaypointDrag({
element,
initial: { lat: 48, lng: 11 },
coordinateAt: (clientX, clientY) => ({ lat: clientY / 10, lng: clientX / 10 }),
setPosition: vi.fn(),
onCommit,
});
element.dispatchEvent(pointer('pointerdown', 5, 5, 9, 'touch'));
element.dispatchEvent(pointer('pointermove', 25, 35, 9, 'touch'));
expect(onCommit).not.toHaveBeenCalled();
element.dispatchEvent(pointer('pointerup', 25, 35, 9, 'touch'));
expect(onCommit).toHaveBeenCalledOnce();
expect(onCommit).toHaveBeenCalledWith({ lat: 3.5, lng: 2.5 });
cleanup();
});
it('restores existing touch and selection styles when editing drag wiring is removed', () => {
const element = document.createElement('button');
element.style.touchAction = 'pan-x';
element.style.userSelect = 'text';
const cleanup = wirePlannerWaypointDrag({
element,
initial: { lat: 48, lng: 11 },
coordinateAt: () => ({ lat: 48, lng: 11 }),
setPosition: vi.fn(),
onCommit: vi.fn(),
});
expect(element.style.touchAction).toBe('none');
expect(element.style.userSelect).toBe('none');
cleanup();
expect(element.style.touchAction).toBe('pan-x');
expect(element.style.userSelect).toBe('text');
});
});
@@ -0,0 +1,124 @@
interface PlannerWaypointCoordinate {
lat: number;
lng: number;
}
interface PlannerWaypointDragOptions {
element: HTMLElement;
initial: PlannerWaypointCoordinate;
coordinateAt: (clientX: number, clientY: number) => PlannerWaypointCoordinate;
setPosition: (coordinate: PlannerWaypointCoordinate) => void;
onCommit: (coordinate: PlannerWaypointCoordinate) => boolean | void;
}
const DRAG_THRESHOLD_PX = 4;
export function wirePlannerWaypointDrag({
element,
initial,
coordinateAt,
setPosition,
onCommit,
}: PlannerWaypointDragOptions): () => void {
let pointerId: number | null = null;
let start: { x: number; y: number } | null = null;
let dragged = false;
let suppressClick = false;
const originalTouchAction = element.style.touchAction;
const originalUserSelect = element.style.userSelect;
const stopMapGesture = (event: Event) => event.stopPropagation();
const restore = () => setPosition(initial);
const cancel = (event?: Event) => {
if (pointerId === null) return;
event?.stopPropagation();
restore();
pointerId = null;
start = null;
dragged = false;
suppressClick = false;
};
const onPointerDown = (event: PointerEvent) => {
if (event.button !== 0 || pointerId !== null) {
event.stopPropagation();
return;
}
event.stopPropagation();
pointerId = event.pointerId;
start = { x: event.clientX, y: event.clientY };
dragged = false;
suppressClick = false;
try {
element.setPointerCapture(event.pointerId);
} catch {
// Pointer capture is unavailable in some test DOMs and older browsers.
}
};
const onPointerMove = (event: PointerEvent) => {
if (event.pointerId !== pointerId || !start) return;
event.stopPropagation();
if (!dragged && Math.hypot(event.clientX - start.x, event.clientY - start.y) < DRAG_THRESHOLD_PX) return;
dragged = true;
event.preventDefault();
setPosition(coordinateAt(event.clientX, event.clientY));
};
const onPointerUp = (event: PointerEvent) => {
if (event.pointerId !== pointerId || !start) return;
event.stopPropagation();
const travelled = Math.hypot(event.clientX - start.x, event.clientY - start.y);
if (dragged || travelled >= DRAG_THRESHOLD_PX) {
const coordinate = coordinateAt(event.clientX, event.clientY);
setPosition(coordinate);
const accepted = onCommit(coordinate) !== false;
suppressClick = true;
if (!accepted) restore();
}
pointerId = null;
start = null;
dragged = false;
};
const onClickCapture = (event: MouseEvent) => {
if (!suppressClick) return;
suppressClick = false;
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
};
const onTouchCancel = (event: Event) => cancel(event);
element.addEventListener('pointerdown', onPointerDown);
element.addEventListener('pointermove', onPointerMove);
element.addEventListener('pointerup', onPointerUp);
element.addEventListener('pointercancel', cancel);
element.addEventListener('lostpointercapture', cancel);
element.addEventListener('click', onClickCapture, true);
element.addEventListener('mousedown', stopMapGesture);
element.addEventListener('touchstart', stopMapGesture, { passive: true });
element.addEventListener('touchmove', stopMapGesture, { passive: true });
element.addEventListener('touchend', stopMapGesture, { passive: true });
element.addEventListener('touchcancel', onTouchCancel, { passive: true });
element.style.touchAction = 'none';
element.style.userSelect = 'none';
return () => {
cancel();
element.removeEventListener('pointerdown', onPointerDown);
element.removeEventListener('pointermove', onPointerMove);
element.removeEventListener('pointerup', onPointerUp);
element.removeEventListener('pointercancel', cancel);
element.removeEventListener('lostpointercapture', cancel);
element.removeEventListener('click', onClickCapture, true);
element.removeEventListener('mousedown', stopMapGesture);
element.removeEventListener('touchstart', stopMapGesture);
element.removeEventListener('touchmove', stopMapGesture);
element.removeEventListener('touchend', stopMapGesture);
element.removeEventListener('touchcancel', onTouchCancel);
element.style.touchAction = originalTouchAction;
element.style.userSelect = originalUserSelect;
};
}
@@ -0,0 +1,34 @@
// FE-COMP-PLUGINPOIICON-001 to FE-COMP-PLUGINPOIICON-004
import { describe, it, expect } from 'vitest'
import * as Lucide from 'lucide-react'
import { MapPin, Signpost } from 'lucide-react'
import { PLUGIN_POI_ICONS } from '@trek/shared'
import { POI_DEFAULT_COLOR, pluginPoiColor, resolvePluginPoiIcon } from './pluginPoiIcons'
describe('resolvePluginPoiIcon', () => {
it('FE-COMP-PLUGINPOIICON-001: every allow-listed name resolves to the lucide icon of that name', () => {
const lucide = Lucide as unknown as Record<string, unknown>
for (const name of PLUGIN_POI_ICONS) expect(resolvePluginPoiIcon(name)).toBe(lucide[name])
expect(resolvePluginPoiIcon('Signpost')).toBe(Signpost)
})
it('FE-COMP-PLUGINPOIICON-002: anything off the list is a pin, never a lucide export of that name', () => {
// Real lucide exports, just not on the list, and names that are not icons at all.
for (const name of ['Skull', 'Blocks', 'createLucideIcon', 'icons', 'toString', '', null, undefined, 42]) {
expect(resolvePluginPoiIcon(name)).toBe(MapPin)
}
})
})
describe('pluginPoiColor', () => {
it('FE-COMP-PLUGINPOIICON-003: a #rrggbb colour passes through unchanged', () => {
expect(pluginPoiColor('#2f855a')).toBe('#2f855a')
expect(pluginPoiColor('#2F855A')).toBe('#2F855A')
})
it('FE-COMP-PLUGINPOIICON-004: anything else is the default grey, markup included', () => {
for (const value of ['red', '#fff', '#2f855a;background:url(https://x)', 'url(https://x)', '"><script>', '', null, 7]) {
expect(pluginPoiColor(value)).toBe(POI_DEFAULT_COLOR)
}
})
})
@@ -0,0 +1,56 @@
import {
Accessibility, Bath, Bike, Droplet, Droplets, Footprints, Heart, Info, Landmark, MapPin,
Mountain, MountainSnow, PlugZap, Signpost, Star, Tent, TentTree, Trees, Waves, Zap,
type LucideIcon,
} from 'lucide-react'
import { isPluginPoiColor, isPluginPoiIcon, type PluginPoiIcon } from '@trek/shared'
/**
* How a plugin POI category (#1781) looks: its icon and its colour, resolved in one
* place for everything that draws one (the explore pill, the Leaflet and GL markers,
* the hover card and the admin panel).
*
* The icon table is keyed by the shared allow-list, so a name added to
* PLUGIN_POI_ICONS without a component here is a type error rather than a chip
* without a glyph. Imported one by one, unlike resolvePluginIcon's lookup over the
* whole lucide module: a plugin names one of twenty shapes, never an arbitrary export.
*/
const PLUGIN_POI_ICON_COMPONENTS: Record<PluginPoiIcon, LucideIcon> = {
Footprints,
Mountain,
MountainSnow,
Signpost,
Trees,
TentTree,
Tent,
Accessibility,
Droplet,
Droplets,
PlugZap,
Zap,
Bath,
Bike,
Waves,
Landmark,
MapPin,
Star,
Heart,
Info,
}
/** The grey an unknown POI category has always been drawn in. */
export const POI_DEFAULT_COLOR = '#6b7280'
/** The lucide component for an allow-listed icon name; MapPin for anything else. */
export function resolvePluginPoiIcon(name: unknown): LucideIcon {
return isPluginPoiIcon(name) ? PLUGIN_POI_ICON_COMPONENTS[name] : MapPin
}
/**
* The colour to draw, checked again even though the server already did: it ends up
* inside marker markup and a CSS background, so only a strict `#rrggbb` gets through
* and anything else is the default grey.
*/
export function pluginPoiColor(value: unknown): string {
return isPluginPoiColor(value) ? value : POI_DEFAULT_COLOR
}
@@ -0,0 +1,34 @@
// FE-COMP-POIAPPEAR-001 to FE-COMP-POIAPPEAR-005
import { describe, it, expect } from 'vitest'
import { Coffee, Fuel, MapPin, Signpost } from 'lucide-react'
import { poiAppearance, POI_CATEGORIES, ROADTRIP_POI_CATEGORIES } from './poiCategories'
import { POI_DEFAULT_COLOR } from './pluginPoiIcons'
const PLUGIN_KEY = 'plugin:trail-finder/trailheads'
const coreColor = (key: string) => [...POI_CATEGORIES, ...ROADTRIP_POI_CATEGORIES].find(c => c.key === key)?.color
describe('poiAppearance', () => {
it('FE-COMP-POIAPPEAR-001: a core category is drawn with its own colour and icon', () => {
expect(poiAppearance({ category: 'cafe' })).toEqual({ color: coreColor('cafe'), Icon: Coffee })
})
it('FE-COMP-POIAPPEAR-002: a road trip category keeps its look, even for a plugin hit with its own colour', () => {
// The corridor search asks plugins for core kinds; their hits answer `fuel`, not a plugin key.
expect(poiAppearance({ category: 'fuel', color: '#123456', icon: 'Star' })).toEqual({ color: coreColor('fuel'), Icon: Fuel })
})
it('FE-COMP-POIAPPEAR-003: a plugin category is drawn with the colour and icon its POI carries', () => {
expect(poiAppearance({ category: PLUGIN_KEY, color: '#2f855a', icon: 'Signpost' })).toEqual({ color: '#2f855a', Icon: Signpost })
})
it('FE-COMP-POIAPPEAR-004: a plugin POI with a colour or icon that fails the checks is grey with a pin', () => {
expect(poiAppearance({ category: PLUGIN_KEY, color: 'red;background:url(x)', icon: 'Skull' })).toEqual({ color: POI_DEFAULT_COLOR, Icon: MapPin })
expect(poiAppearance({ category: PLUGIN_KEY })).toEqual({ color: POI_DEFAULT_COLOR, Icon: MapPin })
})
it('FE-COMP-POIAPPEAR-005: an unknown category, prototype names included, is the plain grey disc', () => {
for (const category of ['unknown', 'constructor', 'toString', 'plugin:trail-finder', 'plugin:TF/x']) {
expect(poiAppearance({ category, color: '#2f855a', icon: 'Signpost' })).toEqual({ color: POI_DEFAULT_COLOR, Icon: null })
}
})
})
+73 -3
View File
@@ -1,8 +1,11 @@
import { Utensils, Coffee, Wine, BedDouble, Camera, Landmark, Trees, Ticket, Fuel, Zap, ParkingSquare, Tent, type LucideIcon } from 'lucide-react'
import { Utensils, Coffee, Wine, BedDouble, Camera, Landmark, Trees, Ticket, Fuel, Zap, ParkingSquare, Tent, Binoculars, Mountain, Warehouse, Droplet, Toilet, Sandwich, Anchor, Sailboat, Wrench, Store, BatteryCharging, type LucideIcon } from 'lucide-react'
import type { TourPoiCategory } from '@trek/shared'
import { parsePluginPoiCategoryKey, type PluginPoiDetail } from '@trek/shared'
// The road-trip kinds take their colour from the one place that defines it, so the
// search result, the map pin and the road-trip rail cannot drift apart.
import { SERVICE_COLORS } from '../Roadtrip/roadtripModel'
import { CORRIDOR_CATEGORIES, HOTEL_COLOR } from '../Roadtrip/stopKinds'
import { POI_DEFAULT_COLOR, pluginPoiColor, resolvePluginPoiIcon } from './pluginPoiIcons'
// The POI categories shown in the map "explore" pill. The `key` is the contract
// with the server (CATEGORY_OSM_FILTERS in mapsService.ts) — the OSM tag mapping
@@ -38,8 +41,42 @@ export const ROADTRIP_POI_CATEGORIES: PoiCategory[] = CORRIDOR_CATEGORIES.map(
({ key, labelKey, Icon, color }) => ({ key, labelKey, Icon, color }),
)
export const POI_CATEGORY_BY_KEY: Record<string, PoiCategory> = Object.fromEntries(
[...POI_CATEGORIES, ...ROADTRIP_POI_CATEGORIES].map(c => [c.key, c]),
const CORE_COLOR = new Map(POI_CATEGORIES.map(c => [c.key, c.color] as const))
const coreColor = (key: string) => CORE_COLOR.get(key) ?? POI_DEFAULT_COLOR
/**
* What a hike, a ride or a paddle tour stops for (PLN-02), searched along a tour in the
* planner and drawn on its map. Each takes the colour of the explore category
* it is closest to, so the map keeps one palette.
*/
export const TOUR_POI_LOOKS: Record<TourPoiCategory, PoiCategory> = {
viewpoint: { key: 'viewpoint', labelKey: 'tours.poi.cat.viewpoint', Icon: Binoculars, color: coreColor('sights') },
peak: { key: 'peak', labelKey: 'tours.poi.cat.peak', Icon: Mountain, color: coreColor('nature') },
shelter: { key: 'shelter', labelKey: 'tours.poi.cat.shelter', Icon: Warehouse, color: HOTEL_COLOR },
drinking_water: { key: 'drinking_water', labelKey: 'tours.poi.cat.drinking_water', Icon: Droplet, color: coreColor('museum') },
food: { key: 'food', labelKey: 'tours.poi.cat.food', Icon: Utensils, color: coreColor('restaurant') },
toilets: { key: 'toilets', labelKey: 'tours.poi.cat.toilets', Icon: Toilet, color: coreColor('bar') },
picnic: { key: 'picnic', labelKey: 'tours.poi.cat.picnic', Icon: Sandwich, color: coreColor('nature') },
campsite: { key: 'campsite', labelKey: 'tours.poi.cat.campsite', Icon: Tent, color: coreColor('activity') },
sights: { key: 'sights', labelKey: 'tours.poi.cat.sights', Icon: Camera, color: coreColor('sights') },
slipway: { key: 'slipway', labelKey: 'tours.poi.cat.slipway', Icon: Anchor, color: coreColor('museum') },
boat_rental: { key: 'boat_rental', labelKey: 'tours.poi.cat.boat_rental', Icon: Sailboat, color: coreColor('cafe') },
bike_repair: { key: 'bike_repair', labelKey: 'tours.poi.cat.bike_repair', Icon: Wrench, color: coreColor('activity') },
// CW-05: a city walk's own, each in the colour of the explore category it comes from.
museum: { key: 'museum', labelKey: 'tours.poi.cat.museum', Icon: Landmark, color: coreColor('museum') },
park: { key: 'park', labelKey: 'tours.poi.cat.park', Icon: Trees, color: coreColor('nature') },
cafe: { key: 'cafe', labelKey: 'tours.poi.cat.cafe', Icon: Coffee, color: coreColor('cafe') },
restaurant: { key: 'restaurant', labelKey: 'tours.poi.cat.restaurant', Icon: Utensils, color: coreColor('restaurant') },
market: { key: 'market', labelKey: 'tours.poi.cat.market', Icon: Store, color: coreColor('shopping') },
// BIK-07: the road trip's charging colour, so a charger reads as one on every map.
ebike_charging: { key: 'ebike_charging', labelKey: 'tours.poi.cat.ebike_charging', Icon: BatteryCharging, color: SERVICE_COLORS.charging },
}
// A Map rather than an object, so a category named after an Object.prototype member
// (`constructor`, `toString`) finds nothing rather than a function. A Tours category
// that shares a key with an explore one (`sights`, `campsite`) keeps the explore look.
const CATEGORY_BY_KEY = new Map(
[...Object.values(TOUR_POI_LOOKS), ...POI_CATEGORIES, ...ROADTRIP_POI_CATEGORIES].map(c => [c.key, c] as const),
)
// One POI result from /api/maps/pois (mirror of the server's OverpassPoi).
@@ -73,4 +110,37 @@ export interface Poi {
source: string
pluginId?: string
rating?: number | null
/**
* Only on a POI from a plugin category (GET /api/plugin-pois): what the plugin knows
* that open data does not, and the declaring category's icon and colour. Plugin text
* and a plugin value either way, so they are drawn through poiAppearance and
* textContent, never straight into markup.
*/
details?: PluginPoiDetail[]
icon?: string
color?: string
}
/** What a POI pin and its hover card are drawn with. */
export interface PoiAppearance {
color: string
/** Null for a category nobody knows, which is drawn as a plain grey disc. */
Icon: LucideIcon | null
}
/**
* How to draw `poi`. A core or road trip category has its own look; a plugin category
* has the one its POI carries, checked again here (a colour that is not `#rrggbb`
* turns grey, an icon off the allow-list turns into a pin); anything else is the grey
* disc an unknown category has always been. Keyed by the category rather than by
* `pluginId`, because a plugin's hit in the road trip corridor search answers a core
* category and is drawn like one.
*/
export function poiAppearance(poi: Pick<Poi, 'category' | 'icon' | 'color'>): PoiAppearance {
const core = CATEGORY_BY_KEY.get(poi.category)
if (core) return { color: core.color, Icon: core.Icon }
if (parsePluginPoiCategoryKey(poi.category)) {
return { color: pluginPoiColor(poi.color), Icon: resolvePluginPoiIcon(poi.icon) }
}
return { color: POI_DEFAULT_COLOR, Icon: null }
}
@@ -0,0 +1,68 @@
// FE-COMP-POIMARKER-001 to FE-COMP-POIMARKER-008
import { describe, it, expect } from 'vitest'
import { createElement } from 'react'
import { Coffee, MapPin, Signpost, type LucideIcon } from 'lucide-react'
import { PLUGIN_POI_DETAILS_MAX } from '@trek/shared'
import { renderIconMarkup } from '../../utils/iconMarkup'
import { POI_CATEGORIES } from './poiCategories'
import { POI_DEFAULT_COLOR } from './pluginPoiIcons'
import { poiDetailRowKey, poiDetailRows, poiPinCacheKey, poiPinParts } from './poiMarker'
const PLUGIN_KEY = 'plugin:trail-finder/trailheads'
const coreColor = (key: string) => POI_CATEGORIES.find(c => c.key === key)?.color
const glyph = (Icon: LucideIcon) => renderIconMarkup(createElement(Icon, { size: 13, color: 'white', strokeWidth: 2.5 }))
describe('poiPinParts', () => {
it('FE-COMP-POIMARKER-001: a core category keeps the colour and glyph it has always had', () => {
expect(poiPinParts({ category: 'cafe' })).toEqual({ color: coreColor('cafe'), svg: glyph(Coffee) })
// An unknown category is the grey disc without a glyph, as before.
expect(poiPinParts({ category: 'spaceport' })).toEqual({ color: POI_DEFAULT_COLOR, svg: '' })
})
it('FE-COMP-POIMARKER-002: a plugin POI is drawn with its own colour and allow-listed icon', () => {
expect(poiPinParts({ category: PLUGIN_KEY, color: '#2f855a', icon: 'Signpost' })).toEqual({ color: '#2f855a', svg: glyph(Signpost) })
})
it('FE-COMP-POIMARKER-003: a colour or icon that fails the checks never reaches the markup', () => {
const parts = poiPinParts({ category: PLUGIN_KEY, color: 'red;background:url(https://evil.example/x)', icon: '<img src=x onerror=alert(1)>' })
expect(parts).toEqual({ color: POI_DEFAULT_COLOR, svg: glyph(MapPin) })
expect(parts.svg).not.toContain('evil')
expect(parts.svg).not.toContain('<img')
})
})
describe('poiPinCacheKey', () => {
it('FE-COMP-POIMARKER-004: a core category is cached under its key alone', () => {
expect(poiPinCacheKey({ category: 'museum', color: '#123456', icon: 'Star' })).toBe('museum')
expect(poiPinCacheKey({ category: 'spaceport' })).toBe('spaceport')
})
it('FE-COMP-POIMARKER-005: a plugin category adds its checked colour and icon to the key', () => {
const key = poiPinCacheKey({ category: PLUGIN_KEY, color: '#2f855a', icon: 'Signpost' })
expect(key).toBe(`${PLUGIN_KEY}|#2f855a|Signpost`)
// A plugin update that changes the look is a new pin, not the one cached before it.
expect(poiPinCacheKey({ category: PLUGIN_KEY, color: '#c53030', icon: 'Signpost' })).not.toBe(key)
expect(poiPinCacheKey({ category: PLUGIN_KEY, color: '#2f855a', icon: 'Mountain' })).not.toBe(key)
// Values that fail the checks are keyed by what is drawn instead: the grey and no icon name.
expect(poiPinCacheKey({ category: PLUGIN_KEY, color: 'url(x)', icon: 'Skull' })).toBe(`${PLUGIN_KEY}|${POI_DEFAULT_COLOR}|`)
})
})
describe('poiDetailRows', () => {
it('FE-COMP-POIMARKER-006: a POI without details has no rows', () => {
expect(poiDetailRows({})).toEqual([])
expect(poiDetailRows({ details: undefined })).toEqual([])
expect(poiDetailRows({ details: 'Length: 3 km' as never })).toEqual([])
})
it('FE-COMP-POIMARKER-007: rows are capped at the contract limit and a repeated one shows once', () => {
const rows = Array.from({ length: PLUGIN_POI_DETAILS_MAX + 3 }, (_, i) => ({ label: `L${i}`, value: `V${i}` }))
expect(poiDetailRows({ details: rows })).toEqual(rows.slice(0, PLUGIN_POI_DETAILS_MAX))
const repeated = [{ label: 'Length', value: '3 km' }, { label: 'Length', value: '3 km' }, { label: 'Length', value: '5 km' }]
expect(poiDetailRows({ details: repeated })).toEqual([repeated[0], repeated[2]])
})
it('FE-COMP-POIMARKER-008: the row key tells label and value apart', () => {
expect(poiDetailRowKey({ label: 'a', value: 'bc' })).not.toBe(poiDetailRowKey({ label: 'ab', value: 'c' }))
})
})
+59
View File
@@ -0,0 +1,59 @@
import { createElement } from 'react'
import { PLUGIN_POI_DETAILS_MAX, isPluginPoiIcon, parsePluginPoiCategoryKey, type PluginPoiDetail } from '@trek/shared'
import { renderIconMarkup } from '../../utils/iconMarkup'
import { poiAppearance, type Poi } from './poiCategories'
import { pluginPoiColor } from './pluginPoiIcons'
/**
* What an explore POI pin is drawn with, for both map renderers (the Leaflet divIcon
* and the GL marker element), so the two cannot draw one POI two ways.
*
* Each renderer keeps its own disc markup around these parts, because the two have
* always differed by a style or two and a core pin has to come out exactly as it did.
*/
type PoiLook = Pick<Poi, 'category' | 'icon' | 'color'>
/**
* The disc colour and the white glyph inside it. The colour has been through
* poiAppearance, so a plugin value that is not `#rrggbb` never reaches the markup it is
* written into; an unknown category has no glyph.
*/
export function poiPinParts(poi: PoiLook): { color: string; svg: string } {
const { color, Icon } = poiAppearance(poi)
const svg = Icon ? renderIconMarkup(createElement(Icon, { size: 13, color: 'white', strokeWidth: 2.5 })) : ''
return { color, svg }
}
/**
* What a cached pin is looked up by. A core category is drawn the same way every time,
* so its key alone is enough. A plugin category is drawn from what its POI carries, and
* the plugin can change that with an update, so its key adds the checked colour and
* icon: a pin cached before the update is never handed out after it.
*/
export function poiPinCacheKey(poi: PoiLook): string {
if (!parsePluginPoiCategoryKey(poi.category)) return poi.category
const icon = isPluginPoiIcon(poi.icon) ? poi.icon : ''
return `${poi.category}|${pluginPoiColor(poi.color)}|${icon}`
}
/** One detail row told apart from the others, for a React key. */
export function poiDetailRowKey(row: PluginPoiDetail): string {
return `${row.label}\n${row.value}`
}
/**
* The plugin's detail rows to show on the hover card, at most as many as the contract
* allows and each one once. Plugin text, so every renderer writes it as text (React or
* escapeHtml), never as markup. Empty for a core POI, which has none.
*/
export function poiDetailRows(poi: Pick<Poi, 'details'>): PluginPoiDetail[] {
if (!Array.isArray(poi.details)) return []
const seen = new Set<string>()
return poi.details.slice(0, PLUGIN_POI_DETAILS_MAX).filter(row => {
const key = poiDetailRowKey(row)
if (seen.has(key)) return false
seen.add(key)
return true
})
}
+13 -133
View File
@@ -3,158 +3,38 @@
// react-leaflet is component-driven, mapbox-gl is imperative — so instead of
// a React component, this exports a small manager class the MapViewGL wires
// up next to its other sources/layers. The geometry logic (great-circle arcs,
// antimeridian split, duration math) mirrors the Leaflet overlay so both
// renderers produce the same visual result on the globe or a flat projection.
// duration math) lives in transportHops, shared with the Leaflet overlay, so
// both renderers produce the same visual result on the globe or a flat projection.
import { createElement } from 'react'
import { renderIconMarkup } from '../../utils/iconMarkup'
import type mapboxgl from 'mapbox-gl'
import { Plane, Train, Ship, Car, Bus, Sailboat, Bike, CarTaxiFront, Route, TramFront } from 'lucide-react'
import { getTransitMapSegments } from './transitGeometry'
import { geodesicArcs } from './flightGeodesy'
import { cleanEndpointName } from './reservationName'
import { hopIsVisible, labelFloorPx } from '../../utils/reservationRoutes'
import { escapeHtml } from '@trek/shared'
import type { Reservation, ReservationEndpoint } from '../../types'
import { TRANSPORT_COLOR, TRANSPORT_META, transportHop, type TransportHop, type TransportType } from './transportHops'
import type { Reservation } from '../../types'
export const RESERVATION_SOURCE_ID = 'trek-reservations'
export const RESERVATION_LINE_LAYER_ID = 'trek-reservations-lines'
/** Sits under the coloured transit lines; named here so teardown can find it. */
export const TRANSIT_CASING_LAYER_ID = `${RESERVATION_LINE_LAYER_ID}-transit-casing`
type TransportType = 'flight' | 'train' | 'cruise' | 'car' | 'bus' | 'taxi' | 'bicycle' | 'ferry' | 'transit' | 'transport_other'
const TRANSPORT_TYPES: TransportType[] = ['flight', 'train', 'cruise', 'car', 'bus', 'taxi', 'bicycle', 'ferry', 'transit', 'transport_other']
const TRANSPORT_COLOR = '#3b82f6'
const TYPE_META: Record<TransportType, { icon: typeof Plane; geodesic: boolean }> = {
flight: { icon: Plane, geodesic: true },
train: { icon: Train, geodesic: false },
cruise: { icon: Ship, geodesic: true },
car: { icon: Car, geodesic: false },
bus: { icon: Bus, geodesic: false },
taxi: { icon: CarTaxiFront, geodesic: false },
bicycle: { icon: Bike, geodesic: false },
ferry: { icon: Sailboat, geodesic: true },
transit: { icon: TramFront, geodesic: false },
transport_other: { icon: Route, geodesic: false },
}
// ── geometry helpers (shared with ReservationOverlay via flightGeodesy) ──
const toRad = (d: number) => d * Math.PI / 180
function haversineKm(a: [number, number], b: [number, number]): number {
const R = 6371
const dLat = toRad(b[0] - a[0])
const dLng = toRad(b[1] - a[1])
const h = Math.sin(dLat / 2) ** 2 + Math.cos(toRad(a[0])) * Math.cos(toRad(b[0])) * Math.sin(dLng / 2) ** 2
return 2 * R * Math.asin(Math.sqrt(h))
}
function parseInTz(isoLocal: string, tz: string): number {
const [datePart, timePart] = isoLocal.split('T')
const [y, mo, d] = datePart.split('-').map(Number)
const [h, mi] = (timePart || '00:00').split(':').map(Number)
const guess = Date.UTC(y, mo - 1, d, h, mi)
// A malformed date/time (e.g. an imported booking whose time is missing its
// minutes) makes Date.UTC NaN; bail before formatToParts, which throws on a
// non-finite date and would blank the whole trip. computeDuration's finiteness
// check then drops the duration cleanly.
if (!Number.isFinite(guess)) return Number.NaN
const fmt = new Intl.DateTimeFormat('en-US', {
timeZone: tz, hour12: false,
year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit',
})
const parts = Object.fromEntries(fmt.formatToParts(new Date(guess)).filter(p => p.type !== 'literal').map(p => [p.type, p.value]))
const asUtc = Date.UTC(Number(parts.year), Number(parts.month) - 1, Number(parts.day), Number(parts.hour) % 24, Number(parts.minute), Number(parts.second))
return guess - (asUtc - guess)
}
function computeDuration(from: ReservationEndpoint, to: ReservationEndpoint, fallbackStart: string | null, fallbackEnd: string | null): string | null {
let start = from.local_date && from.local_time ? `${from.local_date}T${from.local_time}` : fallbackStart
let end = to.local_date && to.local_time ? `${to.local_date}T${to.local_time}` : fallbackEnd
if (!start || !end) return null
if (!start.includes('T') && end.includes('T')) start = `${end.split('T')[0]}T${start}`
if (!end.includes('T') && start.includes('T')) end = `${start.split('T')[0]}T${end}`
if (!start.includes('T') || !end.includes('T')) return null
const fromTz = from.timezone || to.timezone
const toTz = to.timezone || fromTz
let startMs: number, endMs: number
if (fromTz && toTz) {
startMs = parseInTz(start, fromTz)
endMs = parseInTz(end, toTz)
} else {
startMs = new Date(start).getTime()
endMs = new Date(end).getTime()
}
if (!Number.isFinite(startMs) || !Number.isFinite(endMs)) return null
if (endMs <= startMs) endMs += 24 * 60 * 60000
const minutes = Math.round((endMs - startMs) / 60000)
if (minutes <= 0 || minutes > 48 * 60) return null
const h = Math.floor(minutes / 60)
const m = minutes % 60
return h > 0 ? `${h}h ${m}m` : `${m}m`
}
// ── item building ─────────────────────────────────────────────────────────
interface TransportItem {
res: Reservation
from: ReservationEndpoint
to: ReservationEndpoint
waypoints: ReservationEndpoint[]
type: TransportType
arcs: [number, number][][]
// Route ("VIE → LHR") and duration/distance line. Computed on every update but
// not drawn since the stats badge was dropped; computeDuration still guards the
// non-finite date that used to blank the trip (#1620).
mainLabel: string | null
subLabel: string | null
}
function buildItems(reservations: Reservation[]): TransportItem[] {
const out: TransportItem[] = []
// What each booking draws comes from transportHops. GL maps repeat features
// across world copies themselves, so arcs are not wrapped at the antimeridian.
function buildItems(reservations: Reservation[]): TransportHop[] {
const out: TransportHop[] = []
for (const r of reservations) {
if (!TRANSPORT_TYPES.includes(r.type as TransportType)) continue
// Ordered waypoints (from · stops · to); a single-leg booking has exactly two.
const waypoints = (r.endpoints || [])
.filter(e => e.role === 'from' || e.role === 'to' || e.role === 'stop')
.slice()
.sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0))
if (waypoints.length < 2) continue
const from = waypoints[0]
const to = waypoints[waypoints.length - 1]
const type = r.type as TransportType
const isGeo = TYPE_META[type].geodesic
// One arc per leg (between consecutive waypoints), concatenated.
const arcs: [number, number][][] = []
let distanceKm = 0
for (let i = 0; i < waypoints.length - 1; i++) {
const a = waypoints[i]
const b = waypoints[i + 1]
const segArcs = isGeo
// GL maps repeat features across world copies themselves, so one
// continuous unwrapped arc is enough (a shifted duplicate would
// coincide with the wrapped copy and double the line opacity).
? geodesicArcs([a.lat, a.lng], [b.lat, b.lng], false)
: [[[a.lat, a.lng], [b.lat, b.lng]] as [number, number][]]
arcs.push(...segArcs)
distanceKm += haversineKm([a.lat, a.lng], [b.lat, b.lng])
}
const duration = computeDuration(from, to, r.reservation_time || null, r.reservation_end_time || null)
const distance = `${Math.round(distanceKm)} km`
const mainLabel = waypoints.every(w => w.code)
? waypoints.map(w => w.code).join(' → ')
: (from.code && to.code ? `${from.code} → ${to.code}` : null)
const subParts = [duration, distance].filter(Boolean) as string[]
const subLabel = subParts.length > 0 ? subParts.join(' · ') : null
out.push({ res: r, from, to, waypoints, type, arcs, mainLabel, subLabel })
const hop = transportHop(r, false)
if (hop) out.push(hop)
}
return out
}
// ── DOM helpers for HTML markers ──────────────────────────────────────────
function endpointMarkerHtml(type: TransportType, label: string | null): string {
const { icon: IconCmp } = TYPE_META[type]
const { icon: IconCmp } = TRANSPORT_META[type]
const svg = renderIconMarkup(createElement(IconCmp, { size: 13, color: 'white', strokeWidth: 2.5 }))
const labelHtml = label ? `<span style="display:inline-flex;align-items:center;line-height:1">${escapeHtml(label)}</span>` : ''
return `<div style="
@@ -188,7 +68,7 @@ type MarkerConstructor = new (options?: { element?: HTMLElement; anchor?: string
export class ReservationMapboxOverlay {
private map: mapboxgl.Map
private items: TransportItem[] = []
private items: TransportHop[] = []
private roadRoutes: Map<number, [number, number][]> = new Map()
private opts: ReservationOverlayOptions
private MarkerCtor: MarkerConstructor
@@ -261,7 +141,7 @@ export class ReservationMapboxOverlay {
}
/** What a hop will draw: the road it was routed along when there is one, else its arcs. */
private linesFor(item: TransportItem): [number, number][][] {
private linesFor(item: TransportHop): [number, number][][] {
const road = this.roadRoutes.get(item.res.id)
return road && road.length >= 2 ? [road] : item.arcs
}
@@ -0,0 +1,85 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { calculateRouteWithLegs, RoutingRefusedError } from './RouteCalculator';
import { calculateRouteWithRetries, ROUTE_RETRY_DELAYS_MS } from './routeRetry';
vi.mock('./RouteCalculator', async (importActual) => {
const actual = await importActual<typeof import('./RouteCalculator')>();
return { ...actual, calculateRouteWithLegs: vi.fn() };
});
const WAYPOINTS = [
{ lat: 47.5, lng: 19.04 },
{ lat: 47.49, lng: 19.05 },
];
const ROUTED = {
coordinates: [
[47.5, 19.04],
[47.49, 19.05],
],
legs: [],
} as unknown as Awaited<ReturnType<typeof calculateRouteWithLegs>>;
beforeEach(() => {
vi.useFakeTimers();
vi.mocked(calculateRouteWithLegs).mockReset();
});
afterEach(() => vi.useRealTimers());
describe('calculateRouteWithRetries', () => {
it('waits out a rate limit and answers with the road (Discord, 16.10.2026)', async () => {
vi.mocked(calculateRouteWithLegs)
.mockRejectedValueOnce(new RoutingRefusedError(429, null))
.mockResolvedValueOnce(ROUTED);
const answer = calculateRouteWithRetries(WAYPOINTS, { profile: 'driving' });
await vi.advanceTimersByTimeAsync(ROUTE_RETRY_DELAYS_MS[0]);
await expect(answer).resolves.toBe(ROUTED);
expect(calculateRouteWithLegs).toHaveBeenCalledTimes(2);
});
it('waits as long as the host asks when that is longer', async () => {
vi.mocked(calculateRouteWithLegs)
.mockRejectedValueOnce(new RoutingRefusedError(503, 3000))
.mockResolvedValueOnce(ROUTED);
const answer = calculateRouteWithRetries(WAYPOINTS, {});
await vi.advanceTimersByTimeAsync(ROUTE_RETRY_DELAYS_MS[0]);
expect(calculateRouteWithLegs).toHaveBeenCalledTimes(1);
await vi.advanceTimersByTimeAsync(3000 - ROUTE_RETRY_DELAYS_MS[0]);
await expect(answer).resolves.toBe(ROUTED);
});
it('gives up after the last delay and throws the refusal', async () => {
vi.mocked(calculateRouteWithLegs).mockRejectedValue(new RoutingRefusedError(429, null));
const answer = calculateRouteWithRetries(WAYPOINTS, {});
const settled = expect(answer).rejects.toBeInstanceOf(RoutingRefusedError);
for (const ms of ROUTE_RETRY_DELAYS_MS) await vi.advanceTimersByTimeAsync(ms);
await settled;
expect(calculateRouteWithLegs).toHaveBeenCalledTimes(ROUTE_RETRY_DELAYS_MS.length + 1);
});
it('throws a refusal the host meant at once', async () => {
vi.mocked(calculateRouteWithLegs).mockRejectedValue(new RoutingRefusedError(400, null));
await expect(calculateRouteWithRetries(WAYPOINTS, {})).rejects.toBeInstanceOf(RoutingRefusedError);
expect(calculateRouteWithLegs).toHaveBeenCalledTimes(1);
});
it('stops waiting when the day changes', async () => {
const controller = new AbortController();
vi.mocked(calculateRouteWithLegs)
.mockRejectedValueOnce(new RoutingRefusedError(429, null))
.mockRejectedValueOnce(new DOMException('aborted', 'AbortError'));
const answer = calculateRouteWithRetries(WAYPOINTS, { signal: controller.signal });
const settled = expect(answer).rejects.toMatchObject({ name: 'AbortError' });
await vi.advanceTimersByTimeAsync(10);
controller.abort();
await settled;
});
});
+48
View File
@@ -0,0 +1,48 @@
import { calculateRouteWithLegs, RoutingRefusedError } from './RouteCalculator';
// The profile a caller hands in, so a hook routing through here needs nothing else from Map/.
export type { RouteProfileKey } from './RouteCalculator';
/** How often a rate-limited route is asked for again, and how long after. */
export const ROUTE_RETRY_DELAYS_MS = [1500, 4000];
/** A pause that ends early, without throwing, when the signal aborts. */
export const sleepUnlessAborted = (ms: number, signal?: AbortSignal): Promise<void> =>
new Promise((resolve) => {
if (signal?.aborted || ms <= 0) {
resolve();
return;
}
const timer = setTimeout(done, ms);
function done(): void {
clearTimeout(timer);
signal?.removeEventListener('abort', done);
resolve();
}
signal?.addEventListener('abort', done, { once: true });
});
/**
* `calculateRouteWithLegs`, asked again while the host says it is busy.
*
* The public OSRM hosts allow about one request a second and answer 429 above that. A
* day with a change of mode, or a quick switch between days, asks more often than that,
* and the day route used to give up on the first refusal and keep its straight lines
* until the next edit (reported on Discord, 16.10.2026). A rate limit is waited out, for
* as long as the host asks when it says; a refusal the host meant is thrown at once,
* because the same request earns the same answer. An abort ends the wait, and the next
* attempt then throws the AbortError the caller already handles.
*/
export async function calculateRouteWithRetries(
...[waypoints, opts]: Parameters<typeof calculateRouteWithLegs>
): ReturnType<typeof calculateRouteWithLegs> {
for (let attempt = 0; ; attempt++) {
try {
return await calculateRouteWithLegs(waypoints, opts);
} catch (err) {
const rateLimit = err instanceof RoutingRefusedError && err.isRateLimit ? err : null;
if (!rateLimit || attempt >= ROUTE_RETRY_DELAYS_MS.length || opts?.signal?.aborted) throw err;
await sleepUnlessAborted(Math.max(ROUTE_RETRY_DELAYS_MS[attempt], rateLimit.retryAfterMs ?? 0), opts?.signal);
}
}
}
@@ -0,0 +1,17 @@
// FE-COMP-VIADWELL-001 to FE-COMP-VIADWELL-002: the dwell label both map renderers put on a route via.
import { describe, expect, it } from 'vitest';
import { formatViaDwell } from './routeViaDwell';
describe('formatViaDwell', () => {
it('FE-COMP-VIADWELL-001: under an hour reads as minutes, rounded', () => {
expect(formatViaDwell(0)).toBe('0 min');
expect(formatViaDwell(25 * 60 + 29)).toBe('25 min');
expect(formatViaDwell(25 * 60 + 31)).toBe('26 min');
});
it('FE-COMP-VIADWELL-002: an hour or more splits the hours off', () => {
expect(formatViaDwell(3600)).toBe('1 h 0 min');
expect(formatViaDwell(2 * 3600 + 15 * 60)).toBe('2 h 15 min');
});
});
@@ -0,0 +1,11 @@
/**
* How long a route via (a charging stop, a rest area a plugin route places on
* the drawn day) holds the drive, as both map renderers label it: whole
* minutes, with the hours split off once there are any. One function for both,
* so the Leaflet tooltip and the GL label cannot disagree on the wording.
*/
export function formatViaDwell(seconds: number): string {
const h = Math.floor(seconds / 3600);
const m = Math.round((seconds % 3600) / 60);
return h > 0 ? `${h} h ${m} min` : `${m} min`;
}
+10 -8
View File
@@ -7,16 +7,18 @@
* this because their labels are drawn server-side, which is why it only surfaced
* once the default basemap became a vector style.
*
* Both engines expose the fix as an optional plugin and neither loads it by
* default. Registering is global to the engine, so it happens once per engine
* module rather than at each map's construction site.
* Mapbox GL exposes the fix as an optional plugin and does not load it by
* default. Registering is global to the engine, so it happens once in the engine
* module rather than at each map's construction site. MapLibre needed the same
* plugin up to version 5; since 6.9 it shapes and reorders the text itself, and
* its engine module registers nothing.
*
* The call itself stays with the caller: this is one of the places the two engines
* genuinely differ. MapLibre 5 takes `(url, lazy)` and returns a promise, Mapbox
* GL 3 takes `(url, callback, deferred)` and returns nothing — so each engine
* module passes its own invocation rather than a shared wrapper guessing an arity.
* The call itself stays with the caller: Mapbox GL 3 takes
* `(url, callback, deferred)` and returns nothing, while MapLibre took
* `(url, lazy)` and returned a promise, so the guard below accepts either rather
* than guessing an arity.
*
* Deliberately no getRTLTextPluginStatus() pre-check: reading it makes MapLibre
* Deliberately no getRTLTextPluginStatus() pre-check: reading it made MapLibre
* build its worker pool, which is an eager side effect for a module that is
* imported for its default export, and throws outright under jsdom. Registering
* twice is reported — by a throw or a rejected promise depending on the engine —
@@ -0,0 +1,38 @@
import { describe, expect, it, vi } from 'vitest';
import { isOnTermsBase, tileHealthHandlers, TOUR_RASTER_BASES, tourRasterBaseOf } from './tourRasterBases';
// FE-MAP-TOURBASES-001 to FE-MAP-TOURBASES-003
describe('tourRasterBases (MAP-01, BIK-06)', () => {
it('FE-MAP-TOURBASES-001: knows topo, OpenHikingMap and CyclOSM, CyclOSM on its three shards', () => {
expect(tourRasterBaseOf('topo')).toBe(TOUR_RASTER_BASES.topo);
expect(tourRasterBaseOf('cycle')?.tiles).toEqual([
'https://a.tile-cyclosm.openstreetmap.fr/cyclosm/{z}/{x}/{y}.png',
'https://b.tile-cyclosm.openstreetmap.fr/cyclosm/{z}/{x}/{y}.png',
'https://c.tile-cyclosm.openstreetmap.fr/cyclosm/{z}/{x}/{y}.png',
]);
expect(tourRasterBaseOf('cycle')?.maxZoom).toBe(20);
expect(tourRasterBaseOf('satellite')).toBeNull();
// Inherited names are no base map.
expect(tourRasterBaseOf('toString')).toBeNull();
});
it('FE-MAP-TOURBASES-002: the maps on terms carry their credit; topo is no map on terms', () => {
expect(isOnTermsBase('hiking')).toBe(true);
expect(isOnTermsBase('cycle')).toBe(true);
expect(isOnTermsBase('topo')).toBe(false);
expect(isOnTermsBase('default')).toBe(false);
expect(TOUR_RASTER_BASES.cycle.onTerms?.credit.map((part) => part.href)).toEqual([
'https://www.cyclosm.org',
'https://www.openstreetmap.org/copyright',
]);
expect(TOUR_RASTER_BASES.hiking.onTerms?.credit).toHaveLength(3);
});
it('FE-MAP-TOURBASES-003: a Leaflet layer reports into the health of the map watched, and only of that one', () => {
const health = { base: 'cycle' as const, down: false, onTileError: vi.fn(), onTileLoad: vi.fn() };
expect(tileHealthHandlers(health, 'cycle')).toEqual({ tileerror: health.onTileError, tileload: health.onTileLoad });
expect(tileHealthHandlers(health, 'hiking')).toBeUndefined();
expect(tileHealthHandlers(undefined, 'cycle')).toBeUndefined();
});
});
@@ -0,0 +1,98 @@
import {
CYCLOSM_TILE_ATTRIBUTION,
CYCLOSM_TILE_MAXZOOM,
CYCLOSM_TILE_URL,
OPENHIKINGMAP_TILE_ATTRIBUTION,
OPENHIKINGMAP_TILE_MAXZOOM,
OPENHIKINGMAP_TILE_URL,
OPENTOPOMAP_TILE_ATTRIBUTION,
OPENTOPOMAP_TILE_MAXZOOM,
OPENTOPOMAP_TILE_URL,
} from '../../constants/mapDefaults';
/** The raster base maps only the Tours planner offers, drawn the same way by Leaflet, GL and the 3D map. */
export type TourRasterBase = 'topo' | 'hiking' | 'cycle';
export interface TourRasterBaseSource {
/** The Leaflet template; `{s}` is a shard Leaflet fills in. */
url: string;
/** The same tiles spelled out for a GL source, which knows no shards. */
tiles: string[];
attribution: string;
maxZoom: number;
/**
* A map its operator offers on terms (MAP-01, BIK-06): loaded only as viewed, never
* prefetched or kept offline, its credit readable without a click, and watched for whether it
* answers. `credit` is what the 3D map shows above its controls.
*/
onTerms?: { credit: ReadonlyArray<{ label: string; href: string }> };
}
export const TOUR_RASTER_BASES: Record<TourRasterBase, TourRasterBaseSource> = {
topo: {
url: OPENTOPOMAP_TILE_URL,
tiles: ['a', 'b', 'c'].map((shard) => OPENTOPOMAP_TILE_URL.replace('{s}', shard)),
attribution: OPENTOPOMAP_TILE_ATTRIBUTION,
maxZoom: OPENTOPOMAP_TILE_MAXZOOM,
},
hiking: {
url: OPENHIKINGMAP_TILE_URL,
tiles: [OPENHIKINGMAP_TILE_URL],
attribution: OPENHIKINGMAP_TILE_ATTRIBUTION,
maxZoom: OPENHIKINGMAP_TILE_MAXZOOM,
onTerms: {
credit: [
{ label: '\u00a9 OpenHikingMap', href: 'https://wiki.openstreetmap.org/wiki/OpenHikingMap' },
{ label: '\u00a9 OpenStreetMap', href: 'https://www.openstreetmap.org/copyright' },
{ label: '\u2764\ufe0f Donation', href: 'https://openmaps.fr/donate' },
],
},
},
cycle: {
url: CYCLOSM_TILE_URL,
tiles: ['a', 'b', 'c'].map((shard) => CYCLOSM_TILE_URL.replace('{s}', shard)),
attribution: CYCLOSM_TILE_ATTRIBUTION,
maxZoom: CYCLOSM_TILE_MAXZOOM,
onTerms: {
credit: [
{ label: '\u00a9 CyclOSM', href: 'https://www.cyclosm.org' },
{ label: '\u00a9 OpenStreetMap', href: 'https://www.openstreetmap.org/copyright' },
],
},
},
};
export const TOUR_RASTER_BASE_IDS = Object.keys(TOUR_RASTER_BASES) as TourRasterBase[];
/** The raster source of a base layer, or null for the user's own map and the imagery. */
export function tourRasterBaseOf(layer: string): TourRasterBaseSource | null {
return Object.prototype.hasOwnProperty.call(TOUR_RASTER_BASES, layer)
? TOUR_RASTER_BASES[layer as TourRasterBase]
: null;
}
/** Whether the layer is a map its operator offers on terms (OpenHikingMap, CyclOSM). */
export function isOnTermsBase(layer: string): layer is TourRasterBase {
return !!tourRasterBaseOf(layer)?.onTerms;
}
/**
* Whether a best-effort tile source still answers: a run of failed tiles marks
* it down, one tile arriving clears that. The maps report into it, the switch
* shows it.
*/
export interface TileHealth {
down: boolean;
onTileError: () => void;
onTileLoad: () => void;
}
/** The health of the map on terms that is the base map now, with which one it is. */
export interface BaseMapHealth extends TileHealth {
base: TourRasterBase;
}
/** A Leaflet tile layer's events that report into the health of `layer`, while it is the map watched. */
export function tileHealthHandlers(health: BaseMapHealth | undefined, layer: string) {
return health?.base === layer ? { tileerror: health.onTileError, tileload: health.onTileLoad } : undefined;
}
+3
View File
@@ -1,6 +1,9 @@
import { TRACK_COLOR_FALLBACK } from '@trek/shared'
import type { Place } from '../../types'
/** The light rim under a track that carries a picked colour, and under the track picked on the map. */
export const TRACK_CASING_COLOR = '#ffffff'
/**
* The colour a track's polyline is drawn in (#776): a manually picked colour
* wins, then the category colour, then the blue every imported track used to
@@ -0,0 +1,143 @@
import { describe, expect, it } from 'vitest';
import type { Reservation, ReservationEndpoint } from '../../types';
import { TRANSPORT_META, transportHop } from './transportHops';
function endpoint(over: Partial<ReservationEndpoint>): ReservationEndpoint {
return {
role: 'from',
sequence: 0,
name: 'X',
code: null,
lat: 0,
lng: 0,
timezone: null,
local_time: null,
local_date: null,
...over,
} as ReservationEndpoint;
}
function booking(type: string, endpoints: ReservationEndpoint[], over: Partial<Reservation> = {}): Reservation {
return { id: 7, type, status: 'confirmed', endpoints, ...over } as unknown as Reservation;
}
describe('transportHop', () => {
it('skips a booking that is no transport', () => {
const r = booking('hotel', [endpoint({ role: 'from' }), endpoint({ role: 'to', sequence: 1 })]);
expect(transportHop(r, true)).toBeNull();
});
it('skips a transport with fewer than two places to connect', () => {
expect(transportHop(booking('train', [endpoint({ role: 'from' })]), true)).toBeNull();
expect(
transportHop(booking('train', [endpoint({ role: 'from' }), endpoint({ role: 'check_in' as never })]), true)
).toBeNull();
});
it('orders from, stops and to by sequence and draws one straight leg each for ground transport', () => {
const r = booking('train', [
endpoint({ role: 'to', sequence: 2, code: 'HND', lat: 3, lng: 3 }),
endpoint({ role: 'from', sequence: 0, code: 'FRA', lat: 1, lng: 1 }),
endpoint({ role: 'stop', sequence: 1, code: 'BER', lat: 2, lng: 2 }),
]);
const hop = transportHop(r, true)!;
expect(hop.waypoints.map((w) => w.code)).toEqual(['FRA', 'BER', 'HND']);
expect(hop.from.code).toBe('FRA');
expect(hop.to.code).toBe('HND');
expect(hop.arcs).toEqual([
[
[1, 1],
[2, 2],
],
[
[2, 2],
[3, 3],
],
]);
expect(hop.mainLabel).toBe('FRA → BER → HND');
expect(hop.res).toBe(r);
expect(hop.type).toBe('train');
});
it('falls back to the two end codes when a stop has none, and to no label without them', () => {
const withEnds = booking('bus', [
endpoint({ role: 'from', code: 'A' }),
endpoint({ role: 'stop', sequence: 1 }),
endpoint({ role: 'to', sequence: 2, code: 'B' }),
]);
expect(transportHop(withEnds, true)!.mainLabel).toBe('A → B');
const bare = booking('bus', [endpoint({ role: 'from' }), endpoint({ role: 'to', sequence: 1 })]);
expect(transportHop(bare, true)!.mainLabel).toBeNull();
});
it('puts duration and great-circle distance in the sub label', () => {
const r = booking('car', [
endpoint({ role: 'from', lat: 0, lng: 0, local_date: '2026-05-01', local_time: '08:00' }),
endpoint({ role: 'to', sequence: 1, lat: 0, lng: 1, local_date: '2026-05-01', local_time: '09:30' }),
]);
expect(transportHop(r, true)!.subLabel).toBe('1h 30m · 111 km');
});
it('copies a flight arc across the antimeridian only when asked to wrap', () => {
const r = booking('flight', [
endpoint({ role: 'from', lat: 35, lng: 170 }),
endpoint({ role: 'to', sequence: 1, lat: 40, lng: -170 }),
]);
expect(transportHop(r, true)!.arcs).toHaveLength(2);
expect(transportHop(r, false)!.arcs).toHaveLength(1);
expect(transportHop(r, false)!.arcs[0].length).toBeGreaterThan(2);
});
it('draws ferries and cruises as arcs but a cable car as a straight line', () => {
expect(TRANSPORT_META.ferry.geodesic).toBe(true);
expect(TRANSPORT_META.cruise.geodesic).toBe(true);
expect(TRANSPORT_META.cable_car.geodesic).toBe(false);
});
});
describe('transportHop duration', () => {
// Both ends sit on the same spot, so the sub label is the duration plus "0 km".
const at = (date: string | null, time: string | null, timezone: string | null = null) =>
endpoint({ local_date: date, local_time: time, timezone });
const subLabel = (
from: ReservationEndpoint,
to: ReservationEndpoint,
start: string | null = null,
end: string | null = null
) =>
transportHop(
booking(
'train',
[
{ ...from, role: 'from' },
{ ...to, role: 'to', sequence: 1 },
],
{
reservation_time: start,
reservation_end_time: end,
}
),
true
)!.subLabel;
it('reads each end in its own time zone', () => {
expect(subLabel(at('2026-05-01', '10:00', 'Europe/Berlin'), at('2026-05-01', '10:00', 'Europe/London'))).toBe(
'1h 0m · 0 km'
);
});
it('rolls an arrival before the departure over to the next day', () => {
expect(subLabel(at('2026-05-01', '23:30'), at('2026-05-01', '00:15'))).toBe('45m · 0 km');
});
it('borrows the date of the other end for a bare time from the booking', () => {
expect(subLabel(at(null, null), at('2026-05-01', '12:00'), '11:00')).toBe('1h 0m · 0 km');
});
it('leaves the duration out for missing, malformed or implausible times', () => {
expect(subLabel(at(null, null), at(null, null))).toBe('0 km');
expect(subLabel(at(null, null), at(null, null), '10:00', '11:00')).toBe('0 km');
expect(subLabel(at('2026-05-01', '10', 'Europe/Berlin'), at('2026-05-01', '11:00', 'Europe/Berlin'))).toBe('0 km');
expect(subLabel(at('2026-05-01', '10:00'), at('2026-05-04', '10:00'))).toBe('0 km');
});
});
+188
View File
@@ -0,0 +1,188 @@
// What a transport booking draws on the map, worked out once for both renderers.
//
// ReservationOverlay (Leaflet) and reservationsMapbox (GL) used to carry their own
// copy of this: which booking types count, the great-circle arcs per leg and the
// route/duration labels. The drawing itself stays in each renderer.
import { Bike, Bus, CableCar, Car, CarTaxiFront, Plane, Route, Sailboat, Ship, Train, TramFront } from 'lucide-react';
import type { Reservation, ReservationEndpoint } from '../../types';
import { haversineKm } from '../../utils/geo';
import { geodesicArcs } from './flightGeodesy';
export type TransportType =
| 'flight'
| 'train'
| 'cruise'
| 'car'
| 'bus'
| 'taxi'
| 'bicycle'
| 'ferry'
| 'cable_car'
| 'transit'
| 'transport_other';
const TRANSPORT_TYPES: TransportType[] = [
'flight',
'train',
'cruise',
'car',
'bus',
'taxi',
'bicycle',
'ferry',
'cable_car',
'transit',
'transport_other',
];
export const TRANSPORT_COLOR = '#3b82f6';
export const TRANSPORT_META: Record<TransportType, { icon: typeof Plane; geodesic: boolean }> = {
flight: { icon: Plane, geodesic: true },
train: { icon: Train, geodesic: false },
cruise: { icon: Ship, geodesic: true },
car: { icon: Car, geodesic: false },
bus: { icon: Bus, geodesic: false },
taxi: { icon: CarTaxiFront, geodesic: false },
bicycle: { icon: Bike, geodesic: false },
ferry: { icon: Sailboat, geodesic: true },
// Valley to mountain station as the rope runs: a straight line, never a road (#2535).
cable_car: { icon: CableCar, geodesic: false },
transit: { icon: TramFront, geodesic: false },
transport_other: { icon: Route, geodesic: false },
};
function parseInTz(isoLocal: string, tz: string): number {
const [datePart, timePart] = isoLocal.split('T');
const [y, mo, d] = datePart.split('-').map(Number);
const [h, mi] = (timePart || '00:00').split(':').map(Number);
const guess = Date.UTC(y, mo - 1, d, h, mi);
// A malformed date/time (e.g. an imported booking whose time is missing its
// minutes) makes Date.UTC NaN; bail before formatToParts, which throws on a
// non-finite date and would blank the whole trip. computeDuration's finiteness
// check then drops the duration cleanly.
if (!Number.isFinite(guess)) return Number.NaN;
const fmt = new Intl.DateTimeFormat('en-US', {
timeZone: tz,
hour12: false,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
});
const parts = Object.fromEntries(
fmt
.formatToParts(new Date(guess))
.filter((p) => p.type !== 'literal')
.map((p) => [p.type, p.value])
);
const asUtc = Date.UTC(
Number(parts.year),
Number(parts.month) - 1,
Number(parts.day),
Number(parts.hour) % 24,
Number(parts.minute),
Number(parts.second)
);
return guess - (asUtc - guess);
}
/** "2h 5m" between the two ends, read in their own time zones; null when it cannot be told. */
function computeDuration(
from: ReservationEndpoint,
to: ReservationEndpoint,
fallbackStart: string | null,
fallbackEnd: string | null
): string | null {
let start = from.local_date && from.local_time ? `${from.local_date}T${from.local_time}` : fallbackStart;
let end = to.local_date && to.local_time ? `${to.local_date}T${to.local_time}` : fallbackEnd;
if (!start || !end) return null;
if (!start.includes('T') && end.includes('T')) start = `${end.split('T')[0]}T${start}`;
if (!end.includes('T') && start.includes('T')) end = `${start.split('T')[0]}T${end}`;
if (!start.includes('T') || !end.includes('T')) return null;
const fromTz = from.timezone || to.timezone;
const toTz = to.timezone || fromTz;
let startMs: number, endMs: number;
if (fromTz && toTz) {
startMs = parseInTz(start, fromTz);
endMs = parseInTz(end, toTz);
} else {
startMs = new Date(start).getTime();
endMs = new Date(end).getTime();
}
if (!Number.isFinite(startMs) || !Number.isFinite(endMs)) return null;
if (endMs <= startMs) endMs += 24 * 60 * 60000;
const minutes = Math.round((endMs - startMs) / 60000);
if (minutes <= 0 || minutes > 48 * 60) return null;
const h = Math.floor(minutes / 60);
const m = minutes % 60;
return h > 0 ? `${h}h ${m}m` : `${m}m`;
}
export interface TransportHop {
res: Reservation;
from: ReservationEndpoint;
to: ReservationEndpoint;
waypoints: ReservationEndpoint[];
type: TransportType;
arcs: [number, number][][];
// Route ("VIE → LHR") and duration/distance line. Computed on every update but
// not drawn since the stats badge was dropped; computeDuration still guards the
// non-finite date that used to blank the trip (#1620).
mainLabel: string | null;
subLabel: string | null;
}
/**
* The hop a booking draws, or null when it is no transport or has fewer than two
* places to connect. wrapArcs says whether a great-circle arc that crosses the
* antimeridian also gets a copy shifted by 360 degrees: Leaflet needs that, while a
* GL map repeats features across world copies itself, so there one continuous arc
* is enough (a shifted duplicate would sit on the wrapped copy and double the opacity).
*/
export function transportHop(r: Reservation, wrapArcs: boolean): TransportHop | null {
if (!TRANSPORT_TYPES.includes(r.type as TransportType)) return null;
// Ordered waypoints (from · stops · to). A single-leg booking has exactly two.
const waypoints = (r.endpoints || [])
.filter((e) => e.role === 'from' || e.role === 'to' || e.role === 'stop')
.slice()
.sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0));
if (waypoints.length < 2) return null;
const from = waypoints[0];
const to = waypoints[waypoints.length - 1];
const type = r.type as TransportType;
const isGeo = TRANSPORT_META[type].geodesic;
// One arc per leg (between consecutive waypoints), concatenated.
const arcs: [number, number][][] = [];
let distanceKm = 0;
for (let i = 0; i < waypoints.length - 1; i++) {
const a = waypoints[i];
const b = waypoints[i + 1];
const segArcs = isGeo
? geodesicArcs([a.lat, a.lng], [b.lat, b.lng], wrapArcs)
: [
[
[a.lat, a.lng],
[b.lat, b.lng],
] as [number, number][],
];
arcs.push(...segArcs);
distanceKm += haversineKm(a, b);
}
const duration = computeDuration(from, to, r.reservation_time || null, r.reservation_end_time || null);
const distance = `${Math.round(distanceKm)} km`;
// Show the full route (FRA → BER → HND) when every waypoint has a code.
const mainLabel = waypoints.every((w) => w.code)
? waypoints.map((w) => w.code).join(' → ')
: from.code && to.code
? `${from.code} → ${to.code}`
: null;
const subParts = [duration, distance].filter(Boolean) as string[];
const subLabel = subParts.length > 0 ? subParts.join(' · ') : null;
return { res: r, from, to, waypoints, type, arcs, mainLabel, subLabel };
}
@@ -232,4 +232,26 @@ describe('tripRouteGeometry', () => {
const byRoad = planTripRoute({ ...moving, reservations: [] }, 'driving')
expect(byRoad.map(d => d.day.id)).toEqual([2])
})
it('FE-MAP-TRG-013: a road picked in the road trip bends the overview and still counts as one leg (#2580)', async () => {
// A lodging row hides in the plan but counts in the stored list, so the via behind
// the first stop of day 1 is filed at 1.
const hotel = buildAssignment({ day_id: 1, order_index: -1, accommodation_id: 3, place: buildPlace({ lat: 48.8, lng: 2.3 }) })
const storedAssignments = { ...ASSIGNMENTS, '1': [hotel, ...ASSIGNMENTS['1']] }
const viasByDay = { 1: [{ id: 1, day_id: 1, after_order_index: 1, sequence: 0, lat: 48.95, lng: 2.6, created_at: '' }] }
vi.mocked(calculateRouteWithLegs).mockImplementation(async (points) => ({
coordinates: points.map(p => [p.lat, p.lng] as [number, number]),
distance: 0, duration: 0,
legs: points.slice(1).map(() => leg(10000)),
}))
const plan = planTripRoute({ ...input, storedAssignments, viasByDay }, 'driving')
expect(plan[0].runs[0][0].waypoints.map(p => p.lat)).toEqual([48.86, 48.95, 48.90])
expect(plan[1].runs[0][0].waypoints.map(p => p.lat)).toEqual([45.76, 45.80])
const summary = await routeTrip({ ...input, storedAssignments, viasByDay }, { profile: 'driving', tripId: 7, unit: 'metric' })
expect(summary.days[0].segments).toHaveLength(1)
expect(summary.days[0].distance).toBe(20000)
expect(summary.days[1].distance).toBe(10000)
})
})
+59 -50
View File
@@ -1,8 +1,12 @@
import { calculateRouteWithLegs, RoutingRefusedError, type RouteProfileKey } from './RouteCalculator'
import type { RouteProfileKey } from './RouteCalculator'
import { calculateRouteWithRetries, sleepUnlessAborted as sleep } from './routeRetry'
import { buildDayRouteRuns, type DayRouteInputs, type DayRoutePoint } from './dayRoutePlan'
import { dayViaLookup, foldViaLegs, threadVias, viasOnDayLeg, type DayViaLookup } from '../../utils/dayRouteVias'
import { projectDayItinerary } from './dayTourProjection'
import { resolveLegMode } from '../Planner/legMode'
import { dayColor } from '../Roadtrip/dayColors'
import type { Day, RouteSegment } from '../../types'
import type { RoadtripVia } from '@trek/shared'
import type { AssignmentsMap, Day, DistanceUnit, RouteSegment } from '../../types'
/** One travel day of the overview: the roads it covers, in its own colour. */
export interface TripOverviewDay {
@@ -15,6 +19,8 @@ export interface TripOverviewDay {
color: { line: string; casing: string }
/** One polyline per run of the day, `[lat, lng]`. */
lines: [number, number][][]
/** Saved Tours are not routed legs and keep their own map style. */
tourLines?: [number, number][][]
segments: RouteSegment[]
/** Metres and seconds, summed over the day's legs. */
distance: number
@@ -45,11 +51,19 @@ export interface TripRouteSummary {
}
/** Neighbouring legs of one run that resolve to the same mode travel as one request,
* exactly as the single-day route builds them. */
interface Chunk { points: DayRoutePoint[]; mode: string }
* exactly as the single-day route builds them. `waypoints` are the points with the road
* trip's vias threaded in, and `stopAt` says which waypoint each point became. */
interface Chunk { points: DayRoutePoint[]; mode: string; waypoints: { lat: number; lng: number }[]; stopAt: number[] }
/** The day inputs plus the road trip's vias, which bend a day the way it was picked there (#2580). */
interface TripRouteInputs extends DayRouteInputs {
/** The stored day lists the vias are anchored in, hidden rows included. Absent: `assignments`. */
storedAssignments?: AssignmentsMap
viasByDay?: Record<number, readonly RoadtripVia[]>
}
/** A day reduced to the routing requests it needs, in the order they draw. */
export interface TripRoutePlanDay { day: Day; runs: Chunk[][] }
export interface TripRoutePlanDay { day: Day; runs: Chunk[][]; tourLines?: [number, number][][] }
type Answer = { coordinates: [number, number][]; legs: RouteSegment[] } | null
/** Every leg's answer so far, indexed like the plan: day, run, chunk. */
@@ -59,14 +73,16 @@ export type TripRouteAnswers = Answer[][][]
export const dayRouteColor = (day: Day): { line: string; casing: string } =>
dayColor(day.day_number ?? 0)
function chunkRun(run: DayRoutePoint[], dayDefaultMode: string): Chunk[] {
function chunkRun(run: DayRoutePoint[], dayDefaultMode: string, dayId: number, viaLookup: DayViaLookup | null): Chunk[] {
const chunks: Chunk[] = []
let i = 0
while (i < run.length - 1) {
const mode = resolveLegMode(run[i], run[i + 1], dayDefaultMode)
let end = i + 1
while (end < run.length - 1 && resolveLegMode(run[end], run[end + 1], dayDefaultMode) === mode) end++
chunks.push({ points: run.slice(i, end + 1), mode })
const points = run.slice(i, end + 1)
const { waypoints, stopAt } = threadVias(points, (from, to) => viasOnDayLeg(viaLookup, dayId, mode, from, to))
chunks.push({ points, mode, waypoints, stopAt })
i = end
}
return chunks
@@ -80,14 +96,25 @@ const straight = (points: DayRoutePoint[]): [number, number][] => points.map(p =
* Pure and synchronous, so a caller can compare two plans (the map keys its routing
* round on one) before spending a single request.
*/
export function planTripRoute(input: DayRouteInputs, profile: RouteProfileKey): TripRoutePlanDay[] {
export function planTripRoute(input: TripRouteInputs, profile: RouteProfileKey): TripRoutePlanDay[] {
const viaLookup = dayViaLookup(input.storedAssignments ?? input.assignments, input.viasByDay)
return [...input.days]
.sort((a, b) => (a.day_number ?? 0) - (b.day_number ?? 0))
.map(day => ({ day, runs: buildDayRouteRuns(day.id, input) }))
.filter(entry => entry.runs.length > 0)
.map(({ day, runs }) => ({
.map(day => ({
day,
runs: runs.map(run => chunkRun(run, day.default_transport_mode || profile)),
runs: buildDayRouteRuns(day.id, input),
tourLines: projectDayItinerary(
(input.assignments[String(day.id)] ?? []).filter(assignment => assignment.accommodation_id == null),
input.toursEnabled ?? false,
input.places,
input.tourStageStops,
).flatMap(item => item.kind === 'tour' && item.geometry.length >= 2 ? [item.geometry] : []),
}))
.filter(entry => entry.runs.length > 0 || entry.tourLines.length > 0)
.map(({ day, runs, tourLines }) => ({
day,
runs: runs.map(run => chunkRun(run, day.default_transport_mode || profile, day.id, viaLookup)),
tourLines,
}))
}
@@ -97,7 +124,7 @@ export const emptyAnswers = (plan: TripRoutePlanDay[]): Answer[][][] =>
/** Stitch the routed answers back onto the plan, in the order the days are travelled. */
export function assembleTripRoute(plan: TripRoutePlanDay[], routed: Answer[][][]): TripOverviewDay[] {
return plan.map(({ day, runs }, d) => {
return plan.map(({ day, runs, tourLines }, d) => {
const lines: [number, number][][] = []
const segments: RouteSegment[] = []
let unroutedLegs = 0
@@ -127,6 +154,7 @@ export function assembleTripRoute(plan: TripRoutePlanDay[], routed: Answer[][][]
title: day.title ?? null,
color: dayRouteColor(day),
lines,
tourLines,
segments,
distance: segments.reduce((sum, s) => sum + s.distance, 0),
duration: segments.reduce((sum, s) => sum + s.duration, 0),
@@ -143,7 +171,7 @@ export function summariseTripRoute(days: TripOverviewDay[]): TripRouteSummary {
lines,
lineColors: days.flatMap(d => d.lines.map(() => d.color)),
segments: days.flatMap(d => d.segments),
focusPoints: lines.flat(),
focusPoints: [...lines.flat(), ...days.flatMap(day => (day.tourLines ?? []).flat())],
totalDistance: days.reduce((sum, d) => sum + d.distance, 0),
totalDuration: days.reduce((sum, d) => sum + d.duration, 0),
unroutedLegs: days.reduce((sum, d) => sum + (d.unroutedLegs ?? 0), 0),
@@ -159,20 +187,6 @@ export function summariseTripRoute(days: TripOverviewDay[]): TripRouteSummary {
const REQUEST_SPACING_MS = 1100
/** Anything answered faster than this came out of RouteCalculator's cache, not the network. */
const CACHE_HIT_MS = 60
/** How often a rate-limited leg is tried again, and how long after. */
const RETRY_DELAYS_MS = [1500, 4000]
const sleep = (ms: number, signal?: AbortSignal): Promise<void> =>
new Promise(resolve => {
if (signal?.aborted || ms <= 0) { resolve(); return }
const timer = setTimeout(done, ms)
function done(): void {
clearTimeout(timer)
signal?.removeEventListener('abort', done)
resolve()
}
signal?.addEventListener('abort', done, { once: true })
})
/**
* Ask the router for every leg of every day, one at a time.
@@ -192,9 +206,11 @@ const sleep = (ms: number, signal?: AbortSignal): Promise<void> =>
*/
export async function routeTripLegs(
plan: TripRoutePlanDay[],
{ tripId, signal, onAnswer }: {
{ tripId, signal, onAnswer, unit }: {
tripId: number | null
signal?: AbortSignal
/** The unit a leg bent through vias has its text written again in. */
unit?: DistanceUnit
/** Called after each answer, for a caller that wants to draw as they arrive. */
onAnswer?: (routed: Answer[][][]) => void
},
@@ -205,24 +221,16 @@ export async function routeTripLegs(
runs.forEach((chunks, r) => {
chunks.forEach((chunk, c) => {
tasks.push(async () => {
const waypoints = chunk.points.map(p => ({ lat: p.lat, lng: p.lng }))
for (let attempt = 0; attempt <= RETRY_DELAYS_MS.length; attempt++) {
if (signal?.aborted) return
try {
const answer = await calculateRouteWithLegs(
waypoints,
{ signal, profile: chunk.mode, tripId, dayId: day.id },
)
routed[d][r][c] = { coordinates: answer.coordinates, legs: answer.legs }
onAnswer?.(routed)
return
} catch (err) {
if (signal?.aborted) return
const rateLimit = err instanceof RoutingRefusedError && err.isRateLimit ? err : null
if (!rateLimit || attempt === RETRY_DELAYS_MS.length) return
// When the host says how long to wait, waiting less is just a second refusal.
await sleep(Math.max(RETRY_DELAYS_MS[attempt], rateLimit.retryAfterMs ?? 0), signal)
}
if (signal?.aborted) return
try {
const answer = await calculateRouteWithRetries(
chunk.waypoints,
{ signal, profile: chunk.mode, tripId, dayId: day.id },
)
routed[d][r][c] = { coordinates: answer.coordinates, legs: foldViaLegs(answer.legs, chunk.stopAt, unit) }
onAnswer?.(routed)
} catch {
// Refused for good, or aborted: the leg keeps its straight line.
}
})
})
@@ -248,12 +256,13 @@ export async function routeTripLegs(
* requests against a shared router, and no document is worth that wait.
*/
export async function routeTrip(
input: DayRouteInputs,
{ profile, tripId, signal, timeoutMs }: {
input: TripRouteInputs,
{ profile, tripId, signal, timeoutMs, unit }: {
profile: RouteProfileKey
tripId: number | null
signal?: AbortSignal
timeoutMs?: number
unit?: DistanceUnit
},
): Promise<TripRouteSummary> {
const plan = planTripRoute(input, profile)
@@ -262,7 +271,7 @@ export async function routeTrip(
const timer = deadline ? setTimeout(() => deadline.abort(), timeoutMs) : null
if (deadline && signal) signal.addEventListener('abort', () => deadline.abort(), { once: true })
try {
const routed = await routeTripLegs(plan, { tripId, signal: deadline?.signal ?? signal })
const routed = await routeTripLegs(plan, { tripId, signal: deadline?.signal ?? signal, unit })
return summariseTripRoute(assembleTripRoute(plan, routed))
} finally {
if (timer) clearTimeout(timer)
@@ -0,0 +1,90 @@
// FE-MAP-CAMERA-GL-001 to 003: the GL map moves where the assistant asks, on the same rules as the Leaflet map.
import { renderHook } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { MAX_ZOOM_GL } from '../../utils/mapViewport';
import type { AssistantCamera } from './mapViewContract';
import { useAssistantCameraGL } from './useAssistantCameraGL';
const PADDING = { top: 60, right: 40, bottom: 60, left: 40 };
class Bounds {
points: [number, number][] = [];
extend(lngLat: [number, number]) {
this.points.push(lngLat);
}
}
function camera(key: string, over: Partial<AssistantCamera> = {}): AssistantCamera {
return {
key,
points: [
[41, 12],
[43, 13],
],
mode: 'fit',
animate: true,
auto: false,
...over,
};
}
function setup(first: AssistantCamera | null, inside = false) {
const container = document.createElement('div');
const map = {
getCanvasContainer: () => container,
getBounds: () => ({ contains: () => inside }),
fitBounds: vi.fn(),
easeTo: vi.fn(),
};
const mapRef = { current: map };
const gl = { LngLatBounds: Bounds };
const hook = renderHook(
({ cam }) => useAssistantCameraGL({ mapRef, mapReady: true, gl, camera: cam, padding: PADDING }),
{ initialProps: { cam: first } }
);
return { map, container, hook };
}
afterEach(() => vi.useRealTimers());
describe('useAssistantCameraGL', () => {
it('FE-MAP-CAMERA-GL-001: the request present at mount is skipped; a new one frames its points around the window', () => {
const { map, hook } = setup(camera('1'));
expect(map.fitBounds).not.toHaveBeenCalled();
hook.rerender({ cam: camera('2', { cover: { side: 'right', px: 420 }, animate: false }) });
expect(map.fitBounds).toHaveBeenCalledOnce();
const [bounds, options] = map.fitBounds.mock.calls[0] ?? [];
expect((bounds as Bounds).points).toEqual([
[12, 41],
[13, 43],
]);
expect(options).toEqual({ padding: { ...PADDING, right: 420 }, maxZoom: MAX_ZOOM_GL, duration: 0 });
hook.rerender({ cam: camera('2', { cover: null }) });
expect(map.fitBounds).toHaveBeenCalledOnce();
});
it('FE-MAP-CAMERA-GL-002: a pan moves only when the centre is out of view', () => {
const inside = setup(null, true);
inside.hook.rerender({ cam: camera('1', { mode: 'pan' }) });
expect(inside.map.easeTo).not.toHaveBeenCalled();
const outside = setup(null, false);
outside.hook.rerender({ cam: camera('1', { mode: 'pan' }) });
expect(outside.map.easeTo).toHaveBeenCalledWith({ center: [12.5, 42], duration: 600 });
});
it('FE-MAP-CAMERA-GL-003: a move nobody asked for waits while the user is moving the map', () => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-10-21T08:00:00Z'));
const { map, container, hook } = setup(null);
container.dispatchEvent(new Event('pointerdown'));
hook.rerender({ cam: camera('1', { auto: true }) });
expect(map.fitBounds).not.toHaveBeenCalled();
vi.setSystemTime(new Date('2026-10-21T08:00:06Z'));
hook.rerender({ cam: camera('2', { auto: true }) });
expect(map.fitBounds).toHaveBeenCalledOnce();
});
});
@@ -0,0 +1,55 @@
import { useCallback, useEffect } from 'react';
import { MAX_ZOOM_GL, type ViewportPadding } from '../../utils/mapViewport';
import { ASSISTANT_CAMERA_MS, centreOf, coverPadding, useCameraRequest, useUserMoveClock } from './assistantCamera';
import type { AssistantCamera } from './mapViewContract';
/** The slice of the GL map the camera drives. */
export interface CameraMap {
/** Where the user drags, wheels and pinches the map; marker clicks are not moves. */
getCanvasContainer: () => HTMLElement;
getBounds: () => { contains: (lngLat: [number, number]) => boolean } | null;
fitBounds: (bounds: unknown, options: { padding: ViewportPadding; maxZoom: number; duration: number }) => unknown;
easeTo: (options: { center: [number, number]; duration: number }) => unknown;
}
/** The engine's bounds class, handed in so this module never imports mapbox-gl or maplibre-gl itself. */
export interface CameraEngine {
LngLatBounds: new () => { extend: (lngLat: [number, number]) => unknown };
}
interface AssistantCameraOptions {
mapRef: { readonly current: CameraMap | null };
mapReady: boolean;
gl: CameraEngine;
camera: AssistantCamera | null | undefined;
/** The planner's padding for its panels, in pixels per edge. */
padding: ViewportPadding;
}
/**
* Moves the GL map where the assistant asks, the twin of the Leaflet
* AssistantCameraController: `fit` frames the points, `pan` eases to their
* centre only when it is outside the view. It stops at the same scale as the
* Leaflet map (one GL zoom step is a raster step lower).
*/
export function useAssistantCameraGL({ mapRef, mapReady, gl, camera, padding }: AssistantCameraOptions): void {
const getContainer = useCallback(() => mapRef.current?.getCanvasContainer() ?? null, [mapRef]);
const userMovedAt = useUserMoveClock(getContainer, mapReady);
const request = useCameraRequest(camera, userMovedAt);
useEffect(() => {
const map = mapRef.current;
if (!map || !mapReady) return;
request((next) => {
const duration = next.animate ? ASSISTANT_CAMERA_MS : 0;
if (next.mode === 'pan') {
const [lat, lng] = centreOf(next.points);
if (!map.getBounds()?.contains([lng, lat])) map.easeTo({ center: [lng, lat], duration });
return;
}
const bounds = new gl.LngLatBounds();
next.points.forEach(([lat, lng]) => bounds.extend([lng, lat]));
map.fitBounds(bounds, { padding: coverPadding(padding, next.cover), maxZoom: MAX_ZOOM_GL, duration });
});
}, [gl, mapReady, mapRef, padding, request]);
}
@@ -0,0 +1,218 @@
/**
* FE-MAP-ROUTE-GL-001 to FE-MAP-ROUTE-GL-005
*
* The chat's routes on the GL map, the twin of the Leaflet layer: one
* GeoJSON source (lines with their rims and dashes, grades, ends, the lit
* line's stops) added the first time there is a route and again after a
* basemap rebuilds the style (never into a style still loading), and the
* invisible line reporting the pointer, except where a place pin or a
* cluster bubble over it takes the pointer.
*/
import { renderHook } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import type { AssistantRouteLine } from '../../types/assistantMap';
import {
type LineMap,
ROUTE_LINE_LAYERS,
routeLineFeatures,
useAssistantGhostLinesGL,
} from './useAssistantGhostLinesGL';
const LINE: AssistantRouteLine = {
id: 'c1:look:route',
ref: 'c1',
lines: [
[
[47.77, 12.59],
[47.79, 12.62],
],
],
color: '#0a84ff',
casing: '#ffffff',
ends: { start: [47.77, 12.59], end: [47.79, 12.62] },
stops: [{ lat: 47.78, lng: 12.6, label: 'Strausshütte' }],
tints: [
{
line: [
[47.78, 12.6],
[47.79, 12.62],
],
color: '#7c3aed',
},
],
};
type Listener = (event?: unknown) => void;
/** A stand-in GL map that keeps its sources, layers and listeners, and can rebuild its style. */
function fakeMap() {
const container = document.createElement('div');
document.body.appendChild(container);
const sources = new Map<string, { data: unknown; setData: (data: unknown) => void }>();
const layers: string[] = [];
const listeners: { type: string; layer: string | null; fn: Listener }[] = [];
const map = {
getSource: vi.fn((id: string) => sources.get(id)),
addSource: vi.fn((id: string, source: { data: unknown }) => {
const entry = {
data: source.data,
setData: (data: unknown) => {
entry.data = data;
},
};
sources.set(id, entry);
}),
addLayer: vi.fn((layer: { id: string }) => layers.push(layer.id)),
getLayer: vi.fn((): unknown => undefined),
isStyleLoaded: vi.fn(() => true),
queryRenderedFeatures: vi.fn((): unknown[] => []),
getContainer: () => container,
on: vi.fn((type: string, layerOrFn: string | Listener, fn?: Listener) => {
if (typeof layerOrFn === 'function') listeners.push({ type, layer: null, fn: layerOrFn });
else if (fn) listeners.push({ type, layer: layerOrFn, fn });
}),
off: vi.fn((type: string, layerOrFn: string | Listener, fn?: Listener) => {
const target = typeof layerOrFn === 'function' ? layerOrFn : fn;
const index = listeners.findIndex((l) => l.type === type && l.fn === target);
if (index >= 0) listeners.splice(index, 1);
}),
};
const fire = (type: string, layer: string | null, event?: unknown) =>
listeners.filter((l) => l.type === type && l.layer === layer).forEach((l) => l.fn(event));
const restyle = () => {
sources.clear();
layers.length = 0;
fire('styledata', null);
};
const data = () => sources.get('assistant-route-lines')?.data as ReturnType<typeof routeLineFeatures> | undefined;
return { map, container, layers, listeners, fire, restyle, data };
}
function mount(fake: ReturnType<typeof fakeMap>, lines: AssistantRouteLine[], handlers = {}) {
const mapRef = { current: fake.map as unknown as LineMap };
return renderHook(
(props: { lines: AssistantRouteLine[] }) =>
useAssistantGhostLinesGL({ mapRef, mapReady: true, lines: props.lines, ...handlers }),
{ initialProps: { lines } }
);
}
describe('useAssistantGhostLinesGL', () => {
it('FE-MAP-ROUTE-GL-001: a route is its line, its grade and its ends, in GeoJSON order; its stops only while lit', () => {
const calm = routeLineFeatures([{ ...LINE, dim: true, dashed: true }]);
expect(calm.features.map((f) => f.properties.kind)).toEqual(['line', 'tint', 'end', 'end']);
expect(calm.features[0]?.properties).toMatchObject({ ref: 'c1', dashed: true, hot: false, opacity: 0.45 });
expect(calm.features[0]?.geometry).toEqual({
type: 'MultiLineString',
coordinates: [
[
[12.59, 47.77],
[12.62, 47.79],
],
],
});
expect(calm.features[3]?.properties).toMatchObject({ fill: '#ffffff', stroke: '#0a84ff', strokeWidth: 3 });
const lit = routeLineFeatures([{ ...LINE, hot: true }]);
expect(lit.features[lit.features.length - 1]).toMatchObject({
properties: { kind: 'stop', label: 'Strausshütte' },
geometry: { type: 'Point', coordinates: [12.6, 47.78] },
});
});
it('FE-MAP-ROUTE-GL-002: nothing is added before a route; then one source and its layers, new data on change, back after a restyle', () => {
const fake = fakeMap();
const hook = mount(fake, []);
expect(fake.map.addSource).not.toHaveBeenCalled();
hook.rerender({ lines: [LINE] });
expect(fake.map.addSource).toHaveBeenCalledTimes(1);
expect(fake.layers).toEqual([
ROUTE_LINE_LAYERS.casing,
ROUTE_LINE_LAYERS.line,
ROUTE_LINE_LAYERS.dashed,
ROUTE_LINE_LAYERS.tint,
ROUTE_LINE_LAYERS.ends,
ROUTE_LINE_LAYERS.stops,
ROUTE_LINE_LAYERS.hit,
]);
expect(fake.data()?.features).toHaveLength(4);
hook.rerender({ lines: [{ ...LINE, hot: true }] });
expect(fake.map.addSource).toHaveBeenCalledTimes(1);
expect(fake.data()?.features).toHaveLength(5);
fake.restyle();
expect(fake.map.addSource).toHaveBeenCalledTimes(2);
expect(fake.data()?.features).toHaveLength(5);
hook.rerender({ lines: [] });
expect(fake.data()?.features).toHaveLength(0);
});
it("FE-MAP-ROUTE-GL-003: the pointer onto, along and off a route, a tap on it, and a stop's name; unmounting lets go", () => {
const fake = fakeMap();
const onHover = vi.fn();
const onPoint = vi.fn();
const hook = mount(fake, [LINE], { onHover, onPoint });
const feature = { features: [{ properties: { ref: 'c1' } }] };
fake.fire('mousemove', ROUTE_LINE_LAYERS.hit, { ...feature, lngLat: { lng: 12.6, lat: 47.78 } });
fake.fire('click', ROUTE_LINE_LAYERS.hit, { ...feature, lngLat: { lng: 12.61, lat: 47.79 } });
fake.fire('mouseleave', ROUTE_LINE_LAYERS.hit);
expect(onHover.mock.calls).toEqual([['c1'], [null]]);
expect(onPoint.mock.calls).toEqual([
['c1', 47.78, 12.6],
['c1', 47.79, 12.61],
]);
const stop = { features: [{ properties: { label: 'Strausshütte' } }], lngLat: { lng: 12.6, lat: 47.78 } };
fake.fire('mousemove', ROUTE_LINE_LAYERS.stops, { ...stop, point: { x: 40, y: 50 } });
expect(fake.container.querySelector('[data-testid="assistant-route-label"]')).toHaveTextContent('Strausshütte');
hook.unmount();
expect(fake.listeners).toHaveLength(0);
});
it('FE-MAP-ROUTE-GL-004: a tap or a pointer on a place pin or a cluster bubble over a route is left to the pin', () => {
const fake = fakeMap();
const onHover = vi.fn();
const onPoint = vi.fn();
mount(fake, [LINE], { onHover, onPoint });
const point = { x: 40, y: 50 };
const at = { features: [{ properties: { ref: 'c1' } }], lngLat: { lng: 12.6, lat: 47.78 }, point };
const marker = document.createElement('div');
marker.className = 'maplibregl-marker';
const photo = marker.appendChild(document.createElement('img'));
fake.fire('click', ROUTE_LINE_LAYERS.hit, { ...at, originalEvent: { target: photo } });
fake.fire('mousemove', ROUTE_LINE_LAYERS.hit, { ...at, originalEvent: { target: photo } });
expect(onPoint).not.toHaveBeenCalled();
expect(onHover.mock.calls).toEqual([[null]]);
fake.map.getLayer.mockReturnValue({});
fake.map.queryRenderedFeatures.mockReturnValue([{ id: 7 }]);
fake.fire('click', ROUTE_LINE_LAYERS.hit, at);
expect(onPoint).not.toHaveBeenCalled();
expect(fake.map.queryRenderedFeatures).toHaveBeenCalledWith(at.point, {
layers: ['trip-place-clusters-circle', 'trip-place-clusters-count'],
});
// Off the bubbles the line takes the tap again.
fake.map.queryRenderedFeatures.mockReturnValue([]);
fake.fire('click', ROUTE_LINE_LAYERS.hit, at);
expect(onPoint).toHaveBeenCalledWith('c1', 47.78, 12.6);
});
it('FE-MAP-ROUTE-GL-005: a route that comes while a new basemap is loading is put on once the style is ready', () => {
const fake = fakeMap();
fake.map.isStyleLoaded.mockReturnValue(false);
mount(fake, [LINE]);
expect(fake.map.addSource).not.toHaveBeenCalled();
fake.map.isStyleLoaded.mockReturnValue(true);
fake.fire('styledata', null);
expect(fake.map.addSource).toHaveBeenCalledTimes(1);
expect(fake.data()?.features).toHaveLength(4);
});
});
@@ -0,0 +1,276 @@
import { useEffect, useLayoutEffect, useRef } from 'react';
import type { AssistantRouteLine } from '../../types/assistantMap';
import { mapHoverLabel } from './mapHoverLabel';
import { PLACE_CLUSTER_CIRCLE_LAYER_ID, PLACE_CLUSTER_COUNT_LAYER_ID } from './placeClusterLayers';
const SOURCE_ID = 'assistant-route-lines';
export const ROUTE_LINE_LAYERS = {
casing: `${SOURCE_ID}-casing`,
line: `${SOURCE_ID}-line`,
dashed: `${SOURCE_ID}-line-dashed`,
tint: `${SOURCE_ID}-tint`,
ends: `${SOURCE_ID}-ends`,
stops: `${SOURCE_ID}-stops`,
hit: `${SOURCE_ID}-hit`,
} as const;
/** The way a change replaces, beside the new one. */
const DIM_OPACITY = 0.45;
const ROUND = { 'line-cap': 'round', 'line-join': 'round' } as const;
type Position = [number, number];
interface Feature {
type: 'Feature';
properties: Record<string, string | number | boolean>;
geometry:
| { type: 'MultiLineString'; coordinates: Position[][] }
| { type: 'LineString'; coordinates: Position[] }
| { type: 'Point'; coordinates: Position };
}
interface FeatureCollection {
type: 'FeatureCollection';
features: Feature[];
}
/** What a pointer event on a layer hands over: where, and the feature under it. */
interface LayerEvent {
lngLat: { lng: number; lat: number };
point?: { x: number; y: number };
features?: { properties?: Record<string, unknown> | null }[];
/** The DOM event behind it: a place pin is a DOM marker over the canvas, and its taps reach the layers too. */
originalEvent?: { target?: EventTarget | null };
}
/**
* The slice of the GL map the route lines need. Every call is optional, so a
* stand-in map without them draws nothing instead of throwing; Mapbox and
* MapLibre both fit.
*/
export interface LineMap {
getSource?(id: string): { setData?: (data: FeatureCollection) => void } | undefined;
addSource?(id: string, source: { type: 'geojson'; data: FeatureCollection }): unknown;
addLayer?(layer: Record<string, unknown>): unknown;
getLayer?(id: string): unknown;
isStyleLoaded?(): boolean;
queryRenderedFeatures?(point: { x: number; y: number }, options: { layers: string[] }): unknown[];
getContainer?(): HTMLElement;
getCanvas?(): HTMLElement;
on?(type: 'styledata', listener: () => void): unknown;
on?(type: 'mousemove' | 'mouseleave' | 'click', layer: string, listener: (event: LayerEvent) => void): unknown;
off?(type: 'styledata', listener: () => void): unknown;
off?(type: 'mousemove' | 'mouseleave' | 'click', layer: string, listener: (event: LayerEvent) => void): unknown;
}
/** [lat, lng] as the store keeps points, [lng, lat] as GeoJSON wants them. */
const flip = ([lat, lng]: [number, number]): Position => [lng, lat];
const pointFeature = (properties: Feature['properties'], coordinates: Position): Feature => ({
type: 'Feature',
properties,
geometry: { type: 'Point', coordinates },
});
/**
* The routes as one GeoJSON collection: each route its line (with its rim
* colour, whether it is dashed, how faint, whether it is lit), its hard
* grades, its two ends, and its named stops while it is lit. Pure, for the
* tests.
*/
export function routeLineFeatures(lines: readonly AssistantRouteLine[]): FeatureCollection {
const features: Feature[] = [];
for (const line of lines) {
const opacity = line.dim ? DIM_OPACITY : 1;
features.push({
type: 'Feature',
properties: {
kind: 'line',
ref: line.ref,
color: line.color,
casing: line.casing,
dashed: !!line.dashed,
hot: !!line.hot,
opacity,
},
geometry: { type: 'MultiLineString', coordinates: line.lines.map((part) => part.map(flip)) },
});
for (const tint of line.tints ?? []) {
features.push({
type: 'Feature',
properties: { kind: 'tint', color: tint.color, opacity },
geometry: { type: 'LineString', coordinates: tint.line.map(flip) },
});
}
if (line.ends) {
const start = { kind: 'end', fill: line.color, stroke: line.casing, strokeWidth: 2, opacity };
features.push(pointFeature(start, flip(line.ends.start)));
if (line.ends.end) {
const end = { kind: 'end', fill: line.casing, stroke: line.color, strokeWidth: 3, opacity };
features.push(pointFeature(end, flip(line.ends.end)));
}
}
if (!line.hot) continue;
for (const stop of line.stops ?? []) {
const properties = { kind: 'stop', fill: line.color, stroke: line.casing, label: stop.label };
features.push(pointFeature(properties, [stop.lng, stop.lat]));
}
}
return { type: 'FeatureCollection', features };
}
const kindIs = (kind: string) => ['==', ['get', 'kind'], kind];
/** The layers, bottom first: rims, lines, dashed lines, grades, ends, stops, and the invisible line on top. */
function addRouteLineLayers(map: LineMap): void {
map.addSource?.(SOURCE_ID, { type: 'geojson', data: { type: 'FeatureCollection', features: [] } });
const source = SOURCE_ID;
const line = (id: string, filter: unknown[], paint: Record<string, unknown>) =>
map.addLayer?.({ id, type: 'line', source, filter, paint, layout: ROUND });
const solid = ['all', kindIs('line'), ['==', ['get', 'dashed'], false]];
const dashed = ['all', kindIs('line'), ['==', ['get', 'dashed'], true]];
const opacity = ['get', 'opacity'];
line(ROUTE_LINE_LAYERS.casing, kindIs('line'), {
'line-color': ['get', 'casing'],
'line-width': 7,
'line-opacity': ['*', opacity, 0.9],
});
line(ROUTE_LINE_LAYERS.line, solid, { 'line-color': ['get', 'color'], 'line-width': 4, 'line-opacity': opacity });
// Dashes are counted in line widths: 6 px on, 7 px off at a width of 4, as the Leaflet map draws them.
line(ROUTE_LINE_LAYERS.dashed, dashed, {
'line-color': ['get', 'color'],
'line-width': 4,
'line-opacity': opacity,
'line-dasharray': [1.5, 1.75],
});
line(ROUTE_LINE_LAYERS.tint, kindIs('tint'), {
'line-color': ['get', 'color'],
'line-width': 4,
'line-opacity': opacity,
});
const disc = (id: string, filter: unknown[], radius: number) =>
map.addLayer?.({
id,
type: 'circle',
source,
filter,
paint: {
'circle-radius': radius,
'circle-color': ['get', 'fill'],
'circle-stroke-color': ['get', 'stroke'],
'circle-stroke-width': ['coalesce', ['get', 'strokeWidth'], 2],
'circle-opacity': ['coalesce', opacity, 1],
'circle-stroke-opacity': ['coalesce', opacity, 1],
},
});
disc(ROUTE_LINE_LAYERS.ends, kindIs('end'), 5);
disc(ROUTE_LINE_LAYERS.stops, kindIs('stop'), 4);
line(ROUTE_LINE_LAYERS.hit, kindIs('line'), { 'line-color': ['get', 'casing'], 'line-width': 16, 'line-opacity': 0 });
}
interface AssistantGhostLinesOptions {
mapRef: { readonly current: LineMap | null };
mapReady: boolean;
lines: readonly AssistantRouteLine[] | undefined;
onHover?: (ref: string | null) => void;
onPoint?: (ref: string, lat: number, lng: number) => void;
}
/** The ref of the route line under a pointer event, if any. */
function refOf(event: LayerEvent): string | null {
const ref = event.features?.[0]?.properties?.ref;
return typeof ref === 'string' ? ref : null;
}
/**
* Whether the pointer is on something of the plan's that lies over the route
* on screen: a place pin (a DOM marker) or a cluster bubble (drawn under the
* route's layers, but the bubble is what a tap there means). The plan's own
* tracks leave such a tap alone the same way.
*/
function onPlanPin(map: LineMap, event: LayerEvent): boolean {
const target = event.originalEvent?.target;
if (target instanceof Element && target.closest('.mapboxgl-marker, .maplibregl-marker')) return true;
if (!event.point || !map.queryRenderedFeatures || !map.getLayer?.(PLACE_CLUSTER_CIRCLE_LAYER_ID)) return false;
const layers = [PLACE_CLUSTER_CIRCLE_LAYER_ID, PLACE_CLUSTER_COUNT_LAYER_ID];
return map.queryRenderedFeatures(event.point, { layers }).length > 0;
}
/**
* The routes the chat shows on the GL map, the twin of the Leaflet
* AssistantGhostLineLayer: one GeoJSON source and its layers, added the
* first time there is a route to draw and again whenever the basemap
* rebuilds the style, the data set anew when the routes change. The
* invisible line reports the pointer onto, along and off a route; a stop
* under the pointer shows its name in the map's hover label.
*/
export function useAssistantGhostLinesGL({ mapRef, mapReady, lines, onHover, onPoint }: AssistantGhostLinesOptions) {
const handlers = useRef({ onHover, onPoint });
useLayoutEffect(() => {
handlers.current = { onHover, onPoint };
}, [onHover, onPoint]);
const data = useRef<FeatureCollection>(routeLineFeatures([]));
const added = useRef(false);
useEffect(() => {
const map = mapRef.current;
if (!map || !mapReady || typeof map.getSource !== 'function') return;
data.current = routeLineFeatures(lines ?? []);
// Nothing is added to a map that never had a route to draw.
if (!added.current && data.current.features.length === 0) return;
added.current = true;
if (!map.getSource(SOURCE_ID)) {
// A basemap still loading takes no layers; its styledata puts the routes on once it is ready.
if (map.isStyleLoaded?.() === false) return;
addRouteLineLayers(map);
}
map.getSource(SOURCE_ID)?.setData?.(data.current);
}, [lines, mapReady, mapRef]);
useEffect(() => {
const map = mapRef.current;
if (!map || !mapReady || typeof map.on !== 'function' || typeof map.off !== 'function') return;
const label = mapHoverLabel(map, 'assistant-route-label');
// A new basemap takes every layer with it: put the routes back, as the plan's own tracks are.
const restore = () => {
if (!added.current || !map.getSource || map.getSource(SOURCE_ID)) return;
addRouteLineLayers(map);
map.getSource(SOURCE_ID)?.setData?.(data.current);
};
const move = (event: LayerEvent) => {
const ref = refOf(event);
if (ref === null) return;
// On a pin over the line the pin is what the pointer is on: the line goes out as if left.
if (onPlanPin(map, event)) {
handlers.current.onHover?.(null);
return;
}
handlers.current.onHover?.(ref);
handlers.current.onPoint?.(ref, event.lngLat.lat, event.lngLat.lng);
};
const leave = () => handlers.current.onHover?.(null);
const click = (event: LayerEvent) => {
const ref = refOf(event);
if (ref !== null && !onPlanPin(map, event)) handlers.current.onPoint?.(ref, event.lngLat.lat, event.lngLat.lng);
};
const stop = (event: LayerEvent) => {
const name = event.features?.[0]?.properties?.label;
if (typeof name === 'string' && event.point) label.show({ name, detail: null }, event.point);
};
const hideLabel = () => label.hide();
map.on('styledata', restore);
map.on('mousemove', ROUTE_LINE_LAYERS.hit, move);
map.on('mouseleave', ROUTE_LINE_LAYERS.hit, leave);
map.on('click', ROUTE_LINE_LAYERS.hit, click);
map.on('mousemove', ROUTE_LINE_LAYERS.stops, stop);
map.on('mouseleave', ROUTE_LINE_LAYERS.stops, hideLabel);
return () => {
map.off?.('styledata', restore);
map.off?.('mousemove', ROUTE_LINE_LAYERS.hit, move);
map.off?.('mouseleave', ROUTE_LINE_LAYERS.hit, leave);
map.off?.('click', ROUTE_LINE_LAYERS.hit, click);
map.off?.('mousemove', ROUTE_LINE_LAYERS.stops, stop);
map.off?.('mouseleave', ROUTE_LINE_LAYERS.stops, hideLabel);
label.remove();
};
}, [mapReady, mapRef]);
}
@@ -0,0 +1,71 @@
// FE-MAP-GHOST-GL-001 to 002: the assistant's suggestions on the GL map, as hand-positioned pins.
import { act, renderHook } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import type { AssistantGhost } from './mapViewContract';
import { useAssistantGhostMarkersGL } from './useAssistantGhostMarkersGL';
const GHOSTS: AssistantGhost[] = [
{ id: 'a', lat: 41.9, lng: 12.48, name: 'Pantheon' },
{ id: 'b', lat: 41.89, lng: 12.49, name: '<b>Forum</b>' },
];
function setup(hoveredId: string | null = null) {
const container = document.createElement('div');
document.body.appendChild(container);
const map = { getContainer: () => container, on: vi.fn(), off: vi.fn() };
const attached: { el: HTMLElement; lng: number; lat: number; remove: ReturnType<typeof vi.fn> }[] = [];
const pinsRef = { current: [] as { remove: () => void }[] };
const onHover = vi.fn();
const onClick = vi.fn();
// Stable across renders, as the map view hands them over: only `hovered` changes.
const mapRef = { current: map };
const attachPin = (el: HTMLElement, lng: number, lat: number) => {
container.appendChild(el);
const pin = { el, lng, lat, remove: vi.fn(() => el.remove()) };
attached.push(pin);
return pin;
};
const hook = renderHook(
({ hovered }) =>
useAssistantGhostMarkersGL({
mapRef,
mapReady: true,
pinsRef,
attachPin,
ghosts: GHOSTS,
hoveredId: hovered,
onHover,
onClick,
}),
{ initialProps: { hovered: hoveredId } }
);
return { container, attached, pinsRef, onHover, hook };
}
describe('useAssistantGhostMarkersGL', () => {
it('FE-MAP-GHOST-GL-001: puts each ghost where it belongs, hands the pins to the reposition, and names it as text', () => {
const { container, attached, pinsRef, onHover } = setup();
expect(attached.map((p) => [p.lng, p.lat])).toEqual([
[12.48, 41.9],
[12.49, 41.89],
]);
expect(pinsRef.current).toHaveLength(2);
attached[1]?.el.dispatchEvent(new Event('pointerenter'));
expect(onHover).toHaveBeenCalledWith('b');
const label = container.querySelector('[data-testid="assistant-ghost-label"]');
expect(label?.textContent).toBe('<b>Forum</b>');
expect(label?.querySelector('b')).toBeNull();
});
it('FE-MAP-GHOST-GL-002: a hover marks its ghost without rebuilding a pin, and unmounting takes them all off', () => {
const { attached, pinsRef, hook } = setup();
act(() => hook.rerender({ hovered: 'a' }));
expect(attached).toHaveLength(2);
expect(attached[0]?.el.classList.contains('is-hot')).toBe(true);
expect(attached[1]?.el.classList.contains('is-hot')).toBe(false);
hook.unmount();
expect(attached.every((p) => p.remove.mock.calls.length === 1)).toBe(true);
expect(pinsRef.current).toEqual([]);
});
});

Some files were not shown because too many files have changed in this diff Show More