feat(tours): tidy the tour editor and tour list, set points only on purpose, name waypoints on the map

This commit is contained in:
Maurice
2026-10-14 17:13:24 +02:00
parent 160bc89e78
commit e3983ef857
72 changed files with 2607 additions and 869 deletions
@@ -331,7 +331,7 @@ describe('TripPlannerPage — shell', () => {
expect(plannerActions.addWaypoint).toHaveBeenCalledWith(35.02, 135.77)
})
it('preserves the visible TOUR-PLANNER camera when Plan another starts a new Tour', async () => {
it('preserves the visible TOUR-PLANNER camera when a new Tour starts after a save', async () => {
const savedTour = {
place_id: 82,
name: 'Saved Kyoto tour',
@@ -363,7 +363,7 @@ describe('TripPlannerPage — shell', () => {
const mapElement = screen.getByTestId('map-view')
expect(props('map').focusPoints).toEqual([[35.01, 135.76], [35.02, 135.77]])
fireEvent.click(await screen.findByRole('button', { name: 'Plan another' }))
act(() => { plannerActions.startNewTour() })
expect(plannerActions.startNewTour).toHaveBeenCalledOnce()
view.rerender(<TripPlannerPage />)
@@ -1,4 +1,4 @@
// FE-PAGE-TOURSTAGE-001 to FE-PAGE-TOURSTAGE-012
// FE-PAGE-TOURSTAGE-001 to FE-PAGE-TOURSTAGE-016
import type { Ferrata } from '@trek/shared';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { act, fireEvent, render, screen, waitFor } from '../../../tests/helpers/render';
@@ -99,6 +99,8 @@ function planner(
setSelectedWaypointId: vi.fn(),
setWaypointPosition: vi.fn(() => true),
addWaypoint: vi.fn(),
undo: vi.fn(),
maxHikingDifficulty: null,
routeAnalysis: null,
readOnlyGpxAnalysis: null,
mapBaseLayer: 'default',
@@ -109,8 +111,8 @@ function planner(
} as unknown as Planner;
}
function renderStage(tourPlanner: Planner, canPlaceEdit = true) {
const props = {
function stageProps(tourPlanner: Planner, canPlaceEdit = true) {
return {
tripId: 7,
mapTileUrl: '',
leftHidden: false,
@@ -123,7 +125,24 @@ function renderStage(tourPlanner: Planner, canPlaceEdit = true) {
leftPanelPx: 320,
rightPanelPx: 380,
} as unknown as TourPlannerMapStageProps;
return render(<TourPlannerMapStage {...props} />);
}
function renderStage(tourPlanner: Planner, canPlaceEdit = true) {
return render(<TourPlannerMapStage {...stageProps(tourPlanner, canPlaceEdit)} />);
}
function pointer(type: string, x: number, y: number): Event {
const event = new Event(type, { bubbles: true, cancelable: true });
Object.defineProperties(event, { clientX: { value: x }, clientY: { value: y }, pointerId: { value: 1 } });
return event;
}
/** A press on the map surface that travels `dx` pixels before it is let go. */
function press(dx: number) {
const surface = screen.getByTestId('tour-map-surface');
surface.dispatchEvent(pointer('pointerdown', 100, 100));
surface.dispatchEvent(pointer('pointermove', 100 + dx, 100));
surface.dispatchEvent(pointer('pointerup', 100 + dx, 100));
}
/** Switches the flat map to 3D and waits for the GL engine to load. */
@@ -133,6 +152,7 @@ async function openTerrain() {
}
beforeEach(() => {
window.sessionStorage.clear();
stage.listeners.clear();
stage.flatMap.props = null;
stage.search.props = null;
@@ -157,7 +177,7 @@ describe('TourPlannerMapStage', () => {
const tourPlanner = planner('new-draft');
renderStage(tourPlanner);
const props = stage.flatMap.props;
expect(props?.plannerWaypoints).toEqual([{ id: 'w1', lat: 46, lng: 7 }]);
expect(props?.plannerWaypoints).toEqual([expect.objectContaining({ id: 'w1', lat: 46, lng: 7 })]);
expect(props?.selectedPlannerWaypointId).toBe('w1');
expect(props?.onPlannerWaypointMove).toBe(tourPlanner.setWaypointPosition);
props?.onMapClick?.({ latlng: { lat: 46.2, lng: 7.2 } } as never);
@@ -173,11 +193,21 @@ describe('TourPlannerMapStage', () => {
expect(props?.onPlannerWaypointMove).toBeUndefined();
});
it('FE-PAGE-TOURSTAGE-003: the 3D switch opens the terrain, where a click plans the next point', async () => {
it('FE-PAGE-TOURSTAGE-003: the 3D switch opens the terrain, where a click plans once "set points" is on', async () => {
const tourPlanner = planner('edit-saved');
renderStage(tourPlanner);
await openTerrain();
expect(screen.queryByRole('button', { name: 'flat map' })).toBeNull();
// Off to begin with in 3D, where every look around is a drag.
const tool = screen.getByRole('button', { name: 'Set points' });
expect(tool).toHaveAttribute('aria-pressed', 'false');
expect(screen.getByText('Turn on Set points to click points onto the terrain.')).toBeInTheDocument();
act(() => stage.fire('click', { lngLat: { lat: 46.3, lng: 7.3 } }));
expect(tourPlanner.addWaypoint).not.toHaveBeenCalled();
fireEvent.click(tool);
expect(screen.getByRole('button', { name: 'Set points' })).toHaveAttribute('aria-pressed', 'true');
expect(screen.getByTestId('tour-map-surface')).toHaveAttribute('data-placing', 'true');
expect(screen.getByText(/Click the terrain to set points/)).toBeInTheDocument();
act(() => stage.fire('click', { lngLat: { lat: 46.3, lng: 7.3 } }));
expect(tourPlanner.addWaypoint).toHaveBeenCalledWith(46.3, 7.3);
@@ -317,4 +347,62 @@ describe('TourPlannerMapStage', () => {
act(() => stage.flatMap.props?.onMapClick?.({ latlng: { lat: 46.3, lng: 7.3 } } as never));
expect(tourPlanner.addWaypoint).toHaveBeenCalledWith(46.3, 7.3);
});
it('FE-PAGE-TOURSTAGE-013: on the flat map "set points" starts on, with the crosshair, and off it takes no clicks', () => {
renderStage(planner('new-draft'));
expect(stage.flatMap.props?.placeTool?.active).toBe(true);
expect(screen.getByTestId('tour-map-surface')).toHaveAttribute('data-placing', 'true');
act(() => stage.flatMap.props?.placeTool?.onToggle());
expect(stage.flatMap.props?.placeTool?.active).toBe(false);
expect(stage.flatMap.props?.onMapClick).toBeUndefined();
expect(screen.getByTestId('tour-map-surface')).not.toHaveAttribute('data-placing');
});
it('FE-PAGE-TOURSTAGE-014: the end of a pan or a rotation never places a point, a click does, in 2D and 3D', async () => {
const tourPlanner = planner('new-draft');
renderStage(tourPlanner);
press(12);
act(() => stage.flatMap.props?.onMapClick?.({ latlng: { lat: 46.2, lng: 7.2 } } as never));
expect(tourPlanner.addWaypoint).not.toHaveBeenCalled();
press(1);
act(() => stage.flatMap.props?.onMapClick?.({ latlng: { lat: 46.2, lng: 7.2 } } as never));
expect(tourPlanner.addWaypoint).toHaveBeenCalledTimes(1);
await openTerrain();
fireEvent.click(screen.getByRole('button', { name: 'Set points' }));
press(30);
act(() => stage.fire('click', { lngLat: { lat: 46.3, lng: 7.3 } }));
expect(tourPlanner.addWaypoint).toHaveBeenCalledTimes(1);
press(0);
act(() => stage.fire('click', { lngLat: { lat: 46.3, lng: 7.3 } }));
expect(tourPlanner.addWaypoint).toHaveBeenLastCalledWith(46.3, 7.3);
});
it('FE-PAGE-TOURSTAGE-015: "point set" shows above the bottom row after a click, and its undo takes the point back', () => {
const tourPlanner = planner('new-draft');
const view = renderStage(tourPlanner);
act(() => stage.flatMap.props?.onMapClick?.({ latlng: { lat: 46.2, lng: 7.2 } } as never));
const placed = planner('new-draft', {
waypoints: [
{ id: 'w1', lat: 46, lng: 7 },
{ id: 'w2', lat: 46.2, lng: 7.2 },
],
undo: tourPlanner.undo,
});
view.rerender(<TourPlannerMapStage {...stageProps(placed)} />);
const hint = screen.getByTestId('map-undo-hint');
expect(hint).toHaveTextContent('tours.planner.pointPlaced');
// Clear of the 2D row: its 12px gap, the 42px pill, the same gap again.
expect(hint.parentElement?.parentElement?.style.bottom).toBe('66px');
fireEvent.click(screen.getByRole('button', { name: 'undo.button' }));
expect(tourPlanner.undo).toHaveBeenCalledTimes(1);
expect(screen.queryByTestId('map-undo-hint')).toBeNull();
});
it('FE-PAGE-TOURSTAGE-016: without edit rights there is no "set points" switch and no crosshair', () => {
renderStage(planner('new-draft'), false);
expect(stage.flatMap.props?.placeTool).toBeUndefined();
expect(screen.getByTestId('tour-map-surface')).not.toHaveAttribute('data-placing');
});
});
@@ -3,10 +3,12 @@ import FerrataDetailOverlay from '../../components/Ferratas/FerrataDetailOverlay
import { useFerrataMapLayer } from '../../components/Ferratas/useFerrataMapLayer';
import { useOutsidePressGuard } from '../../components/Ferratas/useOutsidePressGuard';
import { MAP_LAYER_SWITCHER_INSET, MAP_ROUND_CONTROL_SIZE } from '../../components/Map/MapLayerSwitcher';
import { MapUndoHint } from '../../components/Map/MapUndoHint';
import { MapViewAuto as MapView } from '../../components/Map/MapViewAuto';
import LocationSelect from '../../components/Planner/LocationSelect';
import { isRtlLanguage, useTranslation } from '../../i18n';
import { useSettingsStore } from '../../store/settingsStore';
import { useTourMapPoints } from './useTourMapPoints';
import type { useTripPlanner } from './useTripPlanner';
import type { useTripPlannerPage } from './useTripPlannerPage';
@@ -19,6 +21,9 @@ const TOUR_TRACK_COLOR = '#0a84ff';
const CONTROL_GAP = 12;
/** A via ferrata's card floats above the bottom row of controls, at the gap the row keeps to the edge. */
const FERRATA_CARD_BOTTOM = CONTROL_GAP + MAP_ROUND_CONTROL_SIZE + CONTROL_GAP;
/** The crosshair over either engine's map while a click sets a point (markers keep their own cursor). */
const PLACING_CURSOR =
'[&_.leaflet-container]:!cursor-crosshair [&_.maplibregl-canvas-container]:!cursor-crosshair [&_.mapboxgl-canvas-container]:!cursor-crosshair';
type Planner = ReturnType<typeof useTripPlanner>;
type PageState = ReturnType<typeof useTripPlannerPage>;
@@ -65,70 +70,80 @@ export function TourPlannerMapStage({
const { language } = useTranslation();
const distanceUnit = useSettingsStore((s) => s.settings.distance_unit);
const analysis = tourPlanner.mode.type === 'view-gpx' ? tourPlanner.readOnlyGpxAnalysis : tourPlanner.routeAnalysis;
const editing = tourPlanner.mode.type === 'new-draft' || tourPlanner.mode.type === 'edit-saved';
const canEditRoute = canPlaceEdit && !tourPlanner.isSaving && editing;
const waypoints = {
points: editing ? tourPlanner.waypoints : [],
selectedId: editing ? tourPlanner.selectedWaypointId : null,
onSelect: tourPlanner.setSelectedWaypointId,
onMove: canEditRoute ? tourPlanner.setWaypointPosition : undefined,
onAdd: closingPress.guard(canEditRoute ? tourPlanner.addWaypoint : undefined),
};
// The "set points" tool, per mode; only a real click places, never the end of a drag.
const { waypoints, placeTool, placeOn, attachSurface, placedHint } = useTourMapPoints({
tourPlanner,
canPlaceEdit,
mode: terrain3d ? '3d' : '2d',
ferrataOpen: !!ferrata.selected,
guard: closingPress.guard,
});
const onAdd = waypoints.onAdd;
// What each panel covers of the map, a collapsed one its rail.
const leftInset = leftHidden ? 56 : leftPanelPx;
const rightInset = rightHidden ? 56 : rightPanelPx;
const bottomRowTop = terrain3d ? CONTROL_GAP + terrainControlsPx + CONTROL_GAP : FERRATA_CARD_BOTTOM;
return (
<>
{terrain3d ? (
<Suspense fallback={null}>
<TourTerrainMap
samples={analysis?.distanceIndexedProfileSamples ?? []}
routes={tourMap.route}
trackColor={TOUR_TRACK_COLOR}
unit={distanceUnit}
baseLayer={tourPlanner.mapBaseLayer}
onBaseLayerChange={tourPlanner.setMapBaseLayer}
onExit={() => setTerrain3d(false)}
focus={tourPlanner.routeProfileFocus}
onFocusChange={tourPlanner.setRouteProfileFocus}
leftWidth={leftInset}
rightWidth={rightInset}
waypoints={waypoints}
framePoints={tourMap.focusPoints}
{/* Around either map, to follow its presses and show the crosshair while placing. */}
<div
ref={attachSurface}
className={`absolute inset-0 ${placeOn ? PLACING_CURSOR : ''}`}
data-testid="tour-map-surface"
data-placing={placeOn || undefined}
>
{terrain3d ? (
<Suspense fallback={null}>
<TourTerrainMap
samples={analysis?.distanceIndexedProfileSamples ?? []}
routes={tourMap.route}
trackColor={TOUR_TRACK_COLOR}
unit={distanceUnit}
baseLayer={tourPlanner.mapBaseLayer}
onBaseLayerChange={tourPlanner.setMapBaseLayer}
onExit={() => setTerrain3d(false)}
focus={tourPlanner.routeProfileFocus}
onFocusChange={tourPlanner.setRouteProfileFocus}
leftWidth={leftInset}
rightWidth={rightInset}
waypoints={waypoints}
framePoints={tourMap.focusPoints}
ferrataLayer={ferrata.layer}
onViewportChange={ferrata.onViewportChange}
onControlsHeightChange={setTerrainControlsPx}
placeTool={placeTool}
/>
</Suspense>
) : (
<MapView
tripId={tripId}
places={[]}
route={tourMap.route}
followSelection={false}
onMapClick={
onAdd
? ({ latlng }: { latlng: { lat: number; lng: number } }) => onAdd(latlng.lat, latlng.lng)
: undefined
}
tileUrl={mapTileUrl}
leftWidth={leftPanelPx}
rightWidth={rightPanelPx}
focusPoints={tourMap.focusPoints}
focusKey={tourMap.focusKey}
plannerWaypoints={waypoints.points}
selectedPlannerWaypointId={waypoints.selectedId}
onPlannerWaypointClick={tourPlanner.setSelectedWaypointId}
onPlannerWaypointMove={waypoints.onMove}
routeProfileFocus={tourPlanner.routeProfileFocus}
viewBaseLayer={tourPlanner.mapBaseLayer}
onViewBaseLayerChange={tourPlanner.setMapBaseLayer}
onToggleTerrain3d={() => setTerrain3d(true)}
ferrataLayer={ferrata.layer}
onViewportChange={ferrata.onViewportChange}
onControlsHeightChange={setTerrainControlsPx}
placeTool={placeTool}
/>
</Suspense>
) : (
<MapView
tripId={tripId}
places={[]}
route={tourMap.route}
followSelection={false}
onMapClick={closingPress.guard(
canEditRoute
? ({ latlng }: { latlng: { lat: number; lng: number } }) =>
tourPlanner.addWaypoint(latlng.lat, latlng.lng)
: undefined
)}
tileUrl={mapTileUrl}
leftWidth={leftPanelPx}
rightWidth={rightPanelPx}
focusPoints={tourMap.focusPoints}
focusKey={tourMap.focusKey}
plannerWaypoints={waypoints.points}
selectedPlannerWaypointId={waypoints.selectedId}
onPlannerWaypointClick={tourPlanner.setSelectedWaypointId}
onPlannerWaypointMove={waypoints.onMove}
routeProfileFocus={tourPlanner.routeProfileFocus}
viewBaseLayer={tourPlanner.mapBaseLayer}
onViewBaseLayerChange={tourPlanner.setMapBaseLayer}
onToggleTerrain3d={() => setTerrain3d(true)}
ferrataLayer={ferrata.layer}
onViewportChange={ferrata.onViewportChange}
/>
)}
)}
</div>
{/* The card sits at the inline end; the panels keep their physical sides, so in a
right-to-left language that end is the left panel's. */}
<FerrataDetailOverlay
@@ -136,8 +151,31 @@ export function TourPlannerMapStage({
onClose={ferrata.close}
onOutsidePress={closingPress.arm}
insetEnd={(isRtlLanguage(language) ? leftInset : rightInset) + MAP_LAYER_SWITCHER_INSET}
bottom={terrain3d ? CONTROL_GAP + terrainControlsPx + CONTROL_GAP : FERRATA_CARD_BOTTOM}
bottom={bottomRowTop}
/>
{/* "Point set", with the way back, above the bottom row and between the panels. */}
{placedHint.shown && (
<div
className="pointer-events-none absolute inset-x-0 z-[19] flex justify-center"
style={{ bottom: bottomRowTop }}
>
<div
className="flex justify-center"
style={{
transform: `translateX(${(leftInset - rightInset) / 2}px)`,
maxWidth: `calc(100% - ${leftInset + rightInset + 2 * MAP_LAYER_SWITCHER_INSET}px)`,
}}
>
<MapUndoHint
key={placedHint.key}
message={t('tours.planner.pointPlaced')}
undoLabel={t('undo.button')}
onUndo={placedHint.undoPlacement}
onHold={placedHint.hold}
/>
</div>
</div>
)}
{/* Centred over the map between the two panels, which sit on fixed physical sides. */}
<div
style={{
@@ -0,0 +1,95 @@
// FE-HOOK-PLACEDHINT-001 to FE-HOOK-PLACEDHINT-006: "point set" after a click on the map, and its undo.
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { PLACED_HINT_MS, usePlacedPointHint } from './usePlacedPointHint';
interface Props {
waypoints: readonly unknown[];
difficulty: unknown;
enabled: boolean;
}
const A = { id: 'a' };
const B = { id: 'b' };
function setup(initial: Partial<Props> = {}) {
const undo = vi.fn();
const view = renderHook((props: Props) => usePlacedPointHint({ ...props, undo }), {
initialProps: { waypoints: [A], difficulty: 'T2', enabled: true, ...initial },
});
/** Notes the click and lands the add in the same update, the way the map does. */
const place = (after: readonly unknown[], rest: Partial<Props> = {}) => {
act(() => view.result.current.notePlacement());
view.rerender({ waypoints: after, difficulty: 'T2', enabled: true, ...rest });
};
return { ...view, undo, place };
}
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
describe('usePlacedPointHint', () => {
it('FE-HOOK-PLACEDHINT-001: shows once the point is in, and its undo takes back exactly that add', () => {
const { result, undo, place } = setup();
expect(result.current.shown).toBe(false);
place([A, B]);
expect(result.current.shown).toBe(true);
act(() => result.current.undoPlacement());
expect(undo).toHaveBeenCalledTimes(1);
expect(result.current.shown).toBe(false);
});
it('FE-HOOK-PLACEDHINT-002: goes by itself after a few seconds, but not while the pointer rests on it', () => {
const { result, place } = setup();
place([A, B]);
act(() => result.current.hold(true));
act(() => vi.advanceTimersByTime(PLACED_HINT_MS * 2));
expect(result.current.shown).toBe(true);
act(() => result.current.hold(false));
act(() => vi.advanceTimersByTime(PLACED_HINT_MS - 1));
expect(result.current.shown).toBe(true);
act(() => vi.advanceTimersByTime(1));
expect(result.current.shown).toBe(false);
});
it('FE-HOOK-PLACEDHINT-003: any later change to the points ends it, so undo never reverts something else', () => {
const { result, rerender, undo, place } = setup();
place([A, B]);
rerender({ waypoints: [A, { id: 'b', moved: true }], difficulty: 'T2', enabled: true });
expect(result.current.shown).toBe(false);
act(() => result.current.undoPlacement());
expect(undo).not.toHaveBeenCalled();
});
it('FE-HOOK-PLACEDHINT-004: so does a new difficulty, which is in the same undo history', () => {
const { result, rerender, place } = setup();
const after = [A, B];
place(after);
rerender({ waypoints: after, difficulty: 'T4', enabled: true });
expect(result.current.shown).toBe(false);
});
it('FE-HOOK-PLACEDHINT-005: a refused add shows nothing, not even at the next change', () => {
const { result, rerender } = setup();
act(() => result.current.notePlacement());
rerender({ waypoints: [A], difficulty: 'T2', enabled: true });
expect(result.current.shown).toBe(false);
rerender({ waypoints: [{ id: 'a', moved: true }], difficulty: 'T2', enabled: true });
expect(result.current.shown).toBe(false);
});
it('FE-HOOK-PLACEDHINT-006: stays hidden while it must give way, and shows again after', () => {
const { result, rerender, place } = setup();
const after = [A, B];
place(after);
rerender({ waypoints: after, difficulty: 'T2', enabled: false });
expect(result.current.shown).toBe(false);
rerender({ waypoints: after, difficulty: 'T2', enabled: true });
expect(result.current.shown).toBe(true);
});
});
@@ -0,0 +1,65 @@
import { useCallback, useEffect, useRef, useState } from 'react';
/** How long the hint stays up after a point was set, unless the pointer rests on it. */
export const PLACED_HINT_MS = 4000;
interface Hint {
id: number;
/** The points before the click, to spot the list the new point produced. */
before: readonly unknown[];
/** The list right after the point went in; any other list means something came after it. */
after: readonly unknown[] | null;
difficulty: unknown;
}
interface Options {
waypoints: readonly unknown[];
/** Part of the editor's undo history too: a change to it after the point makes undo mean that. */
difficulty: unknown;
undo: () => void;
/** False while the hint must not show (not editing, a ferrata card open). */
enabled: boolean;
}
/**
* The "point set" hint after a click on the map, with an undo that takes back
* exactly that point. It goes as soon as anything else changes the tour, so
* the editor's undo, which reverts the latest change, always means the point.
*/
export function usePlacedPointHint({ waypoints, difficulty, undo, enabled }: Options) {
const [hint, setHint] = useState<Hint | null>(null);
const [held, setHeld] = useState(false);
const count = useRef(0);
// Adjusted while rendering: the add lands in the same batch as the click that noted it.
// A list that did not grow by one was no add of this click's point (it was refused).
if (hint && hint.after === null && waypoints !== hint.before) {
setHint(waypoints.length === hint.before.length + 1 ? { ...hint, after: waypoints } : null);
} else if (hint?.after && (waypoints !== hint.after || difficulty !== hint.difficulty)) {
setHint(null);
}
const shown = enabled && !!hint?.after && hint.after === waypoints && hint.difficulty === difficulty;
const hintId = shown ? hint.id : null;
useEffect(() => {
if (hintId === null || held) return;
const timer = window.setTimeout(() => setHint(null), PLACED_HINT_MS);
return () => window.clearTimeout(timer);
}, [hintId, held]);
/** Called right before the point is added. */
const notePlacement = useCallback(() => {
count.current += 1;
setHeld(false);
setHint({ id: count.current, before: waypoints, after: null, difficulty });
}, [waypoints, difficulty]);
const undoPlacement = useCallback(() => {
if (!shown) return;
setHint(null);
undo();
}, [shown, undo]);
return { shown, key: hintId, notePlacement, undoPlacement, hold: setHeld };
}
@@ -0,0 +1,101 @@
// FE-HOOK-TOURPLACING-001 to FE-HOOK-TOURPLACING-004: the tour map's "set points" tool and its click gate.
import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { initialTourPlaceToolState, useTourPlaceToolStore } from '../../store/tourPlaceToolStore';
import { useTourMapPlacing, type TourMapMode } from './useTourMapPlacing';
function pointer(type: string, x: number, y: number): Event {
const event = new Event(type, { bubbles: true, cancelable: true });
Object.defineProperties(event, { clientX: { value: x }, clientY: { value: y }, pointerId: { value: 1 } });
return event;
}
beforeEach(() => {
window.sessionStorage.clear();
useTourPlaceToolStore.setState(initialTourPlaceToolState());
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('useTourMapPlacing', () => {
it('FE-HOOK-TOURPLACING-001: on in 2D and off in 3D to begin with', () => {
const { result, rerender } = renderHook(({ mode }: { mode: TourMapMode }) => useTourMapPlacing(mode), {
initialProps: { mode: '2d' },
});
expect(result.current.active).toBe(true);
rerender({ mode: '3d' });
expect(result.current.active).toBe(false);
});
it('FE-HOOK-TOURPLACING-002: each mode keeps its own choice, for the rest of the session', () => {
const { result, rerender, unmount } = renderHook(({ mode }: { mode: TourMapMode }) => useTourMapPlacing(mode), {
initialProps: { mode: '3d' },
});
act(() => result.current.toggle());
expect(result.current.active).toBe(true);
rerender({ mode: '2d' });
act(() => result.current.toggle());
expect(result.current.active).toBe(false);
unmount();
const again = renderHook(({ mode }: { mode: TourMapMode }) => useTourMapPlacing(mode), {
initialProps: { mode: '3d' },
});
expect(again.result.current.active).toBe(true);
again.rerender({ mode: '2d' });
expect(again.result.current.active).toBe(false);
});
it('FE-HOOK-TOURPLACING-003: the gate lets a click through and drops the end of a drag', () => {
const el = document.createElement('div');
let clock = 0;
vi.spyOn(performance, 'now').mockImplementation(() => clock);
const { result } = renderHook(() => useTourMapPlacing('2d'));
act(() => result.current.attach(el));
const handler = vi.fn();
const gated = result.current.gate(handler);
el.dispatchEvent(pointer('pointerdown', 10, 10));
clock = 90;
el.dispatchEvent(pointer('pointerup', 11, 10));
gated?.(1, 2);
expect(handler).toHaveBeenCalledWith(1, 2);
el.dispatchEvent(pointer('pointerdown', 10, 10));
el.dispatchEvent(pointer('pointermove', 30, 10));
clock = 150;
el.dispatchEvent(pointer('pointerup', 30, 10));
gated?.(3, 4);
expect(handler).toHaveBeenCalledTimes(1);
// A hold that never moved, longer than a click.
clock = 1000;
el.dispatchEvent(pointer('pointerdown', 10, 10));
clock = 1600;
el.dispatchEvent(pointer('pointerup', 10, 10));
gated?.(5, 6);
expect(handler).toHaveBeenCalledTimes(1);
});
it('FE-HOOK-TOURPLACING-004: no handler, no gate; without storage the choice holds while the stage is up', () => {
const { result } = renderHook(() => useTourMapPlacing('2d'));
expect(result.current.gate(undefined)).toBeUndefined();
vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
throw new Error('blocked');
});
vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
throw new Error('blocked');
});
const blocked = renderHook(({ mode }: { mode: TourMapMode }) => useTourMapPlacing(mode), {
initialProps: { mode: '3d' },
});
expect(blocked.result.current.active).toBe(false);
act(() => blocked.result.current.toggle());
blocked.rerender({ mode: '2d' });
blocked.rerender({ mode: '3d' });
expect(blocked.result.current.active).toBe(true);
});
});
@@ -0,0 +1,48 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { createPressTracker, isPlacementTap, type PressTracker } from '../../components/Map/mapPress';
import {
setTourPlaceToolMode,
toggleTourPlacing,
useTourPlaceToolStore,
type TourMapMode,
} from '../../store/tourPlaceToolStore';
export type { TourMapMode } from '../../store/tourPlaceToolStore';
/**
* The tour map's "set points" tool: whether a click on the map places a point
* in the current mode, remembered per mode for the session, and the gate that
* lets only a real click through, never the end of a pan, a rotation or a tilt.
* `attach` goes on the element around the map, where the presses are followed.
*/
export function useTourMapPlacing(mode: TourMapMode) {
const active = useTourPlaceToolStore((state) => state.placing[mode]);
const [element, attach] = useState<HTMLElement | null>(null);
const tracker = useRef<PressTracker | null>(null);
useEffect(() => {
if (!element) return;
const next = createPressTracker(element);
tracker.current = next;
return () => {
next.dispose();
if (tracker.current === next) tracker.current = null;
};
}, [element]);
// The editor's "add point" row switches the tool for whichever mode the map shows.
useEffect(() => {
setTourPlaceToolMode(mode);
}, [mode]);
/** Lets a handler run only for a click that was a click, not a drag or a long hold. */
const gate = useCallback(<A extends unknown[]>(handler: ((...args: A) => void) | undefined) => {
if (!handler) return undefined;
return (...args: A) => {
if (!isPlacementTap(tracker.current?.take() ?? null)) return;
handler(...args);
};
}, []);
return { active, toggle: toggleTourPlacing, gate, attach };
}
@@ -0,0 +1,86 @@
import type { useOutsidePressGuard } from '../../components/Ferratas/useOutsidePressGuard';
import type { TourPlannerController } from '../../components/Tours/planner/useTourPlanner';
import { useWaypointPlaceNames } from '../../components/Tours/planner/useWaypointPlaceNames';
import { useTranslation } from '../../i18n';
import { usePlacedPointHint } from './usePlacedPointHint';
import { useTourMapPlacing, type TourMapMode } from './useTourMapPlacing';
const ROLE_KEY = {
start: 'tours.planner.start',
via: 'tours.planner.via',
end: 'tours.planner.end',
} as const;
type PointsPlanner = Pick<
TourPlannerController,
| 'mode'
| 'isSaving'
| 'waypoints'
| 'selectedWaypointId'
| 'setSelectedWaypointId'
| 'setWaypointPosition'
| 'addWaypoint'
| 'undo'
| 'maxHikingDifficulty'
>;
interface Options {
tourPlanner: PointsPlanner;
canPlaceEdit: boolean;
mode: TourMapMode;
/** A via ferrata card is open: the "point set" hint gives way to it. */
ferrataOpen: boolean;
/** Drops the click that closed a ferrata card. */
guard: ReturnType<typeof useOutsidePressGuard>['guard'];
}
/**
* The tour's control points on the planner map, for either mode: what the map
* shows and may change, the "set points" tool, and the hint with its undo
* after a point went in. A click places a point only while the tool is on,
* only when it was a click and not a drag, and never when it closed a card.
*/
export function useTourMapPoints({ tourPlanner, canPlaceEdit, mode, ferrataOpen, guard }: Options) {
const { t } = useTranslation();
const editing = tourPlanner.mode.type === 'new-draft' || tourPlanner.mode.type === 'edit-saved';
// The same lookup as the waypoint list, so a pin is named on hover as its row is.
const placeNames = useWaypointPlaceNames(editing ? tourPlanner.waypoints : []);
const canEditRoute = canPlaceEdit && !tourPlanner.isSaving && editing;
const { active, toggle, gate, attach } = useTourMapPlacing(mode);
const placeOn = canEditRoute && active;
const placedHint = usePlacedPointHint({
waypoints: tourPlanner.waypoints,
difficulty: tourPlanner.maxHikingDifficulty,
undo: tourPlanner.undo,
enabled: editing && !ferrataOpen,
});
const { notePlacement } = placedHint;
const { addWaypoint } = tourPlanner;
const addPoint = (lat: number, lng: number) => {
notePlacement();
addWaypoint(lat, lng);
};
const onAdd = guard(gate(placeOn ? addPoint : undefined));
return {
waypoints: {
points: editing
? tourPlanner.waypoints.map((point, index) => ({
...point,
name: placeNames[point.id] ?? t('tours.planner.waypointLabel', { n: index + 1 }),
detail: t(ROLE_KEY[point.role]),
}))
: [],
selectedId: editing ? tourPlanner.selectedWaypointId : null,
onSelect: tourPlanner.setSelectedWaypointId,
onMove: canEditRoute ? tourPlanner.setWaypointPosition : undefined,
onAdd,
},
/** The switch for the layer pill, there only while the tour can be edited. */
placeTool: canEditRoute ? { active, onToggle: toggle } : undefined,
placeOn,
/** Goes on the element around the map, where the presses are followed. */
attachSurface: attach,
placedHint,
};
}