Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

feat(tours): 3D terrain view with flyover and grade colours, imported tours carry no hiking difficulty

Maurice98cc57942b6f
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(<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')
+ })
+})
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)}
>
<Icon size={15} strokeWidth={2} />
<span>{label}</span>
</button>
)
})}
+ {onToggleTerrain && (
+ <>
+ <span aria-hidden className="mx-0.5 h-5 w-px bg-edge" />
+ <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>
)
}
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({
<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} />
+ ? <TourMapLayerSwitcher active={baseLayer} onChange={onViewBaseLayerChange}
+ onToggleTerrain={onToggleTerrain3d} />
: <MapLayerSwitcher active={globalBaseLayer} onToggle={toggleBaseLayer} />}
</div>
</div>
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 && <MapLockPill locked={!followSelection} onToggle={onToggleFollow} />}
{hasViewBaseLayer
- ? <TourMapLayerSwitcher active={baseLayer as TourBaseLayer} onChange={onViewBaseLayerChange} />
+ ? <TourMapLayerSwitcher active={baseLayer as TourBaseLayer} onChange={onViewBaseLayerChange}
+ onToggleTerrain={onToggleTerrain3d} />
: <MapLayerSwitcher active={globalBaseLayer as BaseLayer} onToggle={toggleBaseLayer} />}
</div>
{/* 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(<ToursSidebar tripId={1} days={[]} tours={[imported]} onAssignToDay={vi.fn()} onSelectTour={vi.fn()} />)
+
+ 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<void>(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(<TourPlannerRail planner={planner({
mode: { type: 'new-draft' }, hasUnsavedChanges: true, walkingDurationMinutes: 80,
breakAdditionalMinutes: 50, plannedTotalMinutes: 130,
@@ -407,22 +407,19 @@ describe('TourPlannerRail', () => {
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 (
- <span className="inline-flex min-w-0 flex-wrap items-center gap-x-1.5">
- <Tooltip label={description}>
- <button
- type="button"
- aria-label={label}
- aria-expanded={open}
- aria-controls={id}
- onClick={() => setOpen(value => !value)}
- className="grid h-5 w-5 flex-none place-items-center rounded-full text-content-faint transition-colors hover:bg-surface-card hover:text-content focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent"
- >
- <Info size={13} strokeWidth={2} aria-hidden="true" />
- </button>
- </Tooltip>
- <span id={id} hidden={!open} role="note" className="basis-full text-content-muted" style={fs(10.5, 'body')}>
- {description}
- </span>
- </span>
+ <Tooltip label={description}>
+ <button
+ type="button"
+ aria-label={label}
+ aria-describedby={id}
+ className="grid h-5 w-5 flex-none place-items-center rounded-full text-content-faint transition-colors hover:bg-surface-card hover:text-content focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent"
+ >
+ <Info size={13} strokeWidth={2} aria-hidden="true" />
+ <span id={id} className="sr-only">{description}</span>
+ </button>
+ </Tooltip>
)
}
@@ -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')}
/>
<NewTourConfirmDialog planner={planner} canEdit={canEdit} />
<ConfirmDialog
diff --git a/client/src/components/Tours/terrain/TourTerrainMap.test.tsx b/client/src/components/Tours/terrain/TourTerrainMap.test.tsx
new file mode 100644
index 000000000..c4315a3e0
--- /dev/null
+++ b/client/src/components/Tours/terrain/TourTerrainMap.test.tsx
@@ -0,0 +1,375 @@
+// FE-COMP-TERRAIN-001 to FE-COMP-TERRAIN-014
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, fireEvent, render, screen, waitFor } from '../../../../tests/helpers/render';
+import type { DistanceIndexedProfileSample, RouteProfileFocus } from '../../../utils/routeGeometry';
+import TourTerrainMap, { type TourTerrainMapProps } from './TourTerrainMap';
+
+type Handler = (event?: unknown) => void;
+
+interface MarkerStub {
+ element: HTMLElement;
+ draggable: boolean;
+ lngLat: [number, number];
+ handlers: Record<string, Handler>;
+ setLngLat: ReturnType<typeof vi.fn>;
+ addTo: ReturnType<typeof vi.fn>;
+ remove: ReturnType<typeof vi.fn>;
+ on: ReturnType<typeof vi.fn>;
+ getLngLat: ReturnType<typeof vi.fn>;
+}
+
+const gl = vi.hoisted(() => {
+ const listeners = new Map<string, Handler[]>();
+ const sources = new Map<string, Record<string, unknown>>();
+ 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<string, unknown>) => 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> = {}): 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<TourTerrainMapProps> = {}) {
+ const view = render(<TourTerrainMap {...props(overrides)} />);
+ // 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<Response>((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(
+ <TourTerrainMap {...props({ waypoints: { points: [], selectedId: null, onSelect: vi.fn(), onAdd: vi.fn() } })} />
+ );
+ 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(<TourTerrainMap {...props()} />);
+ 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(<TourTerrainMap {...props({ samples: TOUR, focus })} />);
+ expect(rider.setLngLat).toHaveBeenCalledWith([7, 46.0009]);
+ expect(rider.addTo).toHaveBeenCalledWith(gl.map);
+ rerender(<TourTerrainMap {...props({ samples: TOUR, focus: null })} />);
+ 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<typeof vi.fn> | 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(<TourTerrainMap {...props({ samples: TOUR, baseLayer: 'satellite' })} />);
+ 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 (
+ <div className="absolute inset-0">
+ {/* MapLibre makes its container position: relative, so it is sized, not inset. */}
+ <div ref={setContainer} className="h-full w-full bg-surface" />
+
+ {/* The flat map's layer pill, at the same spot, with 3D switched on. */}
+ <div className="absolute bottom-3 z-[19]" style={{ insetInlineStart: leftWidth + MAP_LAYER_SWITCHER_INSET }}>
+ <TourMapLayerSwitcher active={baseLayer} onChange={onBaseLayerChange} terrainActive onToggleTerrain={onExit} />
+ </div>
+
+ {/* The flyover controls and the grade legend share the bottom edge with the pill, short of the right panel. */}
+ <div
+ className="pointer-events-none absolute bottom-3 z-[19] grid grid-cols-[1fr_auto_1fr] items-end gap-3"
+ style={{
+ insetInlineStart: leftWidth + MAP_LAYER_SWITCHER_INSET + LAYER_PILL_WIDTH + 12,
+ insetInlineEnd: rightWidth + MAP_LAYER_SWITCHER_INSET,
+ }}
+ >
+ <span />
+ {terrain.canReplay ? (
+ <TerrainDock terrain={terrain} />
+ ) : (
+ <div
+ className="pointer-events-auto rounded-full px-4 py-2.5 text-content-muted"
+ style={{ ...GLASS, ...fs(12, 'body') }}
+ >
+ <PickHint editing={!!props.waypoints.onAdd} />
+ </div>
+ )}
+ <div className="flex justify-end">{terrain.canReplay && <GradeLegend stats={stats} unit={unit} />}</div>
+ </div>
+ </div>
+ );
+}
+
+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 (
+ <Tooltip label={label} placement="top">
+ <button
+ type="button"
+ onClick={onClick}
+ aria-label={label}
+ className={`flex h-[34px] w-[34px] items-center justify-center rounded-full transition-colors ${primary ? 'bg-accent text-accent-text hover:opacity-90' : 'text-content-muted hover:bg-surface-hover'}`}
+ >
+ {children}
+ </button>
+ </Tooltip>
+ );
+}
+
+function Divider() {
+ return <span aria-hidden className="mx-0.5 h-5 w-px flex-none bg-edge" />;
+}
+
+/** One pill like the layer switcher: play, restart, overview · speed · relief · colour. */
+function TerrainDock({ terrain }: { terrain: Omit<ReturnType<typeof useTourTerrain>, 'setContainer'> }) {
+ const { t } = useTranslation();
+ return (
+ <div className="pointer-events-auto flex items-center gap-0.5 rounded-full p-1" style={GLASS}>
+ {terrain.preloaded < 1 ? (
+ <PreloadRing
+ share={terrain.preloaded}
+ label={t('tours.terrain.preloading', { percent: Math.round(terrain.preloaded * 100) })}
+ />
+ ) : (
+ <IconButton
+ primary
+ label={terrain.playing ? t('tours.terrain.pause') : t('tours.terrain.play')}
+ onClick={terrain.togglePlay}
+ >
+ {terrain.playing ? <Pause size={15} strokeWidth={2.2} /> : <Play size={15} strokeWidth={2.2} />}
+ </IconButton>
+ )}
+ <IconButton label={t('tours.terrain.restart')} onClick={terrain.restart}>
+ <RotateCcw size={15} strokeWidth={2} />
+ </IconButton>
+ <IconButton label={t('tours.terrain.overview')} onClick={terrain.overview}>
+ <Scan size={15} strokeWidth={2} />
+ </IconButton>
+ <Divider />
+ <div className="flex items-center" role="group" aria-label={t('tours.terrain.speed')}>
+ {SPEEDS.map((speed) => (
+ <button
+ key={speed}
+ type="button"
+ aria-pressed={terrain.speed === speed}
+ onClick={() => terrain.setSpeed(speed)}
+ className={`h-[34px] min-w-[34px] rounded-full px-2 font-semibold tabular-nums ${terrain.speed === speed ? 'bg-accent-soft text-accent' : 'text-content-muted hover:bg-surface-hover'}`}
+ style={fs(11)}
+ >
+ {speed}×
+ </button>
+ ))}
+ </div>
+ <Divider />
+ <Tooltip label={t('tours.terrain.exaggeration')} placement="top">
+ <label className="flex h-[34px] items-center gap-2 px-2 text-content-muted" style={fs(11)}>
+ <TrendingUp size={15} strokeWidth={2} aria-hidden />
+ <input
+ type="range"
+ min={1}
+ max={3}
+ step={0.1}
+ value={terrain.exaggeration}
+ aria-label={t('tours.terrain.exaggeration')}
+ onChange={(e) => terrain.setExaggeration(Number(e.target.value))}
+ className="w-20 accent-[var(--accent)]"
+ />
+ <span className="w-7 font-semibold tabular-nums">{terrain.exaggeration.toFixed(1)}×</span>
+ </label>
+ </Tooltip>
+ <Divider />
+ <button
+ type="button"
+ onClick={() => terrain.setColorMode(terrain.colorMode === 'grade' ? 'tour' : 'grade')}
+ aria-pressed={terrain.colorMode === 'grade'}
+ className={`flex h-[34px] items-center gap-1.5 rounded-full px-3 font-semibold ${terrain.colorMode === 'grade' ? 'bg-accent-soft text-accent' : 'text-content-muted hover:bg-surface-hover'}`}
+ style={fs(11)}
+ >
+ <Palette size={15} strokeWidth={2} />
+ {t('tours.terrain.colorByGrade')}
+ </button>
+ </div>
+ );
+}
+
+/** 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 (
+ <Tooltip label={label} placement="top">
+ <span
+ role="progressbar"
+ aria-label={label}
+ aria-valuenow={Math.round(share * 100)}
+ aria-valuemin={0}
+ aria-valuemax={100}
+ className="relative flex h-[34px] w-[34px] items-center justify-center"
+ >
+ <svg width="34" height="34" viewBox="0 0 34 34" className="absolute inset-0 -rotate-90">
+ <circle cx="17" cy="17" r={r} fill="none" stroke="var(--border-primary)" strokeWidth="3" />
+ <circle
+ cx="17"
+ cy="17"
+ r={r}
+ fill="none"
+ stroke="var(--accent)"
+ strokeWidth="3"
+ strokeLinecap="round"
+ strokeDasharray={c}
+ strokeDashoffset={c * (1 - share)}
+ />
+ </svg>
+ <span className="font-semibold tabular-nums text-content-muted" style={fs(9)}>
+ {Math.round(share * 100)}
+ </span>
+ </span>
+ </Tooltip>
+ );
+}
+
+/** 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 (
+ <div className="pointer-events-auto relative">
+ {open && (
+ <div id="tour-terrain-grades" className="absolute inset-x-0 bottom-full mb-2 rounded-2xl p-3" style={GLASS}>
+ <ul className="flex flex-col gap-1">
+ {GRADE_BANDS.map((band) => (
+ <li key={band.key} className="flex items-center gap-2 text-content-secondary" style={fs(11)}>
+ <span className="h-2 w-2 flex-none rounded-full" style={{ background: band.paint }} />
+ <span className="flex-1">{t(`tours.terrain.band.${band.key}`)}</span>
+ <span className="tabular-nums text-content">
+ {Math.round((stats.bandMeters[band.key] / total) * 100)} %
+ </span>
+ </li>
+ ))}
+ </ul>
+ <div className="mt-2 border-t border-edge-faint pt-2 text-content-faint" style={fs(9)}>
+ {t('tours.terrain.attribution')}
+ </div>
+ </div>
+ )}
+ <button
+ type="button"
+ onClick={() => setOpen((v) => !v)}
+ aria-expanded={open}
+ aria-controls="tour-terrain-grades"
+ aria-label={t('tours.terrain.gradeMix')}
+ className="flex h-[42px] items-center gap-2 rounded-full pe-2 ps-3"
+ style={GLASS}
+ >
+ <span className="flex h-1.5 w-14 overflow-hidden rounded-full bg-surface-hover" aria-hidden>
+ {GRADE_BANDS.map((band) => (
+ <span key={band.key} style={{ width: width(band.key), background: band.paint }} />
+ ))}
+ </span>
+ {stats.summit && (
+ <SoftPill icon={<TrendingUp size={11} strokeWidth={2} className="flex-none" />}>
+ {formatElevation(stats.summit.elevationMeters, unit)}
+ </SoftPill>
+ )}
+ {stats.steepest && (
+ <SoftPill
+ tone={stats.steepest.grade >= 27 ? 'danger' : stats.steepest.grade >= 18 ? 'warning' : 'neutral'}
+ icon={<Gauge size={11} strokeWidth={2} className="flex-none" />}
+ >
+ {t('tours.terrain.steepestShort', { grade: Math.round(stats.steepest.grade) })}
+ </SoftPill>
+ )}
+ <span className="flex h-[26px] w-[26px] items-center justify-center rounded-full text-content-muted">
+ {open ? <ChevronDown size={14} strokeWidth={2.2} /> : <ChevronUp size={14} strokeWidth={2.2} />}
+ </span>
+ </button>
+ </div>
+ );
+}
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<string, unknown> = {}) {
+ const added = new Map<string, unknown>(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<Response>((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<number, number> = { 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<string>();
+ 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<void> {
+ 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<GradeBandKey, number>;
+ 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<GradeBandKey, number> {
+ 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<TerrainScene>,
+ 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<TerrainScene>;
+ 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<HTMLDivElement | null>(null);
+ const [gl, setGl] = useState<TerrainGl | null>(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<GeoJSONSource>(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<TerrainWaypoints>
+) {
+ const { points, selectedId, onMove } = waypoints;
+ const editable = !!onMove;
+ const pinsRef = useRef<MapLibreMarker[]>([]);
+
+ 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<TerrainScene>;
+ /** 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<number>,
+ 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<MapLibreMarker | null>(null);
+ const frameRef = useRef<number | null>(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<TrackColorMode>('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 (
+ <Tooltip label={label}>
+ <span aria-label={label} className="inline-flex">
+ <SoftPill>T{level}</SoftPill>
+ </span>
+ </Tooltip>
+ )
+}
+
/** 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 (
<div data-testid="tour-metrics" className={`flex min-w-0 flex-wrap items-center gap-1 ${className}`}>
@@ -68,11 +80,7 @@ export function TourFactPills({ tour, className = '' }: { tour: TourListItem; cl
</span>
</SoftPill>
)}
- <Tooltip label={difficulty}>
- <span aria-label={difficulty} className="inline-flex">
- <SoftPill>T{tour.max_hiking_difficulty}</SoftPill>
- </span>
- </Tooltip>
+ <TourDifficultyPill level={tour.max_hiking_difficulty} t={t} />
<SoftPill>{hikeSourceBadgeLabel(tour, t)}</SoftPill>
{tour.caution && (
<Tooltip label={t('tours.caution.tooltip')}>
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(<TourPlannerRail planner={planner({
diff --git a/client/src/mobile/screens/trip/places/MToursSelectionList.test.tsx b/client/src/mobile/screens/trip/places/MToursSelectionList.test.tsx
index 805bf60c4..aa25f195f 100644
--- a/client/src/mobile/screens/trip/places/MToursSelectionList.test.tsx
+++ b/client/src/mobile/screens/trip/places/MToursSelectionList.test.tsx
@@ -127,6 +127,17 @@ describe('MToursSelectionList', () => {
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(<MToursSelectionList planner={{ ...planner(), tours: [imported] }} shell={shell()} filter="all" />)
+
+ 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(<MToursSelectionList planner={planner()} shell={shell({ id: 'bract' })} filter="all" />)
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:
<span className="shrink-0 rounded-md border border-[color:var(--m-rowbr)] px-1.5 py-0.5 text-[10px] font-medium text-m-faint">
{hikeSourceBadgeLabel(tour, t)}
</span>
- <span
- title={t(`tours.planner.difficulty.t${tour.max_hiking_difficulty}`)}
- aria-label={t(`tours.planner.difficulty.t${tour.max_hiking_difficulty}`)}
- className="shrink-0 rounded-md border border-[color:var(--m-rowbr)] px-1.5 py-0.5 text-[10px] font-semibold text-m-muted"
- >T{tour.max_hiking_difficulty}</span>
+ {tour.max_hiking_difficulty != null && (
+ <span
+ title={t(`tours.planner.difficulty.t${tour.max_hiking_difficulty}`)}
+ aria-label={t(`tours.planner.difficulty.t${tour.max_hiking_difficulty}`)}
+ className="shrink-0 rounded-md border border-[color:var(--m-rowbr)] px-1.5 py-0.5 text-[10px] font-semibold text-m-muted"
+ >T{tour.max_hiking_difficulty}</span>
+ )}
{tour.caution && (
<span className="inline-flex shrink-0 items-center gap-1 rounded-md border border-[color:var(--warning)] px-1.5 py-0.5 text-[10px] text-[color:var(--warning)]" aria-label={t('tours.caution.badge')} title={t('tours.caution.tooltip')}>
<AlertTriangle className="h-3 w-3" strokeWidth={2} aria-hidden="true" />{t('tours.caution.badge')}
diff --git a/client/src/pages/tripPlanner/TourPlannerMapStage.test.tsx b/client/src/pages/tripPlanner/TourPlannerMapStage.test.tsx
new file mode 100644
index 000000000..10628ad07
--- /dev/null
+++ b/client/src/pages/tripPlanner/TourPlannerMapStage.test.tsx
@@ -0,0 +1,168 @@
+// FE-PAGE-TOURSTAGE-001 to FE-PAGE-TOURSTAGE-005
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, fireEvent, render, screen, waitFor } from '../../../tests/helpers/render';
+import type { MapViewProps } from '../../components/Map/mapViewContract';
+import { TourPlannerMapStage, type TourPlannerMapStageProps } from './TourPlannerMapStage';
+
+type Handler = (event?: unknown) => void;
+
+const stage = vi.hoisted(() => {
+ const listeners = new Map<string, Handler[]>();
+ const map = {
+ on: vi.fn((type: string, fn: Handler) => {
+ listeners.set(type, [...(listeners.get(type) ?? []), fn]);
+ return map;
+ }),
+ once: vi.fn(() => map),
+ remove: vi.fn(),
+ fitBounds: vi.fn(),
+ setTerrain: vi.fn(),
+ setStyle: vi.fn(),
+ getSource: vi.fn(),
+ };
+ const marker = { setLngLat: vi.fn(), addTo: vi.fn(), remove: vi.fn(), on: vi.fn() };
+ marker.setLngLat.mockReturnValue(marker);
+ marker.addTo.mockReturnValue(marker);
+ const engine = {
+ Map: vi.fn(function () {
+ return map;
+ }),
+ Marker: vi.fn(function () {
+ return marker;
+ }),
+ };
+ const fire = (type: string, event?: unknown) => (listeners.get(type) ?? []).forEach((fn) => fn(event));
+ return { map, engine, listeners, fire, flatMap: { props: null as MapViewProps | null } };
+});
+
+vi.mock('../../components/Map/engines/maplibre', () => ({ default: stage.engine }));
+vi.mock('../../components/Map/MapViewAuto', () => ({
+ MapViewAuto: (props: MapViewProps) => {
+ stage.flatMap.props = props;
+ return (
+ <button type="button" onClick={props.onToggleTerrain3d}>
+ flat map
+ </button>
+ );
+ },
+}));
+vi.mock('../../components/Planner/LocationSelect', () => ({ default: () => <input aria-label="location search" /> }));
+
+type Planner = TourPlannerMapStageProps['tourPlanner'];
+
+function planner(
+ mode: 'new-draft' | 'edit-saved' | 'view-saved' | 'view-gpx',
+ overrides: Record<string, unknown> = {}
+) {
+ return {
+ mode: { type: mode },
+ isSaving: false,
+ waypoints: [{ id: 'w1', lat: 46, lng: 7 }],
+ selectedWaypointId: 'w1',
+ setSelectedWaypointId: vi.fn(),
+ setWaypointPosition: vi.fn(() => true),
+ addWaypoint: vi.fn(),
+ routeAnalysis: null,
+ readOnlyGpxAnalysis: null,
+ mapBaseLayer: 'default',
+ setMapBaseLayer: vi.fn(),
+ routeProfileFocus: null,
+ setRouteProfileFocus: vi.fn(),
+ ...overrides,
+ } as unknown as Planner;
+}
+
+function renderStage(tourPlanner: Planner, canPlaceEdit = true) {
+ const props = {
+ tripId: 7,
+ mapTileUrl: '',
+ leftHidden: false,
+ rightHidden: false,
+ t: (key: string) => key,
+ tourPlanner,
+ tourMap: { route: null, focusPoints: [[46, 7]], focusKey: 'k', captureViewport: vi.fn() },
+ locationSearch: { value: null, onChange: vi.fn() },
+ canPlaceEdit,
+ leftPanelPx: 320,
+ rightPanelPx: 380,
+ } as unknown as TourPlannerMapStageProps;
+ return render(<TourPlannerMapStage {...props} />);
+}
+
+/** Switches the flat map to 3D and waits for the GL engine to load. */
+async function openTerrain() {
+ fireEvent.click(screen.getByRole('button', { name: 'flat map' }));
+ await waitFor(() => expect(stage.engine.Marker).toHaveBeenCalled());
+}
+
+beforeEach(() => {
+ stage.listeners.clear();
+ stage.flatMap.props = null;
+ vi.clearAllMocks();
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(() => new Promise<Response>(() => {}))
+ );
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('TourPlannerMapStage', () => {
+ it('FE-PAGE-TOURSTAGE-001: the flat map adds and moves control points while a tour is edited', () => {
+ const tourPlanner = planner('new-draft');
+ renderStage(tourPlanner);
+ const props = stage.flatMap.props;
+ expect(props?.plannerWaypoints).toEqual([{ id: 'w1', lat: 46, lng: 7 }]);
+ expect(props?.selectedPlannerWaypointId).toBe('w1');
+ expect(props?.onPlannerWaypointMove).toBe(tourPlanner.setWaypointPosition);
+ props?.onMapClick?.({ latlng: { lat: 46.2, lng: 7.2 } } as never);
+ expect(tourPlanner.addWaypoint).toHaveBeenCalledWith(46.2, 7.2);
+ });
+
+ it('FE-PAGE-TOURSTAGE-002: the flat map shows no control points and takes no clicks outside editing', () => {
+ renderStage(planner('view-saved'));
+ const props = stage.flatMap.props;
+ expect(props?.plannerWaypoints).toEqual([]);
+ expect(props?.selectedPlannerWaypointId).toBeNull();
+ expect(props?.onMapClick).toBeUndefined();
+ expect(props?.onPlannerWaypointMove).toBeUndefined();
+ });
+
+ it('FE-PAGE-TOURSTAGE-003: the 3D switch opens the terrain, where a click plans the next point', async () => {
+ const tourPlanner = planner('edit-saved');
+ renderStage(tourPlanner);
+ await openTerrain();
+ expect(screen.queryByRole('button', { name: 'flat map' })).toBeNull();
+ expect(screen.getByText(/Click the terrain to set points/)).toBeInTheDocument();
+ act(() => stage.fire('click', { lngLat: { lat: 46.3, lng: 7.3 } }));
+ expect(tourPlanner.addWaypoint).toHaveBeenCalledWith(46.3, 7.3);
+
+ fireEvent.click(screen.getByRole('button', { name: '3D' }));
+ expect(await screen.findByRole('button', { name: 'flat map' })).toBeInTheDocument();
+ expect(stage.map.remove).toHaveBeenCalled();
+ });
+
+ it('FE-PAGE-TOURSTAGE-004: without edit rights the terrain only says how to open a tour', async () => {
+ const tourPlanner = planner('new-draft');
+ renderStage(tourPlanner, false);
+ await openTerrain();
+ expect(screen.getByText('Open a tour on the right to fly it in 3D and colour it by grade.')).toBeInTheDocument();
+ act(() => stage.fire('click', { lngLat: { lat: 46.3, lng: 7.3 } }));
+ expect(tourPlanner.addWaypoint).not.toHaveBeenCalled();
+ });
+
+ it('FE-PAGE-TOURSTAGE-005: an opened GPX tour gets the flyover dock, loading its landscape first', async () => {
+ const samples = [0, 1, 2].map((i) => ({
+ distanceMeters: i * 100,
+ elevationMeters: 500,
+ lat: 46 + i / 1000,
+ lng: 7,
+ }));
+ renderStage(planner('view-gpx', { readOnlyGpxAnalysis: { distanceIndexedProfileSamples: samples } }));
+ await openTerrain();
+ expect(screen.getByRole('progressbar', { name: 'Loading the landscape: 0 %' })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Grade mix' })).toBeInTheDocument();
+ });
+});
diff --git a/client/src/pages/tripPlanner/TourPlannerMapStage.tsx b/client/src/pages/tripPlanner/TourPlannerMapStage.tsx
index 92509c63e..16e6f2146 100644
--- a/client/src/pages/tripPlanner/TourPlannerMapStage.tsx
+++ b/client/src/pages/tripPlanner/TourPlannerMapStage.tsx
@@ -1,9 +1,16 @@
-import type { ReactElement } from 'react';
+import { lazy, Suspense, useState, type ReactElement } from 'react';
import { MapViewAuto as MapView } from '../../components/Map/MapViewAuto';
import LocationSelect from '../../components/Planner/LocationSelect';
+import { useSettingsStore } from '../../store/settingsStore';
import type { useTripPlanner } from './useTripPlanner';
import type { useTripPlannerPage } from './useTripPlannerPage';
+// The 3D mode pulls the GL engine in, so it loads only once someone switches to it.
+const TourTerrainMap = lazy(() => import('../../components/Tours/terrain/TourTerrainMap'));
+
+/** The route blue the planner draws a tour in. */
+const TOUR_TRACK_COLOR = '#0a84ff';
+
type Planner = ReturnType<typeof useTripPlanner>;
type PageState = ReturnType<typeof useTripPlannerPage>;
@@ -34,45 +41,68 @@ export function TourPlannerMapStage({
leftPanelPx,
rightPanelPx,
}: Readonly<TourPlannerMapStageProps>): ReactElement {
+ const [terrain3d, setTerrain3d] = useState(false);
+ const distanceUnit = useSettingsStore((s) => s.settings.distance_unit);
+ const analysis = tourPlanner.mode.type === 'view-gpx' ? tourPlanner.readOnlyGpxAnalysis : tourPlanner.routeAnalysis;
+ const editing = tourPlanner.mode.type === 'new-draft' || tourPlanner.mode.type === 'edit-saved';
+ const canEditRoute = canPlaceEdit && !tourPlanner.isSaving && editing;
+ const waypoints = {
+ points: editing ? tourPlanner.waypoints : [],
+ selectedId: editing ? tourPlanner.selectedWaypointId : null,
+ onSelect: tourPlanner.setSelectedWaypointId,
+ onMove: canEditRoute ? tourPlanner.setWaypointPosition : undefined,
+ onAdd: canEditRoute ? tourPlanner.addWaypoint : undefined,
+ };
+ // What each panel covers of the map, a collapsed one its rail.
+ const leftInset = leftHidden ? 56 : leftPanelPx;
+ const rightInset = rightHidden ? 56 : rightPanelPx;
return (
<>
- <MapView
- tripId={tripId}
- places={[]}
- route={tourMap.route}
- followSelection={false}
- onMapClick={
- canPlaceEdit &&
- !tourPlanner.isSaving &&
- (tourPlanner.mode.type === 'new-draft' || tourPlanner.mode.type === 'edit-saved')
- ? ({ latlng }: { latlng: { lat: number; lng: number } }) => tourPlanner.addWaypoint(latlng.lat, latlng.lng)
- : undefined
- }
- tileUrl={mapTileUrl}
- leftWidth={leftPanelPx}
- rightWidth={rightPanelPx}
- focusPoints={tourMap.focusPoints}
- focusKey={tourMap.focusKey}
- plannerWaypoints={
- tourPlanner.mode.type === 'new-draft' || tourPlanner.mode.type === 'edit-saved' ? tourPlanner.waypoints : []
- }
- selectedPlannerWaypointId={
- tourPlanner.mode.type === 'new-draft' || tourPlanner.mode.type === 'edit-saved'
- ? tourPlanner.selectedWaypointId
- : null
- }
- onPlannerWaypointClick={tourPlanner.setSelectedWaypointId}
- onPlannerWaypointMove={
- canPlaceEdit &&
- !tourPlanner.isSaving &&
- (tourPlanner.mode.type === 'new-draft' || tourPlanner.mode.type === 'edit-saved')
- ? tourPlanner.setWaypointPosition
- : undefined
- }
- routeProfileFocus={tourPlanner.routeProfileFocus}
- viewBaseLayer={tourPlanner.mapBaseLayer}
- onViewBaseLayerChange={tourPlanner.setMapBaseLayer}
- />
+ {terrain3d ? (
+ <Suspense fallback={null}>
+ <TourTerrainMap
+ samples={analysis?.distanceIndexedProfileSamples ?? []}
+ routes={tourMap.route}
+ trackColor={TOUR_TRACK_COLOR}
+ unit={distanceUnit}
+ baseLayer={tourPlanner.mapBaseLayer}
+ onBaseLayerChange={tourPlanner.setMapBaseLayer}
+ onExit={() => setTerrain3d(false)}
+ focus={tourPlanner.routeProfileFocus}
+ onFocusChange={tourPlanner.setRouteProfileFocus}
+ leftWidth={leftInset}
+ rightWidth={rightInset}
+ waypoints={waypoints}
+ framePoints={tourMap.focusPoints}
+ />
+ </Suspense>
+ ) : (
+ <MapView
+ tripId={tripId}
+ places={[]}
+ route={tourMap.route}
+ followSelection={false}
+ onMapClick={
+ canEditRoute
+ ? ({ latlng }: { latlng: { lat: number; lng: number } }) =>
+ tourPlanner.addWaypoint(latlng.lat, latlng.lng)
+ : undefined
+ }
+ tileUrl={mapTileUrl}
+ leftWidth={leftPanelPx}
+ rightWidth={rightPanelPx}
+ focusPoints={tourMap.focusPoints}
+ focusKey={tourMap.focusKey}
+ plannerWaypoints={waypoints.points}
+ selectedPlannerWaypointId={waypoints.selectedId}
+ onPlannerWaypointClick={tourPlanner.setSelectedWaypointId}
+ onPlannerWaypointMove={waypoints.onMove}
+ routeProfileFocus={tourPlanner.routeProfileFocus}
+ viewBaseLayer={tourPlanner.mapBaseLayer}
+ onViewBaseLayerChange={tourPlanner.setMapBaseLayer}
+ onToggleTerrain3d={() => setTerrain3d(true)}
+ />
+ )}
{/* Centred over the map between the two panels, which sit on fixed physical sides. */}
<div
style={{
@@ -87,8 +117,8 @@ export function TourPlannerMapStage({
>
<div
style={{
- transform: `translateX(${((leftHidden ? 56 : leftPanelPx) - (rightHidden ? 56 : rightPanelPx)) / 2}px)`,
- width: `min(360px, calc(100vw - ${(leftHidden ? 56 : leftPanelPx) + (rightHidden ? 56 : rightPanelPx) + 32}px))`,
+ transform: `translateX(${(leftInset - rightInset) / 2}px)`,
+ width: `min(360px, calc(100vw - ${leftInset + rightInset + 32}px))`,
pointerEvents: 'auto',
}}
>
diff --git a/server/src/db/entities/Tours.entity.ts b/server/src/db/entities/Tours.entity.ts
index 91ba143ce..25aced850 100644
--- a/server/src/db/entities/Tours.entity.ts
+++ b/server/src/db/entities/Tours.entity.ts
@@ -1,4 +1,4 @@
-import { Collection, EntityRepositoryType, type Opt, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
+import { Collection, EntityRepositoryType, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
import { ToursRepository } from '../repositories/Tours.repository';
import { Places } from './Places.entity';
import { TourTypes } from './TourTypes.entity';
@@ -18,7 +18,7 @@ export class Tours {
wanderer_ref?: string | null;
match_confidence?: number | null;
created_at?: string | null;
- max_hiking_difficulty: number & Opt = 2;
+ max_hiking_difficulty?: number | null = 2;
planned_duration_minutes?: number | null;
break_additional_minutes?: number | null;
tourTypeRef!: Ref<TourTypes>;
@@ -40,7 +40,7 @@ export const ToursSchema = defineEntity({
wanderer_ref: p.text().nullable(),
match_confidence: p.double().nullable(),
created_at: p.text().nullable().defaultRaw(`CURRENT_TIMESTAMP`),
- max_hiking_difficulty: p.integer().default(2),
+ max_hiking_difficulty: p.integer().nullable(),
planned_duration_minutes: p.integer().nullable(),
break_additional_minutes: p.integer().nullable(),
tourTypeRef: () => p.manyToOne(TourTypes).ref().joinColumn('tour_type').hidden().index('idx_tours_tour_type'),
diff --git a/server/src/db/kysely/Tours.table.ts b/server/src/db/kysely/Tours.table.ts
index 7646becb5..1bea5791b 100644
--- a/server/src/db/kysely/Tours.table.ts
+++ b/server/src/db/kysely/Tours.table.ts
@@ -13,7 +13,7 @@ export interface ToursTable {
wanderer_ref: InsertOptional<string | null>;
match_confidence: InsertOptional<number | null>;
created_at: InsertOptional<string | null>;
- max_hiking_difficulty: InsertOptional<number>;
+ max_hiking_difficulty: InsertOptional<number | null>;
planned_duration_minutes: InsertOptional<number | null>;
break_additional_minutes: InsertOptional<number | null>;
}
diff --git a/server/src/db/migrations/Migration20200101043100_an_imported_tour_has_no_hiking_difficulty.ts b/server/src/db/migrations/Migration20200101043100_an_imported_tour_has_no_hiking_difficulty.ts
new file mode 100644
index 000000000..640240595
--- /dev/null
+++ b/server/src/db/migrations/Migration20200101043100_an_imported_tour_has_no_hiking_difficulty.ts
@@ -0,0 +1,74 @@
+import { Migration } from '@mikro-orm/migrations';
+
+/**
+ * `tours.max_hiking_difficulty` may be NULL. A tour drawn in the planner still
+ * gets the default of 2, but a GPX import knows nothing about the route's
+ * difficulty, and writing 2 there claimed a value nobody chose.
+ *
+ * SQLite cannot drop a NOT NULL in place, so the table is rebuilt. With
+ * `foreign_keys = ON` a `DROP TABLE tours` runs an implicit `DELETE FROM
+ * tours` first, and the `ON DELETE CASCADE` on `tour_waypoints` would empty
+ * that table with it. So `tour_waypoints` is rebuilt as well, pointing at
+ * `tours_new`, and the old waypoint table goes before the old tours table:
+ * by then nothing references `tours`. Renaming `tours_new` to `tours`
+ * rewrites the waypoints' foreign key to the new name. Waypoint ids are
+ * copied, so AUTOINCREMENT carries on where it was.
+ *
+ * Existing rows keep their value: nothing tells an imported tour from a
+ * drawn one, so only imports from now on are written without a difficulty.
+ */
+export class Migration20200101043100_an_imported_tour_has_no_hiking_difficulty extends Migration {
+ override name = 'Migration20200101043100_an_imported_tour_has_no_hiking_difficulty';
+
+ override up(): void {
+ this.addSql(`
+ CREATE TABLE tours_new (
+ place_id INTEGER PRIMARY KEY REFERENCES places(id) ON DELETE CASCADE,
+ tour_type TEXT NOT NULL REFERENCES tour_types(key),
+ distance REAL,
+ elevation_gain REAL,
+ elevation_loss REAL,
+ duration REAL,
+ difficulty TEXT,
+ wanderer_ref TEXT,
+ match_confidence REAL,
+ created_at TEXT DEFAULT CURRENT_TIMESTAMP,
+ max_hiking_difficulty INTEGER DEFAULT 2 CHECK(max_hiking_difficulty BETWEEN 1 AND 6),
+ planned_duration_minutes INTEGER CHECK(planned_duration_minutes BETWEEN 0 AND 1440),
+ break_additional_minutes INTEGER CHECK(break_additional_minutes BETWEEN 0 AND 1440)
+ )
+ `);
+ this.addSql(`
+ INSERT INTO tours_new (
+ place_id, tour_type, distance, elevation_gain, elevation_loss, duration, difficulty, wanderer_ref,
+ match_confidence, created_at, max_hiking_difficulty, planned_duration_minutes, break_additional_minutes
+ )
+ SELECT
+ place_id, tour_type, distance, elevation_gain, elevation_loss, duration, difficulty, wanderer_ref,
+ match_confidence, created_at, max_hiking_difficulty, planned_duration_minutes, break_additional_minutes
+ FROM tours
+ `);
+
+ this.addSql(`
+ CREATE TABLE tour_waypoints_new (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ place_id INTEGER NOT NULL REFERENCES tours_new(place_id) ON DELETE CASCADE,
+ lat REAL NOT NULL CHECK(lat >= -90 AND lat <= 90),
+ lng REAL NOT NULL CHECK(lng >= -180 AND lng <= 180),
+ role TEXT NOT NULL CHECK(role IN ('start', 'via', 'end')),
+ sequence INTEGER NOT NULL CHECK(sequence >= 0),
+ UNIQUE(place_id, sequence)
+ )
+ `);
+ this.addSql(`
+ INSERT INTO tour_waypoints_new (id, place_id, lat, lng, role, sequence)
+ SELECT id, place_id, lat, lng, role, sequence FROM tour_waypoints
+ `);
+
+ this.addSql('DROP TABLE tour_waypoints');
+ this.addSql('DROP TABLE tours');
+ this.addSql('ALTER TABLE tours_new RENAME TO tours');
+ this.addSql('ALTER TABLE tour_waypoints_new RENAME TO tour_waypoints');
+ this.addSql('CREATE INDEX IF NOT EXISTS idx_tours_tour_type ON tours(tour_type)');
+ }
+}
diff --git a/server/src/db/repositories/Tours.repository.ts b/server/src/db/repositories/Tours.repository.ts
index a4daae742..5715783cb 100644
--- a/server/src/db/repositories/Tours.repository.ts
+++ b/server/src/db/repositories/Tours.repository.ts
@@ -24,7 +24,7 @@ export interface TourListRow {
difficulty: string | null;
wanderer_ref: string | null;
match_confidence: number | null;
- max_hiking_difficulty: number;
+ max_hiking_difficulty: number | null;
planned: number;
has_waypoints: number;
}
@@ -43,7 +43,7 @@ export interface TourRow {
wanderer_ref: string | null;
match_confidence: number | null;
created_at: string | null;
- max_hiking_difficulty: number;
+ max_hiking_difficulty: number | null;
}
const _tourRowKeys: AssertRowKeys<TourRow, Tours> = true;
@@ -58,7 +58,7 @@ export interface TourInsert {
planned_duration_minutes: number | null;
break_additional_minutes?: number | null;
match_confidence: number | null;
- max_hiking_difficulty: number;
+ max_hiking_difficulty: number | null;
}
/** What a route edit replaces on an existing tour. */
diff --git a/server/src/middleware/globalMiddleware.ts b/server/src/middleware/globalMiddleware.ts
index 61e1186bb..8e078af53 100644
--- a/server/src/middleware/globalMiddleware.ts
+++ b/server/src/middleware/globalMiddleware.ts
@@ -285,6 +285,8 @@ export function applyGlobalMiddleware(
'ws:',
'wss:',
'https://nominatim.openstreetmap.org',
+ // Open elevation tiles (Mapzen Terrarium on AWS Open Data) for the 3D tour view.
+ 'https://elevation-tiles-prod.s3.amazonaws.com',
'https://overpass-api.de',
'https://places.googleapis.com',
'https://api.openweathermap.org',
diff --git a/server/src/nest/tours/tours.service.ts b/server/src/nest/tours/tours.service.ts
index 547eafdf2..96b0aaad7 100644
--- a/server/src/nest/tours/tours.service.ts
+++ b/server/src/nest/tours/tours.service.ts
@@ -67,7 +67,7 @@ export class ToursService {
difficulty: r.difficulty,
wanderer_ref: r.wanderer_ref,
match_confidence: r.match_confidence,
- max_hiking_difficulty: r.max_hiking_difficulty ?? 2,
+ max_hiking_difficulty: r.max_hiking_difficulty,
planned: Boolean(r.planned),
caution: r.match_confidence !== null && r.match_confidence < LOW_CONFIDENCE_THRESHOLD,
has_waypoints: Boolean(r.has_waypoints),
@@ -309,7 +309,7 @@ export class ToursService {
planned_duration_minutes: null,
break_additional_minutes: null,
match_confidence: matchConfidence,
- max_hiking_difficulty: 2,
+ max_hiking_difficulty: null,
});
tours.push(
this.toItem({
@@ -327,7 +327,7 @@ export class ToursService {
difficulty: null,
wanderer_ref: null,
match_confidence: matchConfidence,
- max_hiking_difficulty: 2,
+ max_hiking_difficulty: null,
planned: 0,
has_waypoints: 0,
}),
diff --git a/server/tests/e2e/tours.e2e.test.ts b/server/tests/e2e/tours.e2e.test.ts
index a5ca5c055..2c93f8ac6 100644
--- a/server/tests/e2e/tours.e2e.test.ts
+++ b/server/tests/e2e/tours.e2e.test.ts
@@ -463,11 +463,14 @@ describe('Tours e2e (real guards + temp SQLite)', () => {
name: 'Alpine loop',
tour_type: 'hike',
match_confidence: 1,
- max_hiking_difficulty: 2,
+ max_hiking_difficulty: null,
has_waypoints: false,
});
expect(await placeColumns(tour.place_id, 'trip_id')).toEqual({ trip_id: 5 });
- expect((await findRow(orm, Tours, { place: tour.place_id }))?.tour_type).toBe('hike');
+ expect(await findRow(orm, Tours, { place: tour.place_id })).toMatchObject({
+ tour_type: 'hike',
+ max_hiking_difficulty: null,
+ });
expect(broadcast.mock.calls.map((c) => c[1])).toEqual(expect.arrayContaining(['tours:changed', 'place:created']));
});
diff --git a/server/tests/unit/db/known-migrations.test.ts b/server/tests/unit/db/known-migrations.test.ts
index 64c98c286..d0f6c0992 100644
--- a/server/tests/unit/db/known-migrations.test.ts
+++ b/server/tests/unit/db/known-migrations.test.ts
@@ -13,6 +13,7 @@ describe('known migrations', () => {
expect(known.has('Migration20200101042000_tours')).toBe(true);
expect(known.has('Migration20200101042900_tour_planned_total_duration')).toBe(true);
expect(known.has('Migration20200101043000_tour_break_additional_duration')).toBe(true);
+ expect(known.has('Migration20200101043100_an_imported_tour_has_no_hiking_difficulty')).toBe(true);
expect(known.size).toBe(fs.readdirSync(path.join(__dirname, '../../../src/db/migrations')).length);
});
diff --git a/server/tests/unit/db/legacy-baseline.test.ts b/server/tests/unit/db/legacy-baseline.test.ts
index bb14fffa4..98a55da25 100644
--- a/server/tests/unit/db/legacy-baseline.test.ts
+++ b/server/tests/unit/db/legacy-baseline.test.ts
@@ -42,6 +42,7 @@ const UNNUMBERED = [
'Migration20200101042800_an_email_the_account_typed_in_itself',
'Migration20200101042900_tour_planned_total_duration',
'Migration20200101043000_tour_break_additional_duration',
+ 'Migration20200101043100_an_imported_tour_has_no_hiking_difficulty',
];
// The last step the positional runner ever had; planLegacyBaseline refuses a
// schema_version past it.
diff --git a/server/tests/unit/db/tour-imported-difficulty-migration.test.ts b/server/tests/unit/db/tour-imported-difficulty-migration.test.ts
new file mode 100644
index 000000000..e7fae860a
--- /dev/null
+++ b/server/tests/unit/db/tour-imported-difficulty-migration.test.ts
@@ -0,0 +1,121 @@
+/**
+ * `Migration20200101043100_an_imported_tour_has_no_hiking_difficulty`:
+ * `tours.max_hiking_difficulty` turns nullable through a rebuild of `tours`
+ * and `tour_waypoints`, without losing a row of either, and the constraints
+ * around it still hold.
+ */
+import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step';
+import type { MikroORM } from '@mikro-orm/sqlite';
+
+import { describe, expect, it } from 'vitest';
+
+const TARGET = 'Migration20200101043100_an_imported_tour_has_no_hiking_difficulty';
+
+async function ormBeforeTarget(): Promise<MikroORM> {
+ const orm = await createMigrationOrm();
+ const names = await pendingNames(orm);
+ const index = names.indexOf(TARGET);
+ expect(index).toBeGreaterThan(0);
+ await migrateTo(orm, names[index - 1]);
+ return orm;
+}
+
+async function seedTripWithPlaces(orm: MikroORM, placeIds: number[]): Promise<void> {
+ await rawExec(orm, "INSERT INTO users (id, username, email, password_hash) VALUES (1, 'owner', 'owner@test', 'x')");
+ await rawExec(orm, "INSERT INTO trips (id, user_id, title) VALUES (10, 1, 'Alps')");
+ const rows = placeIds.map((id) => `(${id}, 10, 'Place ${id}')`).join(', ');
+ await rawExec(orm, `INSERT INTO places (id, trip_id, name) VALUES ${rows}`);
+}
+
+describe('Imported tour hiking difficulty migration', () => {
+ it('TOURDIFFMIG-001: keeps every tour and waypoint while the difficulty becomes optional', async () => {
+ const orm = await ormBeforeTarget();
+ try {
+ await seedTripWithPlaces(orm, [100, 101]);
+ await rawExec(
+ orm,
+ `INSERT INTO tours (place_id, tour_type, distance, difficulty, wanderer_ref, match_confidence, created_at,
+ max_hiking_difficulty, planned_duration_minutes, break_additional_minutes)
+ VALUES (100, 'hike', 12.5, 'T3', 'w-1', 0.3, '2026-01-02 10:00:00', 4, 125, 35)`,
+ );
+ await rawExec(
+ orm,
+ `INSERT INTO tour_waypoints (place_id, lat, lng, role, sequence)
+ VALUES (100, 47, 11, 'start', 0), (100, 47.1, 11.1, 'end', 1)`,
+ );
+
+ await migrateTo(orm, TARGET);
+
+ expect(await rawQuery(orm, 'SELECT * FROM tours')).toEqual([
+ {
+ place_id: 100,
+ tour_type: 'hike',
+ distance: 12.5,
+ elevation_gain: null,
+ elevation_loss: null,
+ duration: null,
+ difficulty: 'T3',
+ wanderer_ref: 'w-1',
+ match_confidence: 0.3,
+ created_at: '2026-01-02 10:00:00',
+ max_hiking_difficulty: 4,
+ planned_duration_minutes: 125,
+ break_additional_minutes: 35,
+ },
+ ]);
+ expect(await rawQuery(orm, 'SELECT id, place_id, role, sequence FROM tour_waypoints ORDER BY id')).toEqual([
+ { id: 1, place_id: 100, role: 'start', sequence: 0 },
+ { id: 2, place_id: 100, role: 'end', sequence: 1 },
+ ]);
+
+ const column = await rawQuery<{ notnull: number; dflt_value: string | null }>(
+ orm,
+ "SELECT \"notnull\", dflt_value FROM pragma_table_info('tours') WHERE name = 'max_hiking_difficulty'",
+ );
+ expect(column).toEqual([{ notnull: 0, dflt_value: '2' }]);
+
+ await rawExec(orm, "INSERT INTO tours (place_id, tour_type, max_hiking_difficulty) VALUES (101, 'hike', NULL)");
+ expect(await rawQuery(orm, 'SELECT max_hiking_difficulty FROM tours WHERE place_id = 101')).toEqual([
+ { max_hiking_difficulty: null },
+ ]);
+ await expect(rawExec(orm, 'UPDATE tours SET max_hiking_difficulty = 7 WHERE place_id = 101')).rejects.toThrow(
+ /CHECK/,
+ );
+ } finally {
+ await orm.close(true);
+ }
+ }, 30000);
+
+ it('TOURDIFFMIG-002: a drawn tour still defaults to 2 and the cascades and index survive the rebuild', async () => {
+ const orm = await ormBeforeTarget();
+ try {
+ await seedTripWithPlaces(orm, [100]);
+
+ await migrateTo(orm, TARGET);
+
+ await rawExec(orm, "INSERT INTO tours (place_id, tour_type) VALUES (100, 'hike')");
+ await rawExec(
+ orm,
+ "INSERT INTO tour_waypoints (place_id, lat, lng, role, sequence) VALUES (100, 47, 11, 'start', 0)",
+ );
+ expect(await rawQuery(orm, 'SELECT max_hiking_difficulty FROM tours')).toEqual([{ max_hiking_difficulty: 2 }]);
+
+ await expect(
+ rawExec(orm, "INSERT INTO tour_waypoints (place_id, lat, lng, role, sequence) VALUES (999, 47, 11, 'end', 1)"),
+ ).rejects.toThrow(/FOREIGN KEY/);
+
+ const indexes = await rawQuery<{ name: string }>(
+ orm,
+ "SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'tours' AND name = 'idx_tours_tour_type'",
+ );
+ expect(indexes).toEqual([{ name: 'idx_tours_tour_type' }]);
+
+ await rawExec(orm, 'DELETE FROM places WHERE id = 100');
+ expect(await rawQuery(orm, 'SELECT COUNT(*) AS n FROM tours')).toEqual([{ n: 0 }]);
+ expect(await rawQuery(orm, 'SELECT COUNT(*) AS n FROM tour_waypoints')).toEqual([{ n: 0 }]);
+ expect(await rawQuery(orm, 'SELECT * FROM pragma_foreign_key_check')).toEqual([]);
+ } finally {
+ await orm.close(true);
+ }
+ }, 30000);
+});
diff --git a/server/tests/unit/middleware/globalMiddleware.csp.test.ts b/server/tests/unit/middleware/globalMiddleware.csp.test.ts
index b71e52154..aa29d81c3 100644
--- a/server/tests/unit/middleware/globalMiddleware.csp.test.ts
+++ b/server/tests/unit/middleware/globalMiddleware.csp.test.ts
@@ -96,6 +96,21 @@ describe('global CSP: the imagery host (#2307)', () => {
});
});
+describe('global CSP: the elevation tiles of the 3D tour view', () => {
+ it('allows the Terrarium tiles, which MapLibre and the flyover preload fetch', async () => {
+ // The 3D view drapes the route over Mapzen's open elevation model on AWS Open
+ // Data. MapLibre reads raster-dem tiles through fetch, and the corridor preload
+ // warms the cache with fetch too, so both land on connect-src; img-src is not asked.
+ expect(await connectSrcSources()).toContain('https://elevation-tiles-prod.s3.amazonaws.com');
+ });
+
+ it('names that one bucket host, not every S3 bucket', async () => {
+ const sources = await connectSrcSources();
+ expect(sources).not.toContain('https://*.s3.amazonaws.com');
+ expect(sources).not.toContain('https://*.amazonaws.com');
+ });
+});
+
describe('global CSP: script-src', () => {
it("allows 'wasm-unsafe-eval' so the WASM decoders keep running", async () => {
expect(await directiveSources('script-src')).toContain("'wasm-unsafe-eval'");
diff --git a/server/tests/unit/nest/tours.gpx.atomic.test.ts b/server/tests/unit/nest/tours.gpx.atomic.test.ts
index 8019fa9cc..cc80fdd11 100644
--- a/server/tests/unit/nest/tours.gpx.atomic.test.ts
+++ b/server/tests/unit/nest/tours.gpx.atomic.test.ts
@@ -209,7 +209,7 @@ describe('Tours GPX atomic persistence and postcommit publication', () => {
expect(result.tours[0]).toMatchObject({
name: 'walk',
tour_type: 'hike',
- max_hiking_difficulty: 2,
+ max_hiking_difficulty: null,
planned: false,
has_waypoints: false,
caution: true,
diff --git a/shared/src/i18n/ar/tours.ts b/shared/src/i18n/ar/tours.ts
index 111af3ff5..637cfda7e 100644
--- a/shared/src/i18n/ar/tours.ts
+++ b/shared/src/i18n/ar/tours.ts
@@ -54,7 +54,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': 'العودة إلى الجولات',
'tours.planner.restored': 'تمت استعادة المسودة غير المحفوظة',
'tours.planner.discardChanges': 'تجاهل التغييرات',
- 'tours.planner.discardUnsaved': 'تجاهل التغييرات غير المحفوظة',
'tours.planner.newTourConfirmTitle': 'هل تريد بدء جولة جديدة؟',
'tours.planner.newTourConfirmBody': 'ستُحذف تغييراتك غير المحفوظة على هذه الجولة. لن تتغيّر الجولات المحفوظة.',
'tours.planner.newTourConfirm': 'تجاهل التغييرات وبدء جولة جديدة',
@@ -149,5 +148,23 @@ const tours: TranslationStrings = {
'tourTypes.kayak': 'تجديف بالكاياك',
'tourTypes.walk': 'مشي في المدينة / مشاهدة المعالم',
'tourTypes.food': 'جولة طعام / نبيذ',
+ 'tours.terrain.play': 'تشغيل التحليق',
+ 'tours.terrain.pause': 'إيقاف مؤقت',
+ 'tours.terrain.restart': 'البدء من جديد',
+ 'tours.terrain.speed': 'السرعة',
+ 'tours.terrain.exaggeration': 'التضاريس',
+ 'tours.terrain.overview': 'نظرة عامة',
+ 'tours.terrain.colorByGrade': 'الانحدار',
+ 'tours.terrain.gradeMix': 'توزيع الانحدار',
+ 'tours.terrain.band.flat': 'أقل من 5 %',
+ 'tours.terrain.band.gentle': 'من 5 إلى 10 %',
+ 'tours.terrain.band.moderate': 'من 10 إلى 18 %',
+ 'tours.terrain.band.steep': 'من 18 إلى 27 %',
+ 'tours.terrain.band.verySteep': '27 % فأكثر',
+ 'tours.terrain.attribution': 'الارتفاعات: Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour': 'افتح جولة من اليمين للتحليق فوقها بالأبعاد الثلاثية وتلوينها حسب الانحدار.',
+ 'tours.terrain.steepestShort': 'الأقصى {grade} %',
+ 'tours.terrain.preloading': 'جارٍ تحميل المشهد: {percent} %',
+ 'tours.terrain.clickToPlan': 'انقر على التضاريس لإضافة نقاط. بمجرد وجود مسار يمكن التحليق فوقه وتلوينه حسب الانحدار.',
};
export default tours;
diff --git a/shared/src/i18n/az/tours.ts b/shared/src/i18n/az/tours.ts
index 3b806da48..a6298a392 100644
--- a/shared/src/i18n/az/tours.ts
+++ b/shared/src/i18n/az/tours.ts
@@ -51,7 +51,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': 'Turlara qayıt',
'tours.planner.restored': 'Saxlanılmamış qaralama bərpa edildi',
'tours.planner.discardChanges': 'Dəyişiklikləri ləğv et',
- 'tours.planner.discardUnsaved': 'Saxlanılmamış dəyişiklikləri ləğv et',
'tours.planner.newTourConfirmTitle': 'Yeni tur başlansın?',
'tours.planner.newTourConfirmBody':
'Bu turda saxlanılmamış dəyişiklikləriniz ləğv ediləcək. Saxlanılmış turlar dəyişməyəcək.',
@@ -144,5 +143,24 @@ const tours: TranslationStrings = {
'tourTypes.kayak': 'Kayak gəzintisi',
'tourTypes.walk': 'Şəhər / görməli yerlər gəzintisi',
'tourTypes.food': 'Yemək/şərab turu',
+ 'tours.terrain.play': 'Uçuşu oynat',
+ 'tours.terrain.pause': 'Fasilə',
+ 'tours.terrain.restart': 'Yenidən başla',
+ 'tours.terrain.speed': 'Sürət',
+ 'tours.terrain.exaggeration': 'Relyef',
+ 'tours.terrain.overview': 'Ümumi baxış',
+ 'tours.terrain.colorByGrade': 'Meyil',
+ 'tours.terrain.gradeMix': 'Meyil bölgüsü',
+ 'tours.terrain.band.flat': '5%-dən az',
+ 'tours.terrain.band.gentle': '5% ilə 10% arası',
+ 'tours.terrain.band.moderate': '10% ilə 18% arası',
+ 'tours.terrain.band.steep': '18% ilə 27% arası',
+ 'tours.terrain.band.verySteep': '27% və daha çox',
+ 'tours.terrain.attribution': 'Hündürlük: Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour': 'Turu 3D-də uçmaq və meyilə görə rəngləmək üçün sağ tərəfdə açın.',
+ 'tours.terrain.steepestShort': 'maks. {grade}%',
+ 'tours.terrain.preloading': 'Mənzərə yüklənir: {percent}%',
+ 'tours.terrain.clickToPlan':
+ 'Nöqtə qoymaq üçün əraziyə klikləyin. Marşrut yarandıqdan sonra onun üzərindən uçmaq və meyilə görə rəngləmək olar.',
};
export default tours;
diff --git a/shared/src/i18n/br/tours.ts b/shared/src/i18n/br/tours.ts
index bc0c37896..92272cea8 100644
--- a/shared/src/i18n/br/tours.ts
+++ b/shared/src/i18n/br/tours.ts
@@ -52,7 +52,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': 'Voltar aos passeios',
'tours.planner.restored': 'Rascunho não salvo restaurado',
'tours.planner.discardChanges': 'Descartar alterações',
- 'tours.planner.discardUnsaved': 'Descartar alterações não salvas',
'tours.planner.newTourConfirmTitle': 'Começar um novo passeio?',
'tours.planner.newTourConfirmBody':
'As alterações não salvas deste passeio serão descartadas. Os passeios salvos não serão alterados.',
@@ -145,5 +144,24 @@ const tours: TranslationStrings = {
'tourTypes.kayak': 'Passeio de caiaque',
'tourTypes.walk': 'Caminhada urbana / turística',
'tourTypes.food': 'Passeio gastronômico / enológico',
+ 'tours.terrain.play': 'Reproduzir sobrevoo',
+ 'tours.terrain.pause': 'Pausar',
+ 'tours.terrain.restart': 'Recomeçar',
+ 'tours.terrain.speed': 'Velocidade',
+ 'tours.terrain.exaggeration': 'Relevo',
+ 'tours.terrain.overview': 'Visão geral',
+ 'tours.terrain.colorByGrade': 'Inclinação',
+ 'tours.terrain.gradeMix': 'Distribuição da inclinação',
+ 'tours.terrain.band.flat': 'menos de 5 %',
+ 'tours.terrain.band.gentle': 'de 5 a 10 %',
+ 'tours.terrain.band.moderate': 'de 10 a 18 %',
+ 'tours.terrain.band.steep': 'de 18 a 27 %',
+ 'tours.terrain.band.verySteep': '27 % ou mais',
+ 'tours.terrain.attribution': 'Altitudes: Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour': 'Abra um passeio à direita para sobrevoá-lo em 3D e colori-lo pela inclinação.',
+ 'tours.terrain.steepestShort': 'máx. {grade} %',
+ 'tours.terrain.preloading': 'Carregando a paisagem: {percent} %',
+ 'tours.terrain.clickToPlan':
+ 'Clique no terreno para adicionar pontos. Assim que houver uma rota, ela pode ser sobrevoada e colorida pela inclinação.',
};
export default tours;
diff --git a/shared/src/i18n/ca/tours.ts b/shared/src/i18n/ca/tours.ts
index 96220fb73..8562aafcd 100644
--- a/shared/src/i18n/ca/tours.ts
+++ b/shared/src/i18n/ca/tours.ts
@@ -51,7 +51,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': 'Torna a excursions',
'tours.planner.restored': 'Esborrany sense desar restaurat',
'tours.planner.discardChanges': 'Descarta els canvis',
- 'tours.planner.discardUnsaved': 'Descarta els canvis sense desar',
'tours.planner.newTourConfirmTitle': 'Vols començar una nova excursió?',
'tours.planner.newTourConfirmBody':
"Es descartaran els canvis sense desar d'aquesta excursió. Les excursions desades no es modificaran.",
@@ -144,5 +143,24 @@ const tours: TranslationStrings = {
'tourTypes.kayak': 'Ruta en caiac',
'tourTypes.walk': 'Passeig urbà / turístic',
'tourTypes.food': 'Ruta gastronòmica / enològica',
+ 'tours.terrain.play': 'Reprodueix el sobrevol',
+ 'tours.terrain.pause': 'Pausa',
+ 'tours.terrain.restart': 'Torna a començar',
+ 'tours.terrain.speed': 'Velocitat',
+ 'tours.terrain.exaggeration': 'Relleu',
+ 'tours.terrain.overview': 'Vista general',
+ 'tours.terrain.colorByGrade': 'Pendent',
+ 'tours.terrain.gradeMix': 'Distribució dels pendents',
+ 'tours.terrain.band.flat': 'menys del 5 %',
+ 'tours.terrain.band.gentle': 'del 5 al 10 %',
+ 'tours.terrain.band.moderate': 'del 10 al 18 %',
+ 'tours.terrain.band.steep': 'del 18 al 27 %',
+ 'tours.terrain.band.verySteep': '27 % o més',
+ 'tours.terrain.attribution': 'Altituds: Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour': 'Obre una excursió a la dreta per sobrevolar-la en 3D i acolorir-la segons el pendent.',
+ 'tours.terrain.steepestShort': 'màx. {grade} %',
+ 'tours.terrain.preloading': 'Carregant el paisatge: {percent} %',
+ 'tours.terrain.clickToPlan':
+ 'Fes clic al terreny per afegir punts. Quan hi hagi una ruta, es podrà sobrevolar i acolorir segons el pendent.',
};
export default tours;
diff --git a/shared/src/i18n/cs/tours.ts b/shared/src/i18n/cs/tours.ts
index 7cad7246d..ffd5cd48c 100644
--- a/shared/src/i18n/cs/tours.ts
+++ b/shared/src/i18n/cs/tours.ts
@@ -51,7 +51,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': 'Zpět na výlety',
'tours.planner.restored': 'Neuložený koncept obnoven',
'tours.planner.discardChanges': 'Zahodit změny',
- 'tours.planner.discardUnsaved': 'Zahodit neuložené změny',
'tours.planner.newTourConfirmTitle': 'Začít nový výlet?',
'tours.planner.newTourConfirmBody': 'Neuložené změny tohoto výletu budou zahozeny. Uložené výlety se nezmění.',
'tours.planner.newTourConfirm': 'Zahodit změny a začít nový výlet',
@@ -143,5 +142,24 @@ const tours: TranslationStrings = {
'tourTypes.kayak': 'Kajak',
'tourTypes.walk': 'Procházka městem / po památkách',
'tourTypes.food': 'Gastronomický / vinařský výlet',
+ 'tours.terrain.play': 'Přehrát přelet',
+ 'tours.terrain.pause': 'Pozastavit',
+ 'tours.terrain.restart': 'Od začátku',
+ 'tours.terrain.speed': 'Rychlost',
+ 'tours.terrain.exaggeration': 'Reliéf',
+ 'tours.terrain.overview': 'Přehled',
+ 'tours.terrain.colorByGrade': 'Sklon',
+ 'tours.terrain.gradeMix': 'Rozložení sklonu',
+ 'tours.terrain.band.flat': 'pod 5 %',
+ 'tours.terrain.band.gentle': '5 až 10 %',
+ 'tours.terrain.band.moderate': '10 až 18 %',
+ 'tours.terrain.band.steep': '18 až 27 %',
+ 'tours.terrain.band.verySteep': '27 % a více',
+ 'tours.terrain.attribution': 'Výšky: Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour': 'Otevřete vpravo výlet, abyste ho mohli proletět ve 3D a obarvit podle sklonu.',
+ 'tours.terrain.steepestShort': 'max. {grade} %',
+ 'tours.terrain.preloading': 'Načítání krajiny: {percent} %',
+ 'tours.terrain.clickToPlan':
+ 'Kliknutím do terénu přidáte body. Jakmile vznikne trasa, lze ji proletět a obarvit podle sklonu.',
};
export default tours;
diff --git a/shared/src/i18n/de/tours.ts b/shared/src/i18n/de/tours.ts
index e855f0e7b..8125b6448 100644
--- a/shared/src/i18n/de/tours.ts
+++ b/shared/src/i18n/de/tours.ts
@@ -51,7 +51,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': 'Zurück zu den Touren',
'tours.planner.restored': 'Ungespeicherter Entwurf wiederhergestellt',
'tours.planner.discardChanges': 'Änderungen verwerfen',
- 'tours.planner.discardUnsaved': 'Ungespeicherte Änderungen verwerfen',
'tours.planner.newTourConfirmTitle': 'Neue Tour beginnen?',
'tours.planner.newTourConfirmBody':
'Ungespeicherte Änderungen an dieser Tour gehen verloren. Gespeicherte Touren bleiben erhalten.',
@@ -145,6 +144,25 @@ const tours: TranslationStrings = {
'tourTypes.kayak': 'Kajaktour',
'tourTypes.walk': 'Stadt- und Spaziergang',
'tourTypes.food': 'Genusstour',
+ 'tours.terrain.play': 'Flug abspielen',
+ 'tours.terrain.pause': 'Pause', // same-as-en
+ 'tours.terrain.restart': 'Von vorn',
+ 'tours.terrain.speed': 'Tempo',
+ 'tours.terrain.exaggeration': 'Relief', // same-as-en
+ 'tours.terrain.overview': 'Übersicht',
+ 'tours.terrain.colorByGrade': 'Steigung',
+ 'tours.terrain.gradeMix': 'Steigungsanteile',
+ 'tours.terrain.band.flat': 'unter 5 %',
+ 'tours.terrain.band.gentle': '5 bis 10 %',
+ 'tours.terrain.band.moderate': '10 bis 18 %',
+ 'tours.terrain.band.steep': '18 bis 27 %',
+ 'tours.terrain.band.verySteep': 'ab 27 %',
+ 'tours.terrain.attribution': 'Höhen: Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour': 'Öffne rechts eine Tour, um sie in 3D abzufliegen und nach Steigung einzufärben.',
+ 'tours.terrain.steepestShort': 'max. {grade} %',
+ 'tours.terrain.preloading': 'Landschaft wird vorgeladen: {percent} %',
+ 'tours.terrain.clickToPlan':
+ 'Klicke ins Gelände, um Punkte zu setzen. Sobald eine Route steht, lässt sie sich abfliegen und nach Steigung einfärben.',
};
export default tours;
diff --git a/shared/src/i18n/en/tours.ts b/shared/src/i18n/en/tours.ts
index b9690c800..6a51b93c4 100644
--- a/shared/src/i18n/en/tours.ts
+++ b/shared/src/i18n/en/tours.ts
@@ -50,7 +50,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': 'Back to Tours',
'tours.planner.restored': 'Unsaved draft restored',
'tours.planner.discardChanges': 'Discard changes',
- 'tours.planner.discardUnsaved': 'Discard unsaved changes',
'tours.planner.newTourConfirmTitle': 'Start a new tour?',
'tours.planner.newTourConfirmBody':
'Your unsaved changes to this tour will be discarded. Saved tours will not be changed.',
@@ -142,5 +141,24 @@ const tours: TranslationStrings = {
'tourTypes.kayak': 'Kayak',
'tourTypes.walk': 'City / sightseeing walk',
'tourTypes.food': 'Food/wine tour',
+ 'tours.terrain.play': 'Play flyover',
+ 'tours.terrain.pause': 'Pause',
+ 'tours.terrain.restart': 'Start over',
+ 'tours.terrain.speed': 'Speed',
+ 'tours.terrain.exaggeration': 'Relief',
+ 'tours.terrain.overview': 'Overview',
+ 'tours.terrain.colorByGrade': 'Grade',
+ 'tours.terrain.gradeMix': 'Grade mix',
+ 'tours.terrain.band.flat': 'under 5 %',
+ 'tours.terrain.band.gentle': '5 to 10 %',
+ 'tours.terrain.band.moderate': '10 to 18 %',
+ 'tours.terrain.band.steep': '18 to 27 %',
+ 'tours.terrain.band.verySteep': '27 % and more',
+ 'tours.terrain.attribution': 'Elevation: Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour': 'Open a tour on the right to fly it in 3D and colour it by grade.',
+ 'tours.terrain.steepestShort': 'max {grade} %',
+ 'tours.terrain.preloading': 'Loading the landscape: {percent} %',
+ 'tours.terrain.clickToPlan':
+ 'Click the terrain to set points. Once there is a route, it can be flown and coloured by grade.',
};
export default tours;
diff --git a/shared/src/i18n/es/tours.ts b/shared/src/i18n/es/tours.ts
index dde4b5177..26bd1c3cb 100644
--- a/shared/src/i18n/es/tours.ts
+++ b/shared/src/i18n/es/tours.ts
@@ -51,7 +51,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': 'Volver a excursiones',
'tours.planner.restored': 'Borrador sin guardar restaurado',
'tours.planner.discardChanges': 'Descartar cambios',
- 'tours.planner.discardUnsaved': 'Descartar cambios sin guardar',
'tours.planner.newTourConfirmTitle': '¿Empezar una nueva excursión?',
'tours.planner.newTourConfirmBody':
'Se descartarán los cambios sin guardar de esta excursión. Las excursiones guardadas no se modificarán.',
@@ -143,5 +142,24 @@ const tours: TranslationStrings = {
'tourTypes.kayak': 'Ruta en kayak',
'tourTypes.walk': 'Paseo urbano / turístico',
'tourTypes.food': 'Ruta gastronómica / enológica',
+ 'tours.terrain.play': 'Reproducir sobrevuelo',
+ 'tours.terrain.pause': 'Pausa',
+ 'tours.terrain.restart': 'Empezar de nuevo',
+ 'tours.terrain.speed': 'Velocidad',
+ 'tours.terrain.exaggeration': 'Relieve',
+ 'tours.terrain.overview': 'Vista general',
+ 'tours.terrain.colorByGrade': 'Pendiente',
+ 'tours.terrain.gradeMix': 'Reparto de pendientes',
+ 'tours.terrain.band.flat': 'menos del 5 %',
+ 'tours.terrain.band.gentle': 'del 5 al 10 %',
+ 'tours.terrain.band.moderate': 'del 10 al 18 %',
+ 'tours.terrain.band.steep': 'del 18 al 27 %',
+ 'tours.terrain.band.verySteep': '27 % o más',
+ 'tours.terrain.attribution': 'Altitudes: Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour': 'Abre una excursión a la derecha para sobrevolarla en 3D y colorearla según la pendiente.',
+ 'tours.terrain.steepestShort': 'máx. {grade} %',
+ 'tours.terrain.preloading': 'Cargando el paisaje: {percent} %',
+ 'tours.terrain.clickToPlan':
+ 'Haz clic en el terreno para añadir puntos. En cuanto haya una ruta, se podrá sobrevolar y colorear según la pendiente.',
};
export default tours;
diff --git a/shared/src/i18n/et/tours.ts b/shared/src/i18n/et/tours.ts
index e16d5788c..2a9bf5bbf 100644
--- a/shared/src/i18n/et/tours.ts
+++ b/shared/src/i18n/et/tours.ts
@@ -50,7 +50,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': 'Tagasi retkede juurde',
'tours.planner.restored': 'Salvestamata mustand taastatud',
'tours.planner.discardChanges': 'Loobu muudatustest',
- 'tours.planner.discardUnsaved': 'Loobu salvestamata muudatustest',
'tours.planner.newTourConfirmTitle': 'Kas alustada uut retke?',
'tours.planner.newTourConfirmBody':
'Selle retke salvestamata muudatused lähevad kaotsi. Salvestatud retki ei muudeta.',
@@ -143,5 +142,24 @@ const tours: TranslationStrings = {
'tourTypes.kayak': 'Süstaretk',
'tourTypes.walk': 'Linna- / vaatamisväärsuste jalutuskäik',
'tourTypes.food': 'Toidu- / veiniretk',
+ 'tours.terrain.play': 'Esita ülelend',
+ 'tours.terrain.pause': 'Paus',
+ 'tours.terrain.restart': 'Alusta otsast',
+ 'tours.terrain.speed': 'Kiirus',
+ 'tours.terrain.exaggeration': 'Reljeef',
+ 'tours.terrain.overview': 'Ülevaade',
+ 'tours.terrain.colorByGrade': 'Kalle',
+ 'tours.terrain.gradeMix': 'Kallete jaotus',
+ 'tours.terrain.band.flat': 'alla 5%',
+ 'tours.terrain.band.gentle': '5 kuni 10%',
+ 'tours.terrain.band.moderate': '10 kuni 18%',
+ 'tours.terrain.band.steep': '18 kuni 27%',
+ 'tours.terrain.band.verySteep': '27% ja rohkem',
+ 'tours.terrain.attribution': 'Kõrgused: Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour': 'Ava paremal retk, et seda 3D-s üle lennata ja kalde järgi värvida.',
+ 'tours.terrain.steepestShort': 'kuni {grade}%',
+ 'tours.terrain.preloading': 'Maastiku laadimine: {percent}%',
+ 'tours.terrain.clickToPlan':
+ 'Klõpsa maastikul, et punkte lisada. Kui marsruut on olemas, saab selle üle lennata ja kalde järgi värvida.',
};
export default tours;
diff --git a/shared/src/i18n/fr/tours.ts b/shared/src/i18n/fr/tours.ts
index 28add24f6..cffef2d8d 100644
--- a/shared/src/i18n/fr/tours.ts
+++ b/shared/src/i18n/fr/tours.ts
@@ -53,7 +53,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': 'Retour aux sorties',
'tours.planner.restored': 'Brouillon non enregistré restauré',
'tours.planner.discardChanges': 'Abandonner les modifications',
- 'tours.planner.discardUnsaved': 'Abandonner les modifications non enregistrées',
'tours.planner.newTourConfirmTitle': 'Commencer une nouvelle sortie ?',
'tours.planner.newTourConfirmBody':
'Les modifications non enregistrées de cette sortie seront perdues. Les sorties enregistrées resteront inchangées.',
@@ -148,5 +147,24 @@ const tours: TranslationStrings = {
'tourTypes.kayak': 'Sortie en kayak',
'tourTypes.walk': 'Balade urbaine / touristique',
'tourTypes.food': 'Circuit gastronomique / œnologique',
+ 'tours.terrain.play': 'Lancer le survol',
+ 'tours.terrain.pause': 'Pause', // same-as-en
+ 'tours.terrain.restart': 'Recommencer',
+ 'tours.terrain.speed': 'Vitesse',
+ 'tours.terrain.exaggeration': 'Relief', // same-as-en
+ 'tours.terrain.overview': "Vue d'ensemble",
+ 'tours.terrain.colorByGrade': 'Pente',
+ 'tours.terrain.gradeMix': 'Répartition des pentes',
+ 'tours.terrain.band.flat': 'moins de 5 %',
+ 'tours.terrain.band.gentle': 'de 5 à 10 %',
+ 'tours.terrain.band.moderate': 'de 10 à 18 %',
+ 'tours.terrain.band.steep': 'de 18 à 27 %',
+ 'tours.terrain.band.verySteep': '27 % et plus',
+ 'tours.terrain.attribution': 'Altitudes : Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour': 'Ouvrez une sortie à droite pour la survoler en 3D et la colorer selon la pente.',
+ 'tours.terrain.steepestShort': 'max. {grade} %',
+ 'tours.terrain.preloading': 'Chargement du paysage : {percent} %',
+ 'tours.terrain.clickToPlan':
+ "Cliquez sur le relief pour placer des points. Dès qu'un itinéraire existe, il peut être survolé et coloré selon la pente.",
};
export default tours;
diff --git a/shared/src/i18n/gr/tours.ts b/shared/src/i18n/gr/tours.ts
index bf5fed683..4365f80b6 100644
--- a/shared/src/i18n/gr/tours.ts
+++ b/shared/src/i18n/gr/tours.ts
@@ -53,7 +53,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': 'Πίσω στις εκδρομές',
'tours.planner.restored': 'Το μη αποθηκευμένο πρόχειρο επαναφέρθηκε',
'tours.planner.discardChanges': 'Απόρριψη αλλαγών',
- 'tours.planner.discardUnsaved': 'Απόρριψη μη αποθηκευμένων αλλαγών',
'tours.planner.newTourConfirmTitle': 'Έναρξη νέας εκδρομής;',
'tours.planner.newTourConfirmBody':
'Οι μη αποθηκευμένες αλλαγές αυτής της εκδρομής θα απορριφθούν. Οι αποθηκευμένες εκδρομές δεν θα αλλάξουν.',
@@ -152,5 +151,24 @@ const tours: TranslationStrings = {
'tourTypes.kayak': 'Καγιάκ',
'tourTypes.walk': 'Περίπατος στην πόλη / στα αξιοθέατα',
'tourTypes.food': 'Γαστρονομική / οινική εκδρομή',
+ 'tours.terrain.play': 'Αναπαραγωγή πτήσης',
+ 'tours.terrain.pause': 'Παύση',
+ 'tours.terrain.restart': 'Από την αρχή',
+ 'tours.terrain.speed': 'Ταχύτητα',
+ 'tours.terrain.exaggeration': 'Ανάγλυφο',
+ 'tours.terrain.overview': 'Επισκόπηση',
+ 'tours.terrain.colorByGrade': 'Κλίση',
+ 'tours.terrain.gradeMix': 'Κατανομή κλίσεων',
+ 'tours.terrain.band.flat': 'κάτω από 5 %',
+ 'tours.terrain.band.gentle': '5 έως 10 %',
+ 'tours.terrain.band.moderate': '10 έως 18 %',
+ 'tours.terrain.band.steep': '18 έως 27 %',
+ 'tours.terrain.band.verySteep': '27 % και άνω',
+ 'tours.terrain.attribution': 'Υψόμετρα: Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour': 'Άνοιξε μια εκδρομή δεξιά για να την πετάξεις σε 3D και να τη χρωματίσεις κατά κλίση.',
+ 'tours.terrain.steepestShort': 'έως {grade} %',
+ 'tours.terrain.preloading': 'Φόρτωση τοπίου: {percent} %',
+ 'tours.terrain.clickToPlan':
+ 'Κάνε κλικ στο έδαφος για να ορίσεις σημεία. Μόλις υπάρξει διαδρομή, μπορείς να την πετάξεις και να τη χρωματίσεις κατά κλίση.',
};
export default tours;
diff --git a/shared/src/i18n/hu/tours.ts b/shared/src/i18n/hu/tours.ts
index e7a339bb4..a3508ac35 100644
--- a/shared/src/i18n/hu/tours.ts
+++ b/shared/src/i18n/hu/tours.ts
@@ -51,7 +51,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': 'Vissza a túrákhoz',
'tours.planner.restored': 'Nem mentett vázlat visszaállítva',
'tours.planner.discardChanges': 'Módosítások elvetése',
- 'tours.planner.discardUnsaved': 'Nem mentett módosítások elvetése',
'tours.planner.newTourConfirmTitle': 'Új túrát kezdesz?',
'tours.planner.newTourConfirmBody': 'A túra nem mentett módosításai elvesznek. A mentett túrák nem változnak.',
'tours.planner.newTourConfirm': 'Módosítások elvetése és új túra kezdése',
@@ -145,5 +144,25 @@ const tours: TranslationStrings = {
'tourTypes.kayak': 'Kajakozás',
'tourTypes.walk': 'Városi / városnéző séta',
'tourTypes.food': 'Gasztro- / bortúra',
+ 'tours.terrain.play': 'Átrepülés lejátszása',
+ 'tours.terrain.pause': 'Szünet',
+ 'tours.terrain.restart': 'Újrakezdés',
+ 'tours.terrain.speed': 'Sebesség',
+ 'tours.terrain.exaggeration': 'Domborzat',
+ 'tours.terrain.overview': 'Áttekintés',
+ 'tours.terrain.colorByGrade': 'Meredekség',
+ 'tours.terrain.gradeMix': 'Meredekség megoszlása',
+ 'tours.terrain.band.flat': '5% alatt',
+ 'tours.terrain.band.gentle': '5 és 10% között',
+ 'tours.terrain.band.moderate': '10 és 18% között',
+ 'tours.terrain.band.steep': '18 és 27% között',
+ 'tours.terrain.band.verySteep': '27% vagy több',
+ 'tours.terrain.attribution': 'Magasság: Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour':
+ 'Nyiss meg jobb oldalt egy túrát, hogy 3D-ben átrepülhesd és meredekség szerint színezhesd.',
+ 'tours.terrain.steepestShort': 'max. {grade}%',
+ 'tours.terrain.preloading': 'A táj betöltése: {percent}%',
+ 'tours.terrain.clickToPlan':
+ 'Kattints a terepre pontok elhelyezéséhez. Ha már van útvonal, átrepülheted és meredekség szerint színezheted.',
};
export default tours;
diff --git a/shared/src/i18n/id/tours.ts b/shared/src/i18n/id/tours.ts
index 4f4d569c3..1ad8f7c53 100644
--- a/shared/src/i18n/id/tours.ts
+++ b/shared/src/i18n/id/tours.ts
@@ -50,7 +50,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': 'Kembali ke daftar tur',
'tours.planner.restored': 'Draf yang belum disimpan telah dipulihkan',
'tours.planner.discardChanges': 'Buang perubahan',
- 'tours.planner.discardUnsaved': 'Buang perubahan yang belum disimpan',
'tours.planner.newTourConfirmTitle': 'Mulai tur baru?',
'tours.planner.newTourConfirmBody':
'Perubahan yang belum disimpan pada tur ini akan dibuang. Tur yang sudah disimpan tidak akan diubah.',
@@ -142,5 +141,25 @@ const tours: TranslationStrings = {
'tourTypes.kayak': 'Berkayak',
'tourTypes.walk': 'Jalan-jalan kota / wisata',
'tourTypes.food': 'Tur kuliner / anggur',
+ 'tours.terrain.play': 'Putar penerbangan',
+ 'tours.terrain.pause': 'Jeda',
+ 'tours.terrain.restart': 'Mulai ulang',
+ 'tours.terrain.speed': 'Kecepatan',
+ 'tours.terrain.exaggeration': 'Relief', // same-as-en
+ 'tours.terrain.overview': 'Ikhtisar',
+ 'tours.terrain.colorByGrade': 'Kemiringan',
+ 'tours.terrain.gradeMix': 'Sebaran kemiringan',
+ 'tours.terrain.band.flat': 'di bawah 5%',
+ 'tours.terrain.band.gentle': '5 hingga 10%',
+ 'tours.terrain.band.moderate': '10 hingga 18%',
+ 'tours.terrain.band.steep': '18 hingga 27%',
+ 'tours.terrain.band.verySteep': '27% atau lebih',
+ 'tours.terrain.attribution': 'Ketinggian: Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour':
+ 'Buka tur di sebelah kanan untuk menerbanginya dalam 3D dan mewarnainya menurut kemiringan.',
+ 'tours.terrain.steepestShort': 'maks. {grade}%',
+ 'tours.terrain.preloading': 'Memuat lanskap: {percent}%',
+ 'tours.terrain.clickToPlan':
+ 'Klik medan untuk menambahkan titik. Setelah ada rute, rute itu bisa diterbangi dan diwarnai menurut kemiringan.',
};
export default tours;
diff --git a/shared/src/i18n/it/tours.ts b/shared/src/i18n/it/tours.ts
index 8bf328c24..1f4a0cb27 100644
--- a/shared/src/i18n/it/tours.ts
+++ b/shared/src/i18n/it/tours.ts
@@ -52,7 +52,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': 'Torna alle escursioni',
'tours.planner.restored': 'Bozza non salvata ripristinata',
'tours.planner.discardChanges': 'Scarta modifiche',
- 'tours.planner.discardUnsaved': 'Scarta modifiche non salvate',
'tours.planner.newTourConfirmTitle': 'Iniziare una nuova escursione?',
'tours.planner.newTourConfirmBody':
'Le modifiche non salvate a questa escursione verranno scartate. Le escursioni salvate non verranno modificate.',
@@ -145,5 +144,24 @@ const tours: TranslationStrings = {
'tourTypes.kayak': 'Escursione in kayak',
'tourTypes.walk': 'Passeggiata urbana / turistica',
'tourTypes.food': 'Tour enogastronomico',
+ 'tours.terrain.play': 'Avvia il sorvolo',
+ 'tours.terrain.pause': 'Pausa',
+ 'tours.terrain.restart': 'Ricomincia',
+ 'tours.terrain.speed': 'Velocità',
+ 'tours.terrain.exaggeration': 'Rilievo',
+ 'tours.terrain.overview': 'Panoramica',
+ 'tours.terrain.colorByGrade': 'Pendenza',
+ 'tours.terrain.gradeMix': 'Distribuzione delle pendenze',
+ 'tours.terrain.band.flat': 'meno del 5 %',
+ 'tours.terrain.band.gentle': 'dal 5 al 10 %',
+ 'tours.terrain.band.moderate': 'dal 10 al 18 %',
+ 'tours.terrain.band.steep': 'dal 18 al 27 %',
+ 'tours.terrain.band.verySteep': '27 % e oltre',
+ 'tours.terrain.attribution': 'Quote: Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour': "Apri un'escursione a destra per sorvolarla in 3D e colorarla in base alla pendenza.",
+ 'tours.terrain.steepestShort': 'mass. {grade} %',
+ 'tours.terrain.preloading': 'Caricamento del paesaggio: {percent} %',
+ 'tours.terrain.clickToPlan':
+ "Fai clic sul terreno per aggiungere punti. Appena c'è un percorso, puoi sorvolarlo e colorarlo in base alla pendenza.",
};
export default tours;
diff --git a/shared/src/i18n/ja/tours.ts b/shared/src/i18n/ja/tours.ts
index 594fdc081..d01e5ff2f 100644
--- a/shared/src/i18n/ja/tours.ts
+++ b/shared/src/i18n/ja/tours.ts
@@ -49,7 +49,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': 'ツアー一覧に戻る',
'tours.planner.restored': '未保存の下書きを復元しました',
'tours.planner.discardChanges': '変更を破棄',
- 'tours.planner.discardUnsaved': '未保存の変更を破棄',
'tours.planner.newTourConfirmTitle': '新しいツアーを開始しますか?',
'tours.planner.newTourConfirmBody': 'このツアーの未保存の変更は破棄されます。保存済みのツアーは変更されません。',
'tours.planner.newTourConfirm': '変更を破棄して新しいツアーを開始',
@@ -139,5 +138,23 @@ const tours: TranslationStrings = {
'tourTypes.kayak': 'カヤック',
'tourTypes.walk': '街歩き・観光',
'tourTypes.food': 'グルメ・ワインツアー',
+ 'tours.terrain.play': 'フライオーバーを再生',
+ 'tours.terrain.pause': '一時停止',
+ 'tours.terrain.restart': '最初から',
+ 'tours.terrain.speed': '速度',
+ 'tours.terrain.exaggeration': '起伏',
+ 'tours.terrain.overview': '全体表示',
+ 'tours.terrain.colorByGrade': '勾配',
+ 'tours.terrain.gradeMix': '勾配の内訳',
+ 'tours.terrain.band.flat': '5 % 未満',
+ 'tours.terrain.band.gentle': '5〜10 %',
+ 'tours.terrain.band.moderate': '10〜18 %',
+ 'tours.terrain.band.steep': '18〜27 %',
+ 'tours.terrain.band.verySteep': '27 % 以上',
+ 'tours.terrain.attribution': '標高: Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour': '右側でツアーを開くと、3D で飛行し勾配で色分けできます。',
+ 'tours.terrain.steepestShort': '最大 {grade} %',
+ 'tours.terrain.preloading': '地形を読み込み中: {percent} %',
+ 'tours.terrain.clickToPlan': '地形をクリックしてポイントを置きます。ルートができると、飛行して勾配で色分けできます。',
};
export default tours;
diff --git a/shared/src/i18n/ko/tours.ts b/shared/src/i18n/ko/tours.ts
index c7d180af9..f758ceb75 100644
--- a/shared/src/i18n/ko/tours.ts
+++ b/shared/src/i18n/ko/tours.ts
@@ -49,7 +49,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': '투어 목록으로',
'tours.planner.restored': '저장하지 않은 초안을 복원했습니다',
'tours.planner.discardChanges': '변경 사항 버리기',
- 'tours.planner.discardUnsaved': '저장하지 않은 변경 사항 버리기',
'tours.planner.newTourConfirmTitle': '새 투어를 시작할까요?',
'tours.planner.newTourConfirmBody':
'이 투어의 저장하지 않은 변경 사항은 삭제됩니다. 저장된 투어는 변경되지 않습니다.',
@@ -140,5 +139,24 @@ const tours: TranslationStrings = {
'tourTypes.kayak': '카약',
'tourTypes.walk': '도심 산책 / 관광',
'tourTypes.food': '미식 / 와인 투어',
+ 'tours.terrain.play': '비행 재생',
+ 'tours.terrain.pause': '일시정지',
+ 'tours.terrain.restart': '처음부터',
+ 'tours.terrain.speed': '속도',
+ 'tours.terrain.exaggeration': '기복',
+ 'tours.terrain.overview': '전체 보기',
+ 'tours.terrain.colorByGrade': '경사',
+ 'tours.terrain.gradeMix': '경사 분포',
+ 'tours.terrain.band.flat': '5 % 미만',
+ 'tours.terrain.band.gentle': '5~10 %',
+ 'tours.terrain.band.moderate': '10~18 %',
+ 'tours.terrain.band.steep': '18~27 %',
+ 'tours.terrain.band.verySteep': '27 % 이상',
+ 'tours.terrain.attribution': '고도: Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour': '오른쪽에서 투어를 열면 3D로 비행하고 경사별로 색을 입힐 수 있습니다.',
+ 'tours.terrain.steepestShort': '최대 {grade} %',
+ 'tours.terrain.preloading': '지형 불러오는 중: {percent} %',
+ 'tours.terrain.clickToPlan':
+ '지형을 클릭해 지점을 추가하세요. 경로가 생기면 비행하고 경사별로 색을 입힐 수 있습니다.',
};
export default tours;
diff --git a/shared/src/i18n/nl/tours.ts b/shared/src/i18n/nl/tours.ts
index 15c681613..b7c7ffa78 100644
--- a/shared/src/i18n/nl/tours.ts
+++ b/shared/src/i18n/nl/tours.ts
@@ -51,7 +51,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': 'Terug naar tochten',
'tours.planner.restored': 'Niet-opgeslagen concept hersteld',
'tours.planner.discardChanges': 'Wijzigingen verwerpen',
- 'tours.planner.discardUnsaved': 'Niet-opgeslagen wijzigingen verwerpen',
'tours.planner.newTourConfirmTitle': 'Een nieuwe tocht starten?',
'tours.planner.newTourConfirmBody':
'Je niet-opgeslagen wijzigingen aan deze tocht worden verworpen. Opgeslagen tochten blijven ongewijzigd.',
@@ -144,5 +143,24 @@ const tours: TranslationStrings = {
'tourTypes.kayak': 'Kajaktocht',
'tourTypes.walk': 'Stadswandeling / bezienswaardigheden',
'tourTypes.food': 'Culinaire tocht / wijntocht',
+ 'tours.terrain.play': 'Overvlucht afspelen',
+ 'tours.terrain.pause': 'Pauzeren',
+ 'tours.terrain.restart': 'Opnieuw beginnen',
+ 'tours.terrain.speed': 'Snelheid',
+ 'tours.terrain.exaggeration': 'Reliëf',
+ 'tours.terrain.overview': 'Overzicht',
+ 'tours.terrain.colorByGrade': 'Helling',
+ 'tours.terrain.gradeMix': 'Hellingsverdeling',
+ 'tours.terrain.band.flat': 'onder de 5 %',
+ 'tours.terrain.band.gentle': '5 tot 10 %',
+ 'tours.terrain.band.moderate': '10 tot 18 %',
+ 'tours.terrain.band.steep': '18 tot 27 %',
+ 'tours.terrain.band.verySteep': '27 % en meer',
+ 'tours.terrain.attribution': 'Hoogtes: Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour': 'Open rechts een tocht om er in 3D overheen te vliegen en hem op helling te kleuren.',
+ 'tours.terrain.steepestShort': 'max. {grade} %',
+ 'tours.terrain.preloading': 'Landschap wordt geladen: {percent} %',
+ 'tours.terrain.clickToPlan':
+ 'Klik in het terrein om punten te zetten. Zodra er een route is, kun je eroverheen vliegen en hem op helling kleuren.',
};
export default tours;
diff --git a/shared/src/i18n/pl/tours.ts b/shared/src/i18n/pl/tours.ts
index 785bcdc88..a019542eb 100644
--- a/shared/src/i18n/pl/tours.ts
+++ b/shared/src/i18n/pl/tours.ts
@@ -53,7 +53,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': 'Wróć do wycieczek',
'tours.planner.restored': 'Przywrócono niezapisany szkic',
'tours.planner.discardChanges': 'Odrzuć zmiany',
- 'tours.planner.discardUnsaved': 'Odrzuć niezapisane zmiany',
'tours.planner.newTourConfirmTitle': 'Rozpocząć nową wycieczkę?',
'tours.planner.newTourConfirmBody':
'Niezapisane zmiany tej wycieczki zostaną odrzucone. Zapisane wycieczki nie zostaną zmienione.',
@@ -147,5 +146,25 @@ const tours: TranslationStrings = {
'tourTypes.kayak': 'Kajak',
'tourTypes.walk': 'Spacer po mieście / zwiedzanie',
'tourTypes.food': 'Wycieczka kulinarna / winiarska',
+ 'tours.terrain.play': 'Odtwórz przelot',
+ 'tours.terrain.pause': 'Pauza',
+ 'tours.terrain.restart': 'Od początku',
+ 'tours.terrain.speed': 'Prędkość',
+ 'tours.terrain.exaggeration': 'Rzeźba terenu',
+ 'tours.terrain.overview': 'Przegląd',
+ 'tours.terrain.colorByGrade': 'Nachylenie',
+ 'tours.terrain.gradeMix': 'Rozkład nachylenia',
+ 'tours.terrain.band.flat': 'poniżej 5%',
+ 'tours.terrain.band.gentle': 'od 5 do 10%',
+ 'tours.terrain.band.moderate': 'od 10 do 18%',
+ 'tours.terrain.band.steep': 'od 18 do 27%',
+ 'tours.terrain.band.verySteep': '27% i więcej',
+ 'tours.terrain.attribution': 'Wysokości: Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour':
+ 'Otwórz wycieczkę po prawej, aby przelecieć nad nią w 3D i pokolorować ją według nachylenia.',
+ 'tours.terrain.steepestShort': 'maks. {grade}%',
+ 'tours.terrain.preloading': 'Wczytywanie krajobrazu: {percent}%',
+ 'tours.terrain.clickToPlan':
+ 'Kliknij teren, aby dodać punkty. Gdy powstanie trasa, można nad nią przelecieć i pokolorować ją według nachylenia.',
};
export default tours;
diff --git a/shared/src/i18n/ru/tours.ts b/shared/src/i18n/ru/tours.ts
index f1f35108c..348780d85 100644
--- a/shared/src/i18n/ru/tours.ts
+++ b/shared/src/i18n/ru/tours.ts
@@ -53,7 +53,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': 'К турам',
'tours.planner.restored': 'Несохранённый черновик восстановлен',
'tours.planner.discardChanges': 'Отменить изменения',
- 'tours.planner.discardUnsaved': 'Отменить несохранённые изменения',
'tours.planner.newTourConfirmTitle': 'Начать новый тур?',
'tours.planner.newTourConfirmBody':
'Несохранённые изменения этого тура будут отменены. Сохранённые туры не изменятся.',
@@ -148,5 +147,24 @@ const tours: TranslationStrings = {
'tourTypes.kayak': 'Каякинг',
'tourTypes.walk': 'Прогулка по городу / достопримечательностям',
'tourTypes.food': 'Гастрономический / винный тур',
+ 'tours.terrain.play': 'Запустить облёт',
+ 'tours.terrain.pause': 'Пауза',
+ 'tours.terrain.restart': 'С начала',
+ 'tours.terrain.speed': 'Скорость',
+ 'tours.terrain.exaggeration': 'Рельеф',
+ 'tours.terrain.overview': 'Обзор',
+ 'tours.terrain.colorByGrade': 'Уклон',
+ 'tours.terrain.gradeMix': 'Распределение уклонов',
+ 'tours.terrain.band.flat': 'до 5 %',
+ 'tours.terrain.band.gentle': 'от 5 до 10 %',
+ 'tours.terrain.band.moderate': 'от 10 до 18 %',
+ 'tours.terrain.band.steep': 'от 18 до 27 %',
+ 'tours.terrain.band.verySteep': '27 % и больше',
+ 'tours.terrain.attribution': 'Высоты: Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour': 'Откройте тур справа, чтобы облететь его в 3D и раскрасить по уклону.',
+ 'tours.terrain.steepestShort': 'макс. {grade} %',
+ 'tours.terrain.preloading': 'Загрузка ландшафта: {percent} %',
+ 'tours.terrain.clickToPlan':
+ 'Нажмите на рельеф, чтобы поставить точки. Когда появится маршрут, его можно облететь и раскрасить по уклону.',
};
export default tours;
diff --git a/shared/src/i18n/sk/tours.ts b/shared/src/i18n/sk/tours.ts
index b81bd3b1b..704e14108 100644
--- a/shared/src/i18n/sk/tours.ts
+++ b/shared/src/i18n/sk/tours.ts
@@ -51,7 +51,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': 'Späť na túry',
'tours.planner.restored': 'Neuložený návrh obnovený',
'tours.planner.discardChanges': 'Zahodiť zmeny',
- 'tours.planner.discardUnsaved': 'Zahodiť neuložené zmeny',
'tours.planner.newTourConfirmTitle': 'Začať novú túru?',
'tours.planner.newTourConfirmBody': 'Neuložené zmeny tejto túry sa zahodia. Uložené túry zostanú nezmenené.',
'tours.planner.newTourConfirm': 'Zahodiť zmeny a začať novú túru',
@@ -143,5 +142,24 @@ const tours: TranslationStrings = {
'tourTypes.kayak': 'Kajak',
'tourTypes.walk': 'Prechádzka mestom / po pamiatkach',
'tourTypes.food': 'Gastronomická / vínna túra',
+ 'tours.terrain.play': 'Prehrať prelet',
+ 'tours.terrain.pause': 'Pozastaviť',
+ 'tours.terrain.restart': 'Od začiatku',
+ 'tours.terrain.speed': 'Rýchlosť',
+ 'tours.terrain.exaggeration': 'Reliéf',
+ 'tours.terrain.overview': 'Prehľad',
+ 'tours.terrain.colorByGrade': 'Sklon',
+ 'tours.terrain.gradeMix': 'Rozloženie sklonu',
+ 'tours.terrain.band.flat': 'pod 5 %',
+ 'tours.terrain.band.gentle': '5 až 10 %',
+ 'tours.terrain.band.moderate': '10 až 18 %',
+ 'tours.terrain.band.steep': '18 až 27 %',
+ 'tours.terrain.band.verySteep': '27 % a viac',
+ 'tours.terrain.attribution': 'Výšky: Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour': 'Otvorte vpravo túru, aby ste ju mohli preletieť v 3D a zafarbiť podľa sklonu.',
+ 'tours.terrain.steepestShort': 'max. {grade} %',
+ 'tours.terrain.preloading': 'Načítava sa krajina: {percent} %',
+ 'tours.terrain.clickToPlan':
+ 'Kliknutím do terénu pridáte body. Keď vznikne trasa, dá sa preletieť a zafarbiť podľa sklonu.',
};
export default tours;
diff --git a/shared/src/i18n/sv/tours.ts b/shared/src/i18n/sv/tours.ts
index 716ed4164..dfe9873bc 100644
--- a/shared/src/i18n/sv/tours.ts
+++ b/shared/src/i18n/sv/tours.ts
@@ -51,7 +51,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': 'Tillbaka till turer',
'tours.planner.restored': 'Osparat utkast återställt',
'tours.planner.discardChanges': 'Kasta ändringar',
- 'tours.planner.discardUnsaved': 'Kasta osparade ändringar',
'tours.planner.newTourConfirmTitle': 'Börja på en ny tur?',
'tours.planner.newTourConfirmBody': 'Dina osparade ändringar i den här turen kastas. Sparade turer ändras inte.',
'tours.planner.newTourConfirm': 'Kasta ändringar och börja på ny tur',
@@ -142,5 +141,24 @@ const tours: TranslationStrings = {
'tourTypes.kayak': 'Kajaktur',
'tourTypes.walk': 'Stadspromenad / sightseeing',
'tourTypes.food': 'Mat- och vintur',
+ 'tours.terrain.play': 'Spela upp överflygning',
+ 'tours.terrain.pause': 'Pausa',
+ 'tours.terrain.restart': 'Börja om',
+ 'tours.terrain.speed': 'Hastighet',
+ 'tours.terrain.exaggeration': 'Överhöjning',
+ 'tours.terrain.overview': 'Översikt',
+ 'tours.terrain.colorByGrade': 'Lutning',
+ 'tours.terrain.gradeMix': 'Lutningsfördelning',
+ 'tours.terrain.band.flat': 'lägre än 5 %',
+ 'tours.terrain.band.gentle': '5 till 10 %',
+ 'tours.terrain.band.moderate': '10 till 18 %',
+ 'tours.terrain.band.steep': '18 till 27 %',
+ 'tours.terrain.band.verySteep': '27 % och mer',
+ 'tours.terrain.attribution': 'Höjddata: Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour': 'Öppna en tur till höger för att flyga över den i 3D och färga den efter lutning.',
+ 'tours.terrain.steepestShort': 'högst {grade} %',
+ 'tours.terrain.preloading': 'Landskapet laddas: {percent} %',
+ 'tours.terrain.clickToPlan':
+ 'Klicka i terrängen för att sätta ut punkter. När det finns en rutt kan du flyga över den och färga den efter lutning.',
};
export default tours;
diff --git a/shared/src/i18n/th/tours.ts b/shared/src/i18n/th/tours.ts
index 00db36907..cc1e53173 100644
--- a/shared/src/i18n/th/tours.ts
+++ b/shared/src/i18n/th/tours.ts
@@ -49,7 +49,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': 'กลับไปที่ทัวร์',
'tours.planner.restored': 'กู้คืนฉบับร่างที่ยังไม่บันทึกแล้ว',
'tours.planner.discardChanges': 'ยกเลิกการเปลี่ยนแปลง',
- 'tours.planner.discardUnsaved': 'ทิ้งการเปลี่ยนแปลงที่ยังไม่บันทึก',
'tours.planner.newTourConfirmTitle': 'เริ่มทัวร์ใหม่ไหม?',
'tours.planner.newTourConfirmBody':
'การเปลี่ยนแปลงของทัวร์นี้ที่ยังไม่บันทึกจะถูกทิ้ง ทัวร์ที่บันทึกแล้วจะไม่เปลี่ยนแปลง',
@@ -139,5 +138,23 @@ const tours: TranslationStrings = {
'tourTypes.kayak': 'พายเรือคายัก',
'tourTypes.walk': 'เดินชมเมือง / สถานที่ท่องเที่ยว',
'tourTypes.food': 'ทัวร์อาหาร/ไวน์',
+ 'tours.terrain.play': 'เล่นการบินผ่าน',
+ 'tours.terrain.pause': 'หยุดชั่วคราว',
+ 'tours.terrain.restart': 'เริ่มใหม่',
+ 'tours.terrain.speed': 'ความเร็ว',
+ 'tours.terrain.exaggeration': 'ความสูงต่ำ',
+ 'tours.terrain.overview': 'ภาพรวม',
+ 'tours.terrain.colorByGrade': 'ความชัน',
+ 'tours.terrain.gradeMix': 'สัดส่วนความชัน',
+ 'tours.terrain.band.flat': 'ต่ำกว่า 5 %',
+ 'tours.terrain.band.gentle': '5 ถึง 10 %',
+ 'tours.terrain.band.moderate': '10 ถึง 18 %',
+ 'tours.terrain.band.steep': '18 ถึง 27 %',
+ 'tours.terrain.band.verySteep': '27 % ขึ้นไป',
+ 'tours.terrain.attribution': 'ความสูง: Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour': 'เปิดทัวร์ทางด้านขวาเพื่อบินผ่านแบบ 3D และระบายสีตามความชัน',
+ 'tours.terrain.steepestShort': 'สูงสุด {grade} %',
+ 'tours.terrain.preloading': 'กำลังโหลดภูมิทัศน์: {percent} %',
+ 'tours.terrain.clickToPlan': 'คลิกบนภูมิประเทศเพื่อวางจุด เมื่อมีเส้นทางแล้ว จะบินผ่านและระบายสีตามความชันได้',
};
export default tours;
diff --git a/shared/src/i18n/tours-locales.spec.ts b/shared/src/i18n/tours-locales.spec.ts
index 86fdab272..e9cf14bbe 100644
--- a/shared/src/i18n/tours-locales.spec.ts
+++ b/shared/src/i18n/tours-locales.spec.ts
@@ -20,7 +20,7 @@ const tokens = (value: string) => [...value.matchAll(/\{[^{}]+\}/g)].map((match)
// placeholder spec; here only the general keys are.
const groups = pluralGroups(Object.keys(english));
const generalKeys = (keys: string[]) => keys.filter((key) => !pluralFormOf(key, groups));
-const GENERAL_KEY_COUNT = 130;
+const GENERAL_KEY_COUNT = 147;
function literalKeys(source: string): string[] {
const tree = ts.createSourceFile('locale.ts', source, ts.ScriptTarget.Latest, true);
@@ -34,7 +34,7 @@ function literalKeys(source: string): string[] {
}
describe('Tours locale contracts', () => {
- it('covers all 27 supported locales with 130 general source keys', () => {
+ it('covers all 27 supported locales with 147 general source keys', () => {
expect(Object.keys(domains)).toHaveLength(27);
expect(Object.keys(domains).sort()).toEqual(SUPPORTED_LANGUAGE_CODES.map((code) => `./${code}/tours.ts`).sort());
expect(generalKeys(Object.keys(english))).toHaveLength(GENERAL_KEY_COUNT);
diff --git a/shared/src/i18n/tr/tours.ts b/shared/src/i18n/tr/tours.ts
index 25adc6702..bfbad0c7e 100644
--- a/shared/src/i18n/tr/tours.ts
+++ b/shared/src/i18n/tr/tours.ts
@@ -50,7 +50,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': 'Turlara dön',
'tours.planner.restored': 'Kaydedilmemiş taslak geri yüklendi',
'tours.planner.discardChanges': 'Değişiklikleri sil',
- 'tours.planner.discardUnsaved': 'Kaydedilmemiş değişiklikleri sil',
'tours.planner.newTourConfirmTitle': 'Yeni bir tur başlatılsın mı?',
'tours.planner.newTourConfirmBody':
'Bu turdaki kaydedilmemiş değişiklikler silinecek. Kaydedilmiş turlar değişmeyecek.',
@@ -143,5 +142,24 @@ const tours: TranslationStrings = {
'tourTypes.kayak': 'Kayak kanosu',
'tourTypes.walk': 'Şehir / gezi yürüyüşü',
'tourTypes.food': 'Yemek / şarap turu',
+ 'tours.terrain.play': 'Uçuşu oynat',
+ 'tours.terrain.pause': 'Duraklat',
+ 'tours.terrain.restart': 'Baştan başlat',
+ 'tours.terrain.speed': 'Hız',
+ 'tours.terrain.exaggeration': 'Rölyef',
+ 'tours.terrain.overview': 'Genel bakış',
+ 'tours.terrain.colorByGrade': 'Eğim',
+ 'tours.terrain.gradeMix': 'Eğim dağılımı',
+ 'tours.terrain.band.flat': "%5'in altı",
+ 'tours.terrain.band.gentle': '%5 ile %10 arası',
+ 'tours.terrain.band.moderate': '%10 ile %18 arası',
+ 'tours.terrain.band.steep': '%18 ile %27 arası',
+ 'tours.terrain.band.verySteep': '%27 ve üzeri',
+ 'tours.terrain.attribution': 'Yükseklik: Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour': 'Bir turu 3D olarak uçmak ve eğime göre renklendirmek için sağ taraftan açın.',
+ 'tours.terrain.steepestShort': 'en fazla %{grade}',
+ 'tours.terrain.preloading': 'Manzara yükleniyor: %{percent}',
+ 'tours.terrain.clickToPlan':
+ 'Nokta eklemek için araziye tıklayın. Bir rota oluştuğunda üzerinden uçabilir ve eğime göre renklendirebilirsiniz.',
};
export default tours;
diff --git a/shared/src/i18n/uk/tours.ts b/shared/src/i18n/uk/tours.ts
index b7dfdec77..0cd9e1ca4 100644
--- a/shared/src/i18n/uk/tours.ts
+++ b/shared/src/i18n/uk/tours.ts
@@ -53,7 +53,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': 'До турів',
'tours.planner.restored': 'Незбережену чернетку відновлено',
'tours.planner.discardChanges': 'Скасувати зміни',
- 'tours.planner.discardUnsaved': 'Скасувати незбережені зміни',
'tours.planner.newTourConfirmTitle': 'Почати новий тур?',
'tours.planner.newTourConfirmBody': 'Незбережені зміни цього туру буде скасовано. Збережені тури не зміняться.',
'tours.planner.newTourConfirm': 'Скасувати зміни й почати новий тур',
@@ -147,5 +146,24 @@ const tours: TranslationStrings = {
'tourTypes.kayak': 'Каякінг',
'tourTypes.walk': 'Прогулянка містом / визначними місцями',
'tourTypes.food': 'Гастрономічний / винний тур',
+ 'tours.terrain.play': 'Запустити обліт',
+ 'tours.terrain.pause': 'Пауза',
+ 'tours.terrain.restart': 'Спочатку',
+ 'tours.terrain.speed': 'Швидкість',
+ 'tours.terrain.exaggeration': 'Рельєф',
+ 'tours.terrain.overview': 'Огляд',
+ 'tours.terrain.colorByGrade': 'Ухил',
+ 'tours.terrain.gradeMix': 'Розподіл ухилів',
+ 'tours.terrain.band.flat': 'до 5 %',
+ 'tours.terrain.band.gentle': 'від 5 до 10 %',
+ 'tours.terrain.band.moderate': 'від 10 до 18 %',
+ 'tours.terrain.band.steep': 'від 18 до 27 %',
+ 'tours.terrain.band.verySteep': '27 % і більше',
+ 'tours.terrain.attribution': 'Висоти: Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour': 'Відкрийте тур праворуч, щоб облетіти його в 3D і розфарбувати за ухилом.',
+ 'tours.terrain.steepestShort': 'макс. {grade} %',
+ 'tours.terrain.preloading': 'Завантаження ландшафту: {percent} %',
+ 'tours.terrain.clickToPlan':
+ "Натисніть на рельєф, щоб поставити точки. Коли з'явиться маршрут, його можна облетіти й розфарбувати за ухилом.",
};
export default tours;
diff --git a/shared/src/i18n/vi/tours.ts b/shared/src/i18n/vi/tours.ts
index 36d69e539..07a5a0cbb 100644
--- a/shared/src/i18n/vi/tours.ts
+++ b/shared/src/i18n/vi/tours.ts
@@ -50,7 +50,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': 'Về danh sách chuyến tham quan',
'tours.planner.restored': 'Đã khôi phục bản nháp chưa lưu',
'tours.planner.discardChanges': 'Bỏ thay đổi',
- 'tours.planner.discardUnsaved': 'Bỏ thay đổi chưa lưu',
'tours.planner.newTourConfirmTitle': 'Bắt đầu chuyến tham quan mới?',
'tours.planner.newTourConfirmBody':
'Các thay đổi chưa lưu của chuyến tham quan này sẽ bị bỏ. Các chuyến tham quan đã lưu sẽ không thay đổi.',
@@ -143,5 +142,24 @@ const tours: TranslationStrings = {
'tourTypes.kayak': 'Chèo kayak',
'tourTypes.walk': 'Đi bộ trong thành phố / ngắm cảnh',
'tourTypes.food': 'Chuyến khám phá ẩm thực / rượu vang',
+ 'tours.terrain.play': 'Phát chuyến bay',
+ 'tours.terrain.pause': 'Tạm dừng',
+ 'tours.terrain.restart': 'Bắt đầu lại',
+ 'tours.terrain.speed': 'Tốc độ',
+ 'tours.terrain.exaggeration': 'Địa hình',
+ 'tours.terrain.overview': 'Tổng quan',
+ 'tours.terrain.colorByGrade': 'Độ dốc',
+ 'tours.terrain.gradeMix': 'Phân bố độ dốc',
+ 'tours.terrain.band.flat': 'dưới 5 %',
+ 'tours.terrain.band.gentle': 'từ 5 đến 10 %',
+ 'tours.terrain.band.moderate': 'từ 10 đến 18 %',
+ 'tours.terrain.band.steep': 'từ 18 đến 27 %',
+ 'tours.terrain.band.verySteep': 'từ 27 % trở lên',
+ 'tours.terrain.attribution': 'Độ cao: Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour': 'Mở một chuyến tham quan ở bên phải để bay qua ở chế độ 3D và tô màu theo độ dốc.',
+ 'tours.terrain.steepestShort': 'tối đa {grade} %',
+ 'tours.terrain.preloading': 'Đang tải cảnh quan: {percent} %',
+ 'tours.terrain.clickToPlan':
+ 'Nhấp vào địa hình để đặt điểm. Khi đã có tuyến đường, bạn có thể bay qua và tô màu theo độ dốc.',
};
export default tours;
diff --git a/shared/src/i18n/zh-TW/tours.ts b/shared/src/i18n/zh-TW/tours.ts
index 98aaedc80..4fc2a51f1 100644
--- a/shared/src/i18n/zh-TW/tours.ts
+++ b/shared/src/i18n/zh-TW/tours.ts
@@ -48,7 +48,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': '返回遊程清單',
'tours.planner.restored': '已還原尚未儲存的草稿',
'tours.planner.discardChanges': '捨棄變更',
- 'tours.planner.discardUnsaved': '捨棄尚未儲存的變更',
'tours.planner.newTourConfirmTitle': '開始新的遊程?',
'tours.planner.newTourConfirmBody': '這個遊程中尚未儲存的變更將被捨棄。已儲存的遊程不會變更。',
'tours.planner.newTourConfirm': '捨棄變更並開始新遊程',
@@ -134,5 +133,23 @@ const tours: TranslationStrings = {
'tourTypes.kayak': '獨木舟',
'tourTypes.walk': '城市散步 / 觀光',
'tourTypes.food': '美食 / 葡萄酒之旅',
+ 'tours.terrain.play': '播放飛越',
+ 'tours.terrain.pause': '暫停',
+ 'tours.terrain.restart': '從頭開始',
+ 'tours.terrain.speed': '速度',
+ 'tours.terrain.exaggeration': '地形起伏',
+ 'tours.terrain.overview': '總覽',
+ 'tours.terrain.colorByGrade': '坡度',
+ 'tours.terrain.gradeMix': '坡度分布',
+ 'tours.terrain.band.flat': '低於 5 %',
+ 'tours.terrain.band.gentle': '5 至 10 %',
+ 'tours.terrain.band.moderate': '10 至 18 %',
+ 'tours.terrain.band.steep': '18 至 27 %',
+ 'tours.terrain.band.verySteep': '27 % 以上',
+ 'tours.terrain.attribution': '高程:Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour': '在右側開啟一個遊程,即可在 3D 中飛越並依坡度著色。',
+ 'tours.terrain.steepestShort': '最大 {grade} %',
+ 'tours.terrain.preloading': '正在載入地形:{percent} %',
+ 'tours.terrain.clickToPlan': '點擊地形來設定點。有了路線後,就可以飛越並依坡度著色。',
};
export default tours;
diff --git a/shared/src/i18n/zh/tours.ts b/shared/src/i18n/zh/tours.ts
index 47208235e..d79323eff 100644
--- a/shared/src/i18n/zh/tours.ts
+++ b/shared/src/i18n/zh/tours.ts
@@ -48,7 +48,6 @@ const tours: TranslationStrings = {
'tours.planner.backToTours': '返回游览列表',
'tours.planner.restored': '已恢复未保存的草稿',
'tours.planner.discardChanges': '放弃更改',
- 'tours.planner.discardUnsaved': '放弃未保存的更改',
'tours.planner.newTourConfirmTitle': '开始规划新游览路线?',
'tours.planner.newTourConfirmBody': '此游览路线中未保存的更改将被丢弃。已保存的游览路线不会改变。',
'tours.planner.newTourConfirm': '放弃更改并开始新游览路线',
@@ -134,5 +133,23 @@ const tours: TranslationStrings = {
'tourTypes.kayak': '皮划艇',
'tourTypes.walk': '城市漫步 / 观光',
'tourTypes.food': '美食 / 葡萄酒之旅',
+ 'tours.terrain.play': '播放飞越',
+ 'tours.terrain.pause': '暂停',
+ 'tours.terrain.restart': '从头开始',
+ 'tours.terrain.speed': '速度',
+ 'tours.terrain.exaggeration': '地形起伏',
+ 'tours.terrain.overview': '总览',
+ 'tours.terrain.colorByGrade': '坡度',
+ 'tours.terrain.gradeMix': '坡度分布',
+ 'tours.terrain.band.flat': '低于 5 %',
+ 'tours.terrain.band.gentle': '5 至 10 %',
+ 'tours.terrain.band.moderate': '10 至 18 %',
+ 'tours.terrain.band.steep': '18 至 27 %',
+ 'tours.terrain.band.verySteep': '27 % 及以上',
+ 'tours.terrain.attribution': '高程:Mapzen Terrain Tiles (AWS Open Data)',
+ 'tours.terrain.pickTour': '在右侧打开一条游览路线,即可在 3D 中飞越并按坡度着色。',
+ 'tours.terrain.steepestShort': '最大 {grade} %',
+ 'tours.terrain.preloading': '正在加载地形:{percent} %',
+ 'tours.terrain.clickToPlan': '点击地形来设置点。有了路线后,就可以飞越并按坡度着色。',
};
export default tours;
diff --git a/shared/src/tours/tours.schema.test.ts b/shared/src/tours/tours.schema.test.ts
index 97520c199..e63bafe1b 100644
--- a/shared/src/tours/tours.schema.test.ts
+++ b/shared/src/tours/tours.schema.test.ts
@@ -2,6 +2,7 @@ import {
MAX_PLANNED_TOUR_DURATION_MINUTES,
plannedTourDurationMinutesSchema,
tourCreateRequestSchema,
+ tourListItemSchema,
tourMaxHikingDifficultySchema,
tourWebsiteSchema,
} from './tours.schema';
@@ -25,6 +26,31 @@ describe('Tours maximum hiking difficulty', () => {
expect(tourCreateRequestSchema.parse(baseRequest).max_hiking_difficulty).toBe(2);
});
+ it('keeps a drawn tour from saving without one', () => {
+ expect(() => tourCreateRequestSchema.parse({ ...baseRequest, max_hiking_difficulty: null })).toThrow();
+ });
+
+ it('lets a GPX-imported tour carry none', () => {
+ const imported = {
+ place_id: 1,
+ tour_type: 'hike',
+ distance: 4.2,
+ elevation_gain: null,
+ elevation_loss: null,
+ duration: null,
+ difficulty: null,
+ wanderer_ref: null,
+ match_confidence: 0.3,
+ max_hiking_difficulty: null,
+ name: 'Ridge walk',
+ planned: false,
+ caution: true,
+ has_waypoints: false,
+ };
+ expect(tourListItemSchema.parse(imported).max_hiking_difficulty).toBeNull();
+ expect(() => tourListItemSchema.parse({ ...imported, max_hiking_difficulty: 7 })).toThrow();
+ });
+
it('accepts only integer values from T1 through T6', () => {
for (const value of [1, 2, 3, 4, 5, 6]) {
expect(tourMaxHikingDifficultySchema.parse(value)).toBe(value);
diff --git a/shared/src/tours/tours.schema.ts b/shared/src/tours/tours.schema.ts
index f97df915d..26570c992 100644
--- a/shared/src/tours/tours.schema.ts
+++ b/shared/src/tours/tours.schema.ts
@@ -75,7 +75,8 @@ export const tourSchema = z.object({
// Nullable reference to a tour in wanderer.
wanderer_ref: z.string().nullable(),
match_confidence: z.number().min(0).max(1).nullable(),
- max_hiking_difficulty: tourMaxHikingDifficultySchema,
+ // NULL for a GPX import: the track carries no difficulty. A drawn tour always has one.
+ max_hiking_difficulty: tourMaxHikingDifficultySchema.nullable(),
});
export type Tour = z.infer<typeof tourSchema>;