mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-25 22:27:32 +00:00
feat(tours): complete planner follow-up scope
This commit completes the reviewed Tours follow-up scope after the Tours MVP was merged into dev. Included feature blocks: - RC-01: identify Tours in PLAN day rows and show compact Tour facts; - RC-06: search for a city or address in TOUR-PLANNER without hidden writes; - RC-07: reorder Tour waypoints in the left sidebar; - RC-08: drag Tour waypoints on Leaflet, MapLibre and Mapbox with stable viewport, history and routing behavior; - RS-01: persist Tour descriptions and HTTPS information links with local provider classification; - RS-02: persist breaks/additional time and calculated or manually adjusted planned Tour duration without changing scheduling semantics. The implementation preserves: - ordinary Place and Legacy Track behavior; - Tours-off fallback behavior; - existing GPX/import behavior; - Tour assignment and deletion behavior; - calculated routing duration as a separate value; - existing Tour provenance fields; - keyboard/list alternatives for waypoint editing. Not included: - PR1-09 trip-wide Tour summary; - Wanderer integration; - GPX import changes; - new Tour types; - Tour-to-Day drag-and-drop; - further roadmap or Post-Release features. Validation: - focused RC-01/RC-06/RC-07/RC-08/RS-01/RS-02 tests passed; - affected shared/server/client typechecks passed; - migration and generated DB type checks passed; - scoped ESLint passed; - staged diff checks passed; - owner manual tests passed for all six feature blocks.
This commit is contained in:
@@ -94,6 +94,17 @@ function clickOn(el: Element) {
|
||||
})
|
||||
}
|
||||
|
||||
function pointer(type: string, x: number, y: number): Event {
|
||||
const event = new Event(type, { bubbles: true, cancelable: true })
|
||||
Object.defineProperties(event, {
|
||||
button: { value: 0 },
|
||||
clientX: { value: x },
|
||||
clientY: { value: y },
|
||||
pointerId: { value: 1 },
|
||||
})
|
||||
return event
|
||||
}
|
||||
|
||||
// Two stops a few hundred metres apart in Nara: separate pins at this zoom, not a cluster.
|
||||
const places = [
|
||||
{ ...buildPlace({ id: 1, name: 'Todai-ji', lat: 34.689, lng: 135.8398 }), category_name: null, category_color: null, category_icon: null },
|
||||
@@ -114,6 +125,143 @@ async function renderMap() {
|
||||
}
|
||||
|
||||
describe('MapView on a real Leaflet map', () => {
|
||||
it('RC-08: previews waypoint drags locally and commits only at pointer up without panning', async () => {
|
||||
const waypoint = { id: 'via-1', lat: 34.689, lng: 135.8398, role: 'via' as const }
|
||||
const waypoints = [waypoint]
|
||||
const onMove = vi.fn(() => true)
|
||||
const onSelect = vi.fn()
|
||||
const onMapClick = vi.fn()
|
||||
const view = render(
|
||||
<MapView
|
||||
places={[]}
|
||||
center={[waypoint.lat, waypoint.lng]}
|
||||
zoom={15}
|
||||
tileUrl={RASTER}
|
||||
plannerWaypoints={waypoints}
|
||||
onPlannerWaypointClick={onSelect}
|
||||
onPlannerWaypointMove={onMove}
|
||||
onMapClick={onMapClick}
|
||||
focusKey="tour:1"
|
||||
focusPoints={[[waypoint.lat, waypoint.lng]]}
|
||||
routeProfileFocus={null}
|
||||
/>
|
||||
)
|
||||
const map = maps[maps.length - 1]
|
||||
await waitFor(() => expect(view.container.querySelector('.tour-planner-waypoint-marker')).not.toBeNull())
|
||||
const pin = view.container.querySelector('.tour-planner-waypoint-marker') as HTMLElement
|
||||
let marker: L.Marker | null = null
|
||||
map.eachLayer(layer => {
|
||||
if (layer instanceof L.Marker && layer.getElement() === pin) marker = layer
|
||||
})
|
||||
expect(marker).not.toBeNull()
|
||||
const start = map.latLngToContainerPoint([waypoint.lat, waypoint.lng])
|
||||
const end = start.add([30, 20])
|
||||
const expected = map.containerPointToLatLng(end)
|
||||
const center = map.getCenter()
|
||||
|
||||
act(() => {
|
||||
pin.dispatchEvent(pointer('pointerdown', start.x, start.y))
|
||||
pin.dispatchEvent(mouse('mousedown', start.x, start.y))
|
||||
pin.dispatchEvent(pointer('pointermove', end.x, end.y))
|
||||
})
|
||||
expect(marker!.getLatLng().lat).toBeCloseTo(expected.lat, 6)
|
||||
expect(marker!.getLatLng().lng).toBeCloseTo(expected.lng, 6)
|
||||
expect(onMove).not.toHaveBeenCalled()
|
||||
expect(waypoints[0]).toEqual(waypoint)
|
||||
|
||||
view.rerender(
|
||||
<MapView
|
||||
places={[]}
|
||||
center={[waypoint.lat, waypoint.lng]}
|
||||
zoom={15}
|
||||
tileUrl={RASTER}
|
||||
plannerWaypoints={waypoints}
|
||||
onPlannerWaypointClick={onSelect}
|
||||
onPlannerWaypointMove={onMove}
|
||||
onMapClick={onMapClick}
|
||||
focusKey="tour:1"
|
||||
focusPoints={[[waypoint.lat, waypoint.lng]]}
|
||||
routeProfileFocus={{ distanceMeters: 100, elevationMeters: 0, lat: 34.69, lng: 135.84, sampleIndex: 0 }}
|
||||
/>
|
||||
)
|
||||
expect(marker!.getLatLng().lat).toBeCloseTo(expected.lat, 6)
|
||||
expect(marker!.getLatLng().lng).toBeCloseTo(expected.lng, 6)
|
||||
|
||||
act(() => {
|
||||
pin.dispatchEvent(pointer('pointerup', end.x, end.y))
|
||||
pin.dispatchEvent(mouse('mouseup', end.x, end.y))
|
||||
pin.dispatchEvent(mouse('click', end.x, end.y))
|
||||
})
|
||||
expect(onMove).toHaveBeenCalledOnce()
|
||||
expect(onMove).toHaveBeenCalledWith(waypoint.id, expected.lat, expected.lng)
|
||||
expect(onSelect).not.toHaveBeenCalled()
|
||||
expect(onMapClick).not.toHaveBeenCalled()
|
||||
expect(map.getCenter().lat).toBeCloseTo(center.lat, 6)
|
||||
expect(map.getCenter().lng).toBeCloseTo(center.lng, 6)
|
||||
|
||||
view.rerender(
|
||||
<MapView
|
||||
places={[]}
|
||||
center={[waypoint.lat, waypoint.lng]}
|
||||
zoom={15}
|
||||
tileUrl={RASTER}
|
||||
plannerWaypoints={[{ ...waypoint, lat: expected.lat, lng: expected.lng }]}
|
||||
onPlannerWaypointClick={onSelect}
|
||||
onPlannerWaypointMove={onMove}
|
||||
onMapClick={onMapClick}
|
||||
focusKey="tour:1"
|
||||
focusPoints={[[expected.lat, expected.lng]]}
|
||||
routeProfileFocus={{ distanceMeters: 100, elevationMeters: 0, lat: 34.69, lng: 135.84, sampleIndex: 0 }}
|
||||
/>
|
||||
)
|
||||
expect(map.getCenter().lat).toBeCloseTo(center.lat, 6)
|
||||
expect(map.getCenter().lng).toBeCloseTo(center.lng, 6)
|
||||
})
|
||||
|
||||
it('RC-08: cancellation restores the marker and a plain click still selects without affecting map-add', async () => {
|
||||
const waypoint = { id: 'start', lat: 34.689, lng: 135.8398, role: 'start' as const }
|
||||
const onMove = vi.fn(() => true)
|
||||
const onSelect = vi.fn()
|
||||
const onMapClick = vi.fn()
|
||||
const view = render(
|
||||
<MapView
|
||||
places={[]}
|
||||
center={[waypoint.lat, waypoint.lng]}
|
||||
zoom={15}
|
||||
tileUrl={RASTER}
|
||||
plannerWaypoints={[waypoint]}
|
||||
onPlannerWaypointClick={onSelect}
|
||||
onPlannerWaypointMove={onMove}
|
||||
onMapClick={onMapClick}
|
||||
/>
|
||||
)
|
||||
const map = maps[maps.length - 1]
|
||||
await waitFor(() => expect(view.container.querySelector('.tour-planner-waypoint-marker')).not.toBeNull())
|
||||
const pin = view.container.querySelector('.tour-planner-waypoint-marker') as HTMLElement
|
||||
let marker: L.Marker | null = null
|
||||
map.eachLayer(layer => {
|
||||
if (layer instanceof L.Marker && layer.getElement() === pin) marker = layer
|
||||
})
|
||||
const start = map.latLngToContainerPoint([waypoint.lat, waypoint.lng])
|
||||
const end = start.add([30, 20])
|
||||
|
||||
act(() => {
|
||||
pin.dispatchEvent(pointer('pointerdown', start.x, start.y))
|
||||
pin.dispatchEvent(pointer('pointermove', end.x, end.y))
|
||||
pin.dispatchEvent(pointer('pointercancel', end.x, end.y))
|
||||
})
|
||||
expect(marker!.getLatLng().lat).toBeCloseTo(waypoint.lat, 6)
|
||||
expect(marker!.getLatLng().lng).toBeCloseTo(waypoint.lng, 6)
|
||||
expect(onMove).not.toHaveBeenCalled()
|
||||
|
||||
clickOn(pin)
|
||||
expect(onSelect).toHaveBeenCalledOnce()
|
||||
expect(onSelect).toHaveBeenCalledWith(waypoint.id)
|
||||
expect(onMapClick).not.toHaveBeenCalled()
|
||||
act(() => map.fire('click', { latlng: L.latLng(34.7, 135.85) }))
|
||||
expect(onMapClick).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('uses WGS-84 for Tours-local Topo over global Amap and preserves a Beijing click through layer switches', async () => {
|
||||
useSettingsStore.setState({ settings: { ...useSettingsStore.getState().settings, map_base_layer: 'default' } })
|
||||
const beijing = { ...buildPlace({ id: 201, name: 'Beijing', lat: 39.9042, lng: 116.4074 }), category_name: null, category_color: null, category_icon: null }
|
||||
|
||||
@@ -442,6 +442,48 @@ describe('MapView', () => {
|
||||
expect(mapMock.fitBounds).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('honors a location-search camera intent and preserves it through later route updates', () => {
|
||||
const searchPoint: [number, number] = [35.0116, 135.7681];
|
||||
const { rerender } = render(
|
||||
<MapView
|
||||
places={[]}
|
||||
route={null}
|
||||
followSelection={false}
|
||||
focusKey="tour:0:search:1"
|
||||
focusPoints={[searchPoint]}
|
||||
/>
|
||||
);
|
||||
expect(mapMock.fitBounds).toHaveBeenCalledOnce();
|
||||
expect(mapMock.fitBounds).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ maxZoom: 16 }));
|
||||
const mapContainer = screen.getByTestId('map-container');
|
||||
mapMock.fitBounds.mockClear();
|
||||
|
||||
rerender(
|
||||
<MapView
|
||||
places={[]}
|
||||
route={[[searchPoint, [35.02, 135.77]]]}
|
||||
followSelection={false}
|
||||
focusKey="tour:0:search:1"
|
||||
focusPoints={[searchPoint, [35.02, 135.77]]}
|
||||
/>
|
||||
);
|
||||
expect(mapMock.fitBounds).not.toHaveBeenCalled();
|
||||
expect(screen.getByTestId('map-container')).toBe(mapContainer);
|
||||
|
||||
rerender(
|
||||
<MapView
|
||||
places={[]}
|
||||
followSelection={false}
|
||||
focusKey="tour:1"
|
||||
focusPoints={[
|
||||
[46.8, 9.5],
|
||||
[47.1, 10.1],
|
||||
]}
|
||||
/>
|
||||
);
|
||||
expect(mapMock.fitBounds).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('frames Tour focus once, ignores waypoint and route updates, then honors a new focus intent', () => {
|
||||
const route: [number, number][][] = [[[48, 11], [48.2, 11.3]]]
|
||||
const { rerender } = render(
|
||||
|
||||
@@ -6,6 +6,7 @@ import MarkerClusterGroup from 'react-leaflet-cluster'
|
||||
import { makeMarkerDraggable, makePoiDraggable, draggedPoiId } from './markerDrag'
|
||||
import { CLUSTER_OPTIONS, createClusterIcon, revealInCluster, type ClusterGroupLike } from './markerCluster'
|
||||
import RoadtripViaMarkers from './RoadtripViaMarkers'
|
||||
import { wirePlannerWaypointDrag } from './plannerWaypointDrag'
|
||||
import HazardLayers from './HazardLayers'
|
||||
import { ALT_CASING, ALT_LABEL_TEXT } from '../Roadtrip/alternativeColors'
|
||||
import { serviceMarkerHtml, serviceMarkerOuter } from '../Roadtrip/serviceMarker'
|
||||
@@ -449,7 +450,7 @@ interface BoundsControllerProps {
|
||||
*/
|
||||
focusPoints?: [number, number][]
|
||||
/** Changes only when the caller intentionally wants a new initial frame. */
|
||||
focusKey?: number
|
||||
focusKey?: number | string
|
||||
/** False while the map is locked (#2010): an arriving route no longer re-fits it. */
|
||||
follow?: boolean
|
||||
/**
|
||||
@@ -757,16 +758,71 @@ const MemoMarker = memo(function MemoMarker({
|
||||
)
|
||||
})
|
||||
|
||||
function plannerWaypointIcon(index: number, selected: boolean): L.DivIcon {
|
||||
function plannerWaypointIcon(index: number, selected: boolean, draggable: boolean): L.DivIcon {
|
||||
const size = selected ? 30 : 26
|
||||
return L.divIcon({
|
||||
className: '',
|
||||
className: 'tour-planner-waypoint-marker',
|
||||
iconSize: [size, size],
|
||||
iconAnchor: [size / 2, size / 2],
|
||||
html: `<span style="display:flex;width:${size}px;height:${size}px;align-items:center;justify-content:center;border-radius:9999px;background:#0a84ff;color:white;border:${selected ? 3 : 2}px solid white;box-shadow:0 2px 7px rgba(0,0,0,.4);font:700 11px system-ui;cursor:pointer">${index + 1}</span>`,
|
||||
html: `<span style="display:flex;width:${size}px;height:${size}px;align-items:center;justify-content:center;border-radius:9999px;background:#0a84ff;color:white;border:${selected ? 3 : 2}px solid white;box-shadow:0 2px 7px rgba(0,0,0,.4);font:700 11px system-ui;cursor:${draggable ? 'grab' : 'pointer'};touch-action:${draggable ? 'none' : 'auto'};user-select:none">${index + 1}</span>`,
|
||||
})
|
||||
}
|
||||
|
||||
function PlannerWaypointMarker({
|
||||
point,
|
||||
index,
|
||||
selected,
|
||||
onClick,
|
||||
onMove,
|
||||
}: {
|
||||
point: { id: string; lat: number; lng: number };
|
||||
index: number;
|
||||
selected: boolean;
|
||||
onClick?: (id: string) => void;
|
||||
onMove?: (id: string, lat: number, lng: number) => boolean;
|
||||
}) {
|
||||
const map = useMap()
|
||||
const [marker, setMarker] = useState<L.Marker | null>(null)
|
||||
const handlersRef = useRef({ onClick, onMove })
|
||||
handlersRef.current = { onClick, onMove }
|
||||
const position = useMemo(() => [point.lat, point.lng] as [number, number], [point.lat, point.lng])
|
||||
const icon = useMemo(() => plannerWaypointIcon(index, selected, !!onMove), [index, onMove, selected])
|
||||
const eventHandlers = useMemo(() => ({
|
||||
click: (event: { originalEvent: MouseEvent }) => {
|
||||
event.originalEvent.stopPropagation()
|
||||
handlersRef.current.onClick?.(point.id)
|
||||
},
|
||||
}), [point.id])
|
||||
|
||||
useEffect(() => {
|
||||
if (!marker || !onMove) return
|
||||
const element = marker.getElement()
|
||||
return wirePlannerWaypointDrag({
|
||||
element,
|
||||
initial: { lat: point.lat, lng: point.lng },
|
||||
coordinateAt: (clientX, clientY) => {
|
||||
const rect = map.getContainer().getBoundingClientRect()
|
||||
const at = map.containerPointToLatLng([clientX - rect.left, clientY - rect.top])
|
||||
return { lat: at.lat, lng: at.lng }
|
||||
},
|
||||
setPosition: ({ lat, lng }) => { marker.setLatLng([lat, lng]) },
|
||||
onCommit: ({ lat, lng }) => handlersRef.current.onMove?.(point.id, lat, lng) ?? false,
|
||||
})
|
||||
}, [map, marker, onMove, point.id, point.lat, point.lng])
|
||||
|
||||
return (
|
||||
<Marker
|
||||
ref={setMarker}
|
||||
position={position}
|
||||
icon={icon}
|
||||
zIndexOffset={selected ? 1200 : 1100}
|
||||
eventHandlers={eventHandlers}
|
||||
>
|
||||
<Tooltip direction="top" offset={[0, -12]}>{index + 1}</Tooltip>
|
||||
</Marker>
|
||||
)
|
||||
}
|
||||
|
||||
export const MapView = memo(function MapView({
|
||||
places = [],
|
||||
dayPlaces = [],
|
||||
@@ -836,6 +892,7 @@ export const MapView = memo(function MapView({
|
||||
plannerWaypoints = [],
|
||||
selectedPlannerWaypointId = null,
|
||||
onPlannerWaypointClick,
|
||||
onPlannerWaypointMove,
|
||||
routeProfileFocus = null,
|
||||
viewBaseLayer,
|
||||
onViewBaseLayerChange,
|
||||
@@ -1307,20 +1364,14 @@ export const MapView = memo(function MapView({
|
||||
) : null}
|
||||
|
||||
{(plannerWaypoints as Array<{ id: string; lat: number; lng: number }>).map((point, index) => (
|
||||
<Marker
|
||||
<PlannerWaypointMarker
|
||||
key={`planner-waypoint-${point.id}`}
|
||||
position={[point.lat, point.lng]}
|
||||
icon={plannerWaypointIcon(index, point.id === selectedPlannerWaypointId)}
|
||||
zIndexOffset={point.id === selectedPlannerWaypointId ? 1200 : 1100}
|
||||
eventHandlers={{
|
||||
click: (event: { originalEvent: MouseEvent }) => {
|
||||
event.originalEvent.stopPropagation()
|
||||
onPlannerWaypointClick?.(point.id)
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Tooltip direction="top" offset={[0, -12]}>{index + 1}</Tooltip>
|
||||
</Marker>
|
||||
point={point}
|
||||
index={index}
|
||||
selected={point.id === selectedPlannerWaypointId}
|
||||
onClick={onPlannerWaypointClick}
|
||||
onMove={onPlannerWaypointMove}
|
||||
/>
|
||||
))}
|
||||
|
||||
{/* GPX imported route geometries */}
|
||||
|
||||
@@ -47,6 +47,7 @@ const glMap = vi.hoisted(() => ({
|
||||
getStyle: vi.fn().mockReturnValue({ layers: [] }),
|
||||
isStyleLoaded: vi.fn().mockReturnValue(true),
|
||||
getCanvasContainer: vi.fn(() => glCanvasContainer),
|
||||
getContainer: vi.fn(() => glCanvasContainer),
|
||||
getLayer: vi.fn().mockReturnValue(null),
|
||||
queryRenderedFeatures: vi.fn().mockReturnValue([]),
|
||||
querySourceFeatures: vi.fn().mockReturnValue([]),
|
||||
@@ -246,6 +247,17 @@ function buildMapPlace(overrides: Record<string, any> = {}) {
|
||||
} as any
|
||||
}
|
||||
|
||||
function pointer(type: string, x: number, y: number): Event {
|
||||
const event = new Event(type, { bubbles: true, cancelable: true })
|
||||
Object.defineProperties(event, {
|
||||
button: { value: 0 },
|
||||
clientX: { value: x },
|
||||
clientY: { value: y },
|
||||
pointerId: { value: 1 },
|
||||
})
|
||||
return event
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
glMap.on.mockImplementation(() => glMap)
|
||||
glMap.off.mockImplementation(() => glMap)
|
||||
@@ -931,6 +943,55 @@ describe('MapViewGL', () => {
|
||||
expect(glMap.easeTo).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('honors a location-search camera intent and preserves it through later route updates', async () => {
|
||||
loadOnAttach();
|
||||
const searchPoint: [number, number] = [35.0116, 135.7681];
|
||||
const { rerender } = render(
|
||||
<MapViewGL
|
||||
places={[]}
|
||||
route={null}
|
||||
followSelection={false}
|
||||
focusKey="tour:0:search:1"
|
||||
focusPoints={[searchPoint]}
|
||||
glProvider="maplibre-gl"
|
||||
/>
|
||||
);
|
||||
await act(async () => {});
|
||||
expect(glMap.fitBounds).toHaveBeenCalledOnce();
|
||||
expect(glMap.fitBounds).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ maxZoom: 15 }));
|
||||
const mapConstructions = (maplibregl.Map as any).mock.calls.length;
|
||||
glMap.fitBounds.mockClear();
|
||||
|
||||
rerender(
|
||||
<MapViewGL
|
||||
places={[]}
|
||||
route={[[searchPoint, [35.02, 135.77]]]}
|
||||
followSelection={false}
|
||||
focusKey="tour:0:search:1"
|
||||
focusPoints={[searchPoint, [35.02, 135.77]]}
|
||||
glProvider="maplibre-gl"
|
||||
/>
|
||||
);
|
||||
await act(async () => {});
|
||||
expect(glMap.fitBounds).not.toHaveBeenCalled();
|
||||
expect((maplibregl.Map as any).mock.calls).toHaveLength(mapConstructions);
|
||||
|
||||
rerender(
|
||||
<MapViewGL
|
||||
places={[]}
|
||||
followSelection={false}
|
||||
focusKey="tour:1"
|
||||
focusPoints={[
|
||||
[46.8, 9.5],
|
||||
[47.1, 10.1],
|
||||
]}
|
||||
glProvider="maplibre-gl"
|
||||
/>
|
||||
);
|
||||
await act(async () => {});
|
||||
expect(glMap.fitBounds).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('frames Tour focus once, ignores waypoint and route updates, then honors a new focus intent', async () => {
|
||||
loadOnAttach()
|
||||
const { rerender } = render(
|
||||
@@ -982,6 +1043,126 @@ describe('MapViewGL', () => {
|
||||
expect(glMap.fitBounds).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it.each(['maplibre-gl', 'mapbox-gl'] as const)('RC-08: %s previews waypoint drags locally and commits only on pointer up without changing the camera', async (provider) => {
|
||||
loadOnAttach()
|
||||
glMap.project.mockImplementation((lngLat: [number, number]) => ({ x: lngLat[0] * 10, y: lngLat[1] * 10 }))
|
||||
glMap.unproject.mockReturnValue({ lng: 2.3522, lat: 48.8566 })
|
||||
glMap.getContainer.mockReturnValue(glCanvasContainer)
|
||||
const waypoint = { id: 'via-1', lat: 48, lng: 11, role: 'via' as const }
|
||||
const waypoints = [waypoint]
|
||||
const onMove = vi.fn(() => true)
|
||||
const onSelect = vi.fn()
|
||||
const onMapClick = vi.fn()
|
||||
const view = render(
|
||||
<MapViewGL
|
||||
places={[]}
|
||||
plannerWaypoints={waypoints}
|
||||
onPlannerWaypointClick={onSelect}
|
||||
onPlannerWaypointMove={onMove}
|
||||
onMapClick={onMapClick}
|
||||
focusKey="tour:1"
|
||||
focusPoints={[[waypoint.lat, waypoint.lng]]}
|
||||
routeProfileFocus={null}
|
||||
glProvider={provider}
|
||||
/>
|
||||
)
|
||||
await act(async () => {})
|
||||
glMap.fitBounds.mockClear()
|
||||
const pin = provider === 'maplibre-gl'
|
||||
? glCanvasContainer.querySelector('[aria-label="Waypoint 1"]') as HTMLButtonElement
|
||||
: glMarkers.created.find(marker => marker.element.getAttribute('aria-label') === 'Waypoint 1')?.element as HTMLButtonElement
|
||||
const startTransform = pin.style.transform
|
||||
const libraryMarker = provider === 'mapbox-gl' ? glMarkers.created.find(marker => marker.element === pin) : undefined
|
||||
const startLngLat = libraryMarker?.lngLat
|
||||
|
||||
act(() => {
|
||||
pin.dispatchEvent(pointer('pointerdown', 10, 10))
|
||||
pin.dispatchEvent(pointer('pointermove', 30, 40))
|
||||
})
|
||||
if (provider === 'maplibre-gl') expect(pin.style.transform).not.toBe(startTransform)
|
||||
else expect(libraryMarker?.lngLat).not.toEqual(startLngLat)
|
||||
expect(onMove).not.toHaveBeenCalled()
|
||||
expect(waypoints[0]).toEqual(waypoint)
|
||||
|
||||
view.rerender(
|
||||
<MapViewGL
|
||||
places={[]}
|
||||
plannerWaypoints={waypoints}
|
||||
onPlannerWaypointClick={onSelect}
|
||||
onPlannerWaypointMove={onMove}
|
||||
onMapClick={onMapClick}
|
||||
focusKey="tour:1"
|
||||
focusPoints={[[waypoint.lat, waypoint.lng]]}
|
||||
routeProfileFocus={{ distanceMeters: 100, elevationMeters: 0, lat: 48.1, lng: 11.1, sampleIndex: 0 }}
|
||||
glProvider={provider}
|
||||
/>
|
||||
)
|
||||
if (provider === 'maplibre-gl') expect(pin.style.transform).not.toBe(startTransform)
|
||||
else expect(libraryMarker?.lngLat).not.toEqual(startLngLat)
|
||||
|
||||
act(() => {
|
||||
pin.dispatchEvent(pointer('pointerup', 30, 40))
|
||||
pin.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }))
|
||||
})
|
||||
expect(onMove).toHaveBeenCalledOnce()
|
||||
expect(onMove).toHaveBeenCalledWith(waypoint.id, 48.8566, 2.3522)
|
||||
expect(onSelect).not.toHaveBeenCalled()
|
||||
expect(onMapClick).not.toHaveBeenCalled()
|
||||
view.rerender(
|
||||
<MapViewGL
|
||||
places={[]}
|
||||
plannerWaypoints={[{ ...waypoint, lat: 48.4, lng: 11.3 }]}
|
||||
onPlannerWaypointClick={onSelect}
|
||||
onPlannerWaypointMove={onMove}
|
||||
onMapClick={onMapClick}
|
||||
focusKey="tour:1"
|
||||
focusPoints={[[48.4, 11.3]]}
|
||||
routeProfileFocus={{ distanceMeters: 100, elevationMeters: 0, lat: 48.1, lng: 11.1, sampleIndex: 0 }}
|
||||
glProvider={provider}
|
||||
/>
|
||||
)
|
||||
expect(glMap.fitBounds).not.toHaveBeenCalled()
|
||||
expect(glMap.flyTo).not.toHaveBeenCalled()
|
||||
expect(glMap.jumpTo).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('RC-08: pointer cancellation restores the MapLibre pin and plain clicks still select and add separately', async () => {
|
||||
loadOnAttach()
|
||||
const waypoint = { id: 'start', lat: 48, lng: 11, role: 'start' as const }
|
||||
const onMove = vi.fn(() => true)
|
||||
const onSelect = vi.fn()
|
||||
const onMapClick = vi.fn()
|
||||
render(
|
||||
<MapViewGL
|
||||
places={[]}
|
||||
plannerWaypoints={[waypoint]}
|
||||
onPlannerWaypointClick={onSelect}
|
||||
onPlannerWaypointMove={onMove}
|
||||
onMapClick={onMapClick}
|
||||
glProvider="maplibre-gl"
|
||||
/>
|
||||
)
|
||||
await act(async () => {})
|
||||
const pin = glCanvasContainer.querySelector('[aria-label="Waypoint 1"]') as HTMLButtonElement
|
||||
const initialTransform = pin.style.transform
|
||||
act(() => {
|
||||
pin.dispatchEvent(pointer('pointerdown', 10, 10))
|
||||
pin.dispatchEvent(pointer('pointermove', 30, 40))
|
||||
pin.dispatchEvent(pointer('pointercancel', 30, 40))
|
||||
})
|
||||
expect(pin.style.transform).toBe(initialTransform)
|
||||
expect(onMove).not.toHaveBeenCalled()
|
||||
|
||||
act(() => {
|
||||
pin.dispatchEvent(pointer('pointerdown', 10, 10))
|
||||
pin.dispatchEvent(pointer('pointerup', 10, 10))
|
||||
pin.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }))
|
||||
})
|
||||
expect(onSelect).toHaveBeenCalledOnce()
|
||||
expect(onSelect).toHaveBeenCalledWith(waypoint.id)
|
||||
expect(onMapClick).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps selection fit and the pending route-arrival refit for semantic changes', async () => {
|
||||
loadOnAttach()
|
||||
const selectedPlace = buildPlace({ id: 902, lat: 48, lng: 11 })
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useRef, useMemo, useState, createElement, useCallback } from 'react'
|
||||
import { makeMarkerDraggable, makePoiDraggable, draggedPoiId } from './markerDrag'
|
||||
import { useStableVias } from './viaMarkerState'
|
||||
import { wirePlannerWaypointDrag } from './plannerWaypointDrag'
|
||||
import { ALT_CASING, ALT_LABEL_TEXT } from '../Roadtrip/alternativeColors'
|
||||
import { serviceMarkerHtml, serviceMarkerOuter } from '../Roadtrip/serviceMarker'
|
||||
import { renderIconMarkup } from '../../utils/iconMarkup'
|
||||
@@ -622,6 +623,7 @@ export function MapViewGL({
|
||||
plannerWaypoints = [],
|
||||
selectedPlannerWaypointId = null,
|
||||
onPlannerWaypointClick,
|
||||
onPlannerWaypointMove,
|
||||
routeProfileFocus = null,
|
||||
viewBaseLayer,
|
||||
onViewBaseLayerChange,
|
||||
@@ -708,6 +710,9 @@ export function MapViewGL({
|
||||
/** The road-trip via handles (#1797) — hand-positioned like the rest, so listed here. */
|
||||
const viaPinsRef = useRef<PlacePin[]>([])
|
||||
const plannerWaypointPinsRef = useRef<PlacePin[]>([])
|
||||
const plannerWaypointHandlersRef = useRef({ onPlannerWaypointClick, onPlannerWaypointMove })
|
||||
plannerWaypointHandlersRef.current = { onPlannerWaypointClick, onPlannerWaypointMove }
|
||||
const plannerWaypointsDraggable = !!onPlannerWaypointMove
|
||||
const profileFocusPinRef = useRef<PlacePin | null>(null)
|
||||
/** The drive-time pills on the offered routes; same treatment. */
|
||||
const altLabelsRef = useRef<PlacePin[]>([])
|
||||
@@ -744,6 +749,7 @@ export function MapViewGL({
|
||||
if (!map || !mapReady) return
|
||||
plannerWaypointPinsRef.current.forEach(pin => pin.remove())
|
||||
plannerWaypointPinsRef.current = []
|
||||
const dragCleanups: (() => void)[] = []
|
||||
|
||||
for (const [index, point] of plannerWaypoints.entries()) {
|
||||
const selected = point.id === selectedPlannerWaypointId
|
||||
@@ -754,18 +760,34 @@ export function MapViewGL({
|
||||
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:#0a84ff;color:white;border:${selected ? 3 : 2}px solid white;box-shadow:0 2px 7px rgba(0,0,0,.4);font:700 11px system-ui;cursor:pointer;padding:0`
|
||||
const swallow = (event: Event) => event.stopPropagation()
|
||||
const select = (event: Event) => { event.stopPropagation(); onPlannerWaypointClick?.(point.id) }
|
||||
const select = (event: Event) => { event.stopPropagation(); plannerWaypointHandlersRef.current.onPlannerWaypointClick?.(point.id) }
|
||||
el.addEventListener('pointerdown', swallow)
|
||||
el.addEventListener('touchstart', swallow, { passive: true })
|
||||
el.addEventListener('click', select)
|
||||
plannerWaypointPinsRef.current.push(attachPin(map, gl, pinLayerRef.current, el, point.lng, point.lat))
|
||||
const pin = attachPin(map, gl, pinLayerRef.current, el, point.lng, point.lat)
|
||||
plannerWaypointPinsRef.current.push(pin)
|
||||
if (plannerWaypointsDraggable) {
|
||||
el.style.cursor = 'grab'
|
||||
dragCleanups.push(wirePlannerWaypointDrag({
|
||||
element: el,
|
||||
initial: { lat: point.lat, lng: point.lng },
|
||||
coordinateAt: (clientX, clientY) => {
|
||||
const rect = map.getContainer().getBoundingClientRect()
|
||||
const at = map.unproject([clientX - rect.left, clientY - rect.top])
|
||||
return { lat: at.lat, lng: at.lng }
|
||||
},
|
||||
setPosition: ({ lat, lng }) => pin.setLngLat([lng, lat]),
|
||||
onCommit: ({ lat, lng }) => plannerWaypointHandlersRef.current.onPlannerWaypointMove?.(point.id, lat, lng) ?? false,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
return () => {
|
||||
dragCleanups.forEach(cleanup => cleanup())
|
||||
plannerWaypointPinsRef.current.forEach(pin => pin.remove())
|
||||
plannerWaypointPinsRef.current = []
|
||||
}
|
||||
}, [gl, mapReady, onPlannerWaypointClick, plannerWaypoints, selectedPlannerWaypointId])
|
||||
}, [gl, mapReady, plannerWaypoints, plannerWaypointsDraggable, selectedPlannerWaypointId])
|
||||
|
||||
useEffect(() => () => {
|
||||
profileFocusPinRef.current?.remove()
|
||||
|
||||
@@ -111,6 +111,8 @@ export interface MapViewProps {
|
||||
plannerWaypoints?: Array<{ id: string; lat: number; lng: number }>;
|
||||
selectedPlannerWaypointId?: string | null;
|
||||
onPlannerWaypointClick?: (id: string) => void;
|
||||
/** Drops a dragged control point; returns false when the move was refused. */
|
||||
onPlannerWaypointMove?: (id: string, lat: number, lng: number) => boolean;
|
||||
routeProfileFocus?: RouteProfileFocus | null;
|
||||
viewBaseLayer?: TourBaseLayer;
|
||||
onViewBaseLayerChange?: (layer: TourBaseLayer) => void;
|
||||
@@ -123,7 +125,7 @@ export interface MapViewProps {
|
||||
*/
|
||||
focusPoints?: [number, number][];
|
||||
/** Changes only when the caller intentionally wants a new initial frame. */
|
||||
focusKey?: number;
|
||||
focusKey?: number | string;
|
||||
/**
|
||||
* What the caller's own chrome covers while `focusPoints` is framed, in pixels per edge.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { wirePlannerWaypointDrag } from './plannerWaypointDrag';
|
||||
|
||||
function pointer(type: string, x: number, y: number, pointerId = 1, pointerType: 'mouse' | 'touch' = 'mouse'): Event {
|
||||
const event = new Event(type, { bubbles: true, cancelable: true });
|
||||
Object.defineProperties(event, {
|
||||
button: { value: 0 },
|
||||
clientX: { value: x },
|
||||
clientY: { value: y },
|
||||
pointerId: { value: pointerId },
|
||||
pointerType: { value: pointerType },
|
||||
});
|
||||
return event;
|
||||
}
|
||||
|
||||
describe('Tour waypoint marker drag lifecycle', () => {
|
||||
it('previews during a drag and commits once on pointer up, swallowing only the generated click', () => {
|
||||
const element = document.createElement('button');
|
||||
const initial = { lat: 48, lng: 11 };
|
||||
const preview = vi.fn();
|
||||
const onCommit = vi.fn(() => true);
|
||||
const cleanup = wirePlannerWaypointDrag({
|
||||
element,
|
||||
initial,
|
||||
coordinateAt: (clientX, clientY) => ({ lat: clientY / 100, lng: clientX / 100 }),
|
||||
setPosition: preview,
|
||||
onCommit,
|
||||
});
|
||||
|
||||
element.dispatchEvent(pointer('pointerdown', 10, 10));
|
||||
element.dispatchEvent(pointer('pointermove', 11, 11));
|
||||
expect(preview).not.toHaveBeenCalled();
|
||||
expect(onCommit).not.toHaveBeenCalled();
|
||||
|
||||
element.dispatchEvent(pointer('pointermove', 20, 30));
|
||||
expect(preview).toHaveBeenLastCalledWith({ lat: 0.3, lng: 0.2 });
|
||||
expect(onCommit).not.toHaveBeenCalled();
|
||||
element.dispatchEvent(pointer('pointerup', 30, 40));
|
||||
expect(preview).toHaveBeenLastCalledWith({ lat: 0.4, lng: 0.3 });
|
||||
expect(onCommit).toHaveBeenCalledOnce();
|
||||
expect(onCommit).toHaveBeenCalledWith({ lat: 0.4, lng: 0.3 });
|
||||
|
||||
const generatedClick = new MouseEvent('click', { bubbles: true, cancelable: true });
|
||||
element.dispatchEvent(generatedClick);
|
||||
expect(generatedClick.defaultPrevented).toBe(true);
|
||||
const nextClick = new MouseEvent('click', { bubbles: true, cancelable: true });
|
||||
element.dispatchEvent(nextClick);
|
||||
expect(nextClick.defaultPrevented).toBe(false);
|
||||
cleanup();
|
||||
});
|
||||
|
||||
it('restores the starting coordinate on pointer cancellation and does not commit', () => {
|
||||
const element = document.createElement('button');
|
||||
const initial = { lat: 48, lng: 11 };
|
||||
const preview = vi.fn();
|
||||
const onCommit = vi.fn();
|
||||
const cleanup = wirePlannerWaypointDrag({
|
||||
element,
|
||||
initial,
|
||||
coordinateAt: (clientX, clientY) => ({ lat: clientY, lng: clientX }),
|
||||
setPosition: preview,
|
||||
onCommit,
|
||||
});
|
||||
|
||||
element.dispatchEvent(pointer('pointerdown', 10, 10));
|
||||
element.dispatchEvent(pointer('pointermove', 20, 30));
|
||||
element.dispatchEvent(pointer('pointercancel', 20, 30));
|
||||
expect(preview).toHaveBeenLastCalledWith(initial);
|
||||
expect(onCommit).not.toHaveBeenCalled();
|
||||
cleanup();
|
||||
});
|
||||
|
||||
it('restores the preview when the canonical commit is rejected', () => {
|
||||
const element = document.createElement('button');
|
||||
const initial = { lat: 48, lng: 11 };
|
||||
const preview = vi.fn();
|
||||
const cleanup = wirePlannerWaypointDrag({
|
||||
element,
|
||||
initial,
|
||||
coordinateAt: (clientX, clientY) => ({ lat: clientY, lng: clientX }),
|
||||
setPosition: preview,
|
||||
onCommit: () => false,
|
||||
});
|
||||
|
||||
element.dispatchEvent(pointer('pointerdown', 10, 10));
|
||||
element.dispatchEvent(pointer('pointermove', 20, 30));
|
||||
element.dispatchEvent(pointer('pointerup', 20, 30));
|
||||
expect(preview).toHaveBeenLastCalledWith(initial);
|
||||
cleanup();
|
||||
});
|
||||
|
||||
it('keeps pointer, mouse, and touch starts from bubbling into map pan handlers', () => {
|
||||
const mapSurface = document.createElement('div');
|
||||
const element = document.createElement('button');
|
||||
mapSurface.append(element);
|
||||
const mapPan = vi.fn();
|
||||
mapSurface.addEventListener('pointerdown', mapPan);
|
||||
mapSurface.addEventListener('mousedown', mapPan);
|
||||
mapSurface.addEventListener('touchstart', mapPan);
|
||||
const cleanup = wirePlannerWaypointDrag({
|
||||
element,
|
||||
initial: { lat: 48, lng: 11 },
|
||||
coordinateAt: () => ({ lat: 48, lng: 11 }),
|
||||
setPosition: vi.fn(),
|
||||
onCommit: vi.fn(),
|
||||
});
|
||||
|
||||
element.dispatchEvent(pointer('pointerdown', 10, 10));
|
||||
element.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button: 0 }));
|
||||
element.dispatchEvent(new Event('touchstart', { bubbles: true, cancelable: true }));
|
||||
expect(mapPan).not.toHaveBeenCalled();
|
||||
cleanup();
|
||||
});
|
||||
|
||||
it('commits a touch-pointer drag once at release', () => {
|
||||
const element = document.createElement('button');
|
||||
const onCommit = vi.fn(() => true);
|
||||
const cleanup = wirePlannerWaypointDrag({
|
||||
element,
|
||||
initial: { lat: 48, lng: 11 },
|
||||
coordinateAt: (clientX, clientY) => ({ lat: clientY / 10, lng: clientX / 10 }),
|
||||
setPosition: vi.fn(),
|
||||
onCommit,
|
||||
});
|
||||
|
||||
element.dispatchEvent(pointer('pointerdown', 5, 5, 9, 'touch'));
|
||||
element.dispatchEvent(pointer('pointermove', 25, 35, 9, 'touch'));
|
||||
expect(onCommit).not.toHaveBeenCalled();
|
||||
element.dispatchEvent(pointer('pointerup', 25, 35, 9, 'touch'));
|
||||
expect(onCommit).toHaveBeenCalledOnce();
|
||||
expect(onCommit).toHaveBeenCalledWith({ lat: 3.5, lng: 2.5 });
|
||||
cleanup();
|
||||
});
|
||||
|
||||
it('restores existing touch and selection styles when editing drag wiring is removed', () => {
|
||||
const element = document.createElement('button');
|
||||
element.style.touchAction = 'pan-x';
|
||||
element.style.userSelect = 'text';
|
||||
const cleanup = wirePlannerWaypointDrag({
|
||||
element,
|
||||
initial: { lat: 48, lng: 11 },
|
||||
coordinateAt: () => ({ lat: 48, lng: 11 }),
|
||||
setPosition: vi.fn(),
|
||||
onCommit: vi.fn(),
|
||||
});
|
||||
expect(element.style.touchAction).toBe('none');
|
||||
expect(element.style.userSelect).toBe('none');
|
||||
cleanup();
|
||||
expect(element.style.touchAction).toBe('pan-x');
|
||||
expect(element.style.userSelect).toBe('text');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
export interface PlannerWaypointCoordinate {
|
||||
lat: number;
|
||||
lng: number;
|
||||
}
|
||||
|
||||
interface PlannerWaypointDragOptions {
|
||||
element: HTMLElement;
|
||||
initial: PlannerWaypointCoordinate;
|
||||
coordinateAt: (clientX: number, clientY: number) => PlannerWaypointCoordinate;
|
||||
setPosition: (coordinate: PlannerWaypointCoordinate) => void;
|
||||
onCommit: (coordinate: PlannerWaypointCoordinate) => boolean | void;
|
||||
}
|
||||
|
||||
const DRAG_THRESHOLD_PX = 4;
|
||||
|
||||
export function wirePlannerWaypointDrag({
|
||||
element,
|
||||
initial,
|
||||
coordinateAt,
|
||||
setPosition,
|
||||
onCommit,
|
||||
}: PlannerWaypointDragOptions): () => void {
|
||||
let pointerId: number | null = null;
|
||||
let start: { x: number; y: number } | null = null;
|
||||
let dragged = false;
|
||||
let suppressClick = false;
|
||||
const originalTouchAction = element.style.touchAction;
|
||||
const originalUserSelect = element.style.userSelect;
|
||||
|
||||
const stopMapGesture = (event: Event) => event.stopPropagation();
|
||||
const restore = () => setPosition(initial);
|
||||
const cancel = (event?: Event) => {
|
||||
if (pointerId === null) return;
|
||||
event?.stopPropagation();
|
||||
restore();
|
||||
pointerId = null;
|
||||
start = null;
|
||||
dragged = false;
|
||||
suppressClick = false;
|
||||
};
|
||||
|
||||
const onPointerDown = (event: PointerEvent) => {
|
||||
if (event.button !== 0 || pointerId !== null) {
|
||||
event.stopPropagation();
|
||||
return;
|
||||
}
|
||||
event.stopPropagation();
|
||||
pointerId = event.pointerId;
|
||||
start = { x: event.clientX, y: event.clientY };
|
||||
dragged = false;
|
||||
suppressClick = false;
|
||||
try {
|
||||
element.setPointerCapture(event.pointerId);
|
||||
} catch {
|
||||
// Pointer capture is unavailable in some test DOMs and older browsers.
|
||||
}
|
||||
};
|
||||
|
||||
const onPointerMove = (event: PointerEvent) => {
|
||||
if (event.pointerId !== pointerId || !start) return;
|
||||
event.stopPropagation();
|
||||
if (!dragged && Math.hypot(event.clientX - start.x, event.clientY - start.y) < DRAG_THRESHOLD_PX) return;
|
||||
dragged = true;
|
||||
event.preventDefault();
|
||||
setPosition(coordinateAt(event.clientX, event.clientY));
|
||||
};
|
||||
|
||||
const onPointerUp = (event: PointerEvent) => {
|
||||
if (event.pointerId !== pointerId || !start) return;
|
||||
event.stopPropagation();
|
||||
const travelled = Math.hypot(event.clientX - start.x, event.clientY - start.y);
|
||||
if (dragged || travelled >= DRAG_THRESHOLD_PX) {
|
||||
const coordinate = coordinateAt(event.clientX, event.clientY);
|
||||
setPosition(coordinate);
|
||||
const accepted = onCommit(coordinate) !== false;
|
||||
suppressClick = true;
|
||||
if (!accepted) restore();
|
||||
}
|
||||
pointerId = null;
|
||||
start = null;
|
||||
dragged = false;
|
||||
};
|
||||
|
||||
const onClickCapture = (event: MouseEvent) => {
|
||||
if (!suppressClick) return;
|
||||
suppressClick = false;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
event.stopImmediatePropagation();
|
||||
};
|
||||
|
||||
const onTouchCancel = (event: Event) => cancel(event);
|
||||
|
||||
element.addEventListener('pointerdown', onPointerDown);
|
||||
element.addEventListener('pointermove', onPointerMove);
|
||||
element.addEventListener('pointerup', onPointerUp);
|
||||
element.addEventListener('pointercancel', cancel);
|
||||
element.addEventListener('lostpointercapture', cancel);
|
||||
element.addEventListener('click', onClickCapture, true);
|
||||
element.addEventListener('mousedown', stopMapGesture);
|
||||
element.addEventListener('touchstart', stopMapGesture, { passive: true });
|
||||
element.addEventListener('touchmove', stopMapGesture, { passive: true });
|
||||
element.addEventListener('touchend', stopMapGesture, { passive: true });
|
||||
element.addEventListener('touchcancel', onTouchCancel, { passive: true });
|
||||
element.style.touchAction = 'none';
|
||||
element.style.userSelect = 'none';
|
||||
|
||||
return () => {
|
||||
cancel();
|
||||
element.removeEventListener('pointerdown', onPointerDown);
|
||||
element.removeEventListener('pointermove', onPointerMove);
|
||||
element.removeEventListener('pointerup', onPointerUp);
|
||||
element.removeEventListener('pointercancel', cancel);
|
||||
element.removeEventListener('lostpointercapture', cancel);
|
||||
element.removeEventListener('click', onClickCapture, true);
|
||||
element.removeEventListener('mousedown', stopMapGesture);
|
||||
element.removeEventListener('touchstart', stopMapGesture);
|
||||
element.removeEventListener('touchmove', stopMapGesture);
|
||||
element.removeEventListener('touchend', stopMapGesture);
|
||||
element.removeEventListener('touchcancel', onTouchCancel);
|
||||
element.style.touchAction = originalTouchAction;
|
||||
element.style.userSelect = originalUserSelect;
|
||||
};
|
||||
}
|
||||
@@ -1534,6 +1534,58 @@ describe('DayPlanSidebar', () => {
|
||||
expect(onDeletePlace).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('RS-01: previews Tour descriptions in two lines only while Tours is enabled', () => {
|
||||
const description = 'A long description of the ridge route, the lake overlook, and the return path.'
|
||||
const place = buildPlace({ id: 45, name: 'Ridge walk', description, tour_place_id: 45 })
|
||||
const day = buildDay({ id: 10, date: '2025-06-01', title: 'Day 1' })
|
||||
const assignment = buildAssignment({ id: 101, day_id: 10, order_index: 0, place })
|
||||
const times = { walkingMinutes: 60, breakMinutes: 35, plannedTotalMinutes: 95, manuallyOverridden: false }
|
||||
const props = makeDefaultProps({ days: [day], places: [place], tourPlaceIds: new Set([place.id]), plannedTourDurations: new Map([[place.id, times]]), assignments: { '10': [assignment] } })
|
||||
useAddonStore.setState({ addons: [{ id: 'tours', name: 'Tours', type: 'trip', icon: '', enabled: true }] })
|
||||
const view = render(<DayPlanSidebar {...props} />)
|
||||
const tourPreview = view.container.querySelector('[data-testid="trip-plan-tour-description"]') as HTMLElement
|
||||
expect(tourPreview).toHaveTextContent(description)
|
||||
expect(tourPreview.style.display).toBe('-webkit-box')
|
||||
expect(tourPreview.style.webkitLineClamp).toBe('2')
|
||||
expect(tourPreview.style.maxHeight).toBe('2.6em')
|
||||
expect(screen.getByTestId('trip-plan-tour-walking-time')).toHaveTextContent('Walk: 1 h')
|
||||
expect(screen.getByTestId('trip-plan-tour-breaks')).toHaveTextContent('Breaks: 35 min')
|
||||
expect(screen.getByTestId('trip-plan-tour-planned-duration')).toHaveTextContent('Planned: 1 h 35 min')
|
||||
|
||||
view.rerender(<DayPlanSidebar {...{ ...props, plannedTourDurations: new Map([[place.id, { ...times, plannedTotalMinutes: 125, manuallyOverridden: true }]]) }} />)
|
||||
expect(screen.getByTestId('trip-plan-tour-planned-duration')).toHaveTextContent('Manual override')
|
||||
|
||||
useAddonStore.setState({ addons: [{ id: 'tours', name: 'Tours', type: 'trip', icon: '', enabled: false }] })
|
||||
view.rerender(<DayPlanSidebar {...props} />)
|
||||
expect(view.container.querySelector('[data-testid="trip-plan-tour-description"]')).toBeNull()
|
||||
expect(view.container.querySelector('[data-testid="trip-plan-tour-planned-duration"]')).toBeNull()
|
||||
expect(screen.getByText(description).closest('.collab-note-md')).toHaveStyle({ whiteSpace: 'nowrap', maxHeight: '1.3em' })
|
||||
})
|
||||
|
||||
it('RC-01: uses facet type and compact facts only for Tours, preserving Tours-off Place presentation', () => {
|
||||
const place = buildPlace({ id: 45, name: 'Ridge walk', description: 'Above the lake', tour_place_id: 45 })
|
||||
const day = buildDay({ id: 10, title: 'Day 1' })
|
||||
const assignment = buildAssignment({ id: 101, day_id: 10, order_index: 0, place })
|
||||
const tour = {
|
||||
place_id: 45, name: place.name, tour_type: 'hike' as const, distance: 4, elevation_gain: 100, elevation_loss: 80,
|
||||
duration: 53, break_additional_minutes: 10, planned_duration_minutes: null, difficulty: null,
|
||||
wanderer_ref: null, match_confidence: 1, max_hiking_difficulty: 2, planned: true, caution: false,
|
||||
}
|
||||
const props = makeDefaultProps({ days: [day], places: [place], tourPlaceIds: new Set([45]), assignments: { '10': [assignment] },
|
||||
plannedTourDurations: new Map([[45, { tour, walkingMinutes: 53, breakMinutes: 10, plannedTotalMinutes: 63, manuallyOverridden: false }]]) })
|
||||
useAddonStore.setState({ addons: [{ id: 'tours', name: 'Tours', type: 'trip', icon: '', enabled: true }] })
|
||||
const view = render(<DayPlanSidebar {...props} />)
|
||||
expect(screen.getByTestId('plan-tour-icon').querySelector('.lucide-mountain')).toBeTruthy()
|
||||
expect(screen.getByTestId('plan-tour-distance')).toHaveTextContent('4')
|
||||
expect(screen.getByTestId('plan-tour-ascent')).toHaveTextContent('100')
|
||||
expect(screen.getByTestId('trip-plan-tour-walking-time')).toHaveAccessibleName('Walking time: 53 min')
|
||||
expect(screen.getByTestId('trip-plan-tour-planned-duration')).toHaveTextContent('1 h 3 min')
|
||||
useAddonStore.setState({ addons: [{ id: 'tours', name: 'Tours', type: 'trip', icon: '', enabled: false }] })
|
||||
view.rerender(<DayPlanSidebar {...props} />)
|
||||
expect(screen.queryByTestId('plan-tour-icon')).not.toBeInTheDocument()
|
||||
expect(screen.queryByTestId('plan-tour-facts')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('TRIP-PLAN preserves legacy route-backed Place Delete when Tours is disabled', async () => {
|
||||
const user = userEvent.setup()
|
||||
useAddonStore.setState({ addons: [{ id: 'tours', name: 'Tours', type: 'trip', icon: '', enabled: false }] })
|
||||
|
||||
@@ -80,6 +80,9 @@ import { DayPlanSidebarFooter } from './DayPlanSidebarFooter'
|
||||
import type { DayAddControls } from '../../utils/dayAdd'
|
||||
import type { DayDeleteQuestion } from '../../utils/dayImpactLines'
|
||||
import type { Trip, Day, Place, Category, Assignment, Accommodation, Reservation, AssignmentsMap, RouteResult, RouteSegment, DayNote } from '../../types'
|
||||
import { formatPlannedTourDuration, type TourPlannedTimes } from '../Tours/tourPresentation'
|
||||
import type { TourListItem } from '@trek/shared'
|
||||
import TourDayRowFacts, { TourDayRowIcon } from '../Tours/TourDayRowFacts'
|
||||
|
||||
export interface DayPlanSidebarProps {
|
||||
tripId: number
|
||||
@@ -87,6 +90,7 @@ export interface DayPlanSidebarProps {
|
||||
days: Day[]
|
||||
places: Place[]
|
||||
tourPlaceIds?: ReadonlySet<number>
|
||||
plannedTourDurations?: ReadonlyMap<number, TourPlannedTimes & { tour?: TourListItem }>
|
||||
categories: Category[]
|
||||
assignments: AssignmentsMap
|
||||
selectedDayId: number | null
|
||||
@@ -1823,6 +1827,9 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
const assignment = item.data
|
||||
const place = assignment.place
|
||||
if (!place) return null
|
||||
const isTourPlace = toursEnabled && (props.tourPlaceIds?.has(place.id) || place.tour_place_id === place.id)
|
||||
const tourTimes = isTourPlace ? props.plannedTourDurations?.get(place.id) : undefined
|
||||
const dayRowTour = tourTimes?.tour
|
||||
const cat = categories.find(c => c.id === place.category_id)
|
||||
const isPlaceSelected = selectedAssignmentId ? assignment.id === selectedAssignmentId : place.id === selectedPlaceId
|
||||
const isDraggingThis = draggingId === assignment.id
|
||||
@@ -1994,7 +2001,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
onMouseLeave={() => setLockHoverId(null)}
|
||||
className="relative flex flex-none rounded-full"
|
||||
>
|
||||
<PlaceAvatar place={place} category={cat} size={32} />
|
||||
{dayRowTour ? <TourDayRowIcon type={dayRowTour.tour_type} size={32} /> : <PlaceAvatar place={place} category={cat} size={32} />}
|
||||
{/* Hover/locked overlay */}
|
||||
{(lockHoverId === assignment.id || isLocked) && (
|
||||
<span className="absolute inset-0 grid place-items-center rounded-full transition-colors"
|
||||
@@ -2006,7 +2013,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
</Tooltip>
|
||||
<div style={{ flex: 1, minWidth: 0 }}>
|
||||
<div className="flex min-w-0 items-center gap-1.5">
|
||||
{cat && (() => {
|
||||
{!dayRowTour && cat && (() => {
|
||||
const CatIcon = getCategoryIcon(cat.icon)
|
||||
return (
|
||||
<Tooltip label={cat.name}>
|
||||
@@ -2027,15 +2034,37 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar(props: DayPlanSidebarP
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
{(place.place_time || place.description || place.address || cat?.name) && (
|
||||
<div className="mt-0.5 flex min-w-0 items-center gap-1.5">
|
||||
{(dayRowTour || place.place_time || (tourTimes && (tourTimes.walkingMinutes != null || tourTimes.breakMinutes != null || tourTimes.plannedTotalMinutes != null)) || place.description || place.address || cat?.name) && (
|
||||
<div className="mt-0.5 flex min-w-0 flex-wrap items-center gap-1.5">
|
||||
{place.place_time && (
|
||||
<TimePill quiet>
|
||||
{formatTime(place.place_time, locale, timeFormat)}{place.end_time ? ` – ${formatTime(place.end_time, locale, timeFormat)}` : ''}
|
||||
</TimePill>
|
||||
)}
|
||||
{dayRowTour && <TourDayRowFacts tour={dayRowTour} />}
|
||||
{!dayRowTour && tourTimes?.walkingMinutes != null && (
|
||||
<TimePill>
|
||||
<span data-testid="trip-plan-tour-walking-time" aria-label={`${t('tours.planner.inspector.duration')}: ${formatPlannedTourDuration(tourTimes.walkingMinutes)}`}>
|
||||
{t('tours.planner.walkingShort')}: {formatPlannedTourDuration(tourTimes.walkingMinutes)}
|
||||
</span>
|
||||
</TimePill>
|
||||
)}
|
||||
{!dayRowTour && tourTimes?.breakMinutes != null && (
|
||||
<TimePill>
|
||||
<span data-testid="trip-plan-tour-breaks" aria-label={`${t('tours.planner.breaksAdditional')}: ${formatPlannedTourDuration(tourTimes.breakMinutes)}`}>
|
||||
{t('tours.planner.breaksShort')}: {formatPlannedTourDuration(tourTimes.breakMinutes)}
|
||||
</span>
|
||||
</TimePill>
|
||||
)}
|
||||
{!dayRowTour && tourTimes?.plannedTotalMinutes != null && (
|
||||
<TimePill>
|
||||
<span data-testid="trip-plan-tour-planned-duration" aria-label={`${t('tours.planner.plannedTotalDuration')}: ${formatPlannedTourDuration(tourTimes.plannedTotalMinutes)}${tourTimes.manuallyOverridden ? `, ${t('tours.planner.plannedTotalManual')}` : ''}`}>
|
||||
{t('tours.planner.plannedShort')}: {formatPlannedTourDuration(tourTimes.plannedTotalMinutes)}{tourTimes.manuallyOverridden ? ` · ${t('tours.planner.plannedTotalManual')}` : ''}
|
||||
</span>
|
||||
</TimePill>
|
||||
)}
|
||||
{(place.description || place.address || cat?.name) && (
|
||||
<div className="collab-note-md min-w-0 flex-1 text-content-faint" style={{ ...fs(10.5), overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', lineHeight: 1.3, maxHeight: '1.3em' }}>
|
||||
<div data-testid={isTourPlace ? 'trip-plan-tour-description' : undefined} className="collab-note-md min-w-0 flex-1 text-content-faint" style={{ ...fs(10.5), overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: isTourPlace ? 'normal' : 'nowrap', lineHeight: 1.3, maxHeight: isTourPlace ? '2.6em' : '1.3em', ...(isTourPlace ? { display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical' as const } : {}) }}>
|
||||
<Markdown remarkPlugins={[remarkGfm]}>{place.description || place.address || cat?.name || ''}</Markdown>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -364,4 +364,43 @@ describe('LocationSelect', () => {
|
||||
expect(screen.queryByText('Gare du Nord')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('Gare de Lyon')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('marks the keyboard-highlighted result as active and selects it with Enter', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(searchRoute([GARE, LYON]));
|
||||
const onPick = vi.fn();
|
||||
|
||||
render(<LocationSelect value={null} onChange={onPick} ariaLabel="Search map location" showSearchStatus />);
|
||||
const input = screen.getByRole('combobox', { name: 'Search map location' });
|
||||
await user.type(input, 'Gare');
|
||||
const firstOption = await screen.findByRole('option', { name: /Gare du Nord/ });
|
||||
await user.keyboard('{ArrowDown}');
|
||||
|
||||
expect(firstOption).toHaveAttribute('aria-selected', 'true');
|
||||
expect(input).toHaveAttribute('aria-activedescendant', firstOption.id);
|
||||
await user.keyboard('{Enter}');
|
||||
expect(onPick).toHaveBeenCalledWith(expect.objectContaining({ name: 'Gare du Nord' }));
|
||||
});
|
||||
|
||||
it('shows a localized no-result status after an empty successful search', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(searchRoute([]));
|
||||
|
||||
render(<LocationSelect value={null} onChange={vi.fn()} ariaLabel="Search map location" showSearchStatus />);
|
||||
await user.type(screen.getByRole('combobox', { name: 'Search map location' }), 'Nowhere');
|
||||
|
||||
expect(await screen.findByText(/Nothing found for/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows a non-mutating error status when the provider request fails', async () => {
|
||||
const user = userEvent.setup();
|
||||
server.use(http.post('/api/maps/search', () => HttpResponse.json({ error: 'unavailable' }, { status: 503 })));
|
||||
const onChange = vi.fn();
|
||||
|
||||
render(<LocationSelect value={null} onChange={onChange} ariaLabel="Search map location" showSearchStatus />);
|
||||
await user.type(screen.getByRole('combobox', { name: 'Search map location' }), 'Kyoto');
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Error');
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useEffect, useId, useRef, useState } from 'react'
|
||||
import { MapPin } from 'lucide-react'
|
||||
import { mapsApi } from '../../api/client'
|
||||
import { useTranslation } from '../../i18n'
|
||||
@@ -18,6 +18,9 @@ interface Props {
|
||||
value: LocationPoint | null
|
||||
onChange: (loc: LocationPoint | null) => void
|
||||
placeholder?: string
|
||||
ariaLabel?: string
|
||||
/** Announces the field as a combobox and says "nothing found" or an error in its list. */
|
||||
showSearchStatus?: boolean
|
||||
style?: React.CSSProperties
|
||||
/**
|
||||
* The trip's own places, offered while the field is empty or holds fewer than three
|
||||
@@ -27,7 +30,7 @@ interface Props {
|
||||
places?: LocationPoint[]
|
||||
}
|
||||
|
||||
export default function LocationSelect({ value, onChange, placeholder, style, places }: Props) {
|
||||
export default function LocationSelect({ value, onChange, placeholder, ariaLabel, showSearchStatus = false, style, places }: Props) {
|
||||
const { t, locale } = useTranslation()
|
||||
const placeLang = usePlaceLanguage()
|
||||
// Ohne Reisekontext ist der Hinweis leer, und die Suche laeuft wie bisher.
|
||||
@@ -36,6 +39,10 @@ export default function LocationSelect({ value, onChange, placeholder, style, pl
|
||||
const { open, setOpen, highlight, setHighlight, wrapRef, handleKey } = useSuggestionDropdown()
|
||||
const [results, setResults] = useState<any[]>([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [searchError, setSearchError] = useState(false)
|
||||
// The text the last answer was for, so a status never describes older text.
|
||||
const [searchedQuery, setSearchedQuery] = useState<string | null>(null)
|
||||
const listId = `${useId()}-location-results`
|
||||
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
@@ -47,6 +54,9 @@ export default function LocationSelect({ value, onChange, placeholder, style, pl
|
||||
const trimmed = query.trim()
|
||||
if (trimmed.length < 3 || (value && trimmed === value.name)) {
|
||||
setResults([])
|
||||
setLoading(false)
|
||||
setSearchError(false)
|
||||
setSearchedQuery(null)
|
||||
return
|
||||
}
|
||||
// Clearing the timer does nothing to a request already out: an answer for
|
||||
@@ -54,13 +64,20 @@ export default function LocationSelect({ value, onChange, placeholder, style, pl
|
||||
let stale = false
|
||||
debounceRef.current = setTimeout(async () => {
|
||||
setLoading(true)
|
||||
setSearchError(false)
|
||||
setSearchedQuery(null)
|
||||
try {
|
||||
const data = await mapsApi.search(trimmed, placeLang, locationBias)
|
||||
if (stale) return
|
||||
setResults(data.places || [])
|
||||
setHighlight(-1)
|
||||
setSearchedQuery(trimmed)
|
||||
} catch {
|
||||
if (!stale) setResults([])
|
||||
if (!stale) {
|
||||
setResults([])
|
||||
setSearchError(true)
|
||||
setSearchedQuery(trimmed)
|
||||
}
|
||||
} finally {
|
||||
if (!stale) setLoading(false)
|
||||
}
|
||||
@@ -79,13 +96,21 @@ export default function LocationSelect({ value, onChange, placeholder, style, pl
|
||||
onChange(loc)
|
||||
setQuery(loc.name)
|
||||
setOpen(false)
|
||||
setResults([])
|
||||
resetSearch()
|
||||
}
|
||||
|
||||
const clear = () => {
|
||||
onChange(null)
|
||||
setQuery('')
|
||||
resetSearch()
|
||||
}
|
||||
|
||||
function resetSearch() {
|
||||
if (debounceRef.current) clearTimeout(debounceRef.current)
|
||||
setResults([])
|
||||
setLoading(false)
|
||||
setSearchError(false)
|
||||
setSearchedQuery(null)
|
||||
}
|
||||
|
||||
// The trip's places stand in for the search below three characters. Derived rather
|
||||
@@ -96,6 +121,30 @@ export default function LocationSelect({ value, onChange, placeholder, style, pl
|
||||
const rows = showPicks
|
||||
? (places ?? []).filter(p => !typed || p.name.toLowerCase().includes(typed.toLowerCase()))
|
||||
: results
|
||||
const showNoResults =
|
||||
showSearchStatus && !showPicks && searchedQuery === typed && rows.length === 0 && !loading && !searchError
|
||||
const showError = showSearchStatus && searchError && searchedQuery === typed
|
||||
const listOpen = open && ((loading && !showPicks) || rows.length > 0 || showNoResults || showError)
|
||||
const accessibleLabel = ariaLabel ?? placeholder ?? t('reservations.searchLocation')
|
||||
const statusLine = showError ? (
|
||||
<div role="alert" className="text-content-faint" style={{ padding: 10, fontSize: 'calc(12px * var(--fs-scale-body, 1))' }}>
|
||||
{t('common.error')}
|
||||
</div>
|
||||
) : showNoResults ? (
|
||||
<div role="status" className="text-content-faint" style={{ padding: 10, fontSize: 'calc(12px * var(--fs-scale-body, 1))' }}>
|
||||
{t('help.center.searchEmpty', { query: typed })}
|
||||
</div>
|
||||
) : null
|
||||
|
||||
const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
// Escape closes the list even while it only shows a status line.
|
||||
if (e.key === 'Escape' && open) {
|
||||
e.preventDefault()
|
||||
setOpen(false)
|
||||
return
|
||||
}
|
||||
handleKey(e, rows, pick)
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={wrapRef} style={{ position: 'relative', ...style }}>
|
||||
@@ -103,14 +152,27 @@ export default function LocationSelect({ value, onChange, placeholder, style, pl
|
||||
icon={<MapPin size={14} className="text-content-faint" style={{ flexShrink: 0 }} />}
|
||||
query={query}
|
||||
placeholder={placeholder ?? t('reservations.searchLocation')}
|
||||
onType={(text) => { setQuery(text); setOpen(true); setHighlight(-1); if (value) onChange(null) }}
|
||||
onType={(text) => { setQuery(text); setOpen(true); setHighlight(-1); setSearchError(false); setSearchedQuery(null); if (value) onChange(null) }}
|
||||
onOpen={() => setOpen(true)}
|
||||
onKeyDown={(e) => handleKey(e, rows, pick)}
|
||||
onKeyDown={onKeyDown}
|
||||
onClear={value ? clear : undefined}
|
||||
inputAria={showSearchStatus ? {
|
||||
role: 'combobox',
|
||||
'aria-label': accessibleLabel,
|
||||
'aria-autocomplete': 'list',
|
||||
'aria-expanded': listOpen,
|
||||
'aria-controls': listOpen ? listId : undefined,
|
||||
'aria-activedescendant': listOpen && highlight >= 0 ? `${listId}-option-${highlight}` : undefined,
|
||||
} : undefined}
|
||||
/>
|
||||
|
||||
{open && (
|
||||
<SuggestionList loading={loading && !showPicks} rowCount={rows.length}>
|
||||
<SuggestionList
|
||||
loading={loading && !showPicks}
|
||||
rowCount={rows.length}
|
||||
status={statusLine}
|
||||
listbox={showSearchStatus ? { id: listId, label: accessibleLabel } : undefined}
|
||||
>
|
||||
{rows.map((r, i) => (
|
||||
<SuggestionRow
|
||||
key={showPicks ? `pick:${r.name}:${r.lat}:${r.lng}` : `${r.osm_id || r.google_place_id || i}`}
|
||||
@@ -118,6 +180,7 @@ export default function LocationSelect({ value, onChange, placeholder, style, pl
|
||||
onPick={() => pick(r)}
|
||||
onHover={() => setHighlight(i)}
|
||||
align="flex-start"
|
||||
optionId={showSearchStatus ? `${listId}-option-${i}` : undefined}
|
||||
>
|
||||
<PlaceSuggestion name={r.name} address={r.address} />
|
||||
</SuggestionRow>
|
||||
|
||||
@@ -15,6 +15,8 @@ interface SuggestionInputBoxProps {
|
||||
onKeyDown: (e: React.KeyboardEvent<HTMLInputElement>) => void;
|
||||
/** Shown as the clear button while a value is picked. */
|
||||
onClear?: () => void;
|
||||
/** Combobox wiring for a field that announces its list (role, aria-expanded, ...). */
|
||||
inputAria?: React.AriaAttributes & { role?: React.AriaRole };
|
||||
}
|
||||
|
||||
export function SuggestionInputBox({
|
||||
@@ -25,6 +27,7 @@ export function SuggestionInputBox({
|
||||
onOpen,
|
||||
onKeyDown,
|
||||
onClear,
|
||||
inputAria,
|
||||
}: SuggestionInputBoxProps) {
|
||||
return (
|
||||
<div
|
||||
@@ -41,6 +44,7 @@ export function SuggestionInputBox({
|
||||
{icon}
|
||||
<input
|
||||
type="text"
|
||||
{...inputAria}
|
||||
value={query}
|
||||
placeholder={placeholder}
|
||||
onChange={(e) => onType(e.target.value)}
|
||||
@@ -76,13 +80,17 @@ interface SuggestionListProps {
|
||||
/** Shows the loading line while there are no rows yet. */
|
||||
loading: boolean;
|
||||
rowCount: number;
|
||||
/** A line above the rows, such as "nothing found"; keeps the list open without rows. */
|
||||
status?: React.ReactNode;
|
||||
/** Wraps the rows in a listbox when the field is a combobox. */
|
||||
listbox?: { id: string; label: string };
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
/** The floating list under the field. Rendered only while it is loading or has rows; the caller checks `open`. */
|
||||
export function SuggestionList({ loading, rowCount, children }: SuggestionListProps) {
|
||||
/** The floating list under the field. Rendered only while it is loading, has rows or a status; the caller checks `open`. */
|
||||
export function SuggestionList({ loading, rowCount, status, listbox, children }: SuggestionListProps) {
|
||||
const { t } = useTranslation();
|
||||
if (!loading && rowCount === 0) return null;
|
||||
if (!loading && rowCount === 0 && !status) return null;
|
||||
return (
|
||||
<div
|
||||
className="bg-surface-card"
|
||||
@@ -99,11 +107,22 @@ export function SuggestionList({ loading, rowCount, children }: SuggestionListPr
|
||||
}}
|
||||
>
|
||||
{loading && rowCount === 0 && (
|
||||
<div className="text-content-faint" style={{ padding: 10, fontSize: 'calc(12px * var(--fs-scale-body, 1))' }}>
|
||||
<div
|
||||
role={listbox ? 'status' : undefined}
|
||||
className="text-content-faint"
|
||||
style={{ padding: 10, fontSize: 'calc(12px * var(--fs-scale-body, 1))' }}
|
||||
>
|
||||
{t('common.loading')}
|
||||
</div>
|
||||
)}
|
||||
{children}
|
||||
{status}
|
||||
{listbox ? (
|
||||
<div id={listbox.id} role="listbox" aria-label={listbox.label}>
|
||||
{children}
|
||||
</div>
|
||||
) : (
|
||||
children
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -114,13 +133,18 @@ interface SuggestionRowProps {
|
||||
onHover: () => void;
|
||||
/** How the row lines up its icon and text. */
|
||||
align: 'center' | 'flex-start';
|
||||
/** Set inside a listbox: the row becomes an option the input can point at. */
|
||||
optionId?: string;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export function SuggestionRow({ active, onPick, onHover, align, children }: SuggestionRowProps) {
|
||||
export function SuggestionRow({ active, onPick, onHover, align, optionId, children }: SuggestionRowProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
id={optionId}
|
||||
role={optionId ? 'option' : undefined}
|
||||
aria-selected={optionId ? active : undefined}
|
||||
onClick={onPick}
|
||||
onMouseEnter={onHover}
|
||||
className={`text-content ${active ? 'bg-surface-hover' : 'bg-transparent'}`}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import type { TourListItem } from '@trek/shared';
|
||||
import { Bike, Footprints, Mountain, Route } from 'lucide-react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen } from '../../../tests/helpers/render';
|
||||
import TourDayRowFacts, { TourDayRowIcon, tourDayRowIcon } from './TourDayRowFacts';
|
||||
|
||||
const tour: TourListItem = {
|
||||
place_id: 42,
|
||||
name: 'Ridge',
|
||||
tour_type: 'hike',
|
||||
distance: 4,
|
||||
elevation_gain: 100,
|
||||
elevation_loss: 80,
|
||||
duration: 53,
|
||||
break_additional_minutes: 10,
|
||||
planned_duration_minutes: null,
|
||||
difficulty: null,
|
||||
wanderer_ref: null,
|
||||
match_confidence: 1,
|
||||
max_hiking_difficulty: 2,
|
||||
planned: true,
|
||||
caution: false,
|
||||
};
|
||||
|
||||
describe('RC-01 Tour day-row facts', () => {
|
||||
it('selects controlled type icons without enabling any types', () => {
|
||||
expect(tourDayRowIcon('hike')).toBe(Mountain);
|
||||
expect(tourDayRowIcon('bike')).toBe(Bike);
|
||||
expect(tourDayRowIcon('walk')).toBe(Footprints);
|
||||
expect(tourDayRowIcon('unknown')).toBe(Route);
|
||||
render(<TourDayRowIcon type="hike" />);
|
||||
expect(screen.getByTestId('plan-tour-icon').querySelector('.lucide-mountain')).toBeTruthy();
|
||||
});
|
||||
|
||||
it.each([false, true])('renders compact facts with accessible meaning (mobile=%s)', (mobile) => {
|
||||
render(<TourDayRowFacts tour={tour} mobile={mobile} />);
|
||||
expect(screen.getByTestId('plan-tour-distance')).toHaveTextContent('4');
|
||||
expect(screen.getByTestId('plan-tour-ascent')).toHaveTextContent('100');
|
||||
expect(screen.getByTestId('trip-plan-tour-walking-time')).toHaveAccessibleName('Walking time: 53 min');
|
||||
expect(screen.getByTestId('trip-plan-tour-breaks')).toHaveAccessibleName('Breaks / additional time: 10 min');
|
||||
expect(screen.getByTestId('trip-plan-tour-planned-duration')).toHaveTextContent('1 h 3 min');
|
||||
expect(screen.queryByText('80 m')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each([null, 0])('omits missing metrics and empty breaks (%s)', (breaks) => {
|
||||
render(
|
||||
<TourDayRowFacts tour={{ ...tour, distance: null, elevation_gain: null, break_additional_minutes: breaks }} />
|
||||
);
|
||||
expect(screen.queryByTestId('plan-tour-distance')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('plan-tour-ascent')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('trip-plan-tour-breaks')).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId('trip-plan-tour-planned-duration')).toHaveTextContent('53 min');
|
||||
});
|
||||
|
||||
it('supports hover, keyboard focus and touch help without opening the containing row', async () => {
|
||||
const openRow = vi.fn();
|
||||
render(
|
||||
<div onClick={openRow}>
|
||||
<TourDayRowFacts tour={tour} />
|
||||
</div>
|
||||
);
|
||||
const walking = screen.getByTestId('trip-plan-tour-walking-time');
|
||||
fireEvent.mouseEnter(walking);
|
||||
expect(await screen.findByRole('tooltip')).toHaveTextContent('Walking time: 53 min');
|
||||
fireEvent.mouseLeave(walking);
|
||||
const matches = vi.spyOn(walking, 'matches').mockImplementation((selector) => selector === ':focus-visible');
|
||||
fireEvent.focus(walking);
|
||||
expect(await screen.findByRole('tooltip')).toHaveTextContent('Walking time: 53 min');
|
||||
fireEvent.blur(walking);
|
||||
matches.mockRestore();
|
||||
fireEvent.click(walking);
|
||||
expect(screen.getByRole('note')).toHaveTextContent('Walking time: 53 min');
|
||||
expect(openRow).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,141 @@
|
||||
import type { TourListItem } from '@trek/shared';
|
||||
import {
|
||||
ArrowUp,
|
||||
Bike,
|
||||
Clock,
|
||||
Footprints,
|
||||
Mountain,
|
||||
Pause,
|
||||
Route,
|
||||
Ruler,
|
||||
Sailboat,
|
||||
type LucideIcon,
|
||||
} from 'lucide-react';
|
||||
import { useId, useState } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { formatDistance, formatElevation } from '../../utils/units';
|
||||
import { Tooltip } from '../shared/Tooltip';
|
||||
import { formatPlannedTourDuration, tourPlannedTimes } from './tourPresentation';
|
||||
|
||||
export function tourDayRowIcon(type: string): LucideIcon {
|
||||
switch (type) {
|
||||
case 'hike':
|
||||
return Mountain;
|
||||
case 'bike':
|
||||
return Bike;
|
||||
case 'walk':
|
||||
return Footprints;
|
||||
case 'kayak':
|
||||
return Sailboat;
|
||||
default:
|
||||
return Route;
|
||||
}
|
||||
}
|
||||
|
||||
export function TourDayRowIcon({ type, size = 27 }: { type: string; size?: number }) {
|
||||
const { t } = useTranslation();
|
||||
const Icon = tourDayRowIcon(type);
|
||||
const known = ['hike', 'bike', 'walk', 'kayak'].includes(type);
|
||||
return (
|
||||
<span
|
||||
data-testid="plan-tour-icon"
|
||||
aria-label={known ? t(`tourTypes.${type}`) : t('tours.mode.tours')}
|
||||
className="grid flex-none place-items-center rounded-full"
|
||||
style={{ width: size, height: size }}
|
||||
>
|
||||
<Icon size={Math.round(size * 0.6)} aria-hidden="true" />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function Fact({
|
||||
icon: Icon,
|
||||
value,
|
||||
label,
|
||||
testId,
|
||||
mobile,
|
||||
}: {
|
||||
icon: LucideIcon;
|
||||
value: string;
|
||||
label: string;
|
||||
testId: string;
|
||||
mobile: boolean;
|
||||
}) {
|
||||
const id = useId();
|
||||
const [open, setOpen] = useState(false);
|
||||
return (
|
||||
<span className="relative inline-flex max-w-full">
|
||||
<Tooltip label={label}>
|
||||
<button
|
||||
type="button"
|
||||
data-testid={testId}
|
||||
aria-label={label}
|
||||
aria-expanded={open}
|
||||
aria-controls={id}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
setOpen((current) => !current);
|
||||
}}
|
||||
onKeyDown={(event) => {
|
||||
event.stopPropagation();
|
||||
if (event.key === 'Escape') setOpen(false);
|
||||
}}
|
||||
className={`inline-flex items-center gap-1 whitespace-nowrap rounded-[6px] px-1.5 py-0.5 text-[0.65625rem] tabular-nums focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent ${mobile ? 'bg-[color:var(--m-ic)] text-m-muted' : 'bg-surface-card text-content-secondary'}`}
|
||||
>
|
||||
<Icon size={11} aria-hidden="true" />
|
||||
{value}
|
||||
</button>
|
||||
</Tooltip>
|
||||
<span
|
||||
id={id}
|
||||
hidden={!open}
|
||||
role="note"
|
||||
className={`absolute start-0 top-full z-30 mt-1 w-40 whitespace-normal rounded-[6px] border p-2 text-[0.6875rem] shadow-sm ${mobile ? 'bg-[color:var(--m-ic)] text-m-ink' : 'border-edge bg-surface-card text-content'}`}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export default function TourDayRowFacts({ tour, mobile = false }: { tour: TourListItem; mobile?: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const unit = useSettingsStore((state) => state.settings.distance_unit);
|
||||
const times = tourPlannedTimes(tour);
|
||||
const facts: Array<{ icon: LucideIcon; value: string; label: string; testId: string }> = [];
|
||||
const add = (icon: LucideIcon, value: string, label: string, testId: string) =>
|
||||
facts.push({ icon, value, label, testId });
|
||||
if (tour.distance != null)
|
||||
add(Ruler, formatDistance(tour.distance, unit), t('tours.detail.distance'), 'plan-tour-distance');
|
||||
if (tour.elevation_gain != null)
|
||||
add(ArrowUp, formatElevation(tour.elevation_gain, unit), t('tours.detail.ascent'), 'plan-tour-ascent');
|
||||
if (times.walkingMinutes != null)
|
||||
add(
|
||||
Footprints,
|
||||
formatPlannedTourDuration(times.walkingMinutes),
|
||||
t('tours.planner.inspector.duration'),
|
||||
'trip-plan-tour-walking-time'
|
||||
);
|
||||
if (times.breakMinutes != null && times.breakMinutes > 0)
|
||||
add(
|
||||
Pause,
|
||||
formatPlannedTourDuration(times.breakMinutes),
|
||||
t('tours.planner.breaksAdditional'),
|
||||
'trip-plan-tour-breaks'
|
||||
);
|
||||
if (times.plannedTotalMinutes != null)
|
||||
add(
|
||||
Clock,
|
||||
formatPlannedTourDuration(times.plannedTotalMinutes),
|
||||
`${t('tours.planner.plannedTotalDuration')}${times.manuallyOverridden ? `, ${t('tours.planner.plannedTotalManual')}` : ''}`,
|
||||
'trip-plan-tour-planned-duration'
|
||||
);
|
||||
return (
|
||||
<span data-testid="plan-tour-facts" className="flex min-w-0 flex-wrap items-center gap-1">
|
||||
{facts.map((fact) => (
|
||||
<Fact key={fact.testId} {...fact} label={`${fact.label}: ${fact.value}`} mobile={mobile} />
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -104,6 +104,43 @@ describe('TourDetailDialog', () => {
|
||||
expect(screen.queryByText('Participants')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('RS-01: shows Tour description and classified HTTPS information link without fetching it', () => {
|
||||
const fetchSpy = vi.spyOn(globalThis, 'fetch')
|
||||
render(
|
||||
<TourDetailDialog
|
||||
{...defaultProps}
|
||||
tour={{ ...tour, description: 'Ridge above the lake', website: 'https://www.komoot.com/tour/42' }}
|
||||
place={{ ...place, description: 'Ridge above the lake', website: 'https://www.komoot.com/tour/42' }}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText('Ridge above the lake')).toBeInTheDocument()
|
||||
const link = screen.getByRole('link', { name: 'Komoot · komoot.com' })
|
||||
expect(link).toHaveAttribute('href', 'https://www.komoot.com/tour/42')
|
||||
expect(link).toHaveAttribute('rel', 'noopener noreferrer nofollow')
|
||||
expect(fetchSpy).not.toHaveBeenCalled()
|
||||
fetchSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('RS-02: labels calculated walking time and planned total as separate values', () => {
|
||||
render(<TourDetailDialog {...defaultProps} tour={{ ...tour, duration: 60, break_additional_minutes: 35, planned_duration_minutes: 125 }} />)
|
||||
|
||||
expect(screen.getByText('Walking time: 1 h')).toBeInTheDocument()
|
||||
expect(screen.getByText('Breaks / additional time: 35 min')).toBeInTheDocument()
|
||||
expect(screen.getByText('Planned total duration: 2 h 5 min · Manual override')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('RS-01: rejects an unsafe legacy Tour website for rendering', () => {
|
||||
render(
|
||||
<TourDetailDialog
|
||||
{...defaultProps}
|
||||
tour={{ ...tour, website: 'javascript:alert(1)' }}
|
||||
place={{ ...place, website: 'javascript:alert(1)' }}
|
||||
/>
|
||||
)
|
||||
expect(screen.queryByRole('link')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('uses existing assignment callbacks for add and remove actions', () => {
|
||||
const { rerender } = render(<TourDetailDialog {...defaultProps} days={[{ id: 7 } as never]} selectedDayId={7} />)
|
||||
fireEvent.click(screen.getByRole('button', { name: /Add to Day/i }))
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { AlertTriangle, Check, ChevronDown, ChevronUp, File, FileImage, FileText, Info, MapPin, Mountain, Navigation, Pencil, Plus, Minus, Upload } from 'lucide-react'
|
||||
import { AlertTriangle, Check, ChevronDown, ChevronUp, ExternalLink, File, FileImage, FileText, Info, MapPin, Mountain, Navigation, Pencil, Plus, Minus, Upload } from 'lucide-react'
|
||||
import Markdown from 'react-markdown'
|
||||
import remarkBreaks from 'remark-breaks'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
@@ -22,7 +22,7 @@ import { analyzeRouteGeometry } from '../../utils/routeGeometry'
|
||||
import { filesForPlace } from '../../utils/placeFiles'
|
||||
import { openFile } from '../../utils/fileDownload'
|
||||
import { getNavigationTargets, navigationTargetLabel, openNavigationTarget } from '../Planner/placeNavigation'
|
||||
import { hikeSourceBadgeLabel, tourSource } from './tourPresentation'
|
||||
import { formatPlannedTourDuration, hikeSourceBadgeLabel, tourPlannedTimes, tourSource, tourWebsitePresentation } from './tourPresentation'
|
||||
import { TourMetricFields, TourNotice, TourTile } from './tourParts'
|
||||
import { useTourPermissions, type TourPermissionProps } from './useTourPermissions'
|
||||
|
||||
@@ -137,6 +137,9 @@ export default function TourDetailDialog({
|
||||
const navigationTargets = getNavigationTargets(place)
|
||||
const navigationLabel = navigationTargets.length === 1 ? navigationTargetLabel(navigationTargets[0], t) : t('inspector.navigation')
|
||||
const source = tourSource(tour)
|
||||
const tourTimes = tourPlannedTimes(tour)
|
||||
const description = tour.description !== undefined ? tour.description : place.description
|
||||
const website = tourWebsitePresentation(tour.website !== undefined ? tour.website : place.website)
|
||||
const colorLabel = place.route_color ? place.route_color.toUpperCase() : t('inspector.trackColorAuto')
|
||||
|
||||
const saveName = async () => {
|
||||
@@ -217,7 +220,27 @@ export default function TourDetailDialog({
|
||||
<div className="mt-2 flex flex-wrap items-center gap-1.5">
|
||||
<SoftPill icon={<Mountain size={11} strokeWidth={2} className="flex-none" style={{ color: trackColor }} />}>{t(`tourTypes.${tour.tour_type}`)}</SoftPill>
|
||||
{tour.difficulty && <SoftPill>{t('tours.detail.difficulty')}: {tour.difficulty}</SoftPill>}
|
||||
{tour.duration != null && <TimePill>{t('tours.durationMinutes', { count: tour.duration })}</TimePill>}
|
||||
{tourTimes.walkingMinutes != null && (
|
||||
<TimePill>
|
||||
<span aria-label={`${t('tours.planner.inspector.duration')}: ${formatPlannedTourDuration(tourTimes.walkingMinutes)}`}>
|
||||
{t('tours.planner.inspector.duration')}: {formatPlannedTourDuration(tourTimes.walkingMinutes)}
|
||||
</span>
|
||||
</TimePill>
|
||||
)}
|
||||
{tourTimes.breakMinutes != null && (
|
||||
<TimePill>
|
||||
<span aria-label={`${t('tours.planner.breaksAdditional')}: ${formatPlannedTourDuration(tourTimes.breakMinutes)}`}>
|
||||
{t('tours.planner.breaksAdditional')}: {formatPlannedTourDuration(tourTimes.breakMinutes)}
|
||||
</span>
|
||||
</TimePill>
|
||||
)}
|
||||
{tourTimes.plannedTotalMinutes != null && (
|
||||
<TimePill>
|
||||
<span aria-label={`${t('tours.planner.plannedTotalDuration')}: ${formatPlannedTourDuration(tourTimes.plannedTotalMinutes)}${tourTimes.manuallyOverridden ? `, ${t('tours.planner.plannedTotalManual')}` : ''}`}>
|
||||
{t('tours.planner.plannedTotalDuration')}: {formatPlannedTourDuration(tourTimes.plannedTotalMinutes)}{tourTimes.manuallyOverridden ? ` · ${t('tours.planner.plannedTotalManual')}` : ''}
|
||||
</span>
|
||||
</TimePill>
|
||||
)}
|
||||
<SoftPill>{hikeSourceBadgeLabel(tour, t)}</SoftPill>
|
||||
{tour.caution && (
|
||||
<Tooltip label={t('tours.caution.tooltip')}>
|
||||
@@ -313,7 +336,15 @@ export default function TourDetailDialog({
|
||||
)}
|
||||
</DialogSection>
|
||||
|
||||
{place.description && <DialogSection className="flex-none" label={t('places.formDescription')}><MarkdownBox>{place.description}</MarkdownBox></DialogSection>}
|
||||
{description && <DialogSection className="flex-none" label={t('places.formDescription')}><MarkdownBox>{description}</MarkdownBox></DialogSection>}
|
||||
{website && (
|
||||
<DialogSection className="flex-none" label={t('places.formWebsite')}>
|
||||
<a href={website.href} target="_blank" rel="noopener noreferrer nofollow" className="inline-flex max-w-full items-center gap-1.5 text-content hover:underline">
|
||||
<ExternalLink size={13} className="flex-none" />
|
||||
<span className="truncate">{website.provider ? `${website.provider} · ${website.domain}` : `${t('places.formWebsite')} · ${website.domain}`}</span>
|
||||
</a>
|
||||
</DialogSection>
|
||||
)}
|
||||
{place.notes && <DialogSection className="flex-none" label={t('places.formNotes')}><MarkdownBox>{place.notes}</MarkdownBox></DialogSection>}
|
||||
{assignment?.notes && <DialogSection className="flex-none" label={t('places.assignmentNotes')}><MarkdownBox>{assignment.notes}</MarkdownBox></DialogSection>}
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { useId, type ReactNode } from 'react'
|
||||
import type { TourListItem } from '@trek/shared'
|
||||
import { fs } from '../shared/DialogShell'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { TourFactPills, TourTile } from './tourParts'
|
||||
import { tourWebsitePresentation } from './tourPresentation'
|
||||
|
||||
interface TourListRowProps {
|
||||
tour: TourListItem
|
||||
@@ -14,8 +16,10 @@ interface TourListRowProps {
|
||||
|
||||
/** A tour in a list, shaped like a place row: tile, name, its facts as pills and the day action on the right. */
|
||||
export default function TourListRow({ tour, selected = false, disabled = false, onSelect, action, children }: TourListRowProps) {
|
||||
const { t } = useTranslation()
|
||||
const nameId = useId()
|
||||
const tone = selected ? 'bg-surface-selected' : disabled ? '' : 'hover:bg-surface-hover'
|
||||
const website = tourWebsitePresentation(tour.website)
|
||||
return (
|
||||
<li
|
||||
role="option"
|
||||
@@ -38,6 +42,16 @@ export default function TourListRow({ tour, selected = false, disabled = false,
|
||||
<div className="min-w-0 flex-1 pt-px">
|
||||
<span id={nameId} className="block min-w-0 truncate font-semibold leading-tight text-content" style={fs(13, 'body')}>{tour.name}</span>
|
||||
<TourFactPills tour={tour} className="mt-1.5" />
|
||||
{tour.description && (
|
||||
<div data-testid="tour-description-preview" className="mt-1 overflow-hidden text-ellipsis text-content-faint" style={{ ...fs(11), lineHeight: 1.25, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical' }}>
|
||||
{tour.description}
|
||||
</div>
|
||||
)}
|
||||
{website && (
|
||||
<div className="mt-1 truncate text-content-faint" style={fs(10.5)}>
|
||||
{website.provider ? `${website.provider} · ${website.domain}` : `${t('places.formWebsite')} · ${website.domain}`}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{action && (
|
||||
<div data-testid="tour-action-row" role="presentation" className="flex flex-none items-center gap-1.5 pt-1" onClick={event => event.stopPropagation()}>
|
||||
|
||||
@@ -56,6 +56,16 @@ describe('ToursSidebar', () => {
|
||||
expect(row).toHaveClass('bg-surface-selected')
|
||||
})
|
||||
|
||||
it('RS-01: previews the Tour description and classified information-link host', () => {
|
||||
const listed = { ...tour, description: 'A quiet path above the lake', website: 'https://www.komoot.com/tour/42', planned_duration_minutes: 95 }
|
||||
render(<ToursSidebar tripId={1} days={[]} tours={[listed]} onAssignToDay={vi.fn()} onSelectTour={vi.fn()} />)
|
||||
const row = screen.getByRole('option', { name: /Selected ridge walk/i })
|
||||
expect(row).toHaveTextContent('A quiet path above the lake')
|
||||
expect(row).toHaveTextContent('Komoot · komoot.com')
|
||||
expect(row).toHaveTextContent('1 h 35 min')
|
||||
expect(row.querySelector('[data-testid="tour-description-preview"]')).toHaveStyle({ WebkitLineClamp: '2' })
|
||||
})
|
||||
|
||||
it('selects the tour from keyboard activation', () => {
|
||||
const onSelectTour = vi.fn()
|
||||
render(<ToursSidebar tripId={1} days={[]} tours={[tour]} selectedPlaceId={null} onAssignToDay={vi.fn()} onSelectTour={onSelectTour} />)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { act, useState } from 'react'
|
||||
import { fireEvent, render, screen, waitFor } from '../../../../tests/helpers/render'
|
||||
import { fireEvent, render, screen, waitFor, within } from '../../../../tests/helpers/render';
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { TourListItem } from '@trek/shared'
|
||||
@@ -48,6 +48,20 @@ function planner(overrides: Partial<TourPlannerController> = {}): TourPlannerCon
|
||||
maxHikingDifficulty: 2,
|
||||
setMaxHikingDifficulty: vi.fn(),
|
||||
name: '',
|
||||
description: '',
|
||||
setDescription: vi.fn(),
|
||||
website: '',
|
||||
setWebsite: vi.fn(),
|
||||
websiteInvalid: false,
|
||||
plannedDurationMinutes: null,
|
||||
setPlannedDurationMinutes: vi.fn(),
|
||||
plannedDurationInvalid: false,
|
||||
breakAdditionalMinutes: null,
|
||||
setBreakAdditionalMinutes: vi.fn(),
|
||||
breakAdditionalInvalid: false,
|
||||
walkingDurationMinutes: null,
|
||||
plannedTotalMinutes: null,
|
||||
plannedTotalInvalid: false,
|
||||
startNewTour: vi.fn(),
|
||||
newTourConfirmationOpen: false,
|
||||
cancelNewTour: vi.fn(),
|
||||
@@ -65,6 +79,9 @@ function planner(overrides: Partial<TourPlannerController> = {}): TourPlannerCon
|
||||
editingPlaceId: null,
|
||||
openingTourId: null,
|
||||
openTour: vi.fn().mockResolvedValue(true),
|
||||
reorderWaypoint: vi.fn(),
|
||||
moveWaypoint: vi.fn(),
|
||||
removeWaypoint: vi.fn(),
|
||||
saveOutcome: null,
|
||||
hasUnsavedChanges: false,
|
||||
discard: vi.fn(),
|
||||
@@ -92,6 +109,16 @@ beforeEach(() => {
|
||||
})
|
||||
|
||||
describe('TourPlannerToursRail', () => {
|
||||
it('RS-02: keeps calculated Walking time visible in the right Tour metrics rail', () => {
|
||||
render(<TourPlannerToursRail planner={planner({
|
||||
mode: { type: 'new-draft' }, durationSeconds: 4800,
|
||||
walkingDurationMinutes: 80, breakAdditionalMinutes: 50, plannedTotalMinutes: 130,
|
||||
})} tours={[tour]} {...railProps} />)
|
||||
|
||||
expect(screen.getByText('Walking time')).toBeInTheDocument()
|
||||
expect(screen.getByText('1 h 20 min')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('disables saved-tour switching and Plan another while a Save is pending', () => {
|
||||
const controller = planner({
|
||||
isSaving: true,
|
||||
@@ -289,6 +316,227 @@ describe('TourPlannerToursRail', () => {
|
||||
})
|
||||
|
||||
describe('TourPlannerRail', () => {
|
||||
it('RS-01: edits Tour description and HTTPS information link without exposing editable fields in GPX mode', () => {
|
||||
const setDescription = vi.fn()
|
||||
const setWebsite = vi.fn()
|
||||
const { rerender } = render(
|
||||
<TourPlannerRail
|
||||
planner={planner({ mode: { type: 'new-draft' }, hasUnsavedChanges: true, setDescription, setWebsite })}
|
||||
/>
|
||||
)
|
||||
const description = screen.getByLabelText('Description')
|
||||
const website = screen.getByLabelText('Website')
|
||||
fireEvent.change(description, { target: { value: 'A quiet ridge route' } })
|
||||
fireEvent.change(website, { target: { value: 'https://www.komoot.com/tour/42' } })
|
||||
expect(setDescription).toHaveBeenCalledWith('A quiet ridge route')
|
||||
expect(setWebsite).toHaveBeenCalledWith('https://www.komoot.com/tour/42')
|
||||
|
||||
rerender(
|
||||
<TourPlannerRail
|
||||
planner={planner({
|
||||
mode: { type: 'view-gpx', placeId: 42, tour },
|
||||
readOnlyGpxTour: { tour, routeGeometry: null },
|
||||
waypoints: [],
|
||||
websiteInvalid: true,
|
||||
})}
|
||||
/>
|
||||
)
|
||||
expect(screen.queryByLabelText('Description')).not.toBeInTheDocument()
|
||||
expect(screen.queryByLabelText('Website')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('RS-02: edits breaks and planned total directly, and clearing total returns it to automatic', () => {
|
||||
const setPlannedDurationMinutes = vi.fn()
|
||||
const setBreakAdditionalMinutes = vi.fn()
|
||||
const controller = planner({
|
||||
mode: { type: 'new-draft' }, hasUnsavedChanges: true, durationSeconds: 3600,
|
||||
walkingDurationMinutes: 60, breakAdditionalMinutes: 35, setBreakAdditionalMinutes,
|
||||
plannedDurationMinutes: null, plannedTotalMinutes: 95, setPlannedDurationMinutes,
|
||||
})
|
||||
const { rerender } = render(<TourPlannerRail planner={controller} />)
|
||||
|
||||
expect(screen.queryByTestId('tour-planner-walking-time')).not.toBeInTheDocument()
|
||||
expect(screen.getByTestId('tour-planner-time-grid')).toHaveClass('grid')
|
||||
expect(screen.getByTestId('tour-planner-time-grid')).toHaveClass('grid-cols-[repeat(auto-fit,minmax(min(100%,12rem),1fr))]')
|
||||
const breaks = screen.getByLabelText('Breaks / additional time')
|
||||
expect(breaks).toHaveValue(35)
|
||||
fireEvent.change(breaks, { target: { value: '50' } })
|
||||
expect(setBreakAdditionalMinutes).toHaveBeenCalledWith(50)
|
||||
fireEvent.change(breaks, { target: { value: '' } })
|
||||
expect(setBreakAdditionalMinutes).toHaveBeenLastCalledWith(null)
|
||||
fireEvent.change(breaks, { target: { value: '50' } })
|
||||
const input = screen.getByLabelText('Planned total duration')
|
||||
expect(input).toHaveValue(95)
|
||||
expect(input).toHaveStyle({ width: '6rem' })
|
||||
expect(screen.getByText('Calculated total')).toBeInTheDocument()
|
||||
expect(controller.durationSeconds).toBe(3600)
|
||||
fireEvent.change(input, { target: { value: '125' } })
|
||||
expect(setPlannedDurationMinutes).toHaveBeenCalledWith(125)
|
||||
|
||||
rerender(<TourPlannerRail planner={planner({
|
||||
mode: { type: 'new-draft' }, hasUnsavedChanges: true, plannedDurationMinutes: 125,
|
||||
setPlannedDurationMinutes,
|
||||
plannedTotalMinutes: 125, walkingDurationMinutes: 60, breakAdditionalMinutes: 35,
|
||||
})} />)
|
||||
const overriddenInput = screen.getByLabelText(/Planned total duration/)
|
||||
expect(overriddenInput).toHaveValue(125)
|
||||
expect(document.querySelector('label[for="tour-planner-planned-duration"]')).toHaveTextContent('Manual override')
|
||||
fireEvent.change(overriddenInput, { target: { value: '' } })
|
||||
expect(setPlannedDurationMinutes).toHaveBeenCalledWith(null)
|
||||
|
||||
rerender(<TourPlannerRail planner={planner({
|
||||
mode: { type: 'new-draft' }, hasUnsavedChanges: true, plannedDurationMinutes: 1441,
|
||||
plannedDurationInvalid: true,
|
||||
})} />)
|
||||
expect(screen.getByLabelText(/Planned total duration/)).toHaveAttribute('aria-invalid', 'true')
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('Enter a whole value from 0 to 1,440 minutes.')
|
||||
|
||||
rerender(<TourPlannerRail planner={planner({
|
||||
mode: { type: 'new-draft' }, hasUnsavedChanges: true, breakAdditionalMinutes: 1441,
|
||||
breakAdditionalInvalid: true,
|
||||
})} />)
|
||||
expect(screen.getByLabelText('Breaks / additional time')).toHaveAttribute('aria-invalid', 'true')
|
||||
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 () => {
|
||||
render(<TourPlannerRail planner={planner({
|
||||
mode: { type: 'new-draft' }, hasUnsavedChanges: true, walkingDurationMinutes: 80,
|
||||
breakAdditionalMinutes: 50, plannedTotalMinutes: 130,
|
||||
})} />)
|
||||
|
||||
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).toHaveClass('focus-visible:outline')
|
||||
const matches = vi.spyOn(breaksInfo, 'matches').mockImplementation(selector => selector === ':focus-visible')
|
||||
fireEvent.focus(breaksInfo)
|
||||
expect(await screen.findByRole('tooltip')).toHaveTextContent('Optional whole minutes added to calculated walking time.')
|
||||
fireEvent.blur(breaksInfo)
|
||||
matches.mockRestore()
|
||||
fireEvent.click(breaksInfo)
|
||||
expect(breaksInfo).toHaveAttribute('aria-expanded', 'true')
|
||||
expect(screen.getByRole('note')).toHaveTextContent('Optional whole minutes added to calculated walking time.')
|
||||
|
||||
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()
|
||||
})
|
||||
|
||||
it('RS-01: marks unsafe website values invalid and does not offer Save', () => {
|
||||
render(<TourPlannerRail planner={planner({ mode: { type: 'new-draft' }, hasUnsavedChanges: true, website: 'http://example.org', websiteInvalid: true })} />)
|
||||
expect(screen.getByLabelText('Website')).toHaveAttribute('aria-invalid', 'true')
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('TREK cannot use that address.')
|
||||
})
|
||||
|
||||
const reorderWaypoints = [
|
||||
{ id: 'a', lat: 48, lng: 11, role: 'start' as const },
|
||||
{ id: 'b', lat: 48.1, lng: 11.1, role: 'via' as const },
|
||||
{ id: 'c', lat: 48.2, lng: 11.2, role: 'via' as const },
|
||||
{ id: 'd', lat: 48.3, lng: 11.3, role: 'end' as const },
|
||||
];
|
||||
|
||||
it('RC-07: dragging before and after rows commits only on drop by stable waypoint ids', () => {
|
||||
const reorderWaypoint = vi.fn();
|
||||
render(
|
||||
<TourPlannerRail
|
||||
planner={planner({
|
||||
mode: { type: 'new-draft' },
|
||||
hasUnsavedChanges: true,
|
||||
waypoints: reorderWaypoints,
|
||||
reorderWaypoint,
|
||||
})}
|
||||
/>
|
||||
);
|
||||
const rows = screen.getAllByTestId('tour-planner-waypoint-row');
|
||||
const transfer = { setData: vi.fn(), getData: vi.fn(() => 'a'), effectAllowed: 'all', dropEffect: 'move' };
|
||||
const dispatchDrag = (type: string, target: HTMLElement, dataTransfer: typeof transfer, clientY = 0) => {
|
||||
const event = new Event(type, { bubbles: true, cancelable: true });
|
||||
Object.defineProperty(event, 'dataTransfer', { value: dataTransfer });
|
||||
Object.defineProperty(event, 'clientY', { value: clientY });
|
||||
fireEvent(target, event);
|
||||
};
|
||||
for (const row of [rows[1], rows[2]]) {
|
||||
Object.defineProperty(row, 'getBoundingClientRect', {
|
||||
configurable: true,
|
||||
value: () => ({
|
||||
top: 0,
|
||||
bottom: 20,
|
||||
height: 20,
|
||||
left: 0,
|
||||
right: 100,
|
||||
width: 100,
|
||||
x: 0,
|
||||
y: 0,
|
||||
toJSON: () => ({}),
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
dispatchDrag('dragstart', within(rows[0]).getByTestId('tour-planner-waypoint-drag-handle'), transfer);
|
||||
dispatchDrag('dragover', rows[2], transfer, 1);
|
||||
expect(reorderWaypoint).not.toHaveBeenCalled();
|
||||
dispatchDrag('drop', rows[2], transfer, 1);
|
||||
expect(reorderWaypoint).toHaveBeenCalledOnce();
|
||||
expect(reorderWaypoint).toHaveBeenLastCalledWith('a', 'c', 'before');
|
||||
|
||||
reorderWaypoint.mockClear();
|
||||
const lastTransfer = { ...transfer, getData: vi.fn(() => 'd') };
|
||||
dispatchDrag('dragstart', within(rows[3]).getByTestId('tour-planner-waypoint-drag-handle'), lastTransfer);
|
||||
dispatchDrag('dragover', rows[1], lastTransfer, 15);
|
||||
expect(reorderWaypoint).not.toHaveBeenCalled();
|
||||
dispatchDrag('drop', rows[1], lastTransfer, 15);
|
||||
expect(reorderWaypoint).toHaveBeenCalledOnce();
|
||||
expect(reorderWaypoint).toHaveBeenLastCalledWith('d', 'b', 'after');
|
||||
});
|
||||
|
||||
it('RC-07: cancelled drags do not reorder and keyboard arrow controls remain buttons', async () => {
|
||||
const user = userEvent.setup();
|
||||
const reorderWaypoint = vi.fn();
|
||||
const moveWaypoint = vi.fn();
|
||||
render(
|
||||
<TourPlannerRail
|
||||
planner={planner({
|
||||
mode: { type: 'new-draft' },
|
||||
hasUnsavedChanges: true,
|
||||
waypoints: reorderWaypoints,
|
||||
reorderWaypoint,
|
||||
moveWaypoint,
|
||||
})}
|
||||
/>
|
||||
);
|
||||
const rows = screen.getAllByTestId('tour-planner-waypoint-row');
|
||||
const transfer = { setData: vi.fn(), getData: vi.fn(() => 'a'), effectAllowed: 'all', dropEffect: 'move' };
|
||||
Object.defineProperty(rows[2], 'getBoundingClientRect', {
|
||||
configurable: true,
|
||||
value: () => ({
|
||||
top: 0,
|
||||
bottom: 20,
|
||||
height: 20,
|
||||
left: 0,
|
||||
right: 100,
|
||||
width: 100,
|
||||
x: 0,
|
||||
y: 0,
|
||||
toJSON: () => ({}),
|
||||
}),
|
||||
});
|
||||
|
||||
fireEvent.dragStart(within(rows[0]).getByTestId('tour-planner-waypoint-drag-handle'), { dataTransfer: transfer });
|
||||
fireEvent.dragOver(rows[2], { dataTransfer: transfer, clientY: -1 });
|
||||
fireEvent.dragEnd(rows[0], { dataTransfer: transfer });
|
||||
expect(reorderWaypoint).not.toHaveBeenCalled();
|
||||
|
||||
const moveDown = screen.getAllByRole('button', { name: 'Move waypoint down' })[0];
|
||||
expect(moveDown).toBeEnabled();
|
||||
moveDown.focus();
|
||||
await user.keyboard(' ');
|
||||
expect(moveWaypoint).toHaveBeenCalledWith('a', 1);
|
||||
expect(reorderWaypoint).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('disables draft mutation and replacement controls while saving', () => {
|
||||
const controller = planner({
|
||||
mode: { type: 'new-draft' },
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useRef, useState, type ReactNode } from 'react'
|
||||
import { useId, useRef, useState, type ReactNode } from 'react'
|
||||
import type { TourListItem } from '@trek/shared'
|
||||
import { AlertTriangle, ArrowDown, ArrowLeft, ArrowUp, CheckCircle2, Info, MapPin, Plus, Redo2, RotateCcw, Save, ShieldAlert, Trash2, Undo2 } from 'lucide-react'
|
||||
import { AlertTriangle, ArrowDown, ArrowLeft, ArrowUp, CheckCircle2, GripVertical, Info, MapPin, Plus, Redo2, RotateCcw, Save, ShieldAlert, Trash2, Undo2 } from 'lucide-react'
|
||||
import type { Day } from '../../../types'
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import { useSettingsStore } from '../../../store/settingsStore'
|
||||
@@ -16,7 +16,7 @@ import { BOX } from '../../Planner/bookings/bookingParts'
|
||||
import { BarButton, SoftPill } from '../../Planner/planParts'
|
||||
import TourListRow from '../TourListRow'
|
||||
import ElevationProfile from '../../shared/ElevationProfile'
|
||||
import { hikeSourceBadgeLabel, tourSource } from '../tourPresentation'
|
||||
import { formatPlannedTourDuration, hikeSourceBadgeLabel, tourSource } from '../tourPresentation'
|
||||
import { FoldButton, TourDayMenu, TourMetricFields, TourNotice, TourSection } from '../tourParts'
|
||||
import type { DistanceIndexedProfileSample, RouteProfileFocus } from '../../../utils/routeGeometry'
|
||||
import type { TourPlannerController, TourPlannerStatus } from './useTourPlanner'
|
||||
@@ -62,12 +62,38 @@ 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)
|
||||
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>
|
||||
)
|
||||
}
|
||||
|
||||
export function TourPlannerRail({ planner, canEdit: editPermission, canAssign: assignPermission }: { planner: TourPlannerController } & TourPermissionProps) {
|
||||
const { canEdit } = useTourPermissions({ canEdit: editPermission ?? planner.canEdit, canAssign: assignPermission ?? planner.canAssign })
|
||||
const { t } = useTranslation()
|
||||
const distanceUnit = useSettingsStore(state => state.settings.distance_unit)
|
||||
const [confirmDiscard, setConfirmDiscard] = useState(false)
|
||||
const [pendingDifficulty, setPendingDifficulty] = useState<1 | 2 | 3 | 4 | 5 | 6 | null>(null)
|
||||
const [draggedWaypointId, setDraggedWaypointId] = useState<string | null>(null);
|
||||
const [dropTarget, setDropTarget] = useState<{ id: string; placement: 'before' | 'after' } | null>(null);
|
||||
const alpineAcknowledged = useRef(false)
|
||||
const isSaving = planner.isSaving
|
||||
const statusKey = isSaving ? STATUS_KEY.saving : STATUS_KEY[planner.status]
|
||||
@@ -179,6 +205,111 @@ export function TourPlannerRail({ planner, canEdit: editPermission, canAssign: a
|
||||
className={INPUT}
|
||||
/>
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<label className={LABEL} htmlFor="tour-planner-description">{t('places.formDescription')}</label>
|
||||
<textarea
|
||||
id="tour-planner-description"
|
||||
disabled={!canEdit || isSaving}
|
||||
value={planner.description}
|
||||
onChange={event => { if (canEdit && !isSaving) planner.setDescription(event.target.value) }}
|
||||
maxLength={2000}
|
||||
rows={3}
|
||||
className={`${INPUT} min-h-[72px] resize-y`}
|
||||
/>
|
||||
</div>
|
||||
<TourSection label={t('tours.planner.plannedTotalDuration')}>
|
||||
<div data-testid="tour-planner-time-grid" className="grid grid-cols-[repeat(auto-fit,minmax(min(100%,12rem),1fr))] gap-3">
|
||||
<div className="min-w-0">
|
||||
<div className="mb-[5px] flex min-w-0 items-center gap-1">
|
||||
<label className={`${LABEL} mb-0`} htmlFor="tour-planner-breaks">{t('tours.planner.breaksAdditional')}</label>
|
||||
<DurationInfo
|
||||
label={t('tours.planner.breaksAdditionalInfoLabel')}
|
||||
description={t('tours.planner.breaksAdditionalInfo')}
|
||||
/>
|
||||
</div>
|
||||
<input
|
||||
id="tour-planner-breaks"
|
||||
aria-label={t('tours.planner.breaksAdditional')}
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
min={0}
|
||||
max={1440}
|
||||
step={1}
|
||||
disabled={!canEdit || isSaving}
|
||||
value={planner.breakAdditionalMinutes ?? ''}
|
||||
onChange={event => { if (canEdit && !isSaving) planner.setBreakAdditionalMinutes(event.target.value === '' ? null : Number(event.target.value)) }}
|
||||
aria-invalid={planner.breakAdditionalInvalid || undefined}
|
||||
aria-describedby={`tour-planner-breaks-hint${planner.breakAdditionalInvalid ? ' tour-planner-breaks-error' : ''}`}
|
||||
className={INPUT}
|
||||
/>
|
||||
<span id="tour-planner-breaks-hint" className="mt-1 block text-content-faint" style={fs(10.5)}>
|
||||
{t('tours.planner.breaksAdditionalHint')}
|
||||
</span>
|
||||
{planner.breakAdditionalInvalid && (
|
||||
<span id="tour-planner-breaks-error" role="alert" className="mt-1 block text-danger" style={fs(11)}>
|
||||
{t('tours.planner.timeValueInvalid')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="mb-[5px] flex min-w-0 items-center gap-1">
|
||||
<label className={`${LABEL} mb-0`} htmlFor="tour-planner-planned-duration">
|
||||
{t('tours.planner.plannedTotalDuration')}
|
||||
{planner.plannedDurationMinutes != null && <span className="ms-1 normal-case text-info">· {t('tours.planner.plannedTotalManual')}</span>}
|
||||
</label>
|
||||
<DurationInfo
|
||||
label={t('tours.planner.plannedTotalInfoLabel')}
|
||||
description={t('tours.planner.plannedTotalInfo')}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<input
|
||||
id="tour-planner-planned-duration"
|
||||
aria-label={t('tours.planner.plannedTotalDuration')}
|
||||
type="number"
|
||||
inputMode="numeric"
|
||||
min={0}
|
||||
max={1440}
|
||||
step={1}
|
||||
disabled={!canEdit || isSaving}
|
||||
value={planner.plannedDurationMinutes ?? planner.plannedTotalMinutes ?? ''}
|
||||
onChange={event => { if (canEdit && !isSaving) planner.setPlannedDurationMinutes(event.target.value === '' ? null : Number(event.target.value)) }}
|
||||
aria-invalid={planner.plannedDurationInvalid || undefined}
|
||||
aria-describedby={planner.plannedDurationInvalid ? 'tour-planner-planned-duration-error' : undefined}
|
||||
className={`${INPUT} min-w-0 flex-none`}
|
||||
style={{ width: '6rem' }}
|
||||
/>
|
||||
{planner.plannedDurationMinutes == null && <span className="text-content-faint" style={fs(10.5)}>{t('tours.planner.plannedTotalAutomatic')}</span>}
|
||||
</div>
|
||||
{planner.plannedDurationInvalid && (
|
||||
<span id="tour-planner-planned-duration-error" role="alert" className="mt-1 block text-danger" style={fs(11)}>
|
||||
{t('tours.planner.timeValueInvalid')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</TourSection>
|
||||
<div className="min-w-0">
|
||||
<label className={LABEL} htmlFor="tour-planner-website">{t('places.formWebsite')}</label>
|
||||
<input
|
||||
id="tour-planner-website"
|
||||
type="url"
|
||||
inputMode="url"
|
||||
disabled={!canEdit || isSaving}
|
||||
value={planner.website}
|
||||
onChange={event => { if (canEdit && !isSaving) planner.setWebsite(event.target.value) }}
|
||||
maxLength={500}
|
||||
placeholder={t('collab.notes.websitePlaceholder')}
|
||||
aria-invalid={planner.websiteInvalid || undefined}
|
||||
aria-describedby={planner.websiteInvalid ? 'tour-planner-website-error' : undefined}
|
||||
className={INPUT}
|
||||
/>
|
||||
{planner.websiteInvalid && (
|
||||
<span id="tour-planner-website-error" role="alert" className="mt-1 block text-danger" style={fs(11)}>
|
||||
{t('dawarich.error.invalid_url')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<label className={LABEL} htmlFor="tour-planner-difficulty">{t('tours.planner.maxDifficulty')}</label>
|
||||
<CustomSelect
|
||||
@@ -207,17 +338,74 @@ export function TourPlannerRail({ planner, canEdit: editPermission, canAssign: a
|
||||
<p className="m-0">{t('tours.planner.startingPoint')} {t('tours.planner.firstUseDetails')}</p>
|
||||
</div>
|
||||
) : (
|
||||
<ol className="m-0 flex list-none flex-col gap-px p-0">
|
||||
<ol data-touch-drag className="m-0 flex list-none flex-col gap-px p-0">
|
||||
{planner.waypoints.map((point, index) => {
|
||||
const selected = planner.selectedWaypointId === point.id
|
||||
const selected = planner.selectedWaypointId === point.id;
|
||||
const isDropTarget = dropTarget?.id === point.id && draggedWaypointId !== point.id;
|
||||
return (
|
||||
<li key={point.id}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => planner.setSelectedWaypointId(point.id)}
|
||||
className={`group flex w-full items-center gap-2.5 rounded-[12px] px-2 py-1.5 text-start outline-none transition-colors focus-visible:ring-2 focus-visible:ring-[color:var(--text-primary)] ${selected ? 'bg-surface-selected' : 'hover:bg-surface-hover'}`}
|
||||
aria-current={selected ? 'true' : undefined}
|
||||
>
|
||||
<li
|
||||
key={point.id}
|
||||
data-testid="tour-planner-waypoint-row"
|
||||
onDragStart={(event) => {
|
||||
if (!canEdit || isSaving) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
if (event.dataTransfer) {
|
||||
event.dataTransfer.effectAllowed = 'move';
|
||||
event.dataTransfer.setData('text/plain', point.id);
|
||||
}
|
||||
setDraggedWaypointId(point.id);
|
||||
setDropTarget(null);
|
||||
}}
|
||||
onDragOver={(event) => {
|
||||
if (!canEdit || isSaving || !draggedWaypointId || draggedWaypointId === point.id) return;
|
||||
event.preventDefault();
|
||||
if (event.dataTransfer) event.dataTransfer.dropEffect = 'move';
|
||||
const bounds = event.currentTarget.getBoundingClientRect();
|
||||
const placement = event.clientY >= bounds.top + bounds.height / 2 ? 'after' : 'before';
|
||||
setDropTarget((current) =>
|
||||
current?.id === point.id && current.placement === placement
|
||||
? current
|
||||
: { id: point.id, placement }
|
||||
);
|
||||
}}
|
||||
onDrop={(event) => {
|
||||
event.preventDefault();
|
||||
const draggedId = draggedWaypointId || event.dataTransfer.getData('text/plain');
|
||||
if (
|
||||
canEdit &&
|
||||
!isSaving &&
|
||||
draggedId &&
|
||||
draggedId !== point.id &&
|
||||
dropTarget?.id === point.id
|
||||
) {
|
||||
planner.reorderWaypoint(draggedId, point.id, dropTarget.placement);
|
||||
}
|
||||
setDraggedWaypointId(null);
|
||||
setDropTarget(null);
|
||||
}}
|
||||
onDragEnd={() => {
|
||||
setDraggedWaypointId(null);
|
||||
setDropTarget(null);
|
||||
}}
|
||||
className={`relative rounded-[12px] ${draggedWaypointId === point.id ? 'opacity-45' : ''} ${isDropTarget ? 'bg-surface-hover' : ''}`}
|
||||
>
|
||||
{isDropTarget && (
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={`pointer-events-none absolute inset-x-2 z-10 h-0.5 rounded bg-accent ${dropTarget.placement === 'before' ? 'top-0' : 'bottom-0'}`}
|
||||
/>
|
||||
)}
|
||||
<div className="group flex w-full items-center gap-2.5 rounded-[12px] px-2 py-1.5">
|
||||
<span
|
||||
draggable={canEdit && !isSaving}
|
||||
aria-hidden="true"
|
||||
data-testid="tour-planner-waypoint-drag-handle"
|
||||
className={`grid h-6 w-5 flex-none place-items-center text-content-faint ${canEdit && !isSaving ? 'cursor-grab active:cursor-grabbing' : 'opacity-35'}`}
|
||||
>
|
||||
<GripVertical size={14} strokeWidth={1.8} />
|
||||
</span>
|
||||
<span
|
||||
aria-label={t('tours.planner.waypointLabel', { n: index + 1 })}
|
||||
data-waypoint-number={index + 1}
|
||||
@@ -226,26 +414,53 @@ export function TourPlannerRail({ planner, canEdit: editPermission, canAssign: a
|
||||
>
|
||||
{index + 1}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block font-semibold leading-tight text-content" style={fs(12.5, 'body')}>{roleLabel(point.role, t)}</span>
|
||||
<span className="mt-0.5 block truncate font-geist tabular-nums text-content-faint" style={fs(10.5)}>{point.lat.toFixed(5)}, {point.lng.toFixed(5)}</span>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => planner.setSelectedWaypointId(point.id)}
|
||||
className="flex min-w-0 flex-1 flex-col text-start outline-none focus-visible:rounded focus-visible:ring-2 focus-visible:ring-[color:var(--text-primary)]"
|
||||
aria-current={selected ? 'true' : undefined}
|
||||
>
|
||||
<span className="block font-semibold leading-tight text-content" style={fs(12.5, 'body')}>
|
||||
{roleLabel(point.role, t)}
|
||||
</span>
|
||||
<span
|
||||
className="mt-0.5 block truncate font-geist tabular-nums text-content-faint"
|
||||
style={fs(10.5)}
|
||||
>
|
||||
{point.lat.toFixed(5)}, {point.lng.toFixed(5)}
|
||||
</span>
|
||||
</button>
|
||||
{canEdit && (
|
||||
<span className={`flex flex-none items-center gap-0.5 transition-opacity ${selected ? '' : 'opacity-50 group-hover:opacity-100 group-focus-within:opacity-100'}`}>
|
||||
<WaypointAction label={t('tours.planner.moveUp')} disabled={isSaving || index === 0} onAct={() => planner.moveWaypoint(point.id, -1)}>
|
||||
<span
|
||||
className={`flex flex-none items-center gap-0.5 transition-opacity ${selected ? '' : 'opacity-50 group-focus-within:opacity-100 group-hover:opacity-100'}`}
|
||||
>
|
||||
<WaypointAction
|
||||
label={t('tours.planner.moveUp')}
|
||||
disabled={isSaving || index === 0}
|
||||
onAct={() => planner.moveWaypoint(point.id, -1)}
|
||||
>
|
||||
<ArrowUp size={13} strokeWidth={2.2} />
|
||||
</WaypointAction>
|
||||
<WaypointAction label={t('tours.planner.moveDown')} disabled={isSaving || index === lastIndex} onAct={() => planner.moveWaypoint(point.id, 1)}>
|
||||
<WaypointAction
|
||||
label={t('tours.planner.moveDown')}
|
||||
disabled={isSaving || index === lastIndex}
|
||||
onAct={() => planner.moveWaypoint(point.id, 1)}
|
||||
>
|
||||
<ArrowDown size={13} strokeWidth={2.2} />
|
||||
</WaypointAction>
|
||||
<WaypointAction label={t('tours.planner.remove')} disabled={isSaving} danger onAct={() => planner.removeWaypoint(point.id)}>
|
||||
<WaypointAction
|
||||
label={t('tours.planner.remove')}
|
||||
disabled={isSaving}
|
||||
danger
|
||||
onAct={() => planner.removeWaypoint(point.id)}
|
||||
>
|
||||
<Trash2 size={13} strokeWidth={2} />
|
||||
</WaypointAction>
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
)}
|
||||
@@ -316,17 +531,14 @@ export function TourPlannerRail({ planner, canEdit: editPermission, canAssign: a
|
||||
function WaypointAction({ label, disabled, danger = false, onAct, children }: { label: string; disabled: boolean; danger?: boolean; onAct: () => void; children: ReactNode }) {
|
||||
return (
|
||||
<Tooltip label={label}>
|
||||
<span
|
||||
role="button"
|
||||
tabIndex={disabled ? -1 : 0}
|
||||
<button type="button" disabled={disabled}
|
||||
aria-label={label}
|
||||
aria-disabled={disabled}
|
||||
onClick={event => { event.stopPropagation(); if (!disabled) onAct() }}
|
||||
onKeyDown={event => { if (!disabled && event.key === 'Enter') { event.stopPropagation(); onAct() } }}
|
||||
className={`grid h-6 w-6 place-items-center rounded-full transition-colors ${disabled ? 'pointer-events-none opacity-25' : danger ? 'text-danger hover:bg-surface-card' : 'text-content-muted hover:bg-surface-card hover:text-content'}`}
|
||||
>
|
||||
{children}
|
||||
</span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
@@ -421,7 +633,22 @@ export function TourPlannerToursRail({ planner, tours, days, loading, onAssignTo
|
||||
selectTour(tour)
|
||||
}
|
||||
|
||||
const walkingTime = { label: t('tours.planner.inspector.duration'), value: t('tours.durationMinutes', { count: Math.max(1, Math.round((planner.durationSeconds ?? 0) / 60)) }) }
|
||||
const tourTimeFields = [
|
||||
{
|
||||
label: t('tours.planner.inspector.duration'),
|
||||
value: planner.walkingDurationMinutes == null
|
||||
? t('tours.planner.walkingTimeUnknown')
|
||||
: formatPlannedTourDuration(planner.walkingDurationMinutes),
|
||||
},
|
||||
{
|
||||
label: t('tours.planner.breaksAdditional'),
|
||||
value: planner.breakAdditionalMinutes == null ? '—' : formatPlannedTourDuration(planner.breakAdditionalMinutes),
|
||||
},
|
||||
{
|
||||
label: `${t('tours.planner.plannedTotalDuration')}${planner.plannedDurationMinutes != null ? ` · ${t('tours.planner.plannedTotalManual')}` : ''}`,
|
||||
value: planner.plannedTotalMinutes == null ? t('tours.planner.walkingTimeUnknown') : formatPlannedTourDuration(planner.plannedTotalMinutes),
|
||||
},
|
||||
]
|
||||
|
||||
return (
|
||||
<aside className="flex h-full min-h-0 flex-col" aria-label={t('tours.planner.tripTours')}>
|
||||
@@ -433,7 +660,7 @@ export function TourPlannerToursRail({ planner, tours, days, loading, onAssignTo
|
||||
{hasRoute && (
|
||||
<>
|
||||
<TourSection label={t('tours.planner.inspector.title')}>
|
||||
<TourMetricFields analysis={routeAnalysis} unit={distanceUnit} extra={[walkingTime]} columns={2} />
|
||||
<TourMetricFields analysis={routeAnalysis} unit={distanceUnit} extra={tourTimeFields} columns={2} />
|
||||
</TourSection>
|
||||
{routeAnalysis && (
|
||||
<ElevationSection
|
||||
|
||||
@@ -81,6 +81,544 @@ describe('useTourPlanner', () => {
|
||||
expect(result.current.waypoints).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('RC-08: commits a dragged coordinate once and reroutes only after the completed drag', async () => {
|
||||
detailTour.mockResolvedValue({
|
||||
tour: savedTour,
|
||||
waypoints: [
|
||||
{ lat: 48, lng: 11, role: 'start', sequence: 0 },
|
||||
{ lat: 48.01, lng: 11.01, role: 'via', sequence: 1 },
|
||||
{ lat: 48.02, lng: 11.02, role: 'end', sequence: 2 },
|
||||
],
|
||||
})
|
||||
const { result } = renderHook(() => useTourPlanner({ tripId: 76 }))
|
||||
await act(async () => { expect(await result.current.openTour(savedTour)).toBe(true) })
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(450) })
|
||||
const id = result.current.waypoints[1].id
|
||||
const original = { lat: result.current.waypoints[1].lat, lng: result.current.waypoints[1].lng }
|
||||
const callsBeforeDrag = routeWalkingTour.mock.calls.length
|
||||
|
||||
act(() => { expect(result.current.setWaypointPosition(id, 48.03, 11.04)).toBe(true) })
|
||||
expect(result.current.waypoints[1]).toMatchObject({ lat: 48.03, lng: 11.04 })
|
||||
expect(result.current.route).toEqual(routed.coordinates)
|
||||
expect(routeWalkingTour).toHaveBeenCalledTimes(callsBeforeDrag)
|
||||
expect(result.current.canUndo).toBe(true)
|
||||
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(450) })
|
||||
expect(routeWalkingTour).toHaveBeenCalledTimes(callsBeforeDrag + 1)
|
||||
act(() => result.current.undo())
|
||||
expect(result.current.waypoints[1]).toMatchObject(original)
|
||||
expect(result.current.canUndo).toBe(false)
|
||||
expect(result.current.canRedo).toBe(true)
|
||||
act(() => result.current.redo())
|
||||
expect(result.current.waypoints[1]).toMatchObject({ lat: 48.03, lng: 11.04 })
|
||||
})
|
||||
|
||||
it('RC-08: preserves a dragged coordinate through draft recovery', () => {
|
||||
const first = renderHook(() => useTourPlanner({ tripId: 75 }))
|
||||
act(() => {
|
||||
first.result.current.addWaypoint(48, 11)
|
||||
first.result.current.addWaypoint(48.1, 11.1)
|
||||
first.result.current.addWaypoint(48.2, 11.2)
|
||||
})
|
||||
const waypoint = first.result.current.waypoints[1]
|
||||
act(() => { expect(first.result.current.setWaypointPosition(waypoint.id, 48.15, 11.16)).toBe(true) })
|
||||
first.unmount()
|
||||
|
||||
const recovered = renderHook(() => useTourPlanner({ tripId: 75 }))
|
||||
expect(recovered.result.current.waypoints[1]).toMatchObject({ id: waypoint.id, lat: 48.15, lng: 11.16 })
|
||||
})
|
||||
|
||||
it('RC-08: saves and reopens the final dragged coordinate', async () => {
|
||||
const initialWaypoints = [
|
||||
{ lat: 48, lng: 11, role: 'start' as const, sequence: 0 },
|
||||
{ lat: 48.1, lng: 11.1, role: 'via' as const, sequence: 1 },
|
||||
{ lat: 48.2, lng: 11.2, role: 'end' as const, sequence: 2 },
|
||||
]
|
||||
const finalWaypoints = [
|
||||
initialWaypoints[0],
|
||||
{ ...initialWaypoints[1], lat: 48.15, lng: 11.16 },
|
||||
initialWaypoints[2],
|
||||
]
|
||||
detailTour
|
||||
.mockResolvedValueOnce({ tour: savedTour, waypoints: initialWaypoints })
|
||||
.mockResolvedValueOnce({ tour: savedTour, waypoints: finalWaypoints })
|
||||
updateTour.mockResolvedValue({ tour: savedTour, waypoints: finalWaypoints })
|
||||
const { result } = renderHook(() => useTourPlanner({ tripId: 74 }))
|
||||
expect(result.current.breakAdditionalMinutes).toBeNull()
|
||||
await act(async () => { expect(await result.current.openTour(savedTour)).toBe(true) })
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(450) })
|
||||
const id = result.current.waypoints[1].id
|
||||
act(() => { expect(result.current.setWaypointPosition(id, 48.15, 11.16)).toBe(true) })
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(450) })
|
||||
act(() => result.current.setName('Moved ridge'))
|
||||
expect(result.current.canSave).toBe(true)
|
||||
|
||||
await act(async () => { await result.current.save() })
|
||||
expect(updateTour).toHaveBeenCalledWith(
|
||||
74,
|
||||
savedTour.place_id,
|
||||
expect.objectContaining({
|
||||
waypoints: finalWaypoints.map((point, sequence) => ({ ...point, sequence })),
|
||||
})
|
||||
)
|
||||
await act(async () => { expect(await result.current.openTour(savedTour)).toBe(true) })
|
||||
expect(result.current.waypoints[1]).toMatchObject({ lat: 48.15, lng: 11.16 })
|
||||
})
|
||||
|
||||
it('RC-08: aborts an obsolete dragged-coordinate route and ignores its late response', async () => {
|
||||
const staleRoute = deferred<typeof routed | null>()
|
||||
const replacementRoute = { ...routed, coordinates: [[52, 14], [52.01, 14.01]] as [number, number][] }
|
||||
routeWalkingTour
|
||||
.mockResolvedValueOnce(routed)
|
||||
.mockReturnValueOnce(staleRoute.promise)
|
||||
.mockResolvedValueOnce(replacementRoute)
|
||||
const { result } = renderHook(() => useTourPlanner({ tripId: 73 }))
|
||||
act(() => {
|
||||
result.current.addWaypoint(48, 11)
|
||||
result.current.addWaypoint(48.1, 11.1)
|
||||
result.current.addWaypoint(48.2, 11.2)
|
||||
})
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(450) })
|
||||
const [first, second] = result.current.waypoints
|
||||
|
||||
act(() => { expect(result.current.setWaypointPosition(second.id, 48.11, 11.12)).toBe(true) })
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(450) })
|
||||
const obsoleteSignal = routeWalkingTour.mock.calls[1][1] as AbortSignal
|
||||
expect(obsoleteSignal.aborted).toBe(false)
|
||||
|
||||
act(() => { expect(result.current.setWaypointPosition(first.id, 48.02, 11.03)).toBe(true) })
|
||||
expect(obsoleteSignal.aborted).toBe(true)
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(450) })
|
||||
expect(result.current.route).toEqual(replacementRoute.coordinates)
|
||||
await act(async () => { staleRoute.resolve(routed); await Promise.resolve() })
|
||||
expect(result.current.route).toEqual(replacementRoute.coordinates)
|
||||
})
|
||||
|
||||
it('RS-01: saves and reopens description and website with the Tour metadata', async () => {
|
||||
createTour.mockResolvedValue({
|
||||
tour: { ...savedTour, description: 'Lake ridge details', website: 'https://www.komoot.com/tour/42' },
|
||||
waypoints: [],
|
||||
})
|
||||
detailTour.mockResolvedValue({
|
||||
tour: { ...savedTour, description: 'Lake ridge details', website: 'https://www.komoot.com/tour/42' },
|
||||
waypoints: [
|
||||
{ lat: 48, lng: 11, role: 'start', sequence: 0 },
|
||||
{ lat: 48.1, lng: 11.1, role: 'end', sequence: 1 },
|
||||
],
|
||||
})
|
||||
updateTour.mockResolvedValue({
|
||||
tour: { ...savedTour, name: 'Edited ridge', description: 'Updated details', website: 'https://alltrails.com/trail/42' },
|
||||
waypoints: [],
|
||||
})
|
||||
const { result } = renderHook(() => useTourPlanner({ tripId: 72 }))
|
||||
act(() => {
|
||||
result.current.startNewTour()
|
||||
result.current.addWaypoint(48, 11)
|
||||
result.current.addWaypoint(48.1, 11.1)
|
||||
result.current.setName('Ridge notes')
|
||||
result.current.setDescription('Lake ridge details')
|
||||
result.current.setWebsite(' HTTPS://WWW.KOMOOT.COM/tour/42 ')
|
||||
})
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(450) })
|
||||
expect(result.current.canSave).toBe(true)
|
||||
await act(async () => { await result.current.save() })
|
||||
expect(createTour).toHaveBeenCalledWith(72, expect.objectContaining({
|
||||
description: 'Lake ridge details',
|
||||
website: 'https://www.komoot.com/tour/42',
|
||||
}))
|
||||
|
||||
await act(async () => { expect(await result.current.openTour(savedTour)).toBe(true) })
|
||||
expect(result.current.description).toBe('Lake ridge details')
|
||||
expect(result.current.website).toBe('https://www.komoot.com/tour/42')
|
||||
act(() => {
|
||||
result.current.setName('Edited ridge')
|
||||
result.current.setDescription('Updated details')
|
||||
result.current.setWebsite('https://alltrails.com/trail/42')
|
||||
})
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(450) })
|
||||
await act(async () => { await result.current.save() })
|
||||
expect(updateTour).toHaveBeenCalledWith(72, savedTour.place_id, expect.objectContaining({
|
||||
description: 'Updated details',
|
||||
website: 'https://alltrails.com/trail/42',
|
||||
}))
|
||||
})
|
||||
|
||||
it('RS-01: restores informational metadata from draft and blocks an unsafe website', () => {
|
||||
const first = renderHook(() => useTourPlanner({ tripId: 71 }))
|
||||
act(() => {
|
||||
first.result.current.addWaypoint(48, 11)
|
||||
first.result.current.addWaypoint(48.1, 11.1)
|
||||
first.result.current.setName('Ridge notes')
|
||||
first.result.current.setDescription('Restored description')
|
||||
first.result.current.setWebsite('https://example.org/route')
|
||||
first.result.current.setPlannedDurationMinutes(95)
|
||||
first.result.current.setBreakAdditionalMinutes(35)
|
||||
})
|
||||
first.unmount()
|
||||
|
||||
const recovered = renderHook(() => useTourPlanner({ tripId: 71 }))
|
||||
expect(recovered.result.current.description).toBe('Restored description')
|
||||
expect(recovered.result.current.website).toBe('https://example.org/route')
|
||||
expect(recovered.result.current.plannedDurationMinutes).toBe(95)
|
||||
expect(recovered.result.current.breakAdditionalMinutes).toBe(35)
|
||||
act(() => recovered.result.current.setBreakAdditionalMinutes(-1))
|
||||
expect(recovered.result.current.breakAdditionalInvalid).toBe(true)
|
||||
act(() => recovered.result.current.setBreakAdditionalMinutes(35.5))
|
||||
expect(recovered.result.current.breakAdditionalInvalid).toBe(true)
|
||||
act(() => recovered.result.current.setPlannedDurationMinutes(1441))
|
||||
expect(recovered.result.current.plannedDurationInvalid).toBe(true)
|
||||
act(() => recovered.result.current.setPlannedDurationMinutes(95.5))
|
||||
expect(recovered.result.current.plannedDurationInvalid).toBe(true)
|
||||
act(() => recovered.result.current.setWebsite('http://example.org/route'))
|
||||
expect(recovered.result.current.websiteInvalid).toBe(true)
|
||||
expect(recovered.result.current.canSave).toBe(false)
|
||||
})
|
||||
|
||||
it('RS-02: saves, reopens and clears planned total without replacing calculated route duration', async () => {
|
||||
const saved = { ...savedTour, duration: 30, planned_duration_minutes: 95, break_additional_minutes: 40 }
|
||||
createTour.mockResolvedValue({ tour: saved, waypoints: [] })
|
||||
detailTour.mockResolvedValue({
|
||||
tour: saved,
|
||||
waypoints: [
|
||||
{ lat: 48, lng: 11, role: 'start', sequence: 0 },
|
||||
{ lat: 48.1, lng: 11.1, role: 'end', sequence: 1 },
|
||||
],
|
||||
})
|
||||
updateTour.mockResolvedValue({ tour: { ...saved, planned_duration_minutes: null }, waypoints: [] })
|
||||
const { result } = renderHook(() => useTourPlanner({ tripId: 73 }))
|
||||
act(() => {
|
||||
result.current.startNewTour()
|
||||
result.current.addWaypoint(48, 11)
|
||||
result.current.addWaypoint(48.1, 11.1)
|
||||
result.current.setName('Ridge notes')
|
||||
result.current.setBreakAdditionalMinutes(40)
|
||||
result.current.setPlannedDurationMinutes(95)
|
||||
})
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(450) })
|
||||
expect(result.current.durationSeconds).toBe(routed.durationSeconds)
|
||||
expect(result.current.canSave).toBe(true)
|
||||
await act(async () => { await result.current.save() })
|
||||
expect(createTour).toHaveBeenCalledWith(73, expect.objectContaining({
|
||||
duration_seconds: routed.durationSeconds,
|
||||
planned_duration_minutes: 95,
|
||||
break_additional_minutes: 40,
|
||||
}))
|
||||
|
||||
await act(async () => { expect(await result.current.openTour(savedTour)).toBe(true) })
|
||||
expect(result.current.plannedDurationMinutes).toBe(95)
|
||||
expect(result.current.breakAdditionalMinutes).toBe(40)
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(450) })
|
||||
act(() => result.current.setPlannedDurationMinutes(null))
|
||||
await act(async () => { await result.current.save() })
|
||||
expect(updateTour).toHaveBeenCalledWith(73, savedTour.place_id, expect.objectContaining({
|
||||
duration_seconds: routed.durationSeconds,
|
||||
planned_duration_minutes: null,
|
||||
break_additional_minutes: 40,
|
||||
}))
|
||||
})
|
||||
|
||||
it('RS-02: recalculates automatic total when route changes but preserves a manual override', async () => {
|
||||
routeWalkingTour
|
||||
.mockResolvedValueOnce({ ...routed, durationSeconds: 3600 })
|
||||
.mockResolvedValueOnce({ ...routed, durationSeconds: 5400 })
|
||||
.mockResolvedValueOnce({ ...routed, durationSeconds: 7200 })
|
||||
const { result } = renderHook(() => useTourPlanner({ tripId: 74 }))
|
||||
act(() => {
|
||||
result.current.addWaypoint(48, 11)
|
||||
result.current.addWaypoint(48.1, 11.1)
|
||||
result.current.setBreakAdditionalMinutes(30)
|
||||
})
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(450) })
|
||||
expect(result.current.walkingDurationMinutes).toBe(60)
|
||||
expect(result.current.plannedTotalMinutes).toBe(90)
|
||||
|
||||
const waypointId = result.current.waypoints[1].id
|
||||
act(() => result.current.setWaypointPosition(waypointId, 48.2, 11.2))
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(450) })
|
||||
expect(result.current.walkingDurationMinutes).toBe(90)
|
||||
expect(result.current.plannedTotalMinutes).toBe(120)
|
||||
|
||||
act(() => result.current.setPlannedDurationMinutes(110))
|
||||
act(() => result.current.setWaypointPosition(waypointId, 48.3, 11.3))
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(450) })
|
||||
expect(result.current.walkingDurationMinutes).toBe(120)
|
||||
expect(result.current.plannedTotalMinutes).toBe(110)
|
||||
expect(result.current.plannedDurationMinutes).toBe(110)
|
||||
|
||||
act(() => result.current.setPlannedDurationMinutes(null))
|
||||
expect(result.current.plannedTotalMinutes).toBe(150)
|
||||
act(() => result.current.setBreakAdditionalMinutes(null))
|
||||
expect(result.current.breakAdditionalMinutes).toBeNull()
|
||||
expect(result.current.plannedTotalMinutes).toBe(120)
|
||||
})
|
||||
|
||||
it('RS-01: changing informational metadata does not create waypoints or reroute', async () => {
|
||||
const { result } = renderHook(() => useTourPlanner({ tripId: 70 }))
|
||||
act(() => {
|
||||
result.current.addWaypoint(48, 11)
|
||||
result.current.addWaypoint(48.1, 11.1)
|
||||
})
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(450) })
|
||||
const ids = result.current.waypoints.map(point => point.id)
|
||||
const routeBeforeMetadataEdit = result.current.route
|
||||
const routeCalls = routeWalkingTour.mock.calls.length
|
||||
|
||||
act(() => {
|
||||
result.current.setDescription('A ridge above the lake')
|
||||
result.current.setWebsite('https://example.org/ridge')
|
||||
})
|
||||
|
||||
expect(result.current.waypoints.map(point => point.id)).toEqual(ids)
|
||||
expect(result.current.route).toEqual(routeBeforeMetadataEdit)
|
||||
expect(routeWalkingTour).toHaveBeenCalledTimes(routeCalls)
|
||||
})
|
||||
|
||||
it('RC-07: reorders stable waypoint ids once, normalizes roles, and routes only after the drop', async () => {
|
||||
detailTour.mockResolvedValue({
|
||||
tour: savedTour,
|
||||
waypoints: [
|
||||
{ lat: 48, lng: 11, role: 'start', sequence: 0 },
|
||||
{ lat: 48.01, lng: 11.01, role: 'via', sequence: 1 },
|
||||
{ lat: 48.02, lng: 11.02, role: 'via', sequence: 2 },
|
||||
{ lat: 48.03, lng: 11.03, role: 'end', sequence: 3 },
|
||||
],
|
||||
});
|
||||
const { result } = renderHook(() => useTourPlanner({ tripId: 77 }));
|
||||
await act(async () => {
|
||||
expect(await result.current.openTour(savedTour)).toBe(true);
|
||||
});
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(450);
|
||||
});
|
||||
const original = result.current.waypoints.map((point) => point.id);
|
||||
const routeCallsBeforeDrop = routeWalkingTour.mock.calls.length;
|
||||
|
||||
act(() => result.current.reorderWaypoint(original[0], original[2], 'after'));
|
||||
|
||||
expect(result.current.waypoints.map((point) => point.id)).toEqual([
|
||||
original[1],
|
||||
original[2],
|
||||
original[0],
|
||||
original[3],
|
||||
]);
|
||||
expect(result.current.waypoints.map((point) => point.role)).toEqual(['start', 'via', 'via', 'end']);
|
||||
expect(result.current.canUndo).toBe(true);
|
||||
expect(result.current.canRedo).toBe(false);
|
||||
expect(result.current.route).toEqual(routed.coordinates);
|
||||
expect(routeWalkingTour).toHaveBeenCalledTimes(routeCallsBeforeDrop);
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(450);
|
||||
});
|
||||
expect(routeWalkingTour).toHaveBeenCalledTimes(routeCallsBeforeDrop + 1);
|
||||
|
||||
act(() => result.current.undo());
|
||||
expect(result.current.waypoints.map((point) => point.id)).toEqual(original);
|
||||
expect(result.current.canUndo).toBe(false);
|
||||
expect(result.current.canRedo).toBe(true);
|
||||
|
||||
act(() => result.current.redo());
|
||||
expect(result.current.waypoints.map((point) => point.id)).toEqual([
|
||||
original[1],
|
||||
original[2],
|
||||
original[0],
|
||||
original[3],
|
||||
]);
|
||||
});
|
||||
|
||||
it('RC-07: preserves an earlier waypoint move through draft recovery', () => {
|
||||
const first = renderHook(() => useTourPlanner({ tripId: 78 }));
|
||||
act(() => {
|
||||
first.result.current.addWaypoint(48, 11);
|
||||
first.result.current.addWaypoint(48.1, 11.1);
|
||||
first.result.current.addWaypoint(48.2, 11.2);
|
||||
});
|
||||
const ids = first.result.current.waypoints.map((point) => point.id);
|
||||
|
||||
act(() => first.result.current.reorderWaypoint(ids[2], ids[0], 'before'));
|
||||
expect(first.result.current.waypoints.map((point) => point.id)).toEqual([ids[2], ids[0], ids[1]]);
|
||||
expect(first.result.current.waypoints.map((point) => point.role)).toEqual(['start', 'via', 'end']);
|
||||
const stored = JSON.parse(localStorage.getItem('tour-draft-78')!) as { waypoints: { id: string }[] };
|
||||
expect(stored.waypoints.map((point) => point.id)).toEqual([ids[2], ids[0], ids[1]]);
|
||||
|
||||
first.unmount();
|
||||
const recovered = renderHook(() => useTourPlanner({ tripId: 78 }));
|
||||
expect(recovered.result.current.waypoints.map((point) => point.id)).toEqual([ids[2], ids[0], ids[1]]);
|
||||
expect(recovered.result.current.waypoints.map((point) => point.role)).toEqual(['start', 'via', 'end']);
|
||||
});
|
||||
|
||||
it('RC-07: saves reordered sequence and reopens the same waypoint order', async () => {
|
||||
const initialWaypoints = [
|
||||
{ lat: 48, lng: 11, role: 'start' as const, sequence: 0 },
|
||||
{ lat: 48.1, lng: 11.1, role: 'via' as const, sequence: 1 },
|
||||
{ lat: 48.2, lng: 11.2, role: 'via' as const, sequence: 2 },
|
||||
{ lat: 48.3, lng: 11.3, role: 'end' as const, sequence: 3 },
|
||||
];
|
||||
const reorderedWaypoints = [
|
||||
initialWaypoints[0],
|
||||
{ ...initialWaypoints[3], role: 'via' as const },
|
||||
initialWaypoints[1],
|
||||
{ ...initialWaypoints[2], role: 'end' as const },
|
||||
];
|
||||
detailTour
|
||||
.mockResolvedValueOnce({ tour: savedTour, waypoints: initialWaypoints })
|
||||
.mockResolvedValueOnce({ tour: savedTour, waypoints: reorderedWaypoints });
|
||||
updateTour.mockResolvedValue({ tour: savedTour, waypoints: reorderedWaypoints });
|
||||
const { result } = renderHook(() => useTourPlanner({ tripId: 79 }));
|
||||
await act(async () => {
|
||||
expect(await result.current.openTour(savedTour)).toBe(true);
|
||||
});
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(450);
|
||||
});
|
||||
const ids = result.current.waypoints.map((point) => point.id);
|
||||
|
||||
act(() => result.current.reorderWaypoint(ids[3], ids[1], 'before'));
|
||||
expect(result.current.waypoints.map((point) => [point.lat, point.lng])).toEqual(
|
||||
reorderedWaypoints.map((point) => [point.lat, point.lng])
|
||||
);
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(450);
|
||||
});
|
||||
act(() => result.current.setName('Reordered ridge'));
|
||||
expect(result.current.canSave).toBe(true);
|
||||
|
||||
await act(async () => {
|
||||
await result.current.save();
|
||||
});
|
||||
expect(updateTour).toHaveBeenCalledWith(
|
||||
79,
|
||||
savedTour.place_id,
|
||||
expect.objectContaining({
|
||||
waypoints: reorderedWaypoints.map((point, sequence) => ({
|
||||
lat: point.lat,
|
||||
lng: point.lng,
|
||||
role: point.role,
|
||||
sequence,
|
||||
})),
|
||||
})
|
||||
);
|
||||
|
||||
await act(async () => {
|
||||
expect(await result.current.openTour(savedTour)).toBe(true);
|
||||
});
|
||||
expect(result.current.waypoints.map((point) => [point.lat, point.lng])).toEqual(
|
||||
reorderedWaypoints.map((point) => [point.lat, point.lng])
|
||||
);
|
||||
});
|
||||
|
||||
it('RC-07: aborts obsolete reorder routing and ignores its late response', async () => {
|
||||
const staleRoute = deferred<typeof routed | null>();
|
||||
const replacementRoute = {
|
||||
...routed,
|
||||
coordinates: [
|
||||
[52, 14],
|
||||
[52.01, 14.01],
|
||||
] as [number, number][],
|
||||
};
|
||||
routeWalkingTour
|
||||
.mockResolvedValueOnce(routed)
|
||||
.mockReturnValueOnce(staleRoute.promise)
|
||||
.mockResolvedValueOnce(replacementRoute);
|
||||
const { result } = renderHook(() => useTourPlanner({ tripId: 80 }));
|
||||
act(() => {
|
||||
result.current.addWaypoint(48, 11);
|
||||
result.current.addWaypoint(48.1, 11.1);
|
||||
result.current.addWaypoint(48.2, 11.2);
|
||||
});
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(450);
|
||||
});
|
||||
const ids = result.current.waypoints.map((point) => point.id);
|
||||
|
||||
act(() => result.current.reorderWaypoint(ids[0], ids[1], 'after'));
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(450);
|
||||
});
|
||||
const obsoleteSignal = routeWalkingTour.mock.calls[1][1] as AbortSignal;
|
||||
expect(obsoleteSignal.aborted).toBe(false);
|
||||
|
||||
act(() => result.current.reorderWaypoint(ids[1], ids[2], 'after'));
|
||||
expect(obsoleteSignal.aborted).toBe(true);
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(450);
|
||||
});
|
||||
expect(result.current.route).toEqual(replacementRoute.coordinates);
|
||||
await act(async () => {
|
||||
staleRoute.resolve(routed);
|
||||
await Promise.resolve();
|
||||
});
|
||||
expect(result.current.route).toEqual(replacementRoute.coordinates);
|
||||
});
|
||||
|
||||
|
||||
it('RS-01: saves and reopens description and website with the Tour metadata', async () => {
|
||||
createTour.mockResolvedValue({
|
||||
tour: { ...savedTour, description: 'Lake ridge details', website: 'https://www.komoot.com/tour/42' },
|
||||
waypoints: [],
|
||||
})
|
||||
detailTour.mockResolvedValue({
|
||||
tour: { ...savedTour, description: 'Lake ridge details', website: 'https://www.komoot.com/tour/42' },
|
||||
waypoints: [
|
||||
{ lat: 48, lng: 11, role: 'start', sequence: 0 },
|
||||
{ lat: 48.1, lng: 11.1, role: 'end', sequence: 1 },
|
||||
],
|
||||
})
|
||||
updateTour.mockResolvedValue({
|
||||
tour: { ...savedTour, name: 'Edited ridge', description: 'Updated details', website: 'https://alltrails.com/trail/42' },
|
||||
waypoints: [],
|
||||
})
|
||||
const { result } = renderHook(() => useTourPlanner({ tripId: 72 }))
|
||||
act(() => {
|
||||
result.current.startNewTour()
|
||||
result.current.addWaypoint(48, 11)
|
||||
result.current.addWaypoint(48.1, 11.1)
|
||||
result.current.setName('Ridge notes')
|
||||
result.current.setDescription('Lake ridge details')
|
||||
result.current.setWebsite(' HTTPS://WWW.KOMOOT.COM/tour/42 ')
|
||||
})
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(450) })
|
||||
expect(result.current.canSave).toBe(true)
|
||||
await act(async () => { await result.current.save() })
|
||||
expect(createTour).toHaveBeenCalledWith(72, expect.objectContaining({
|
||||
description: 'Lake ridge details',
|
||||
website: 'https://www.komoot.com/tour/42',
|
||||
}))
|
||||
|
||||
await act(async () => { expect(await result.current.openTour(savedTour)).toBe(true) })
|
||||
expect(result.current.description).toBe('Lake ridge details')
|
||||
expect(result.current.website).toBe('https://www.komoot.com/tour/42')
|
||||
act(() => {
|
||||
result.current.setName('Edited ridge')
|
||||
result.current.setDescription('Updated details')
|
||||
result.current.setWebsite('https://alltrails.com/trail/42')
|
||||
})
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(450) })
|
||||
await act(async () => { await result.current.save() })
|
||||
expect(updateTour).toHaveBeenCalledWith(72, savedTour.place_id, expect.objectContaining({
|
||||
description: 'Updated details',
|
||||
website: 'https://alltrails.com/trail/42',
|
||||
}))
|
||||
})
|
||||
|
||||
it('RS-01: restores informational metadata from draft and blocks an unsafe website', () => {
|
||||
const first = renderHook(() => useTourPlanner({ tripId: 71 }))
|
||||
act(() => {
|
||||
first.result.current.addWaypoint(48, 11)
|
||||
first.result.current.addWaypoint(48.1, 11.1)
|
||||
first.result.current.setName('Ridge notes')
|
||||
first.result.current.setDescription('Restored description')
|
||||
first.result.current.setWebsite('https://example.org/route')
|
||||
})
|
||||
first.unmount()
|
||||
|
||||
const recovered = renderHook(() => useTourPlanner({ tripId: 71 }))
|
||||
expect(recovered.result.current.description).toBe('Restored description')
|
||||
expect(recovered.result.current.website).toBe('https://example.org/route')
|
||||
act(() => recovered.result.current.setWebsite('http://example.org/route'))
|
||||
expect(recovered.result.current.websiteInvalid).toBe(true)
|
||||
expect(recovered.result.current.canSave).toBe(false)
|
||||
})
|
||||
|
||||
it('changes the map focus intent only for explicit Tour context changes', async () => {
|
||||
detailTour.mockResolvedValue({
|
||||
tour: savedTour,
|
||||
@@ -944,7 +1482,7 @@ describe('useTourPlanner', () => {
|
||||
|
||||
expect(result.current.mode).toEqual({ type: 'new-draft' })
|
||||
expect(JSON.parse(localStorage.getItem('tour-draft-23') || 'null')).toMatchObject({
|
||||
version: 2,
|
||||
version: 6,
|
||||
name: '',
|
||||
waypoints: [],
|
||||
maxHikingDifficulty: 2,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { TourCreateResponse, TourListItem, TourWaypointRole, TourMaxHikingDifficulty } from '@trek/shared'
|
||||
import { MAX_PLANNED_TOUR_DURATION_MINUTES, tourWebsiteSchema, type TourCreateResponse, type TourListItem, type TourWaypointRole, type TourMaxHikingDifficulty } from '@trek/shared'
|
||||
import { tourRepo } from '../../../repo/tourRepo'
|
||||
import { randomId } from '../../../utils/randomId'
|
||||
import type { TourBaseLayer } from '../../Map/MapLayerSwitcher'
|
||||
@@ -26,8 +26,12 @@ export type TourPlannerStatus =
|
||||
| 'saved'
|
||||
|
||||
interface DraftPayload {
|
||||
version: 1 | 2
|
||||
version: 1 | 2 | 3 | 4 | 5 | 6
|
||||
name: string
|
||||
description?: string
|
||||
website?: string
|
||||
plannedDurationMinutes?: number | null
|
||||
breakAdditionalMinutes?: number | null
|
||||
waypoints: TourPlannerWaypoint[]
|
||||
maxHikingDifficulty?: TourMaxHikingDifficulty
|
||||
editingPlaceId?: number | null
|
||||
@@ -63,7 +67,13 @@ function sameWaypointSnapshot(a: TourPlannerWaypoint[], b: TourPlannerWaypoint[]
|
||||
function validDraft(value: unknown): value is DraftPayload {
|
||||
if (!value || typeof value !== 'object') return false
|
||||
const draft = value as Partial<DraftPayload>
|
||||
return (draft.version === 1 || draft.version === 2) && typeof draft.name === 'string'
|
||||
return (draft.version === 1 || draft.version === 2 || draft.version === 3 || draft.version === 4 || draft.version === 5 || draft.version === 6) && typeof draft.name === 'string'
|
||||
&& (draft.description === undefined || typeof draft.description === 'string')
|
||||
&& (draft.website === undefined || typeof draft.website === 'string')
|
||||
&& (draft.plannedDurationMinutes === undefined || draft.plannedDurationMinutes === null
|
||||
|| (Number.isInteger(draft.plannedDurationMinutes) && draft.plannedDurationMinutes >= 0 && draft.plannedDurationMinutes <= MAX_PLANNED_TOUR_DURATION_MINUTES))
|
||||
&& (draft.breakAdditionalMinutes === undefined || draft.breakAdditionalMinutes === null
|
||||
|| (Number.isInteger(draft.breakAdditionalMinutes) && draft.breakAdditionalMinutes >= 0 && draft.breakAdditionalMinutes <= MAX_PLANNED_TOUR_DURATION_MINUTES))
|
||||
&& (draft.editingPlaceId == null || (Number.isInteger(draft.editingPlaceId) && draft.editingPlaceId > 0))
|
||||
&& (draft.maxHikingDifficulty == null || (Number.isInteger(draft.maxHikingDifficulty) && draft.maxHikingDifficulty >= 1 && draft.maxHikingDifficulty <= 6))
|
||||
&& Array.isArray(draft.waypoints)
|
||||
@@ -112,6 +122,10 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
}, [storageKey])
|
||||
|
||||
const [name, setNameState] = useState(restored?.name ?? '')
|
||||
const [description, setDescriptionState] = useState(restored?.description ?? '')
|
||||
const [website, setWebsiteState] = useState(restored?.website ?? '')
|
||||
const [plannedDurationMinutes, setPlannedDurationMinutesState] = useState<number | null>(restored?.plannedDurationMinutes ?? null)
|
||||
const [breakAdditionalMinutes, setBreakAdditionalMinutesState] = useState<number | null>(restored?.breakAdditionalMinutes ?? null)
|
||||
const [waypoints, setWaypoints] = useState<TourPlannerWaypoint[]>(restored?.waypoints ?? [])
|
||||
const [maxHikingDifficulty, setMaxHikingDifficultyState] = useState<TourMaxHikingDifficulty>(restored?.maxHikingDifficulty ?? 2)
|
||||
const [selectedWaypointId, setSelectedWaypointId] = useState<string | null>(restored?.waypoints[0]?.id ?? null)
|
||||
@@ -238,6 +252,15 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
setSelectedWaypointId(id)
|
||||
}, [commitWaypoints])
|
||||
|
||||
const setWaypointPosition = useCallback((id: string, lat: number, lng: number) => {
|
||||
if (!editPermissionRef.current || saveInFlightRef.current || !Number.isFinite(lat) || !Number.isFinite(lng)) return false
|
||||
const current = waypointsRef.current.find(point => point.id === id)
|
||||
if (!current) return false
|
||||
if (current.lat === lat && current.lng === lng) return true
|
||||
commitWaypoints(points => points.map(point => point.id === id ? { ...point, lat, lng } : point))
|
||||
return true
|
||||
}, [commitWaypoints])
|
||||
|
||||
const removeWaypoint = useCallback((id: string) => {
|
||||
if (!editPermissionRef.current) return
|
||||
commitWaypoints(current => current.filter(point => point.id !== id))
|
||||
@@ -255,6 +278,24 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
})
|
||||
}, [commitWaypoints])
|
||||
|
||||
const reorderWaypoint = useCallback(
|
||||
(id: string, targetId: string, placement: 'before' | 'after') => {
|
||||
if (!editPermissionRef.current || saveInFlightRef.current || id === targetId) return;
|
||||
commitWaypoints((current) => {
|
||||
const fromIndex = current.findIndex((point) => point.id === id);
|
||||
const targetIndex = current.findIndex((point) => point.id === targetId);
|
||||
if (fromIndex < 0 || targetIndex < 0) return current;
|
||||
const next = [...current];
|
||||
const [moved] = next.splice(fromIndex, 1);
|
||||
const targetAfterRemoval = next.findIndex((point) => point.id === targetId);
|
||||
const insertIndex = targetAfterRemoval + (placement === 'after' ? 1 : 0);
|
||||
next.splice(insertIndex, 0, moved);
|
||||
return next;
|
||||
});
|
||||
},
|
||||
[commitWaypoints]
|
||||
);
|
||||
|
||||
const undo = useCallback(() => {
|
||||
if (!editPermissionRef.current) return
|
||||
const previous = history.past[history.past.length - 1]
|
||||
@@ -304,6 +345,60 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
if (status === 'saved' || status === 'saving') setStatus(waypointsRef.current.length < 2 ? 'dirty' : 'ready')
|
||||
}, [invalidateDetailRequest, name, status])
|
||||
|
||||
const setDescription = useCallback((value: string) => {
|
||||
if (!editPermissionRef.current || value === description) return
|
||||
invalidateDetailRequest()
|
||||
draftRevisionRef.current += 1
|
||||
setDescriptionState(value)
|
||||
setHasUnsavedChanges(true)
|
||||
setSaveOutcome(null)
|
||||
if (status === 'saved' || status === 'saving') setStatus(waypointsRef.current.length < 2 ? 'dirty' : 'ready')
|
||||
}, [description, invalidateDetailRequest, status])
|
||||
|
||||
const setWebsite = useCallback((value: string) => {
|
||||
if (!editPermissionRef.current || value === website) return
|
||||
invalidateDetailRequest()
|
||||
draftRevisionRef.current += 1
|
||||
setWebsiteState(value)
|
||||
setHasUnsavedChanges(true)
|
||||
setSaveOutcome(null)
|
||||
if (status === 'saved' || status === 'saving') setStatus(waypointsRef.current.length < 2 ? 'dirty' : 'ready')
|
||||
}, [invalidateDetailRequest, status, website])
|
||||
|
||||
const setPlannedDurationMinutes = useCallback((value: number | null) => {
|
||||
if (!editPermissionRef.current || value === plannedDurationMinutes) return
|
||||
invalidateDetailRequest()
|
||||
draftRevisionRef.current += 1
|
||||
setPlannedDurationMinutesState(value)
|
||||
setHasUnsavedChanges(true)
|
||||
setSaveOutcome(null)
|
||||
if (status === 'saved' || status === 'saving') setStatus(waypointsRef.current.length < 2 ? 'dirty' : 'ready')
|
||||
}, [invalidateDetailRequest, plannedDurationMinutes, status])
|
||||
|
||||
const setBreakAdditionalMinutes = useCallback((value: number | null) => {
|
||||
if (!editPermissionRef.current || value === breakAdditionalMinutes) return
|
||||
invalidateDetailRequest()
|
||||
draftRevisionRef.current += 1
|
||||
setBreakAdditionalMinutesState(value)
|
||||
setHasUnsavedChanges(true)
|
||||
setSaveOutcome(null)
|
||||
if (status === 'saved' || status === 'saving') setStatus(waypointsRef.current.length < 2 ? 'dirty' : 'ready')
|
||||
}, [breakAdditionalMinutes, invalidateDetailRequest, status])
|
||||
|
||||
const websiteInvalid = website.trim().length > 0 && !tourWebsiteSchema.safeParse(website).success
|
||||
const plannedDurationInvalid = plannedDurationMinutes !== null
|
||||
&& (!Number.isInteger(plannedDurationMinutes) || plannedDurationMinutes < 0 || plannedDurationMinutes > MAX_PLANNED_TOUR_DURATION_MINUTES)
|
||||
const walkingDurationMinutes = durationSeconds === null ? null : Math.round(durationSeconds / 60)
|
||||
const automaticPlannedTotalMinutes = walkingDurationMinutes === null
|
||||
? null
|
||||
: walkingDurationMinutes + (breakAdditionalMinutes ?? 0)
|
||||
const breakAdditionalInvalid = breakAdditionalMinutes !== null
|
||||
&& (!Number.isInteger(breakAdditionalMinutes) || breakAdditionalMinutes < 0 || breakAdditionalMinutes > MAX_PLANNED_TOUR_DURATION_MINUTES)
|
||||
const plannedTotalMinutes = plannedDurationMinutes ?? automaticPlannedTotalMinutes
|
||||
const plannedTotalInvalid = plannedDurationMinutes === null
|
||||
&& automaticPlannedTotalMinutes !== null
|
||||
&& automaticPlannedTotalMinutes > MAX_PLANNED_TOUR_DURATION_MINUTES
|
||||
|
||||
const returnToNeutral = useCallback(() => {
|
||||
if (saveInFlightRef.current) return
|
||||
invalidateDetailRequest()
|
||||
@@ -313,6 +408,10 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
setRouteProfileFocus(null)
|
||||
localStorage.removeItem(storageKey)
|
||||
setNameState('')
|
||||
setDescriptionState('')
|
||||
setWebsiteState('')
|
||||
setPlannedDurationMinutesState(null)
|
||||
setBreakAdditionalMinutesState(null)
|
||||
setWaypoints([])
|
||||
setMaxHikingDifficultyState(2)
|
||||
waypointsRef.current = []
|
||||
@@ -430,6 +529,10 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
contextGenerationRef.current += 1
|
||||
draftRevisionRef.current += 1
|
||||
setNameState(result.tour.name)
|
||||
setDescriptionState(result.tour.description ?? '')
|
||||
setWebsiteState(result.tour.website ?? '')
|
||||
setPlannedDurationMinutesState(result.tour.planned_duration_minutes ?? null)
|
||||
setBreakAdditionalMinutesState(result.tour.break_additional_minutes ?? null)
|
||||
setWaypoints(nextWaypoints)
|
||||
setMaxHikingDifficultyState(result.tour.max_hiking_difficulty ?? 2)
|
||||
waypointsRef.current = nextWaypoints
|
||||
@@ -543,9 +646,9 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasUnsavedChanges) return
|
||||
const draft: DraftPayload = { version: 2, name, waypoints, maxHikingDifficulty, editingPlaceId }
|
||||
const draft: DraftPayload = { version: 6, name, description, website, plannedDurationMinutes, breakAdditionalMinutes, waypoints, maxHikingDifficulty, editingPlaceId }
|
||||
localStorage.setItem(storageKey, JSON.stringify(draft))
|
||||
}, [editingPlaceId, hasUnsavedChanges, maxHikingDifficulty, name, storageKey, waypoints])
|
||||
}, [breakAdditionalMinutes, description, editingPlaceId, hasUnsavedChanges, maxHikingDifficulty, name, plannedDurationMinutes, storageKey, waypoints, website])
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasUnsavedChanges) return
|
||||
@@ -556,6 +659,7 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
|
||||
const canSave = canEdit && !isSaving && hasUnsavedChanges && name.trim().length > 0 && status === 'ready'
|
||||
&& routeForKey === waypointKey && hasCompleteElevation(enrichedGeometry)
|
||||
&& description.length <= 2000 && !websiteInvalid && !plannedDurationInvalid && !breakAdditionalInvalid && !plannedTotalInvalid
|
||||
|
||||
const save = useCallback(async () => {
|
||||
if (!mountedRef.current || saveInFlightRef.current || !editPermissionRef.current || !canSave || !hasCompleteElevation(enrichedGeometry)) return null
|
||||
@@ -569,6 +673,8 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
const submittedPlaceId = editingPlaceId
|
||||
const payload = {
|
||||
name: name.trim(),
|
||||
description: description.trim() || null,
|
||||
website: website.trim() ? tourWebsiteSchema.parse(website) : null,
|
||||
tour_type: 'hike',
|
||||
route_geometry: enrichedGeometry.map(point => [point[0], point[1], point[2]]),
|
||||
waypoints: waypoints.map((point, sequence) => ({
|
||||
@@ -579,6 +685,8 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
})),
|
||||
max_hiking_difficulty: maxHikingDifficulty,
|
||||
duration_seconds: durationSeconds,
|
||||
planned_duration_minutes: plannedDurationMinutes,
|
||||
break_additional_minutes: breakAdditionalMinutes,
|
||||
} as const
|
||||
setStatus('saving')
|
||||
setIsSaving(true)
|
||||
@@ -618,13 +726,17 @@ export function useTourPlanner({ tripId, active = true, onSaved, canEdit: editPe
|
||||
setIsSaving(false)
|
||||
}
|
||||
}
|
||||
}, [canSave, durationSeconds, editingPlaceId, enrichedGeometry, invalidateDetailRequest, maxHikingDifficulty, name, onSaved, storageKey, tripId, waypoints])
|
||||
}, [breakAdditionalMinutes, canSave, description, durationSeconds, editingPlaceId, enrichedGeometry, invalidateDetailRequest, maxHikingDifficulty, name, onSaved, plannedDurationMinutes, storageKey, tripId, waypoints, website])
|
||||
|
||||
return {
|
||||
canEdit, canAssign,
|
||||
name, setName, maxHikingDifficulty, setMaxHikingDifficulty,
|
||||
description, setDescription, website, setWebsite, websiteInvalid,
|
||||
plannedDurationMinutes, setPlannedDurationMinutes, plannedDurationInvalid,
|
||||
breakAdditionalMinutes, setBreakAdditionalMinutes, breakAdditionalInvalid,
|
||||
walkingDurationMinutes, plannedTotalMinutes, plannedTotalInvalid,
|
||||
waypoints, selectedWaypointId, setSelectedWaypointId,
|
||||
addWaypoint, removeWaypoint, moveWaypoint,
|
||||
addWaypoint, setWaypointPosition, removeWaypoint, moveWaypoint, reorderWaypoint,
|
||||
undo, redo, canUndo: history.past.length > 0, canRedo: history.future.length > 0,
|
||||
status, error, retry, isSaving,
|
||||
route, enrichedGeometry, routeAnalysis, distanceMeters, durationSeconds,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import type { TourListItem } from '@trek/shared'
|
||||
import { AlertTriangle, ArrowDown, ArrowUp, ChevronDown, Mountain, Plus, Ruler } from 'lucide-react'
|
||||
import { AlertTriangle, ArrowDown, ArrowUp, ChevronDown, Clock, Mountain, Plus, Ruler } from 'lucide-react'
|
||||
import type { Day, DistanceUnit } from '../../types'
|
||||
import type { RouteGeometryAnalysis } from '../../utils/routeGeometry'
|
||||
import { useTranslation } from '../../i18n'
|
||||
@@ -13,7 +13,7 @@ import { Tooltip } from '../shared/Tooltip'
|
||||
import { useTripStore } from '../../store/tripStore'
|
||||
import { BOX, Eyebrow } from '../Planner/bookings/bookingParts'
|
||||
import { SoftPill } from '../Planner/planParts'
|
||||
import { hikeSourceBadgeLabel } from './tourPresentation'
|
||||
import { formatPlannedTourDuration, hikeSourceBadgeLabel, tourPlannedTimes } from './tourPresentation'
|
||||
|
||||
type Translate = (key: string, params?: Record<string, unknown>) => string
|
||||
|
||||
@@ -31,6 +31,7 @@ export function TourFactPills({ tour, className = '' }: { tour: TourListItem; cl
|
||||
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}`}>
|
||||
<SoftPill className="tabular-nums" icon={<Ruler size={10} strokeWidth={2.2} className="flex-none text-content-faint" />}>
|
||||
@@ -46,6 +47,27 @@ export function TourFactPills({ tour, className = '' }: { tour: TourListItem; cl
|
||||
<span aria-label={`${t('tours.detail.descent')}: ${formatElevation(tour.elevation_loss, unit)}`}>{formatElevation(tour.elevation_loss, unit)}</span>
|
||||
</SoftPill>
|
||||
)}
|
||||
{times.walkingMinutes != null && (
|
||||
<SoftPill className="tabular-nums" icon={<Clock size={10} strokeWidth={2.2} className="flex-none text-content-faint" />}>
|
||||
<span aria-label={`${t('tours.planner.inspector.duration')}: ${formatPlannedTourDuration(times.walkingMinutes)}`}>
|
||||
{t('tours.planner.walkingShort')} {formatPlannedTourDuration(times.walkingMinutes)}
|
||||
</span>
|
||||
</SoftPill>
|
||||
)}
|
||||
{times.breakMinutes != null && (
|
||||
<SoftPill className="tabular-nums" icon={<Clock size={10} strokeWidth={2.2} className="flex-none text-content-faint" />}>
|
||||
<span aria-label={`${t('tours.planner.breaksAdditional')}: ${formatPlannedTourDuration(times.breakMinutes)}`}>
|
||||
{t('tours.planner.breaksShort')} {formatPlannedTourDuration(times.breakMinutes)}
|
||||
</span>
|
||||
</SoftPill>
|
||||
)}
|
||||
{times.plannedTotalMinutes != null && (
|
||||
<SoftPill className="tabular-nums" icon={<Clock size={10} strokeWidth={2.2} className="flex-none text-content-faint" />}>
|
||||
<span aria-label={`${t('tours.planner.plannedTotalDuration')}: ${formatPlannedTourDuration(times.plannedTotalMinutes)}${times.manuallyOverridden ? `, ${t('tours.planner.plannedTotalManual')}` : ''}`}>
|
||||
{t('tours.planner.plannedShort')} {formatPlannedTourDuration(times.plannedTotalMinutes)}{times.manuallyOverridden ? ` · ${t('tours.planner.plannedTotalManual')}` : ''}
|
||||
</span>
|
||||
</SoftPill>
|
||||
)}
|
||||
<Tooltip label={difficulty}>
|
||||
<span aria-label={difficulty} className="inline-flex">
|
||||
<SoftPill>T{tour.max_hiking_difficulty}</SoftPill>
|
||||
|
||||
@@ -1,7 +1,23 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { filterTours, hikeSourceBadgeLabel, tourSource } from './tourPresentation'
|
||||
import { filterTours, formatPlannedTourDuration, hikeSourceBadgeLabel, tourPlannedTimes, tourSource, tourWebsitePresentation } from './tourPresentation'
|
||||
|
||||
describe('tourPresentation', () => {
|
||||
it('formats planned Tour totals using the shared compact duration formatter', () => {
|
||||
expect(formatPlannedTourDuration(0)).toBe('0 min')
|
||||
expect(formatPlannedTourDuration(45)).toBe('45 min')
|
||||
expect(formatPlannedTourDuration(95)).toBe('1 h 35 min')
|
||||
})
|
||||
|
||||
it('calculates planned total from walking and breaks unless a manual override exists', () => {
|
||||
expect(tourPlannedTimes({ duration: 80, planned_duration_minutes: null, break_additional_minutes: 25 })).toEqual({
|
||||
walkingMinutes: 80, breakMinutes: 25, plannedTotalMinutes: 105, manuallyOverridden: false,
|
||||
})
|
||||
expect(tourPlannedTimes({ duration: 80, planned_duration_minutes: 130, break_additional_minutes: 25 })).toEqual({
|
||||
walkingMinutes: 80, breakMinutes: 25, plannedTotalMinutes: 130, manuallyOverridden: true,
|
||||
})
|
||||
expect(tourPlannedTimes({ duration: null, planned_duration_minutes: null, break_additional_minutes: 25 }).plannedTotalMinutes).toBeNull()
|
||||
})
|
||||
|
||||
it('uses the source abstraction for TREK, GPX import, and wanderer badges', () => {
|
||||
const t = vi.fn((key: string) => key)
|
||||
|
||||
@@ -27,4 +43,29 @@ describe('tourPresentation', () => {
|
||||
expect(filterTours(tours, 'planned').map(tour => tour.id)).toEqual([1, 3])
|
||||
expect(filterTours([], 'planned')).toEqual([])
|
||||
})
|
||||
it.each([
|
||||
['https://www.komoot.com/tour/42', 'Komoot', 'komoot.com'],
|
||||
['https://trail.alltrails.com/route/42', 'AllTrails', 'trail.alltrails.com'],
|
||||
['https://www.outdooractive.de/route/42', 'Outdooractive', 'outdooractive.de'],
|
||||
['https://demo.wanderer.to/trail/view/42', 'Wanderer', 'demo.wanderer.to'],
|
||||
])('classifies %s by its hostname', (href, provider, domain) => {
|
||||
expect(tourWebsitePresentation(href)).toEqual({ href, provider, domain })
|
||||
})
|
||||
|
||||
it('labels an unknown HTTPS host as an external website domain', () => {
|
||||
expect(tourWebsitePresentation('https://www.example.org/path')).toEqual({
|
||||
href: 'https://www.example.org/path',
|
||||
provider: null,
|
||||
domain: 'example.org',
|
||||
})
|
||||
expect(tourWebsitePresentation('https://komoot.com.evil.test/route')).toMatchObject({
|
||||
provider: null,
|
||||
domain: 'komoot.com.evil.test',
|
||||
})
|
||||
})
|
||||
|
||||
it.each(['http://komoot.com/route', 'https://user:pass@komoot.com/route', 'javascript:alert(1)'])
|
||||
('does not classify unsafe URL %s', value => {
|
||||
expect(tourWebsitePresentation(value)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,9 +1,61 @@
|
||||
import type { TourListItem } from '@trek/shared'
|
||||
import { tourWebsiteSchema } from '@trek/shared'
|
||||
import { formatDurationShort } from '@trek/shared/roadtrip'
|
||||
|
||||
export type TourSource = 'trek' | 'gpx' | 'wanderer'
|
||||
|
||||
/** All / Unplanned / Planned, the same three states as the Places pool. */
|
||||
export type TourFilter = 'all' | 'unplanned' | 'planned'
|
||||
export interface TourWebsitePresentation {
|
||||
href: string
|
||||
domain: string
|
||||
provider: 'Komoot' | 'AllTrails' | 'Outdooractive' | 'Wanderer' | null
|
||||
}
|
||||
|
||||
export function formatPlannedTourDuration(minutes: number): string {
|
||||
return formatDurationShort(minutes * 60)
|
||||
}
|
||||
|
||||
export interface TourPlannedTimes {
|
||||
walkingMinutes: number | null
|
||||
breakMinutes: number | null
|
||||
plannedTotalMinutes: number | null
|
||||
manuallyOverridden: boolean
|
||||
}
|
||||
|
||||
export function tourPlannedTimes(tour: Pick<TourListItem, 'duration' | 'planned_duration_minutes' | 'break_additional_minutes'>): TourPlannedTimes {
|
||||
const manualOverride = tour.planned_duration_minutes ?? null
|
||||
const breaks = tour.break_additional_minutes ?? 0
|
||||
const plannedTotal = manualOverride ?? (tour.duration == null ? null : tour.duration + breaks)
|
||||
return {
|
||||
walkingMinutes: tour.duration,
|
||||
breakMinutes: tour.break_additional_minutes ?? null,
|
||||
plannedTotalMinutes: plannedTotal,
|
||||
manuallyOverridden: manualOverride !== null,
|
||||
}
|
||||
}
|
||||
|
||||
const TOUR_WEBSITE_PROVIDERS = [
|
||||
{ provider: 'Komoot', domains: ['komoot.com'] },
|
||||
{ provider: 'AllTrails', domains: ['alltrails.com'] },
|
||||
{ provider: 'Outdooractive', domains: ['outdooractive.com', 'outdooractive.de'] },
|
||||
{ provider: 'Wanderer', domains: ['wanderer.to'] },
|
||||
] as const
|
||||
|
||||
/** Classifies only the parsed host. It never resolves or requests the URL. */
|
||||
export function tourWebsitePresentation(value: string | null | undefined): TourWebsitePresentation | null {
|
||||
const parsed = tourWebsiteSchema.safeParse(value)
|
||||
if (!parsed.success) return null
|
||||
const hostname = new URL(parsed.data).hostname.toLowerCase().replace(/^www\./, '')
|
||||
const match = TOUR_WEBSITE_PROVIDERS.find(({ domains }) =>
|
||||
domains.some(domain => hostname === domain || hostname.endsWith(`.${domain}`))
|
||||
)
|
||||
return {
|
||||
href: parsed.data,
|
||||
domain: hostname,
|
||||
provider: match?.provider ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
type Translate = (key: string, params?: Record<string, unknown>) => string
|
||||
|
||||
|
||||
@@ -71,6 +71,10 @@ describe('Tours English and German copy', () => {
|
||||
expect(de['tours.planner.safetyNoteDetails']).toMatch(/OSM.*Wetter.*Sperrungen/)
|
||||
expect(de['tours.planner.difficulty.t3Warning']).toMatch(/Trittsicherheit/)
|
||||
expect(de['tours.planner.difficulty.alpineBody']).toMatch(/OSM/)
|
||||
expect(toursText(en, 'tours.planner.breaksAdditionalInfo')).toBe('Optional whole minutes added to calculated walking time.')
|
||||
expect(toursText(en, 'tours.planner.plannedTotalInfo')).toBe('Calculated planned total duration.')
|
||||
expect(toursText(de, 'tours.planner.breaksAdditionalInfo')).toBe('Optionale ganze Minuten, die zur berechneten Gehzeit hinzukommen.')
|
||||
expect(toursText(de, 'tours.planner.plannedTotalInfo')).toBe('Berechnete geplante Gesamtdauer.')
|
||||
})
|
||||
|
||||
for (const [language, neutral, newTitle, editTitle, gpxTitle, back] of [
|
||||
|
||||
Reference in New Issue
Block a user