From 98cc57942b6f060e9bdcdfcc000be8418c28b38a Mon Sep 17 00:00:00 2001 From: Maurice Date: Wed, 14 Oct 2026 12:30:10 +0200 Subject: [PATCH] feat(tours): 3D terrain view with flyover and grade colours, imported tours carry no hiking difficulty The tours map gets a 3D mode on the same map surface between the side panels: a "3D" switch in the layer pill drapes the route over open Terrarium elevation tiles (AWS Open Data), colours it by grade, plays a flyover tied to the elevation profile in the rail, and keeps planning working by clicking and dragging waypoints on the terrain. The corridor around the route is preloaded before the flyover so the landscape never loads in front of the camera. GPX imports no longer get a made-up hiking difficulty: max_hiking_difficulty becomes nullable (new migration, waypoints kept), the import writes null and the client shows no T badge for it. Drawn tours still default to T2. Info hints in the planner show their tooltip only, and the discard confirmation reads "Discard changes". --- .../components/Map/MapLayerSwitcher.test.tsx | 28 +- .../src/components/Map/MapLayerSwitcher.tsx | 38 +- client/src/components/Map/MapView.tsx | 6 +- client/src/components/Map/MapViewGL.tsx | 6 +- client/src/components/Map/mapViewContract.ts | 2 + .../components/Tours/ToursSidebar.test.tsx | 10 + .../Tours/planner/TourPlannerPanels.test.tsx | 23 +- .../Tours/planner/TourPlannerPanels.tsx | 32 +- .../Tours/terrain/TourTerrainMap.test.tsx | 375 ++++++++++++++++++ .../Tours/terrain/TourTerrainMap.tsx | 291 ++++++++++++++ .../Tours/terrain/terrainLayers.test.ts | 195 +++++++++ .../components/Tours/terrain/terrainLayers.ts | 209 ++++++++++ .../Tours/terrain/terrainPrefetch.test.ts | 147 +++++++ .../Tours/terrain/terrainPrefetch.ts | 107 +++++ .../Tours/terrain/tourTerrainModel.test.ts | 145 +++++++ .../Tours/terrain/tourTerrainModel.ts | 165 ++++++++ .../components/Tours/terrain/useTerrainMap.ts | 134 +++++++ .../Tours/terrain/useTerrainPins.ts | 55 +++ .../Tours/terrain/useTerrainPrefetch.ts | 35 ++ .../Tours/terrain/useTerrainReplay.ts | 133 +++++++ .../Tours/terrain/useTourTerrain.ts | 71 ++++ client/src/components/Tours/tourParts.tsx | 20 +- .../src/components/Tours/toursI18n.test.tsx | 2 +- .../trip/places/MToursSelectionList.test.tsx | 11 + .../trip/places/MToursSelectionList.tsx | 12 +- .../tripPlanner/TourPlannerMapStage.test.tsx | 168 ++++++++ .../pages/tripPlanner/TourPlannerMapStage.tsx | 110 +++-- server/src/db/entities/Tours.entity.ts | 6 +- server/src/db/kysely/Tours.table.ts | 2 +- ..._imported_tour_has_no_hiking_difficulty.ts | 74 ++++ .../src/db/repositories/Tours.repository.ts | 6 +- server/src/middleware/globalMiddleware.ts | 2 + server/src/nest/tours/tours.service.ts | 6 +- server/tests/e2e/tours.e2e.test.ts | 7 +- server/tests/unit/db/known-migrations.test.ts | 1 + server/tests/unit/db/legacy-baseline.test.ts | 1 + ...tour-imported-difficulty-migration.test.ts | 121 ++++++ .../middleware/globalMiddleware.csp.test.ts | 15 + .../tests/unit/nest/tours.gpx.atomic.test.ts | 2 +- shared/src/i18n/ar/tours.ts | 19 +- shared/src/i18n/az/tours.ts | 20 +- shared/src/i18n/br/tours.ts | 20 +- shared/src/i18n/ca/tours.ts | 20 +- shared/src/i18n/cs/tours.ts | 20 +- shared/src/i18n/de/tours.ts | 20 +- shared/src/i18n/en/tours.ts | 20 +- shared/src/i18n/es/tours.ts | 20 +- shared/src/i18n/et/tours.ts | 20 +- shared/src/i18n/fr/tours.ts | 20 +- shared/src/i18n/gr/tours.ts | 20 +- shared/src/i18n/hu/tours.ts | 21 +- shared/src/i18n/id/tours.ts | 21 +- shared/src/i18n/it/tours.ts | 20 +- shared/src/i18n/ja/tours.ts | 19 +- shared/src/i18n/ko/tours.ts | 20 +- shared/src/i18n/nl/tours.ts | 20 +- shared/src/i18n/pl/tours.ts | 21 +- shared/src/i18n/ru/tours.ts | 20 +- shared/src/i18n/sk/tours.ts | 20 +- shared/src/i18n/sv/tours.ts | 20 +- shared/src/i18n/th/tours.ts | 19 +- shared/src/i18n/tours-locales.spec.ts | 4 +- shared/src/i18n/tr/tours.ts | 20 +- shared/src/i18n/uk/tours.ts | 20 +- shared/src/i18n/vi/tours.ts | 20 +- shared/src/i18n/zh-TW/tours.ts | 19 +- shared/src/i18n/zh/tours.ts | 19 +- shared/src/tours/tours.schema.test.ts | 26 ++ shared/src/tours/tours.schema.ts | 3 +- 69 files changed, 3203 insertions(+), 141 deletions(-) create mode 100644 client/src/components/Tours/terrain/TourTerrainMap.test.tsx create mode 100644 client/src/components/Tours/terrain/TourTerrainMap.tsx create mode 100644 client/src/components/Tours/terrain/terrainLayers.test.ts create mode 100644 client/src/components/Tours/terrain/terrainLayers.ts create mode 100644 client/src/components/Tours/terrain/terrainPrefetch.test.ts create mode 100644 client/src/components/Tours/terrain/terrainPrefetch.ts create mode 100644 client/src/components/Tours/terrain/tourTerrainModel.test.ts create mode 100644 client/src/components/Tours/terrain/tourTerrainModel.ts create mode 100644 client/src/components/Tours/terrain/useTerrainMap.ts create mode 100644 client/src/components/Tours/terrain/useTerrainPins.ts create mode 100644 client/src/components/Tours/terrain/useTerrainPrefetch.ts create mode 100644 client/src/components/Tours/terrain/useTerrainReplay.ts create mode 100644 client/src/components/Tours/terrain/useTourTerrain.ts create mode 100644 client/src/pages/tripPlanner/TourPlannerMapStage.test.tsx create mode 100644 server/src/db/migrations/Migration20200101043100_an_imported_tour_has_no_hiking_difficulty.ts create mode 100644 server/tests/unit/db/tour-imported-difficulty-migration.test.ts diff --git a/client/src/components/Map/MapLayerSwitcher.test.tsx b/client/src/components/Map/MapLayerSwitcher.test.tsx index 6414d1b77..8355f6fc5 100644 --- a/client/src/components/Map/MapLayerSwitcher.test.tsx +++ b/client/src/components/Map/MapLayerSwitcher.test.tsx @@ -1,4 +1,4 @@ -// FE-COMP-MAPLAYER-001 to FE-COMP-MAPLAYER-006 +// FE-COMP-MAPLAYER-001 to FE-COMP-MAPLAYER-010 import React from 'react' import { describe, it, expect, vi } from 'vitest' import { render, screen, fireEvent } from '../../../tests/helpers/render' @@ -71,3 +71,29 @@ 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( {}} />) + 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( {}} 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( {}} 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') + }) +}) diff --git a/client/src/components/Map/MapLayerSwitcher.tsx b/client/src/components/Map/MapLayerSwitcher.tsx index 45455be01..8a467124c 100644 --- a/client/src/components/Map/MapLayerSwitcher.tsx +++ b/client/src/components/Map/MapLayerSwitcher.tsx @@ -1,4 +1,5 @@ -import { Map as MapIcon, Mountain, Satellite } from 'lucide-react' +import { Map as MapIcon, Mountain, Rotate3d, Satellite } from 'lucide-react' +import type { CSSProperties } from 'react' import { useTranslation } from '../../i18n' import { Tooltip } from '../shared/Tooltip' import { MAP_CONTROL_SHADOW } from './mapControlShadow' @@ -71,13 +72,26 @@ const TOUR_LAYERS = [ { id: 'satellite', labelKey: 'map.baseLayer.satellite', Icon: Satellite }, ] as const +/** A pill segment of the Tours control; `filled` lets its class paint the background. */ +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, +}) + /** Per-view Tours control. It never reads or writes the global map setting. */ export function TourMapLayerSwitcher({ active, onChange, + onToggleTerrain, + terrainActive = false, }: { active: TourBaseLayer onChange: (layer: TourBaseLayer) => void + /** Offers the 3D terrain switch beside the base layers. */ + onToggleTerrain?: () => void + terrainActive?: boolean }) { const { t } = useTranslation() @@ -93,18 +107,28 @@ export function TourMapLayerSwitcher({ onClick={() => onChange(id)} aria-pressed={selected} className={selected ? 'bg-accent-soft text-accent' : 'text-content-muted'} - style={{ - display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 5, - minHeight: 34, borderRadius: 999, border: 'none', cursor: 'pointer', - background: selected ? undefined : 'transparent', padding: '0 10px', - fontSize: 'calc(11px * var(--fs-scale-caption, 1))', fontWeight: 600, - }} + style={segmentStyle(selected)} > {label} ) })} + {onToggleTerrain && ( + <> + + + + )} ) } diff --git a/client/src/components/Map/MapView.tsx b/client/src/components/Map/MapView.tsx index 73707f53c..47060d0bf 100644 --- a/client/src/components/Map/MapView.tsx +++ b/client/src/components/Map/MapView.tsx @@ -834,8 +834,7 @@ export const MapView = memo(function MapView({ onPlannerWaypointClick, onPlannerWaypointMove, routeProfileFocus = null, - viewBaseLayer, - onViewBaseLayerChange, + viewBaseLayer, onViewBaseLayerChange, onToggleTerrain3d, }: MapViewProps) { const globalBaseLayer = useSettingsStore(s => s.settings.map_base_layer) || 'default' const updateSetting = useSettingsStore(s => s.updateSetting) @@ -1384,7 +1383,8 @@ export const MapView = memo(function MapView({
{onToggleFollow && } {hasViewBaseLayer - ? + ? : }
diff --git a/client/src/components/Map/MapViewGL.tsx b/client/src/components/Map/MapViewGL.tsx index b55a5035e..88ffef375 100644 --- a/client/src/components/Map/MapViewGL.tsx +++ b/client/src/components/Map/MapViewGL.tsx @@ -630,8 +630,7 @@ export function MapViewGL({ onPlannerWaypointClick, onPlannerWaypointMove, routeProfileFocus = null, - viewBaseLayer, - onViewBaseLayerChange, + viewBaseLayer, onViewBaseLayerChange, onToggleTerrain3d, roadtripVias, onMoveVia, onRemoveVia, @@ -2354,7 +2353,8 @@ export function MapViewGL({ }}> {onToggleFollow && } {hasViewBaseLayer - ? + ? : } {/* Hover tooltip — cursor-following name/category/address card, identical to diff --git a/client/src/components/Map/mapViewContract.ts b/client/src/components/Map/mapViewContract.ts index a2134004e..ebeafac75 100644 --- a/client/src/components/Map/mapViewContract.ts +++ b/client/src/components/Map/mapViewContract.ts @@ -116,6 +116,8 @@ export interface MapViewProps { routeProfileFocus?: RouteProfileFocus | null; viewBaseLayer?: TourBaseLayer; onViewBaseLayerChange?: (layer: TourBaseLayer) => void; + /** Offers the 3D terrain switch in the tour layer pill. */ + onToggleTerrain3d?: () => void; /** * An explicit stretch of map to frame, independent of the day being shown. * diff --git a/client/src/components/Tours/ToursSidebar.test.tsx b/client/src/components/Tours/ToursSidebar.test.tsx index abe1454ec..2358c2025 100644 --- a/client/src/components/Tours/ToursSidebar.test.tsx +++ b/client/src/components/Tours/ToursSidebar.test.tsx @@ -112,6 +112,16 @@ describe('ToursSidebar', () => { expect(screen.getByRole('button', { name: /Day one/ })).toBeInTheDocument() }) + it('shows no T-badge for an imported tour that carries no difficulty', () => { + const imported = { ...tour, name: 'Imported GPX walk', has_waypoints: false, max_hiking_difficulty: null } + render() + + const metrics = within(screen.getByRole('option', { name: /Imported GPX walk/ })).getByTestId('tour-metrics') + expect(metrics).not.toHaveTextContent(/T\d/) + expect(metrics).not.toHaveTextContent('Tnull') + expect(within(metrics).queryByLabelText(/^T\d/)).not.toBeInTheDocument() + }) + it('leaves the post-write refresh to the shared assignment handler', async () => { let resolveAssignment!: () => void const assignment = new Promise(resolve => { resolveAssignment = resolve }) diff --git a/client/src/components/Tours/planner/TourPlannerPanels.test.tsx b/client/src/components/Tours/planner/TourPlannerPanels.test.tsx index 7a9321d7e..7646ca947 100644 --- a/client/src/components/Tours/planner/TourPlannerPanels.test.tsx +++ b/client/src/components/Tours/planner/TourPlannerPanels.test.tsx @@ -399,7 +399,7 @@ describe('TourPlannerRail', () => { expect(screen.getByRole('alert')).toHaveTextContent('Enter a whole value from 0 to 1,440 minutes.') }) - it('RS-02: Info controls are keyboard focusable, use shared tooltips, and expose touch disclosures', async () => { + it('RS-02: Info controls are keyboard focusable and explain themselves only through the shared tooltip', async () => { render( { const breaksInfo = screen.getByRole('button', { name: 'About breaks and additional time' }) expect(breaksInfo.tabIndex).toBe(0) - expect(breaksInfo).toHaveAttribute('aria-expanded', 'false') - expect(breaksInfo).toHaveAttribute('aria-controls') + expect(breaksInfo).not.toHaveAttribute('aria-expanded') + expect(breaksInfo).toHaveAccessibleDescription('Optional whole minutes added to calculated walking time.') expect(breaksInfo).toHaveClass('focus-visible:outline') - const matches = vi.spyOn(breaksInfo, 'matches').mockImplementation(selector => selector === ':focus-visible') - fireEvent.focus(breaksInfo) + fireEvent.mouseEnter(breaksInfo) expect(await screen.findByRole('tooltip')).toHaveTextContent('Optional whole minutes added to calculated walking time.') - fireEvent.blur(breaksInfo) - matches.mockRestore() + fireEvent.mouseLeave(breaksInfo) + + // A click shows nothing beyond the tooltip: no explanation unfolds in the form. fireEvent.click(breaksInfo) - expect(breaksInfo).toHaveAttribute('aria-expanded', 'true') - expect(screen.getByRole('note')).toHaveTextContent('Optional whole minutes added to calculated walking time.') + expect(screen.queryByRole('note')).not.toBeInTheDocument() const totalInfo = screen.getByRole('button', { name: 'About planned total duration' }) - expect(totalInfo).toHaveAttribute('aria-expanded', 'false') - fireEvent.click(totalInfo) - expect(screen.getByText('Calculated planned total duration.')).toBeInTheDocument() + expect(totalInfo).toHaveAccessibleDescription('Calculated planned total duration.') }) it('RS-01: marks unsafe website values invalid and does not offer Save', () => { @@ -803,7 +800,7 @@ describe('TourPlannerRail', () => { expect(dirty.returnToNeutral).not.toHaveBeenCalled() expect(screen.getByRole('heading', { name: 'Edit tour' })).toBeInTheDocument() fireEvent.click(screen.getByRole('button', { name: 'Back to Tours' })) - fireEvent.click(screen.getByRole('button', { name: 'Discard unsaved changes' })) + fireEvent.click(screen.getByRole('button', { name: 'Discard changes' })) expect(dirty.returnToNeutral).toHaveBeenCalledOnce() }) diff --git a/client/src/components/Tours/planner/TourPlannerPanels.tsx b/client/src/components/Tours/planner/TourPlannerPanels.tsx index e98012fe2..549bc964e 100644 --- a/client/src/components/Tours/planner/TourPlannerPanels.tsx +++ b/client/src/components/Tours/planner/TourPlannerPanels.tsx @@ -64,25 +64,19 @@ function RailTitle({ title, sub, aside }: { title: string; sub?: ReactNode; asid function DurationInfo({ description, label }: { description: string; label: string }) { const id = useId() - const [open, setOpen] = useState(false) + // Hover, focus and a tap show the explanation as a tooltip; nothing unfolds in the form. return ( - - - - - - + + + ) } @@ -236,7 +230,7 @@ export function TourPlannerRail({ planner, canEdit: editPermission, canAssign: a onConfirm={planner.returnToNeutral} title={t('tours.planner.discardTitle')} message={t('tours.planner.discardBody')} - confirmLabel={t('tours.planner.discardUnsaved')} + confirmLabel={t('tours.planner.discardChanges')} /> void; + +interface MarkerStub { + element: HTMLElement; + draggable: boolean; + lngLat: [number, number]; + handlers: Record; + setLngLat: ReturnType; + addTo: ReturnType; + remove: ReturnType; + on: ReturnType; + getLngLat: ReturnType; +} + +const gl = vi.hoisted(() => { + const listeners = new Map(); + const sources = new Map>(); + const markers: MarkerStub[] = []; + const listen = (type: string, fn: Handler) => listeners.set(type, [...(listeners.get(type) ?? []), fn]); + const map = { + on: vi.fn((type: string, fn: Handler) => { + listen(type, fn); + return map; + }), + once: vi.fn((type: string, fn: Handler) => { + const wrapped: Handler = (event) => { + listeners.set( + type, + (listeners.get(type) ?? []).filter((other) => other !== wrapped) + ); + fn(event); + }; + listen(type, wrapped); + return map; + }), + remove: vi.fn(), + fitBounds: vi.fn(), + jumpTo: vi.fn(), + setStyle: vi.fn(), + setTerrain: vi.fn(), + setSky: vi.fn(), + addLayer: vi.fn(), + addSource: vi.fn((id: string, spec: Record) => sources.set(id, { ...spec, setData: vi.fn() })), + getSource: vi.fn((id: string) => sources.get(id)), + getStyle: vi.fn(() => ({ sources: Object.fromEntries(sources) })), + }; + const fire = (type: string, event?: unknown) => [...(listeners.get(type) ?? [])].forEach((fn) => fn(event)); + const createMarker = (options: { element: HTMLElement; draggable?: boolean }): MarkerStub => { + const marker: MarkerStub = { + element: options.element, + draggable: !!options.draggable, + lngLat: [0, 0], + handlers: {}, + setLngLat: vi.fn((at: [number, number]) => { + marker.lngLat = at; + return marker; + }), + addTo: vi.fn(() => marker), + remove: vi.fn(), + on: vi.fn((type: string, fn: Handler) => { + marker.handlers[type] = fn; + return marker; + }), + getLngLat: vi.fn(() => ({ lng: marker.lngLat[0], lat: marker.lngLat[1] })), + }; + markers.push(marker); + return marker; + }; + const engine = { + Map: vi.fn(function () { + return map; + }), + Marker: vi.fn(function (options: { element: HTMLElement; draggable?: boolean }) { + return createMarker(options); + }), + }; + const reset = () => { + listeners.clear(); + sources.clear(); + markers.length = 0; + }; + return { map, engine, markers, sources, fire, reset }; +}); + +vi.mock('../../Map/engines/maplibre', () => ({ default: gl.engine })); + +/** 300 m due north, 20 m up every 100 m, every sample with a position. */ +const TOUR: DistanceIndexedProfileSample[] = [0, 1, 2, 3].map((i) => ({ + distanceMeters: i * 100, + elevationMeters: 1000 + i * 20, + lat: 46 + i * 0.0009, + lng: 7, +})); + +function props(overrides: Partial = {}): TourTerrainMapProps { + return { + samples: [], + routes: null, + trackColor: '#0a84ff', + unit: 'metric', + baseLayer: 'topo', + onBaseLayerChange: vi.fn(), + onExit: vi.fn(), + focus: null, + onFocusChange: vi.fn(), + leftWidth: 300, + rightWidth: 400, + waypoints: { points: [], selectedId: null, onSelect: vi.fn() }, + framePoints: [[46, 7]], + ...overrides, + }; +} + +async function renderTerrain(overrides: Partial = {}) { + const view = render(); + // The engine loads on demand; the rider marker exists once the map is wired up. + await waitFor(() => expect(gl.markers.length).toBeGreaterThan(0)); + return view; +} + +/** The style finishes loading, then its sources know their tile URLs. */ +function loadStyle() { + act(() => { + gl.fire('style.load'); + gl.fire('load'); + gl.fire('idle'); + }); +} + +let openTiles: () => void = () => {}; + +beforeEach(() => { + gl.reset(); + vi.clearAllMocks(); + const gate = new Promise((resolve) => { + openTiles = () => resolve({ ok: true } as Response); + }); + vi.stubGlobal( + 'fetch', + vi.fn(() => gate) + ); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +describe('TourTerrainMap', () => { + it('FE-COMP-TERRAIN-001: opens a pitched GL map with the planner base layer and the layer pill in 3D', async () => { + const onExit = vi.fn(); + await renderTerrain({ onExit }); + expect(gl.engine.Map).toHaveBeenCalledWith(expect.objectContaining({ pitch: 60, maxPitch: 75 })); + const toggle = screen.getByRole('button', { name: '3D' }); + expect(toggle).toHaveAttribute('aria-pressed', 'true'); + fireEvent.click(toggle); + expect(onExit).toHaveBeenCalledTimes(1); + }); + + it('FE-COMP-TERRAIN-002: without a tour it says how to start, by whether the tour can be edited', async () => { + const { rerender } = await renderTerrain(); + expect(screen.getByText('Open a tour on the right to fly it in 3D and colour it by grade.')).toBeInTheDocument(); + rerender( + + ); + expect(screen.getByText(/Click the terrain to set points/)).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Play flyover' })).toBeNull(); + }); + + it('FE-COMP-TERRAIN-003: a click on the terrain adds a control point only while editing', async () => { + const onAdd = vi.fn(); + const { rerender } = await renderTerrain({ waypoints: { points: [], selectedId: null, onSelect: vi.fn(), onAdd } }); + act(() => gl.fire('click', { lngLat: { lat: 46.5, lng: 7.5 } })); + expect(onAdd).toHaveBeenCalledWith(46.5, 7.5); + + rerender(); + act(() => gl.fire('click', { lngLat: { lat: 1, lng: 2 } })); + expect(onAdd).toHaveBeenCalledTimes(1); + }); + + it('FE-COMP-TERRAIN-004: drapes terrain, hillshade and track once the style is in, and frames the start', async () => { + await renderTerrain(); + loadStyle(); + expect(gl.map.setTerrain).toHaveBeenCalledWith({ source: 'tour-terrain-dem', exaggeration: 1.5 }); + expect(gl.map.addLayer).toHaveBeenCalledTimes(3); + expect(gl.map.fitBounds).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ duration: 0, padding: { top: 70, bottom: 150, left: 340, right: 440 } }) + ); + }); + + it('FE-COMP-TERRAIN-005: pins the control points, selects one on click and puts a refused drag back', async () => { + const onSelect = vi.fn(); + const onMove = vi.fn(() => false); + await renderTerrain({ + waypoints: { + points: [ + { id: 'a', lat: 46, lng: 7 }, + { id: 'b', lat: 46.01, lng: 7.01 }, + ], + selectedId: 'b', + onSelect, + onMove, + }, + }); + loadStyle(); + const pins = gl.markers.filter((marker) => marker.element.tagName === 'BUTTON'); + expect(pins.map((pin) => pin.element.textContent)).toEqual(['1', '2']); + expect(pins.every((pin) => pin.draggable)).toBe(true); + expect(pins[1].element.style.width).toBe('30px'); + + fireEvent.click(pins[0].element); + expect(onSelect).toHaveBeenCalledWith('a'); + + pins[0].lngLat = [8, 47]; + pins[0].handlers.dragend(); + expect(onMove).toHaveBeenCalledWith('a', 47, 8); + expect(pins[0].lngLat).toEqual([7, 46]); + }); + + it('FE-COMP-TERRAIN-006: keeps a pin where it was dropped when the move is taken', async () => { + const onMove = vi.fn(() => true); + await renderTerrain({ + waypoints: { points: [{ id: 'a', lat: 46, lng: 7 }], selectedId: null, onSelect: vi.fn(), onMove }, + }); + loadStyle(); + const [pin] = gl.markers.filter((marker) => marker.element.tagName === 'BUTTON'); + pin.lngLat = [8, 47]; + pin.handlers.dragend(); + expect(pin.lngLat).toEqual([8, 47]); + }); + + it('FE-COMP-TERRAIN-007: shows the landscape loading as a ring, then offers the flyover', async () => { + await renderTerrain({ samples: TOUR }); + expect(screen.getByRole('progressbar', { name: 'Loading the landscape: 0 %' })).toHaveAttribute( + 'aria-valuenow', + '0' + ); + loadStyle(); + await waitFor(() => expect(fetch).toHaveBeenCalled()); + expect(fetch).toHaveBeenCalledWith(expect.stringContaining('elevation-tiles-prod'), expect.anything()); + // The play button only comes once the corridor is in the cache. + fireEvent.click(screen.getByRole('button', { name: 'Start over' })); + expect(screen.queryByRole('button', { name: 'Pause' })).toBeNull(); + + await act(async () => openTiles()); + expect(await screen.findByRole('button', { name: 'Play flyover' })).toBeInTheDocument(); + expect(screen.queryByRole('progressbar')).toBeNull(); + }); + + it('FE-COMP-TERRAIN-008: flies the route, moving the profile focus, and stops at its end', async () => { + const frames: FrameRequestCallback[] = []; + vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => frames.push(callback)); + vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {}); + const onFocusChange = vi.fn(); + await renderTerrain({ samples: TOUR, onFocusChange }); + loadStyle(); + await act(async () => openTiles()); + fireEvent.click(await screen.findByRole('button', { name: 'Play flyover' })); + expect(screen.getByRole('button', { name: 'Pause' })).toBeInTheDocument(); + + let now = performance.now(); + for (let i = 0; i < 400 && frames.length; i++) { + const frame = frames.shift(); + now += 100; + act(() => frame?.(now)); + } + expect(gl.map.jumpTo).toHaveBeenCalledWith(expect.objectContaining({ pitch: 52, zoom: 13.4 })); + const calls = onFocusChange.mock.calls; + const last = calls[calls.length - 1]?.[0] as RouteProfileFocus | undefined; + expect(last?.distanceMeters).toBe(300); + expect(screen.getByRole('button', { name: 'Play flyover' })).toBeInTheDocument(); + }); + + it('FE-COMP-TERRAIN-009: pauses, starts over and frames the whole route again', async () => { + const frames: FrameRequestCallback[] = []; + vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => frames.push(callback)); + vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => {}); + await renderTerrain({ samples: TOUR }); + loadStyle(); + await act(async () => openTiles()); + await screen.findByRole('button', { name: 'Play flyover' }); + fireEvent.click(screen.getByRole('button', { name: 'Start over' })); + fireEvent.click(screen.getByRole('button', { name: 'Pause' })); + expect(screen.getByRole('button', { name: 'Play flyover' })).toBeInTheDocument(); + + gl.map.fitBounds.mockClear(); + fireEvent.click(screen.getByRole('button', { name: 'Overview' })); + expect(gl.map.fitBounds).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ duration: 1200 })); + }); + + it('FE-COMP-TERRAIN-010: the rider follows the profile focus while the flyover is not running', async () => { + const focus: RouteProfileFocus = { + distanceMeters: 100, + elevationMeters: 1020, + lat: 46.0009, + lng: 7, + sampleIndex: 1, + }; + const { rerender } = await renderTerrain({ samples: TOUR }); + const rider = gl.markers[0]; + rerender(); + expect(rider.setLngLat).toHaveBeenCalledWith([7, 46.0009]); + expect(rider.addTo).toHaveBeenCalledWith(gl.map); + rerender(); + expect(rider.remove).toHaveBeenCalled(); + }); + + it('FE-COMP-TERRAIN-011: speed, relief and colour change the flight and the drawing', async () => { + await renderTerrain({ samples: TOUR }); + loadStyle(); + await act(async () => openTiles()); + + fireEvent.click(screen.getByRole('button', { name: '4×' })); + expect(screen.getByRole('button', { name: '4×' })).toHaveAttribute('aria-pressed', 'true'); + expect(screen.getByRole('button', { name: '1×' })).toHaveAttribute('aria-pressed', 'false'); + + fireEvent.change(screen.getByRole('slider', { name: 'Relief' }), { target: { value: '2.5' } }); + expect(gl.map.setTerrain).toHaveBeenLastCalledWith({ source: 'tour-terrain-dem', exaggeration: 2.5 }); + expect(screen.getByText('2.5×')).toBeInTheDocument(); + + const track = gl.sources.get('tour-terrain-track'); + const setData = track?.setData as ReturnType | undefined; + setData?.mockClear(); + const colour = screen.getByRole('button', { name: 'Grade' }); + expect(colour).toHaveAttribute('aria-pressed', 'true'); + fireEvent.click(colour); + expect(colour).toHaveAttribute('aria-pressed', 'false'); + const drawCalls = setData?.mock.calls ?? []; + const drawn = drawCalls[drawCalls.length - 1]?.[0] as { features: { properties: { color: string } }[] } | undefined; + expect(drawn?.features.every((feature) => feature.properties.color === '#0a84ff')).toBe(true); + }); + + it('FE-COMP-TERRAIN-012: unfolds the grade mix with its bands and the elevation credit', async () => { + await renderTerrain({ samples: TOUR }); + const legend = screen.getByRole('button', { name: 'Grade mix' }); + expect(legend).toHaveAttribute('aria-expanded', 'false'); + expect(legend).toHaveTextContent('1060 m'); + expect(legend).toHaveTextContent('max 20 %'); + fireEvent.click(legend); + expect(legend).toHaveAttribute('aria-expanded', 'true'); + expect(screen.getByText('18 to 27 %')).toBeInTheDocument(); + expect(screen.getByText('Elevation: Mapzen Terrain Tiles (AWS Open Data)')).toBeInTheDocument(); + fireEvent.click(legend); + expect(screen.queryByText('18 to 27 %')).toBeNull(); + }); + + it('FE-COMP-TERRAIN-013: swaps the style in place for another base layer and draws on it again', async () => { + const { rerender } = await renderTerrain({ samples: TOUR }); + loadStyle(); + rerender(); + expect(gl.map.setStyle).toHaveBeenCalledTimes(1); + expect(gl.engine.Map).toHaveBeenCalledTimes(1); + gl.map.addLayer.mockClear(); + act(() => gl.fire('style.load')); + expect(gl.map.addLayer).toHaveBeenCalledTimes(3); + }); + + it('FE-COMP-TERRAIN-014: removes the map with the view', async () => { + const { unmount } = await renderTerrain({ + waypoints: { points: [{ id: 'a', lat: 46, lng: 7 }], selectedId: null, onSelect: vi.fn() }, + }); + loadStyle(); + const [pin] = gl.markers.filter((marker) => marker.element.tagName === 'BUTTON'); + unmount(); + expect(gl.map.remove).toHaveBeenCalledTimes(1); + expect(pin.remove).toHaveBeenCalled(); + }); +}); diff --git a/client/src/components/Tours/terrain/TourTerrainMap.tsx b/client/src/components/Tours/terrain/TourTerrainMap.tsx new file mode 100644 index 000000000..fe18bdc88 --- /dev/null +++ b/client/src/components/Tours/terrain/TourTerrainMap.tsx @@ -0,0 +1,291 @@ +import { ChevronDown, ChevronUp, Gauge, Palette, Pause, Play, RotateCcw, Scan, TrendingUp } from 'lucide-react'; +import { useMemo, useState, type ReactNode } from 'react'; +import { useTranslation } from '../../../i18n'; +import type { DistanceUnit } from '../../../types'; +import type { DistanceIndexedProfileSample, RouteProfileFocus } from '../../../utils/routeGeometry'; +import { formatElevation } from '../../../utils/units'; +import { MAP_LAYER_SWITCHER_INSET, TourMapLayerSwitcher, type TourBaseLayer } from '../../Map/MapLayerSwitcher'; +import { MAP_CONTROL_SHADOW } from '../../Map/mapControlShadow'; +import { SoftPill } from '../../Planner/planParts'; +import { fs } from '../../shared/DialogShell'; +import { Tooltip } from '../../shared/Tooltip'; +import { GRADE_BANDS, terrainStats, type GradeBandKey, type TerrainStats } from './tourTerrainModel'; +import type { TerrainWaypoints } from './useTerrainPins'; +import { useTourTerrain } from './useTourTerrain'; + +export interface TourTerrainMapProps { + samples: DistanceIndexedProfileSample[]; + routes: [number, number][][] | null; + trackColor: string; + unit?: DistanceUnit; + baseLayer: TourBaseLayer; + onBaseLayerChange: (layer: TourBaseLayer) => void; + onExit: () => void; + focus: RouteProfileFocus | null; + onFocusChange: (focus: RouteProfileFocus | null) => void; + /** How much of the map each side panel covers, so framing and cards stay between them. */ + leftWidth: number; + rightWidth: number; + waypoints: TerrainWaypoints; + framePoints: [number, number][]; +} + +const SPEEDS = [1, 2, 4] as const; +/** Width the layer pill takes with its 3D switch, so the dock starts beside it. */ +const LAYER_PILL_WIDTH = 330; + +// The planner's map-control glass, the same shell as the layer pill. +const GLASS = { + background: 'var(--sidebar-bg)', + backdropFilter: 'blur(20px) saturate(180%)', + WebkitBackdropFilter: 'blur(20px) saturate(180%)', + boxShadow: MAP_CONTROL_SHADOW, +}; + +/** + * The tour planner map in 3D: the same map surface between the side panels, the route + * draped over an open elevation model and coloured by grade, with a flyover that moves + * the cursor on the rail's elevation profile. + */ +export default function TourTerrainMap(props: TourTerrainMapProps) { + const { samples, leftWidth, rightWidth, baseLayer, onBaseLayerChange, onExit, unit = 'metric' } = props; + const { setContainer, ...terrain } = useTourTerrain({ ...props, panels: { leftWidth, rightWidth } }); + const stats = useMemo(() => terrainStats(samples), [samples]); + + return ( +
+ {/* MapLibre makes its container position: relative, so it is sized, not inset. */} +
+ + {/* The flat map's layer pill, at the same spot, with 3D switched on. */} +
+ +
+ + {/* The flyover controls and the grade legend share the bottom edge with the pill, short of the right panel. */} +
+ + {terrain.canReplay ? ( + + ) : ( +
+ +
+ )} +
{terrain.canReplay && }
+
+
+ ); +} + +function PickHint({ editing }: { editing: boolean }) { + const { t } = useTranslation(); + return <>{t(editing ? 'tours.terrain.clickToPlan' : 'tours.terrain.pickTour')}; +} + +function IconButton({ + label, + onClick, + children, + primary = false, +}: { + label: string; + onClick: () => void; + children: ReactNode; + primary?: boolean; +}) { + return ( + + + + ); +} + +function Divider() { + return ; +} + +/** One pill like the layer switcher: play, restart, overview · speed · relief · colour. */ +function TerrainDock({ terrain }: { terrain: Omit, 'setContainer'> }) { + const { t } = useTranslation(); + return ( +
+ {terrain.preloaded < 1 ? ( + + ) : ( + + {terrain.playing ? : } + + )} + + + + + + + +
+ {SPEEDS.map((speed) => ( + + ))} +
+ + + + + + +
+ ); +} + +/** The landscape loading ahead of the flyover: a ring that fills, with the share in its tooltip. */ +function PreloadRing({ share, label }: { share: number; label: string }) { + const r = 13; + const c = 2 * Math.PI * r; + return ( + + + + + + + + {Math.round(share * 100)} + + + + ); +} + +/** The grade mix as a pill like the dock; it unfolds upwards into the bands. */ +function GradeLegend({ stats, unit }: { stats: TerrainStats; unit: DistanceUnit }) { + const { t } = useTranslation(); + const [open, setOpen] = useState(false); + const total = stats.totalMeters || 1; + const width = (key: GradeBandKey) => `${(stats.bandMeters[key] / total) * 100}%`; + return ( +
+ {open && ( +
+
    + {GRADE_BANDS.map((band) => ( +
  • + + {t(`tours.terrain.band.${band.key}`)} + + {Math.round((stats.bandMeters[band.key] / total) * 100)} % + +
  • + ))} +
+
+ {t('tours.terrain.attribution')} +
+
+ )} + +
+ ); +} diff --git a/client/src/components/Tours/terrain/terrainLayers.test.ts b/client/src/components/Tours/terrain/terrainLayers.test.ts new file mode 100644 index 000000000..ca736c140 --- /dev/null +++ b/client/src/components/Tours/terrain/terrainLayers.test.ts @@ -0,0 +1,195 @@ +import type { Map as MapLibreMap } from 'maplibre-gl'; +import { describe, expect, it, vi } from 'vitest'; +import { OPENFREEMAP_DEFAULT_STYLE } from '../../Map/glProviders'; +import { + addTerrainLayers, + corridorPoints, + DEM_SOURCE, + frameBounds, + loadedTemplates, + riderElement, + sidePadding, + styleFor, + TRACK_SOURCE, + trackData, + waypointPinElement, +} from './terrainLayers'; +import { GRADE_BANDS } from './tourTerrainModel'; + +const climb = Array.from({ length: 4 }, (_, i) => ({ + distanceMeters: i * 100, + elevationMeters: i * 20, + lat: 46 + i / 1000, + lng: 7 + i / 1000, +})); + +function fakeMap(sources: Record = {}) { + const added = new Map(Object.entries(sources)); + const map = { + getSource: vi.fn((id: string) => added.get(id)), + addSource: vi.fn((id: string, source: unknown) => added.set(id, source)), + addLayer: vi.fn(), + setTerrain: vi.fn(), + setSky: vi.fn(), + getStyle: vi.fn(() => ({ sources: Object.fromEntries(added) })), + }; + return { map, gl: map as unknown as MapLibreMap }; +} + +describe('styleFor', () => { + it('drapes the planner base layers over the terrain', () => { + expect(styleFor('default')).toBe(OPENFREEMAP_DEFAULT_STYLE); + const topo = styleFor('topo'); + const satellite = styleFor('satellite'); + if (typeof topo === 'string' || typeof satellite === 'string') throw new Error('expected raster styles'); + expect(topo.sources.base).toMatchObject({ type: 'raster', maxzoom: 17 }); + expect(JSON.stringify(topo)).not.toContain('{s}'); + expect(satellite.sources.base).toMatchObject({ type: 'raster', maxzoom: 19 }); + }); +}); + +describe('trackData', () => { + it('paints each piece of the open tour in its grade band', () => { + const data = trackData(climb, null, 'grade', '#0a84ff'); + expect(data.features).toHaveLength(3); + expect(data.features[0].properties.color).toBe(GRADE_BANDS.find((band) => band.key === 'steep')?.paint); + expect(data.features[0].geometry.coordinates).toEqual([ + [7, 46], + [7.001, 46.001], + ]); + }); + + it('paints the open tour in its own colour when asked', () => { + const data = trackData(climb, null, 'tour', '#123456'); + expect(data.features.every((feature) => feature.properties.color === '#123456')).toBe(true); + }); + + it('draws the planner routes, as [lng, lat], while no tour is open', () => { + const data = trackData( + [], + [ + [ + [46, 7], + [46.1, 7.1], + ], + [[47, 8]], + ], + 'grade', + '#0a84ff' + ); + expect(data.features).toHaveLength(1); + expect(data.features[0].geometry.coordinates).toEqual([ + [7, 46], + [7.1, 46.1], + ]); + expect(trackData([], null, 'grade', '#0a84ff').features).toEqual([]); + }); +}); + +describe('frameBounds', () => { + const empty = trackData([], null, 'grade', '#0a84ff'); + + it('frames the drawn route first', () => { + expect(frameBounds(trackData(climb, null, 'grade', '#0a84ff'), [{ lat: 0, lng: 0 }], [])).toEqual([ + [7, 46], + [7.003, 46.003], + ]); + }); + + it('frames the control points while there is no route', () => { + expect( + frameBounds( + empty, + [ + { lat: 46, lng: 7 }, + { lat: 47, lng: 8 }, + ], + [[1, 1]] + ) + ).toEqual([ + [7, 46], + [8, 47], + ]); + }); + + it('frames what the flat map framed, with room around a lone point', () => { + const bounds = frameBounds(empty, [], [[46, 7]]); + expect(bounds?.[0][0]).toBeCloseTo(6.98); + expect(bounds?.[0][1]).toBeCloseTo(45.98); + expect(bounds?.[1][0]).toBeCloseTo(7.02); + expect(bounds?.[1][1]).toBeCloseTo(46.02); + expect(frameBounds(empty, [], [])).toBeNull(); + }); +}); + +describe('camera and markers', () => { + it('pads the camera by the panels on their own sides', () => { + expect(sidePadding({ leftWidth: 300, rightWidth: 420 }, 40)).toEqual({ left: 340, right: 460 }); + }); + + it('keeps one corridor point every 150 m that has a position', () => { + const samples = [ + { distanceMeters: 0, elevationMeters: 0, lat: 46, lng: 7 }, + { distanceMeters: 100, elevationMeters: 0, lat: 46.001, lng: 7 }, + { distanceMeters: 160, elevationMeters: 0 }, + { distanceMeters: 200, elevationMeters: 0, lat: 46.002, lng: 7 }, + { distanceMeters: 400, elevationMeters: 0, lat: 46.004, lng: 7 }, + ]; + expect(corridorPoints(samples)).toEqual([ + { lat: 46, lng: 7 }, + { lat: 46.002, lng: 7 }, + { lat: 46.004, lng: 7 }, + ]); + }); + + it('draws the rider in the tour colour', () => { + expect(riderElement('rgb(1, 2, 3)').style.background).toBe('rgb(1, 2, 3)'); + }); + + it('numbers a control point and shows whether it can be dragged', () => { + const pin = waypointPinElement(2, true, true); + expect(pin.textContent).toBe('3'); + expect(pin.getAttribute('aria-label')).toBe('Waypoint 3'); + expect(pin.style.width).toBe('30px'); + expect(pin.style.cursor).toBe('grab'); + const fixed = waypointPinElement(0, false, false); + expect(fixed.style.width).toBe('26px'); + expect(fixed.style.cursor).toBe('pointer'); + }); +}); + +describe('map layers', () => { + it('adds the elevation model, the hillshade and the track with its casing', () => { + const { map, gl } = fakeMap(); + const data = trackData(climb, null, 'grade', '#0a84ff'); + addTerrainLayers(gl, data, 1.5); + expect(map.setTerrain).toHaveBeenCalledWith({ source: DEM_SOURCE, exaggeration: 1.5 }); + expect(map.addSource).toHaveBeenCalledWith(TRACK_SOURCE, { type: 'geojson', data }); + expect(map.addLayer.mock.calls.map(([layer]) => (layer as { id: string }).id)).toEqual([ + 'tour-terrain-hillshade', + 'tour-terrain-casing', + 'tour-terrain-line', + ]); + expect(map.setSky).toHaveBeenCalledTimes(1); + }); + + it('keeps the elevation sources across a style swap', () => { + const { map, gl } = fakeMap({ [DEM_SOURCE]: {}, 'tour-terrain-hillshade-dem': {} }); + addTerrainLayers(gl, trackData([], null, 'grade', '#0a84ff'), 2); + expect(map.addSource).toHaveBeenCalledTimes(1); + }); + + it('lists the tiled sources to preload, without the hillshade copy and the track', () => { + const { gl } = fakeMap({ + base: { tiles: ['https://tiles/{z}/{x}/{y}.png'], maxzoom: 19 }, + [DEM_SOURCE]: { tiles: ['https://dem/{z}/{x}/{y}.png'], minzoom: 0, maxzoom: 15 }, + 'tour-terrain-hillshade-dem': { tiles: ['https://dem/{z}/{x}/{y}.png'] }, + [TRACK_SOURCE]: { tiles: ['nope'] }, + vector: {}, + }); + expect(loadedTemplates(gl)).toEqual([ + { url: 'https://tiles/{z}/{x}/{y}.png', minzoom: 0, maxzoom: 19 }, + { url: 'https://dem/{z}/{x}/{y}.png', minzoom: 0, maxzoom: 15 }, + ]); + }); +}); diff --git a/client/src/components/Tours/terrain/terrainLayers.ts b/client/src/components/Tours/terrain/terrainLayers.ts new file mode 100644 index 000000000..ff8cf5277 --- /dev/null +++ b/client/src/components/Tours/terrain/terrainLayers.ts @@ -0,0 +1,209 @@ +import type { Map as MapLibreMap, StyleSpecification } from 'maplibre-gl'; +import { OPENTOPOMAP_TILE_URL, SATELLITE_TILE_URL } from '../../../constants/mapDefaults'; +import type { DistanceIndexedProfileSample } from '../../../utils/routeGeometry'; +import { OPENFREEMAP_DEFAULT_STYLE } from '../../Map/glProviders'; +import type { TourBaseLayer } from '../../Map/MapLayerSwitcher'; +import type { TileTemplate } from './terrainPrefetch'; +import { gradeBand, gradeSegments } from './tourTerrainModel'; + +/** + * What the 3D tour map draws and how its camera frames it, kept out of the hooks so + * the hooks only wire it to React. Everything here is map paint on the terrain, not an + * app surface, which is why the colours are fixed hex rather than theme tokens. + */ + +export type TrackColorMode = 'grade' | 'tour'; + +// Mapzen's Terrarium tiles, published as AWS Open Data: free, keyless, worldwide. +const DEM_TILES = 'https://elevation-tiles-prod.s3.amazonaws.com/terrarium/{z}/{x}/{y}.png'; +export const DEM_SOURCE = 'tour-terrain-dem'; +// Hillshade reads its own copy: sharing the terrain's source lowers both renderings. +const HILLSHADE_SOURCE = 'tour-terrain-hillshade-dem'; +export const TRACK_SOURCE = 'tour-terrain-track'; +export const PITCH = 60; +/** The planner's route blue, the colour its numbered control points always had. */ +const PIN_BLUE = '#0a84ff'; + +/** How much of the map each side panel covers. The panels sit on fixed physical sides. */ +export interface PanelWidths { + leftWidth: number; + rightWidth: number; +} + +type Bounds = [[number, number], [number, number]]; + +export type TrackData = { + type: 'FeatureCollection'; + features: { + type: 'Feature'; + properties: { color: string }; + geometry: { type: 'LineString'; coordinates: [number, number][] }; + }[]; +}; + +/** The camera's side padding: the panels plus a margin, on the sides the panels are on. */ +export function sidePadding(panels: PanelWidths, margin: number) { + const left = panels.leftWidth + margin; + const right = panels.rightWidth + margin; + return { left, right }; +} + +function rasterStyle(tiles: string[], maxzoom: number): StyleSpecification { + return { + version: 8, + sources: { base: { type: 'raster', tiles, tileSize: 256, maxzoom } }, + layers: [{ id: 'base', type: 'raster', source: 'base' }], + }; +} + +/** The same three looks as the flat planner map, draped over the terrain. */ +export function styleFor(layer: TourBaseLayer): string | StyleSpecification { + if (layer === 'satellite') return rasterStyle([SATELLITE_TILE_URL], 19); + if (layer === 'topo') + return rasterStyle( + ['a', 'b', 'c'].map((s) => OPENTOPOMAP_TILE_URL.replace('{s}', s)), + 17 + ); + return OPENFREEMAP_DEFAULT_STYLE; +} + +function line(color: string, coordinates: [number, number][]): TrackData['features'][number] { + return { type: 'Feature', properties: { color }, geometry: { type: 'LineString', coordinates } }; +} + +/** The open tour piece by piece in its grade colours, else every planner route in the tour colour. */ +export function trackData( + samples: DistanceIndexedProfileSample[], + routes: [number, number][][] | null, + mode: TrackColorMode, + trackColor: string +): TrackData { + const segments = gradeSegments(samples); + if (segments.length) { + return { + type: 'FeatureCollection', + features: segments.map((segment) => + line(mode === 'grade' ? gradeBand(segment.grade).paint : trackColor, [segment.from, segment.to]) + ), + }; + } + return { + type: 'FeatureCollection', + features: (routes ?? []) + .filter((route) => route.length > 1) + .map((route) => + line( + trackColor, + route.map(([lat, lng]) => [lng, lat] as [number, number]) + ) + ), + }; +} + +function boundsOf(points: [number, number][], pad: number): Bounds | null { + if (!points.length) return null; + const lngs = points.map((p) => p[0]); + const lats = points.map((p) => p[1]); + return [ + [Math.min(...lngs) - pad, Math.min(...lats) - pad], + [Math.max(...lngs) + pad, Math.max(...lats) + pad], + ]; +} + +/** + * What the camera frames: the drawn route, else the control points, else what the flat + * map framed ([lat, lng] each). A lone point gets ~2 km around it, so the terrain shows + * instead of one tile. + */ +export function frameBounds( + data: TrackData, + pins: ReadonlyArray<{ lat: number; lng: number }>, + framePoints: [number, number][] +): Bounds | null { + const route = boundsOf( + data.features.flatMap((feature) => feature.geometry.coordinates), + 0 + ); + if (route) return route; + const fallback = pins.length + ? pins.map((p): [number, number] => [p.lng, p.lat]) + : framePoints.map(([lat, lng]): [number, number] => [lng, lat]); + return boundsOf(fallback, fallback.length === 1 ? 0.02 : 0); +} + +/** The terrain, its hillshade and the route on top; run again after every style swap. */ +export function addTerrainLayers(map: MapLibreMap, data: TrackData, exaggeration: number): void { + for (const id of [DEM_SOURCE, HILLSHADE_SOURCE]) { + if (!map.getSource(id)) { + map.addSource(id, { type: 'raster-dem', tiles: [DEM_TILES], tileSize: 256, encoding: 'terrarium', maxzoom: 15 }); + } + } + map.setTerrain({ source: DEM_SOURCE, exaggeration }); + map.addLayer({ + id: 'tour-terrain-hillshade', + type: 'hillshade', + source: HILLSHADE_SOURCE, + paint: { 'hillshade-exaggeration': 0.35 }, + }); + map.addSource(TRACK_SOURCE, { type: 'geojson', data }); + const layout = { 'line-cap': 'round', 'line-join': 'round' } as const; + map.addLayer({ + id: 'tour-terrain-casing', + type: 'line', + source: TRACK_SOURCE, + layout, + paint: { 'line-color': '#ffffff', 'line-width': 8, 'line-opacity': 0.9 }, + }); + map.addLayer({ + id: 'tour-terrain-line', + type: 'line', + source: TRACK_SOURCE, + layout, + paint: { 'line-color': ['get', 'color'], 'line-width': 5 }, + }); + map.setSky({ 'sky-color': '#9cc3f0', 'horizon-color': '#e8f0fb', 'fog-color': '#f4f7fb', 'sky-horizon-blend': 0.5 }); +} + +/** Every tiled source the loaded style draws from, the elevation model included. */ +export function loadedTemplates(map: MapLibreMap): TileTemplate[] { + const templates: TileTemplate[] = []; + for (const id of Object.keys(map.getStyle().sources)) { + if (id === HILLSHADE_SOURCE || id === TRACK_SOURCE) continue; + const source = map.getSource(id) as { tiles?: string[]; minzoom?: number; maxzoom?: number } | undefined; + const url = source?.tiles?.[0]; + if (url) templates.push({ url, minzoom: source.minzoom ?? 0, maxzoom: source.maxzoom ?? 22 }); + } + return templates; +} + +/** One point every ~150 m of the route: dense enough that no tile of the corridor is skipped. */ +export function corridorPoints(samples: DistanceIndexedProfileSample[]): { lat: number; lng: number }[] { + const points: { lat: number; lng: number }[] = []; + let lastAt = -Infinity; + for (const sample of samples) { + const { lat, lng } = sample; + if (lat === undefined || lng === undefined || !Number.isFinite(lat) || !Number.isFinite(lng)) continue; + if (sample.distanceMeters - lastAt < 150) continue; + lastAt = sample.distanceMeters; + points.push({ lat, lng }); + } + return points; +} + +/** The dot that rides the route during the flyover and marks the rail's focus. */ +export function riderElement(trackColor: string): HTMLElement { + const el = document.createElement('div'); + el.style.cssText = `width:18px;height:18px;border-radius:9999px;background:${trackColor};border:3px solid #fff;box-shadow:0 2px 8px rgba(0,0,0,.45)`; + return el; +} + +/** A numbered control point, the same pin the flat planner map draws. */ +export function waypointPinElement(index: number, selected: boolean, editable: boolean): HTMLButtonElement { + const size = selected ? 30 : 26; + const el = document.createElement('button'); + el.type = 'button'; + el.textContent = String(index + 1); + el.setAttribute('aria-label', `Waypoint ${index + 1}`); + el.style.cssText = `display:flex;width:${size}px;height:${size}px;align-items:center;justify-content:center;border-radius:9999px;background:${PIN_BLUE};color:white;border:${selected ? 3 : 2}px solid white;box-shadow:0 2px 7px rgba(0,0,0,.4);font:700 11px system-ui;cursor:${editable ? 'grab' : 'pointer'};padding:0`; + return el; +} diff --git a/client/src/components/Tours/terrain/terrainPrefetch.test.ts b/client/src/components/Tours/terrain/terrainPrefetch.test.ts new file mode 100644 index 000000000..6caaf3c3d --- /dev/null +++ b/client/src/components/Tours/terrain/terrainPrefetch.test.ts @@ -0,0 +1,147 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { corridorTiles, prefetchTiles, tileUrls } from './terrainPrefetch'; + +const OK = { ok: true } as Response; + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('corridorTiles', () => { + it('takes the ring around a point at each zoom: wide when coarse, tight when fine', () => { + const tiles = corridorTiles([{ lat: 0, lng: 0 }]); + const perZoom = (z: number) => tiles.filter(([zoom]) => zoom === z).length; + expect(perZoom(9)).toBe(9); + expect(perZoom(11)).toBe(25); + expect(perZoom(15)).toBe(9); + expect(tiles).toHaveLength(95); + expect(tiles).toContainEqual([9, 256, 256]); + }); + + it('lists a tile two points share once', () => { + expect( + corridorTiles( + [ + { lat: 0, lng: 0 }, + { lat: 0, lng: 0.0001 }, + ], + [9] + ) + ).toHaveLength(9); + }); + + it('wraps round the antimeridian and stops at the poles', () => { + const atDateLine = corridorTiles([{ lat: 0, lng: -180 }], [9]); + expect(atDateLine).toContainEqual([9, 511, 256]); + const nearPole = corridorTiles([{ lat: 85, lng: 0 }], [9]); + expect(nearPole).toHaveLength(6); + expect(nearPole.every(([, , y]) => y >= 0)).toBe(true); + }); + + it('takes one tile of ring for a zoom it has no ring for', () => { + expect(corridorTiles([{ lat: 0, lng: 0 }], [5])).toHaveLength(9); + }); +}); + +describe('tileUrls', () => { + const tiles: Array<[number, number, number]> = [ + [9, 10, 20], + [12, 80, 160], + [13, 160, 320], + [13, 161, 321], + ]; + + it('fills each template and skips the zooms below its first', () => { + expect(tileUrls([{ url: 'https://t/{z}/{x}/{y}.png', minzoom: 10, maxzoom: 22 }], tiles)).toEqual([ + 'https://t/12/80/160.png', + 'https://t/13/160/320.png', + 'https://t/13/161/321.png', + ]); + }); + + it("fetches a source's deepest tile past its last zoom, once", () => { + expect(tileUrls([{ url: 'https://dem/{z}/{x}/{y}', minzoom: 0, maxzoom: 12 }], tiles)).toEqual([ + 'https://dem/9/10/20', + 'https://dem/12/80/160', + ]); + }); + + it('covers every template', () => { + const urls = tileUrls( + [ + { url: 'a/{z}/{x}/{y}', minzoom: 0, maxzoom: 22 }, + { url: 'b/{z}/{x}/{y}', minzoom: 0, maxzoom: 22 }, + ], + [[9, 1, 2]] + ); + expect(urls).toEqual(['a/9/1/2', 'b/9/1/2']); + }); +}); + +describe('prefetchTiles', () => { + it('reports done at once when there is nothing to fetch', async () => { + const fetchStub = vi.fn(); + vi.stubGlobal('fetch', fetchStub); + const progress = vi.fn(); + await prefetchTiles([], new AbortController().signal, progress); + expect(progress.mock.calls).toEqual([[1]]); + expect(fetchStub).not.toHaveBeenCalled(); + }); + + it('fetches every URL from the cache-first store and counts up to 1', async () => { + const fetchStub = vi.fn(() => Promise.resolve(OK)); + vi.stubGlobal('fetch', fetchStub); + const progress = vi.fn(); + const signal = new AbortController().signal; + await prefetchTiles(['u1', 'u2', 'u3', 'u4'], signal, progress); + expect(fetchStub).toHaveBeenCalledTimes(4); + expect(fetchStub).toHaveBeenCalledWith('u1', { signal, mode: 'cors', cache: 'force-cache' }); + expect(progress.mock.calls.map(([share]) => share)).toEqual([0, 0.25, 0.5, 0.75, 1]); + }); + + it('skips a tile that fails instead of stopping', async () => { + vi.stubGlobal( + 'fetch', + vi.fn((url: string) => (url === 'bad' ? Promise.reject(new Error('offline')) : Promise.resolve(OK))) + ); + const progress = vi.fn(); + await prefetchTiles(['bad', 'good'], new AbortController().signal, progress); + expect(progress).toHaveBeenLastCalledWith(1); + }); + + it('keeps at most eight requests in flight', async () => { + const pending: Array<() => void> = []; + vi.stubGlobal( + 'fetch', + vi.fn( + () => + new Promise((resolve) => { + pending.push(() => resolve(OK)); + }) + ) + ); + const run = prefetchTiles( + Array.from({ length: 12 }, (_, i) => `u${i}`), + new AbortController().signal, + () => {} + ); + expect(pending).toHaveLength(8); + pending.splice(0).forEach((resolve) => resolve()); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(pending).toHaveLength(4); + pending.splice(0).forEach((resolve) => resolve()); + await run; + expect(fetch).toHaveBeenCalledTimes(12); + }); + + it('starts no request once aborted', async () => { + const fetchStub = vi.fn(() => Promise.resolve(OK)); + vi.stubGlobal('fetch', fetchStub); + const controller = new AbortController(); + controller.abort(); + const progress = vi.fn(); + await prefetchTiles(['u1', 'u2'], controller.signal, progress); + expect(fetchStub).not.toHaveBeenCalled(); + expect(progress.mock.calls).toEqual([[0]]); + }); +}); diff --git a/client/src/components/Tours/terrain/terrainPrefetch.ts b/client/src/components/Tours/terrain/terrainPrefetch.ts new file mode 100644 index 000000000..20e2be091 --- /dev/null +++ b/client/src/components/Tours/terrain/terrainPrefetch.ts @@ -0,0 +1,107 @@ +/** + * Warms the browser cache with every tile a flyover along a route will ask for, so the + * 3D replay draws from cache instead of loading the landscape in front of the camera. + */ + +export interface TileTemplate { + /** A `{z}/{x}/{y}` URL template; `{s}` subdomains are resolved before this. */ + url: string; + minzoom: number; + maxzoom: number; +} + +interface LatLng { + lat: number; + lng: number; +} + +/** How far around the route each zoom reaches, in tiles: wide when coarse, tight when fine. */ +const RING_BY_ZOOM: Record = { 9: 1, 10: 1, 11: 2, 12: 2, 13: 1, 14: 1, 15: 1 }; +const ZOOMS = [9, 10, 11, 12, 13, 14, 15]; +const CONCURRENCY = 8; + +function tileOf(point: LatLng, z: number): [number, number] { + const n = 2 ** z; + const x = Math.floor(((point.lng + 180) / 360) * n); + const rad = (point.lat * Math.PI) / 180; + const y = Math.floor(((1 - Math.log(Math.tan(rad) + 1 / Math.cos(rad)) / Math.PI) / 2) * n); + return [Math.min(n - 1, Math.max(0, x)), Math.min(n - 1, Math.max(0, y))]; +} + +/** The tiles within `ring` of a centre tile; x wraps round the antimeridian, y stops at the poles. */ +function ringAround([cx, cy]: [number, number], ring: number, z: number): Array<[number, number, number]> { + const n = 2 ** z; + const tiles: Array<[number, number, number]> = []; + for (let dx = -ring; dx <= ring; dx++) { + for (let dy = -ring; dy <= ring; dy++) { + const y = cy + dy; + if (y >= 0 && y < n) tiles.push([z, (cx + dx + n) % n, y]); + } + } + return tiles; +} + +/** Every tile within the ring of a point on the route, per zoom, without duplicates. */ +export function corridorTiles( + points: readonly LatLng[], + zooms: readonly number[] = ZOOMS +): Array<[number, number, number]> { + const seen = new Set(); + const tiles: Array<[number, number, number]> = []; + for (const z of zooms) { + const ring = RING_BY_ZOOM[z] ?? 1; + for (const point of points) { + for (const tile of ringAround(tileOf(point, z), ring, z)) { + const key = tile.join('/'); + if (seen.has(key)) continue; + seen.add(key); + tiles.push(tile); + } + } + } + return tiles; +} + +export function tileUrls(templates: readonly TileTemplate[], tiles: ReadonlyArray<[number, number, number]>): string[] { + const urls: string[] = []; + for (const template of templates) { + for (const [z, x, y] of tiles) { + if (z < template.minzoom) continue; + // Past a source's last zoom the map overzooms the deepest tile, so fetch that one. + const shift = Math.max(0, z - template.maxzoom); + const zz = z - shift; + urls.push( + template.url + .replace('{z}', String(zz)) + .replace('{x}', String(x >> shift)) + .replace('{y}', String(y >> shift)) + ); + } + } + return [...new Set(urls)]; +} + +/** Fetches the URLs a few at a time and reports progress from 0 to 1. A failed tile is skipped, not retried. */ +export async function prefetchTiles( + urls: readonly string[], + signal: AbortSignal, + onProgress: (share: number) => void +): Promise { + let done = 0; + let next = 0; + const total = urls.length || 1; + onProgress(urls.length ? 0 : 1); + const worker = async () => { + while (next < urls.length && !signal.aborted) { + const url = urls[next++]; + try { + await fetch(url, { signal, mode: 'cors', cache: 'force-cache' }); + } catch { + // A missing tile only means the map loads that one itself later. + } + done++; + onProgress(done / total); + } + }; + await Promise.all(Array.from({ length: CONCURRENCY }, worker)); +} diff --git a/client/src/components/Tours/terrain/tourTerrainModel.test.ts b/client/src/components/Tours/terrain/tourTerrainModel.test.ts new file mode 100644 index 000000000..486b5096e --- /dev/null +++ b/client/src/components/Tours/terrain/tourTerrainModel.test.ts @@ -0,0 +1,145 @@ +import { describe, expect, it } from 'vitest'; +import type { DistanceIndexedProfileSample } from '../../../utils/routeGeometry'; +import { + bearingDegrees, + easeBearing, + GRADE_BANDS, + gradeBand, + gradeSegments, + replayMetresPerSecond, + terrainStats, +} from './tourTerrainModel'; + +/** A walk due east from 46 N 7 E, one sample every `step` metres, at the heights `elevation` returns. */ +function profile(count: number, step: number, elevation: (distance: number) => number): DistanceIndexedProfileSample[] { + return Array.from({ length: count }, (_, i) => { + const distanceMeters = i * step; + return { distanceMeters, elevationMeters: elevation(distanceMeters), lat: 46, lng: 7 + distanceMeters / 77_000 }; + }); +} + +describe('gradeBand', () => { + it('sorts a grade into the band it is below, uphill and downhill alike', () => { + expect(gradeBand(0).key).toBe('flat'); + expect(gradeBand(4.9).key).toBe('flat'); + expect(gradeBand(5).key).toBe('gentle'); + expect(gradeBand(-12).key).toBe('moderate'); + expect(gradeBand(20).key).toBe('steep'); + expect(gradeBand(-30).key).toBe('verySteep'); + }); + + it('falls back to the steepest band for a grade no band holds', () => { + expect(gradeBand(Number.NaN)).toBe(GRADE_BANDS[GRADE_BANDS.length - 1]); + expect(gradeBand(Infinity).key).toBe('verySteep'); + }); + + it('gives every band its own map paint', () => { + expect(new Set(GRADE_BANDS.map((band) => band.paint)).size).toBe(GRADE_BANDS.length); + }); +}); + +describe('gradeSegments', () => { + it('needs two located samples', () => { + expect(gradeSegments([])).toEqual([]); + expect(gradeSegments(profile(1, 100, () => 0))).toEqual([]); + expect( + gradeSegments([ + { distanceMeters: 0, elevationMeters: 0 }, + { distanceMeters: 100, elevationMeters: 10 }, + ]) + ).toEqual([]); + }); + + it('cuts the route into one piece per pair of samples, as [lng, lat]', () => { + const samples = profile(5, 100, (d) => d / 10); + const segments = gradeSegments(samples); + expect(segments).toHaveLength(4); + expect(segments[0].from).toEqual([samples[0].lng, samples[0].lat]); + expect(segments[0].to).toEqual([samples[1].lng, samples[1].lat]); + for (const segment of segments) { + expect(segment.grade).toBeCloseTo(10); + expect(segment.signedGrade).toBeCloseTo(10); + } + }); + + it('keeps the sign for a descent and the absolute value for the colour', () => { + const [segment] = gradeSegments(profile(4, 100, (d) => 500 - d / 5)); + expect(segment.signedGrade).toBeCloseTo(-20); + expect(segment.grade).toBeCloseTo(20); + }); + + it('skips samples without a position', () => { + const samples = [...profile(3, 100, () => 0), { distanceMeters: 300, elevationMeters: 0 }]; + expect(gradeSegments(samples)).toHaveLength(2); + }); + + it('reads a window without length as flat instead of dividing by zero', () => { + const samples = [0, 1, 2].map((i) => ({ distanceMeters: 0, elevationMeters: i * 10, lat: 46, lng: 7 + i / 1000 })); + expect(gradeSegments(samples).map((segment) => segment.grade)).toEqual([0, 0]); + }); + + it('smooths a single jittery sample over the window', () => { + const samples = profile(21, 20, (d) => (d === 200 ? 4 : 0)); + const steepest = Math.max(...gradeSegments(samples).map((segment) => segment.grade)); + // 4 m over 20 m would read 20 %; over the 200 m window it stays gentle. + expect(steepest).toBeLessThan(5); + }); +}); + +describe('terrainStats', () => { + it('is empty for a tour without a located profile', () => { + expect(terrainStats([])).toEqual({ + summit: null, + lowest: null, + steepest: null, + bandMeters: { flat: 0, gentle: 0, moderate: 0, steep: 0, verySteep: 0 }, + totalMeters: 0, + }); + }); + + it('finds the summit, the lowest point and the steepest 200 m', () => { + // Flat for 500 m, then 20 % up for 500 m. + const samples = profile(11, 100, (d) => (d <= 500 ? 1000 : 1000 + (d - 500) / 5)); + const stats = terrainStats(samples); + expect(stats.summit).toEqual({ lat: 46, lng: samples[10].lng, elevationMeters: 1100, distanceMeters: 1000 }); + expect(stats.lowest?.elevationMeters).toBe(1000); + expect(stats.lowest?.distanceMeters).toBe(0); + expect(stats.steepest?.grade).toBeCloseTo(20); + expect(stats.steepest?.startMeters).toBeGreaterThanOrEqual(500); + expect(stats.totalMeters).toBe(1000); + }); + + it('shares the walked metres out between the bands', () => { + const stats = terrainStats(profile(11, 100, (d) => (d <= 500 ? 1000 : 1000 + (d - 500) / 5))); + const walked = Object.values(stats.bandMeters).reduce((sum, metres) => sum + metres, 0); + expect(walked).toBe(1000); + expect(stats.bandMeters.flat).toBeGreaterThan(0); + expect(stats.bandMeters.steep).toBeGreaterThan(0); + }); + + it('names no steepest stretch on a route shorter than 200 m', () => { + expect(terrainStats(profile(2, 100, (d) => d)).steepest).toBeNull(); + }); +}); + +describe('camera helpers', () => { + it('measures the compass bearing between two points', () => { + expect(bearingDegrees({ lat: 0, lng: 0 }, { lat: 1, lng: 0 })).toBeCloseTo(0); + expect(bearingDegrees({ lat: 0, lng: 0 }, { lat: 0, lng: 1 })).toBeCloseTo(90); + expect(bearingDegrees({ lat: 1, lng: 0 }, { lat: 0, lng: 0 })).toBeCloseTo(180); + expect(bearingDegrees({ lat: 0, lng: 1 }, { lat: 0, lng: 0 })).toBeCloseTo(270); + }); + + it('eases the heading the short way round', () => { + expect(easeBearing(350, 10, 0.5)).toBeCloseTo(0); + expect(easeBearing(10, 350, 0.5)).toBeCloseTo(0); + expect(easeBearing(90, 180, 1)).toBeCloseTo(180); + expect(easeBearing(90, 180, 0)).toBeCloseTo(90); + }); + + it('plays a route in about 45 seconds, never slower than 20 m a second', () => { + expect(replayMetresPerSecond(9000)).toBe(200); + expect(replayMetresPerSecond(450)).toBe(20); + expect(replayMetresPerSecond(9000, 90)).toBe(100); + }); +}); diff --git a/client/src/components/Tours/terrain/tourTerrainModel.ts b/client/src/components/Tours/terrain/tourTerrainModel.ts new file mode 100644 index 000000000..d4c207564 --- /dev/null +++ b/client/src/components/Tours/terrain/tourTerrainModel.ts @@ -0,0 +1,165 @@ +import type { DistanceIndexedProfileSample } from '../../../utils/routeGeometry'; + +/** + * The 3D tour view's numbers, derived from the distance-indexed profile the tour + * dialog already builds. Pure and React-free, so the view only draws. + */ + +/** + * Grade bands in percent, the way hiking maps colour a route. `paint` is map paint on + * the terrain, not an app surface: fixed hex like the day colours, since a token that + * follows the user's accent would turn a steep stretch the colour of a flat one. + */ +export const GRADE_BANDS = [ + { max: 5, paint: '#22c55e', key: 'flat' }, + { max: 10, paint: '#a3e635', key: 'gentle' }, + { max: 18, paint: '#facc15', key: 'moderate' }, + { max: 27, paint: '#f97316', key: 'steep' }, + { max: Infinity, paint: '#dc2626', key: 'verySteep' }, +] as const; + +export type GradeBandKey = (typeof GRADE_BANDS)[number]['key']; + +interface GradeSegment { + from: [number, number]; + to: [number, number]; + /** Absolute grade in percent over the smoothing window. */ + grade: number; + /** Signed grade: positive uphill in the walking direction. */ + signedGrade: number; +} + +interface SummitPoint { + lat: number; + lng: number; + elevationMeters: number; + distanceMeters: number; +} + +interface SteepestStretch { + startMeters: number; + endMeters: number; + grade: number; +} + +export interface TerrainStats { + summit: SummitPoint | null; + lowest: SummitPoint | null; + steepest: SteepestStretch | null; + /** Metres walked in each grade band. */ + bandMeters: Record; + totalMeters: number; +} + +type LocatedSample = DistanceIndexedProfileSample & { lat: number; lng: number }; + +function located(samples: readonly DistanceIndexedProfileSample[]): LocatedSample[] { + return samples.filter((s): s is LocatedSample => Number.isFinite(s.lat) && Number.isFinite(s.lng)); +} + +export function gradeBand(grade: number): (typeof GRADE_BANDS)[number] { + return GRADE_BANDS.find((band) => Math.abs(grade) < band.max) ?? GRADE_BANDS[GRADE_BANDS.length - 1]; +} + +/** + * The grade at each sample over a window of about `windowMeters`, so GPS jitter on a + * few metres does not paint a flat path red. + */ +function smoothedGrades(samples: readonly LocatedSample[], windowMeters: number): number[] { + const grades: number[] = []; + let back = 0; + let ahead = 0; + for (let i = 0; i < samples.length; i++) { + const here = samples[i].distanceMeters; + while (back < i && here - samples[back].distanceMeters > windowMeters / 2) back++; + if (ahead < i) ahead = i; + while (ahead < samples.length - 1 && samples[ahead].distanceMeters - here < windowMeters / 2) ahead++; + const run = samples[ahead].distanceMeters - samples[back].distanceMeters; + const rise = samples[ahead].elevationMeters - samples[back].elevationMeters; + grades.push(run > 0 ? (rise / run) * 100 : 0); + } + return grades; +} + +/** One coloured piece per pair of samples, ready for a GeoJSON line layer. */ +export function gradeSegments(samples: readonly DistanceIndexedProfileSample[], windowMeters = 200): GradeSegment[] { + const points = located(samples); + if (points.length < 2) return []; + const grades = smoothedGrades(points, windowMeters); + const segments: GradeSegment[] = []; + for (let i = 1; i < points.length; i++) { + const signedGrade = (grades[i - 1] + grades[i]) / 2; + segments.push({ + from: [points[i - 1].lng, points[i - 1].lat], + to: [points[i].lng, points[i].lat], + grade: Math.abs(signedGrade), + signedGrade, + }); + } + return segments; +} + +function emptyBands(): Record { + return { flat: 0, gentle: 0, moderate: 0, steep: 0, verySteep: 0 }; +} + +function extreme(points: readonly LocatedSample[], pick: (a: number, b: number) => boolean): SummitPoint | null { + let best: LocatedSample | null = null; + for (const point of points) if (!best || pick(point.elevationMeters, best.elevationMeters)) best = point; + return ( + best && { lat: best.lat, lng: best.lng, elevationMeters: best.elevationMeters, distanceMeters: best.distanceMeters } + ); +} + +/** The steepest stretch of at least `minMeters`, uphill or down. */ +function steepestStretch(points: readonly LocatedSample[], minMeters: number): SteepestStretch | null { + let best: SteepestStretch | null = null; + let start = 0; + for (let end = 1; end < points.length; end++) { + while (start < end - 1 && points[end].distanceMeters - points[start + 1].distanceMeters >= minMeters) start++; + const run = points[end].distanceMeters - points[start].distanceMeters; + if (run < minMeters) continue; + const grade = (Math.abs(points[end].elevationMeters - points[start].elevationMeters) / run) * 100; + if (!best || grade > best.grade) + best = { startMeters: points[start].distanceMeters, endMeters: points[end].distanceMeters, grade }; + } + return best; +} + +export function terrainStats(samples: readonly DistanceIndexedProfileSample[]): TerrainStats { + const points = located(samples); + const bandMeters = emptyBands(); + const segments = gradeSegments(samples); + for (let i = 0; i < segments.length; i++) { + bandMeters[gradeBand(segments[i].grade).key] += points[i + 1].distanceMeters - points[i].distanceMeters; + } + return { + summit: extreme(points, (a, b) => a > b), + lowest: extreme(points, (a, b) => a < b), + steepest: steepestStretch(points, 200), + bandMeters, + totalMeters: points.length ? points[points.length - 1].distanceMeters - points[0].distanceMeters : 0, + }; +} + +/** Compass bearing in degrees from one point to another. */ +export function bearingDegrees(from: { lat: number; lng: number }, to: { lat: number; lng: number }): number { + const toRad = (d: number) => (d * Math.PI) / 180; + const dLng = toRad(to.lng - from.lng); + const y = Math.sin(dLng) * Math.cos(toRad(to.lat)); + const x = + Math.cos(toRad(from.lat)) * Math.sin(toRad(to.lat)) - + Math.sin(toRad(from.lat)) * Math.cos(toRad(to.lat)) * Math.cos(dLng); + return ((Math.atan2(y, x) * 180) / Math.PI + 360) % 360; +} + +/** Eases a camera heading towards a target without spinning the long way round. */ +export function easeBearing(current: number, target: number, factor: number): number { + const delta = ((target - current + 540) % 360) - 180; + return (current + delta * factor + 360) % 360; +} + +/** Replay speed: how many route metres pass per second of playback. */ +export function replayMetresPerSecond(totalMeters: number, targetSeconds = 45): number { + return Math.max(20, totalMeters / targetSeconds); +} diff --git a/client/src/components/Tours/terrain/useTerrainMap.ts b/client/src/components/Tours/terrain/useTerrainMap.ts new file mode 100644 index 000000000..05c768fb9 --- /dev/null +++ b/client/src/components/Tours/terrain/useTerrainMap.ts @@ -0,0 +1,134 @@ +import type { GeoJSONSource, Map as MapLibreMap } from 'maplibre-gl'; +import { useCallback, useEffect, useRef, useState, type RefObject } from 'react'; +import type { TourBaseLayer } from '../../Map/MapLayerSwitcher'; +import { + addTerrainLayers, + DEM_SOURCE, + frameBounds, + PITCH, + sidePadding, + styleFor, + TRACK_SOURCE, + type PanelWidths, + type TrackData, +} from './terrainLayers'; + +type MapLibreEngine = typeof import('../../Map/engines/maplibre').default; + +/** The GL map and the engine it came from, there once the engine has loaded. */ +export interface TerrainGl { + map: MapLibreMap; + engine: MapLibreEngine; +} + +/** What the map's own event handlers read at the moment they fire, not when they were bound. */ +export interface TerrainScene { + data: TrackData; + exaggeration: number; + panels: PanelWidths; + baseLayer: TourBaseLayer; + trackColor: string; + pins: ReadonlyArray<{ lat: number; lng: number }>; + framePoints: [number, number][]; + onAdd?: (lat: number, lng: number) => void; +} + +/** Frames the route (or the pins, or what the flat map framed) between the side panels. */ +export function frameCamera(map: MapLibreMap, scene: TerrainScene, duration: number): boolean { + const target = frameBounds(scene.data, scene.pins, scene.framePoints); + if (!target) return false; + map.fitBounds(target, { + padding: { top: 70, bottom: 150, ...sidePadding(scene.panels, 40) }, + pitch: PITCH, + bearing: -20, + duration, + }); + return true; +} + +interface MapHandlers { + onReady: () => void; + onStyleIdle: () => void; +} + +function createTerrainMap( + engine: MapLibreEngine, + container: HTMLDivElement, + scene: RefObject, + handlers: MapHandlers +): MapLibreMap { + const map = new engine.Map({ + container, + style: styleFor(scene.current.baseLayer), + pitch: PITCH, + maxPitch: 75, + fadeDuration: 0, + renderWorldCopies: false, + maxTileCacheSize: 2000, + attributionControl: { compact: true }, + }); + // Clicking the terrain adds a control point, the same as on the flat planner map. + map.on('click', (event) => scene.current.onAdd?.(event.lngLat.lat, event.lngLat.lng)); + map.on('style.load', () => { + addTerrainLayers(map, scene.current.data, scene.current.exaggeration); + handlers.onReady(); + // Vector sources know their tile URLs only once their TileJSON is in. + void map.once('idle', handlers.onStyleIdle); + }); + void map.once('load', () => frameCamera(map, scene.current, 0)); + return map; +} + +interface Options { + scene: RefObject; + baseLayer: TourBaseLayer; + data: TrackData; + exaggeration: number; +} + +/** + * One GL map for as long as 3D mode is on, its engine loaded on demand. The base layer + * swaps the style in place, and the track and relief follow without a rebuild. + */ +export function useTerrainMap({ scene, baseLayer, data, exaggeration }: Options) { + const [container, setContainer] = useState(null); + const [gl, setGl] = useState(null); + const [ready, setReady] = useState(false); + /** Counts the styles that finished loading their sources, so the prefetch knows the tile URLs. */ + const [styleGeneration, setStyleGeneration] = useState(0); + const markReady = useCallback(() => setReady(true), []); + const countStyle = useCallback(() => setStyleGeneration((n) => n + 1), []); + + useEffect(() => { + if (!container) return; + let cancelled = false; + let map: MapLibreMap | null = null; + void import('../../Map/engines/maplibre').then(({ default: engine }) => { + if (cancelled) return; + map = createTerrainMap(engine, container, scene, { onReady: markReady, onStyleIdle: countStyle }); + setGl({ map, engine }); + }); + return () => { + cancelled = true; + map?.remove(); + }; + }, [container, scene, markReady, countStyle]); + + const appliedLayer = useRef(baseLayer); + useEffect(() => { + if (!gl || !ready || appliedLayer.current === baseLayer) return; + appliedLayer.current = baseLayer; + setReady(false); + gl.map.setStyle(styleFor(baseLayer)); + }, [gl, ready, baseLayer]); + + useEffect(() => { + if (gl && ready) gl.map.getSource(TRACK_SOURCE)?.setData(data); + }, [gl, ready, data]); + + useEffect(() => { + if (gl && ready) gl.map.setTerrain({ source: DEM_SOURCE, exaggeration }); + }, [gl, ready, exaggeration]); + + return { setContainer, gl, ready, styleGeneration }; +} diff --git a/client/src/components/Tours/terrain/useTerrainPins.ts b/client/src/components/Tours/terrain/useTerrainPins.ts new file mode 100644 index 000000000..a4488ab50 --- /dev/null +++ b/client/src/components/Tours/terrain/useTerrainPins.ts @@ -0,0 +1,55 @@ +import type { Marker as MapLibreMarker } from 'maplibre-gl'; +import { useEffect, useRef, type RefObject } from 'react'; +import { waypointPinElement } from './terrainLayers'; +import type { TerrainGl } from './useTerrainMap'; + +export interface TerrainWaypoints { + points: Array<{ id: string; lat: number; lng: number }>; + selectedId: string | null; + onSelect: (id: string) => void; + /** Absent while the tour cannot be edited; the pins then stay put. */ + onMove?: (id: string, lat: number, lng: number) => boolean; + /** Absent while the tour cannot be edited; a click on the map then adds nothing. */ + onAdd?: (lat: number, lng: number) => void; +} + +/** + * The planner's numbered control points, pinned to the ground and draggable while + * editing. They stay up while a new style loads and are redrawn once it is in. + */ +export function useTerrainPins( + gl: TerrainGl | null, + ready: boolean, + waypoints: TerrainWaypoints, + handlers: RefObject +) { + const { points, selectedId, onMove } = waypoints; + const editable = !!onMove; + const pinsRef = useRef([]); + + useEffect(() => { + if (!gl || !ready) return; + pinsRef.current.forEach((pin) => pin.remove()); + pinsRef.current = points.map((point, index) => { + const el = waypointPinElement(index, point.id === selectedId, editable); + el.addEventListener('click', (event) => { + event.stopPropagation(); + handlers.current.onSelect(point.id); + }); + const pin = new gl.engine.Marker({ element: el, draggable: editable }) + .setLngLat([point.lng, point.lat]) + .addTo(gl.map); + pin.on('dragend', () => { + const at = pin.getLngLat(); + if (!handlers.current.onMove?.(point.id, at.lat, at.lng)) pin.setLngLat([point.lng, point.lat]); + }); + return pin; + }); + }, [gl, ready, points, selectedId, editable, handlers]); + + // The pins go with the map, not with each redraw. + useEffect(() => { + const pins = pinsRef; + return () => pins.current.forEach((pin) => pin.remove()); + }, []); +} diff --git a/client/src/components/Tours/terrain/useTerrainPrefetch.ts b/client/src/components/Tours/terrain/useTerrainPrefetch.ts new file mode 100644 index 000000000..d8efc184a --- /dev/null +++ b/client/src/components/Tours/terrain/useTerrainPrefetch.ts @@ -0,0 +1,35 @@ +import type { Map as MapLibreMap } from 'maplibre-gl'; +import { useEffect, useMemo, useState } from 'react'; +import type { DistanceIndexedProfileSample } from '../../../utils/routeGeometry'; +import { corridorPoints, loadedTemplates } from './terrainLayers'; +import { corridorTiles, prefetchTiles, tileUrls } from './terrainPrefetch'; + +/** + * The corridor around the route, warmed up front so the flyover never waits on a tile. + * Returns the share already in the browser cache: 0 until the style knows its tile URLs, + * 1 once the flyover can run from the cache (or there is no corridor to load). + */ +export function useTerrainPrefetch( + map: MapLibreMap | null, + styleGeneration: number, + samples: DistanceIndexedProfileSample[] +): number { + const points = useMemo(() => corridorPoints(samples), [samples]); + // One run per route and loaded style; a progress report from an older run never shows. + const run = useMemo(() => ({ points, styleGeneration }), [points, styleGeneration]); + const [progress, setProgress] = useState<{ run: typeof run | null; share: number }>({ run: null, share: 0 }); + + useEffect(() => { + if (!map || run.styleGeneration === 0 || !run.points.length) return; + const controller = new AbortController(); + const urls = tileUrls(loadedTemplates(map), corridorTiles(run.points)); + void prefetchTiles(urls, controller.signal, (share) => { + if (!controller.signal.aborted) setProgress({ run, share }); + }); + return () => controller.abort(); + }, [map, run]); + + if (styleGeneration === 0) return 0; + if (!points.length) return 1; + return progress.run === run ? progress.share : 0; +} diff --git a/client/src/components/Tours/terrain/useTerrainReplay.ts b/client/src/components/Tours/terrain/useTerrainReplay.ts new file mode 100644 index 000000000..90a94d21a --- /dev/null +++ b/client/src/components/Tours/terrain/useTerrainReplay.ts @@ -0,0 +1,133 @@ +import type { Map as MapLibreMap, Marker as MapLibreMarker } from 'maplibre-gl'; +import { useCallback, useEffect, useRef, useState, type RefObject } from 'react'; +import { + focusRouteProfileAtDistance, + type DistanceIndexedProfileSample, + type RouteProfileFocus, +} from '../../../utils/routeGeometry'; +import { riderElement, sidePadding } from './terrainLayers'; +import { bearingDegrees, easeBearing, replayMetresPerSecond } from './tourTerrainModel'; +import type { TerrainGl, TerrainScene } from './useTerrainMap'; + +const REPLAY_LOOKAHEAD_METERS = 180; +// The flyover camera: high and flat enough that the horizon's tiles are already there. +const REPLAY_PITCH = 52; +const REPLAY_ZOOM = 13.4; +/** The rail's profile cursor follows the flyover at this rate, not every frame. */ +const FOCUS_INTERVAL_MS = 100; + +interface Options { + gl: TerrainGl | null; + ready: boolean; + samples: DistanceIndexedProfileSample[]; + focus: RouteProfileFocus | null; + onFocusChange: (focus: RouteProfileFocus | null) => void; + scene: RefObject; + /** Share of the corridor in the cache; the flyover starts only at 1. */ + preloaded: number; +} + +/** Moves the chase camera to `distance` along the route and returns where that is, if anywhere. */ +function chase( + map: MapLibreMap, + samples: DistanceIndexedProfileSample[], + distance: number, + bearing: RefObject, + scene: TerrainScene +): RouteProfileFocus | null { + const here = focusRouteProfileAtDistance(samples, distance); + if (!here) return null; + const ahead = focusRouteProfileAtDistance(samples, distance + REPLAY_LOOKAHEAD_METERS); + if (ahead) bearing.current = easeBearing(bearing.current, bearingDegrees(here, ahead), 0.03); + // Centred on the ground the rider stands on, not on sea level beneath it. + map.jumpTo({ + center: [here.lng, here.lat], + elevation: (here.elevationMeters ?? 0) * scene.exaggeration, + bearing: bearing.current, + pitch: REPLAY_PITCH, + zoom: REPLAY_ZOOM, + padding: { top: 0, bottom: 0, ...sidePadding(scene.panels, 0) }, + }); + return here; +} + +/** The rider and the replay clock: route metres per second, the camera chasing a point ahead. */ +export function useTerrainReplay({ gl, ready, samples, focus, onFocusChange, scene, preloaded }: Options) { + const riderRef = useRef(null); + const frameRef = useRef(null); + const distanceRef = useRef(0); + const bearingRef = useRef(0); + const [playing, setPlaying] = useState(false); + const [speed, setSpeed] = useState<1 | 2 | 4>(1); + const totalMeters = samples.length ? samples[samples.length - 1].distanceMeters : 0; + + useEffect(() => { + if (!gl) return; + const rider = new gl.engine.Marker({ element: riderElement(scene.current.trackColor) }); + riderRef.current = rider; + const frame = frameRef; + return () => { + if (frame.current !== null) cancelAnimationFrame(frame.current); + rider.remove(); + riderRef.current = null; + }; + }, [gl, scene]); + + // The rail's profile and the replay share one focus; the rider follows it. + useEffect(() => { + const rider = riderRef.current; + // In flight the replay clock places the rider every frame; a throttled focus would pull it back. + if (!gl || !rider || playing) return; + if (focus) { + rider.setLngLat([focus.lng, focus.lat]).addTo(gl.map); + distanceRef.current = focus.distanceMeters; + } else rider.remove(); + }, [gl, focus, playing]); + + useEffect(() => { + if (!gl || !playing || !ready || totalMeters <= 0) return; + let last = performance.now(); + let lastFocus = 0; + const tick = (now: number) => { + const dt = Math.min(0.1, (now - last) / 1000); + last = now; + distanceRef.current = Math.min( + totalMeters, + distanceRef.current + replayMetresPerSecond(totalMeters) * speed * dt + ); + const here = chase(gl.map, samples, distanceRef.current, bearingRef, scene.current); + if (here) { + riderRef.current?.setLngLat([here.lng, here.lat]).addTo(gl.map); + if (now - lastFocus >= FOCUS_INTERVAL_MS || distanceRef.current >= totalMeters) { + lastFocus = now; + onFocusChange(here); + } + } + if (distanceRef.current >= totalMeters) { + setPlaying(false); + return; + } + frameRef.current = requestAnimationFrame(tick); + }; + frameRef.current = requestAnimationFrame(tick); + return () => { + if (frameRef.current !== null) cancelAnimationFrame(frameRef.current); + }; + }, [gl, playing, ready, samples, speed, totalMeters, onFocusChange, scene]); + + const togglePlay = useCallback(() => { + if (!playing && preloaded < 1) return; + if (!playing && distanceRef.current >= totalMeters) distanceRef.current = 0; + setPlaying((value) => !value); + }, [playing, preloaded, totalMeters]); + + const restart = useCallback(() => { + if (preloaded < 1) return; + distanceRef.current = 0; + setPlaying(true); + }, [preloaded]); + + const stop = useCallback(() => setPlaying(false), []); + + return { canReplay: totalMeters > 0, playing, togglePlay, restart, stop, speed, setSpeed }; +} diff --git a/client/src/components/Tours/terrain/useTourTerrain.ts b/client/src/components/Tours/terrain/useTourTerrain.ts new file mode 100644 index 000000000..d45ba76c2 --- /dev/null +++ b/client/src/components/Tours/terrain/useTourTerrain.ts @@ -0,0 +1,71 @@ +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; +import type { DistanceIndexedProfileSample, RouteProfileFocus } from '../../../utils/routeGeometry'; +import type { TourBaseLayer } from '../../Map/MapLayerSwitcher'; +import { trackData, type PanelWidths, type TrackColorMode } from './terrainLayers'; +import { frameCamera, useTerrainMap, type TerrainScene } from './useTerrainMap'; +import { useTerrainPins, type TerrainWaypoints } from './useTerrainPins'; +import { useTerrainPrefetch } from './useTerrainPrefetch'; +import { useTerrainReplay } from './useTerrainReplay'; + +interface Options { + /** The open tour's distance-indexed profile; empty when no tour is open. */ + samples: DistanceIndexedProfileSample[]; + /** Every route the planner map draws, shown when no tour is open. */ + routes: [number, number][][] | null; + trackColor: string; + baseLayer: TourBaseLayer; + focus: RouteProfileFocus | null; + onFocusChange: (focus: RouteProfileFocus | null) => void; + panels: PanelWidths; + waypoints: TerrainWaypoints; + /** What the flat map frames, [lat, lng]; the 3D view starts there while there is no route. */ + framePoints: [number, number][]; +} + +/** The planner map's 3D mode: map, pins, corridor preload and the flyover sharing the rail's focus. */ +export function useTourTerrain(options: Options) { + const { samples, routes, trackColor, baseLayer, focus, onFocusChange, panels, waypoints, framePoints } = options; + const [exaggeration, setExaggeration] = useState(1.5); + const [colorMode, setColorMode] = useState('grade'); + const data = useMemo( + () => trackData(samples, routes, colorMode, trackColor), + [samples, routes, colorMode, trackColor] + ); + + // The map's own handlers fire long after they were bound, so they read the latest props here. + const current: TerrainScene = { + data, + exaggeration, + panels, + baseLayer, + trackColor, + pins: waypoints.points, + framePoints, + onAdd: waypoints.onAdd, + }; + const scene = useRef(current); + const handlers = useRef(waypoints); + useLayoutEffect(() => { + scene.current = current; + handlers.current = waypoints; + }); + + const { setContainer, gl, ready, styleGeneration } = useTerrainMap({ scene, baseLayer, data, exaggeration }); + const preloaded = useTerrainPrefetch(gl?.map ?? null, styleGeneration, samples); + useTerrainPins(gl, ready, waypoints, handlers); + const replay = useTerrainReplay({ gl, ready, samples, focus, onFocusChange, scene, preloaded }); + const { stop } = replay; + + const overview = useCallback(() => { + if (!gl || !frameCamera(gl.map, scene.current, 1200)) return; + stop(); + }, [gl, stop]); + + // A different tour, or the same one recoloured, framed anew; pins added later never + // refocus the camera under the user's cursor. + useEffect(() => { + if (ready) overview(); + }, [ready, data, framePoints, overview]); + + return { setContainer, preloaded, overview, exaggeration, setExaggeration, colorMode, setColorMode, ...replay }; +} diff --git a/client/src/components/Tours/tourParts.tsx b/client/src/components/Tours/tourParts.tsx index ff4dd51b1..3d796e9b0 100644 --- a/client/src/components/Tours/tourParts.tsx +++ b/client/src/components/Tours/tourParts.tsx @@ -26,11 +26,23 @@ export function TourTile({ size = 34, color, raised = false }: { size?: number; ) } +/** The T-scale badge; a GPX import carries no difficulty, so it gets none. */ +function TourDifficultyPill({ level, t }: { level: TourListItem['max_hiking_difficulty']; t: Translate }) { + if (level == null) return null + const label = t(`tours.planner.difficulty.t${level}`) + return ( + + + T{level} + + + ) +} + /** The facts of a tour as white pills: how far, how much up and down, how hard, where it came from. */ export function TourFactPills({ tour, className = '' }: { tour: TourListItem; className?: string }) { const { t } = useTranslation() const unit = useSettingsStore(state => state.settings.distance_unit) - const difficulty = t(`tours.planner.difficulty.t${tour.max_hiking_difficulty}`) const times = tourPlannedTimes(tour) return (
@@ -68,11 +80,7 @@ export function TourFactPills({ tour, className = '' }: { tour: TourListItem; cl )} - - - T{tour.max_hiking_difficulty} - - + {hikeSourceBadgeLabel(tour, t)} {tour.caution && ( diff --git a/client/src/components/Tours/toursI18n.test.tsx b/client/src/components/Tours/toursI18n.test.tsx index 92802f498..cea51a2ad 100644 --- a/client/src/components/Tours/toursI18n.test.tsx +++ b/client/src/components/Tours/toursI18n.test.tsx @@ -166,7 +166,7 @@ describe('Tours English and German copy', () => { fireEvent.click(screen.getByRole('button', { name: toursText(de, 'tours.planner.backToTours') })) expect(screen.getByRole('heading', { name: toursText(de, 'tours.planner.discardTitle') })).toBeInTheDocument() expect(screen.getByText(toursText(de, 'tours.planner.discardBody'))).toBeInTheDocument() - expect(screen.getByRole('button', { name: toursText(de, 'tours.planner.discardUnsaved') })).toBeInTheDocument() + expect(screen.getByRole('button', { name: toursText(de, 'tours.planner.discardChanges') })).toBeInTheDocument() assertNoRawToursKeys() rerender( { expect(screen.getByRole('button', { name: 'Zum Tag hinzufügen' })).toHaveClass('w-full') }) + it('shows no T-badge for an imported tour that carries no difficulty', () => { + const imported = { ...tour, has_waypoints: false, max_hiking_difficulty: null } + render() + + const row = screen.getByRole('option', { name: new RegExp(tour.name) }) + expect(row).not.toHaveTextContent(/T\d/) + expect(row).not.toHaveTextContent('Tnull') + expect(screen.queryByTitle(/^T\d/)).not.toBeInTheDocument() + expect(screen.getByText(en['tours.badge.gpx'] as string)).toBeInTheDocument() + }) + it('does not refresh Tours merely because the mobile assignment sheet closes', () => { const { rerender } = render() diff --git a/client/src/mobile/screens/trip/places/MToursSelectionList.tsx b/client/src/mobile/screens/trip/places/MToursSelectionList.tsx index 661b2abbd..082cc4994 100644 --- a/client/src/mobile/screens/trip/places/MToursSelectionList.tsx +++ b/client/src/mobile/screens/trip/places/MToursSelectionList.tsx @@ -70,11 +70,13 @@ export default function MToursSelectionList({ planner, shell, filter, canAssign: {hikeSourceBadgeLabel(tour, t)} - T{tour.max_hiking_difficulty} + {tour.max_hiking_difficulty != null && ( + T{tour.max_hiking_difficulty} + )} {tour.caution && (