diff --git a/client/src/hooks/useLocationBias.test.ts b/client/src/hooks/useLocationBias.test.ts index de8229357..6a5a937f3 100644 --- a/client/src/hooks/useLocationBias.test.ts +++ b/client/src/hooks/useLocationBias.test.ts @@ -1,7 +1,7 @@ -// FE-HOOK-LOCBIAS-001 to FE-HOOK-LOCBIAS-008 +// FE-HOOK-LOCBIAS-001 to FE-HOOK-LOCBIAS-014 import { renderHook } from '@testing-library/react'; import { useTripStore } from '../store/tripStore'; -import { boxFromCoords, pointFromBox, radiusKm, useLocationBias } from './useLocationBias'; +import { boxFromCoords, pointFromBox, radiusKm, useLocationBias, viewportBox } from './useLocationBias'; // Coordinates of real places, because the whole point of the hint is distance // and a made-up grid would not show when a box stops being useful. @@ -10,7 +10,7 @@ const KYOTO_B = { id: 2, lat: 34.9949, lng: 135.7850 }; // Kiyomizu-dera, ~2 k const TOKIO = { id: 3, lat: 35.6762, lng: 139.6503 }; // ~370 km entfernt function seed(state: Record) { - useTripStore.setState({ places: [], assignments: {}, selectedDayId: null, ...state } as never); + useTripStore.setState({ trip: null, places: [], assignments: {}, selectedDayId: null, planMapViewport: null, ...state } as never); } afterEach(() => seed({})); @@ -81,3 +81,62 @@ describe('useLocationBias', () => { expect(renderHook(() => useLocationBias()).result.current).toEqual({}); }); }); + +// Der Kartenausschnitt, auf den gerade geschaut wird (#2620). Rund 11 x 9 km um +// den Kyoto Bahnhof, so wie ihn die Karte auf Zoom 13 meldet. +const KYOTO_VIEW = { tripId: 5, south: 34.96, west: 135.70, north: 35.06, east: 135.82 }; +// Ganz Honshu auf Zoom 6, viel zu weit fuer einen brauchbaren Hinweis. +const HONSHU_VIEW = { tripId: 5, south: 33.0, west: 132.0, north: 38.0, east: 142.0 }; + +describe('useLocationBias mit Kartenausschnitt', () => { + it('nimmt den sichtbaren Ausschnitt vor allem anderen, auch bei zu weiter Reise', () => { + // Kyoto und Tokio: ohne Ausschnitt gaebe es gar keinen Hinweis. + seed({ trip: { id: 5 }, places: [KYOTO_A, TOKIO], planMapViewport: KYOTO_VIEW }); + const { box, point } = renderHook(() => useLocationBias()).result.current; + expect(box).toEqual({ low: { lat: 34.96, lng: 135.70 }, high: { lat: 35.06, lng: 135.82 } }); + expect(point!.lat).toBeCloseTo(35.01, 6); + expect(point!.lng).toBeCloseTo(135.76, 6); + }); + + it('schlaegt auch den geoeffneten Tag', () => { + // Der Tag spielt in Tokio, die Karte steht aber auf Kyoto: gesucht wird, wo hingeschaut wird. + seed({ + trip: { id: 5 }, + places: [KYOTO_A, TOKIO], + assignments: { '7': [{ place_id: 3 }] }, + selectedDayId: 7, + planMapViewport: KYOTO_VIEW, + }); + const { box } = renderHook(() => useLocationBias()).result.current; + expect(box!.high.lng).toBeLessThan(TOKIO.lng); + }); + + it('faellt bei einem zu weiten Ausschnitt auf den Tag zurueck', () => { + seed({ + trip: { id: 5 }, + places: [KYOTO_A, KYOTO_B, TOKIO], + assignments: { '7': [{ place_id: 1 }, { place_id: 2 }] }, + selectedDayId: 7, + planMapViewport: HONSHU_VIEW, + }); + const { box } = renderHook(() => useLocationBias()).result.current; + expect(box).toEqual(boxFromCoords([KYOTO_A, KYOTO_B])); + }); + + it('faellt bei einem zu weiten Ausschnitt und zu weiter Reise auf keinen Hinweis zurueck', () => { + seed({ trip: { id: 5 }, places: [KYOTO_A, TOKIO], planMapViewport: HONSHU_VIEW }); + expect(renderHook(() => useLocationBias()).result.current).toEqual({}); + }); + + it('ignoriert den Ausschnitt einer anderen Reise', () => { + seed({ trip: { id: 9 }, places: [KYOTO_A, TOKIO], planMapViewport: KYOTO_VIEW }); + expect(renderHook(() => useLocationBias()).result.current).toEqual({}); + }); + + it('nimmt keinen Ausschnitt ueber die Datumsgrenze oder ausserhalb der Welt', () => { + expect(viewportBox({ tripId: 5, south: -18, west: 179.5, north: -17, east: -179.5 })).toBeUndefined(); + expect(viewportBox({ tripId: 5, south: -18, west: -180.5, north: -17, east: -179.5 })).toBeUndefined(); + expect(viewportBox({ tripId: 5, south: Number.NaN, west: 1, north: 2, east: 2 })).toBeUndefined(); + expect(viewportBox(KYOTO_VIEW)).toEqual({ low: { lat: 34.96, lng: 135.70 }, high: { lat: 35.06, lng: 135.82 } }); + }); +}); diff --git a/client/src/hooks/useLocationBias.ts b/client/src/hooks/useLocationBias.ts index 292b9503c..18e1fbb18 100644 --- a/client/src/hooks/useLocationBias.ts +++ b/client/src/hooks/useLocationBias.ts @@ -1,5 +1,5 @@ import { useMemo } from 'react' -import { useTripStore } from '../store/tripStore' +import { useTripStore, type PlanMapViewport } from '../store/tripStore' /** * Where the user is planning right now, as a hint for the place search. @@ -21,6 +21,12 @@ import { useTripStore } from '../store/tripStore' * cities, points at nothing, and costs more rank-1 hits than it gains. It is * worse than no hint. So the day being planned comes first, and a hint that * ends up wider than a metropolitan area is dropped rather than sent. + * + * Ahead of both stands the part of the map the user is looking at (#2620). The + * numbers above are about boxes guessed from saved places; a map zoomed in on + * one city says where the next place goes without any guessing. It is held to + * the same width, so a map pulled out to a whole country leaves the search to + * the day and the trip as before. */ export interface LocationBiasBox { @@ -95,20 +101,42 @@ export function pointFromBox(box: LocationBiasBox | undefined): LocationBiasPoin } } +/** + * The plan map's viewport as a box, or nothing when it cannot be one. A view + * across the antimeridian reports west east of east, and a world map scrolled + * sideways reports longitudes past 180; neither is a box the search accepts. + */ +export function viewportBox(v: PlanMapViewport): LocationBiasBox | undefined { + const { south, west, north, east } = v + if (![south, west, north, east].every(Number.isFinite)) return undefined + if (south < -90 || north > 90 || west < -180 || east > 180) return undefined + if (south > north || west > east) return undefined + return { low: { lat: south, lng: west }, high: { lat: north, lng: east } } +} + /** * The hint for the place search, in both shapes the two endpoints want. * * Preference order, narrowest first: - * 1. the places of the day currently open — this is the area being planned - * 2. the trip's places, but only if they still fit inside one region + * 1. the plan map's visible area, while it covers no more than one region + * 2. the places of the day currently open — this is the area being planned + * 3. the trip's places, but only if they still fit inside one region * Anything wider is dropped: no hint beats a hint pointing at open country. */ export function useLocationBias(): { box?: LocationBiasBox; point?: LocationBiasPoint } { const places = useTripStore((s) => s.places) const assignments = useTripStore((s) => s.assignments) const selectedDayId = useTripStore((s) => s.selectedDayId) + const tripId = useTripStore((s) => s.trip?.id) + const viewport = useTripStore((s) => s.planMapViewport) return useMemo(() => { + // Only this trip's map: a viewport left over from another trip points elsewhere. + if (viewport && tripId != null && viewport.tripId === Number(tripId)) { + const sichtbar = viewportBox(viewport) + if (sichtbar && radiusKm(sichtbar) <= MAX_RADIUS_KM) return { box: sichtbar, point: pointFromBox(sichtbar) } + } + const alle = places || [] // The day being planned. Places reach a day through assignments, so the @@ -125,5 +153,5 @@ export function useLocationBias(): { box?: LocationBiasBox; point?: LocationBias const box = boxFromCoords(quelle) if (!box || radiusKm(box) > MAX_RADIUS_KM) return {} return { box, point: pointFromBox(box) } - }, [places, assignments, selectedDayId]) + }, [places, assignments, selectedDayId, tripId, viewport]) } diff --git a/client/src/hooks/usePlanMapViewport.test.ts b/client/src/hooks/usePlanMapViewport.test.ts new file mode 100644 index 000000000..27a6a30db --- /dev/null +++ b/client/src/hooks/usePlanMapViewport.test.ts @@ -0,0 +1,38 @@ +// FE-HOOK-PLANVIEW-001 to FE-HOOK-PLANVIEW-004 +import { act, renderHook } from '@testing-library/react'; +import { useTripStore } from '../store/tripStore'; +import { usePlanMapViewport } from './usePlanMapViewport'; + +const KYOTO = { south: 34.96, west: 135.7, north: 35.06, east: 135.82 }; + +afterEach(() => useTripStore.setState({ planMapViewport: null })); + +describe('usePlanMapViewport', () => { + it('legt den gemeldeten Ausschnitt mit der Reise in den Store', () => { + const { result } = renderHook(() => usePlanMapViewport(5)); + act(() => result.current(KYOTO)); + expect(useTripStore.getState().planMapViewport).toEqual({ tripId: 5, ...KYOTO }); + }); + + it('raeumt den Ausschnitt weg, wenn die Karte verschwindet', () => { + const { result, unmount } = renderHook(() => usePlanMapViewport(5)); + act(() => result.current(KYOTO)); + unmount(); + expect(useTripStore.getState().planMapViewport).toBeNull(); + }); + + it('raeumt ihn auch weg, sobald die Karte nicht mehr zu sehen ist, und nimmt dann nichts an', () => { + const { result, rerender } = renderHook(({ shown }) => usePlanMapViewport(5, shown), { initialProps: { shown: true } }); + act(() => result.current(KYOTO)); + rerender({ shown: false }); + expect(useTripStore.getState().planMapViewport).toBeNull(); + act(() => result.current(KYOTO)); + expect(useTripStore.getState().planMapViewport).toBeNull(); + }); + + it('meldet nichts, solange die Reise keine gueltige Id hat', () => { + const { result } = renderHook(() => usePlanMapViewport(Number.NaN)); + act(() => result.current(KYOTO)); + expect(useTripStore.getState().planMapViewport).toBeNull(); + }); +}); diff --git a/client/src/hooks/usePlanMapViewport.ts b/client/src/hooks/usePlanMapViewport.ts new file mode 100644 index 000000000..9e199cd9e --- /dev/null +++ b/client/src/hooks/usePlanMapViewport.ts @@ -0,0 +1,26 @@ +import { useCallback, useEffect } from 'react' +import { useTripStore } from '../store/tripStore' + +interface Bounds { south: number; west: number; north: number; east: number } + +/** + * Hands the plan map's viewport to the trip store, where the place search reads + * it as its first hint (#2620). Returns the callback for the map's + * `onViewportChange`. While `shown` is false, or once the map is gone, the + * viewport is cleared: a search opened away from the map has nothing visible + * to lean on, and falls back to the day and the trip. + */ +export function usePlanMapViewport(tripId: number, shown = true): (bounds: Bounds) => void { + const setPlanMapViewport = useTripStore((s) => s.setPlanMapViewport) + + useEffect(() => { + if (!shown) setPlanMapViewport(null) + return () => setPlanMapViewport(null) + }, [shown, tripId, setPlanMapViewport]) + + return useCallback((bounds: Bounds) => { + if (!shown || !Number.isFinite(tripId)) return + const { south, west, north, east } = bounds + setPlanMapViewport({ tripId, south, west, north, east }) + }, [shown, tripId, setPlanMapViewport]) +} diff --git a/client/src/mobile/screens/trip/map/MMapArea.tsx b/client/src/mobile/screens/trip/map/MMapArea.tsx index 324bbcc6f..f340a52e7 100644 --- a/client/src/mobile/screens/trip/map/MMapArea.tsx +++ b/client/src/mobile/screens/trip/map/MMapArea.tsx @@ -10,6 +10,7 @@ import { usePoiExplore } from '../../../../components/Map/usePoiExplore' import { useMergedMapPois } from '../../../../components/Map/useMergedMapPois' import { firstStopOfPlace, stageOf } from '../../../../components/Roadtrip/roadtripRowModel' import { stageMapData } from '../../../../components/Roadtrip/stageMap' +import { usePlanMapViewport } from '../../../../hooks/usePlanMapViewport' import { useRoadtripSettings } from '../../../../hooks/useRoadtripSettings' import { useSettingsStore } from '../../../../store/settingsStore' import { useTripStore } from '../../../../store/tripStore' @@ -165,6 +166,13 @@ function holdFocus( */ export default function MMapArea({ planner, shell }: MMapAreaProps) { const poi = usePoiExplore() + // The place sheet's search looks where this map looks (#2620). + const reportViewport = usePlanMapViewport(planner.tripId) + const poiViewportChange = poi.onViewportChange + const onViewportChange = useCallback((bounds: Parameters[0]) => { + poiViewportChange(bounds) + reportViewport(bounds) + }, [poiViewportChange, reportViewport]) const [glMap, setGlMap] = useState(null) const poiPillEnabled = useSettingsStore(s => s.settings.map_poi_pill_enabled) !== false const distanceUnit = useSettingsStore(s => s.settings.distance_unit) @@ -405,7 +413,7 @@ export default function MMapArea({ planner, shell }: MMapAreaProps) { onPoiClick={onStage ? planner.handlePoiClick : marker => planner.openAddPlaceFromPoi(marker, planner.selectedDayId)} - onViewportChange={poi.onViewportChange} + onViewportChange={onViewportChange} onMapReady={setGlMap} // Other ways of driving the leg the stage asked about, and the one lit up. alternativeRoutes={onStage ? planner.alternativeOverlays : undefined} diff --git a/client/src/pages/TripPlannerPage.wiring.test.tsx b/client/src/pages/TripPlannerPage.wiring.test.tsx index d54659537..e6a30a98f 100644 --- a/client/src/pages/TripPlannerPage.wiring.test.tsx +++ b/client/src/pages/TripPlannerPage.wiring.test.tsx @@ -659,10 +659,13 @@ describe('TripPlannerPage — shell', () => { hookState = { ...hookState, activeTab: 'plan' } view.rerender() act(() => props('map').onViewportChange({ south: 46.9, west: 10.8, north: 47.5, east: 12.1 })) + // The place search looks where the plan map looks (#2620), and only while it is shown. + expect(useTripStore.getState().planMapViewport).toEqual({ tripId: 42, south: 46.9, west: 10.8, north: 47.5, east: 12.1 }) plannerActions.mode = { type: 'neutral' } plannerActions.waypoints = [] hookState = { ...hookState, activeTab: 'tour-planner' } view.rerender() + expect(useTripStore.getState().planMapViewport).toBeNull() expect(props('map').focusPoints).toEqual([[46.9, 10.8], [47.5, 12.1]]) expect(props('map').route).toBeNull() diff --git a/client/src/pages/tripPlanner/useTripPlannerPage.ts b/client/src/pages/tripPlanner/useTripPlannerPage.ts index 964d00150..559fc0cca 100644 --- a/client/src/pages/tripPlanner/useTripPlannerPage.ts +++ b/client/src/pages/tripPlanner/useTripPlannerPage.ts @@ -3,6 +3,7 @@ import type { TourListItem } from '@trek/shared' import { usePoiExplore, type Bbox } from '../../components/Map/usePoiExplore' import { placeActions } from '../../components/Planner/usePlaceActions' import { useTourPlanner } from '../../components/Tours/planner/useTourPlanner' +import { usePlanMapViewport } from '../../hooks/usePlanMapViewport' import { useTripPlanner } from './useTripPlanner' export function useTripPlannerPage() { @@ -89,10 +90,13 @@ export function useTripPlannerPage() { const poi = usePoiExplore() const poiViewportChangeRef = useRef(poi.onViewportChange) poiViewportChangeRef.current = poi.onViewportChange + // The place search looks where the plan map looks, and only while it is on screen. + const reportViewport = usePlanMapViewport(tripId, activeTab === 'plan') const captureViewport = useCallback((bounds: Bbox) => { lastPlanMapViewportRef.current = bounds poiViewportChangeRef.current(bounds) - }, []) + reportViewport(bounds) + }, [reportViewport]) const onSelectTour = (tour: TourListItem | null, opener?: HTMLElement) => { tourDetailOpenerRef.current = tour && opener ? { placeId: tour.place_id, element: opener } : null diff --git a/client/src/store/tripStore.test.ts b/client/src/store/tripStore.test.ts index c576a6237..34452bcca 100644 --- a/client/src/store/tripStore.test.ts +++ b/client/src/store/tripStore.test.ts @@ -98,6 +98,7 @@ describe('tripStore', () => { selectedDayId: 1, placesFilter: 'unplanned', placesCategoryFilter: new Set(['3']), + planMapViewport: { tripId: 1, south: 1, west: 1, north: 2, east: 2 }, error: 'stale error', }); @@ -117,6 +118,8 @@ describe('tripStore', () => { expect(state.selectedDayId).toBeNull(); expect(state.placesFilter).toBe('all'); expect(state.placesCategoryFilter.size).toBe(0); + // The next trip's search must not lean on where this trip's map was. + expect(state.planMapViewport).toBeNull(); expect(state.error).toBeNull(); // Global lookups survive a trip switch. expect(state.tags.map(t => t.id)).toEqual([5]); diff --git a/client/src/store/tripStore.ts b/client/src/store/tripStore.ts index 22350a800..6052c084b 100644 --- a/client/src/store/tripStore.ts +++ b/client/src/store/tripStore.ts @@ -38,6 +38,15 @@ import type { ReservationsSlice } from './slices/reservationsSlice' import type { FilesSlice } from './slices/filesSlice' import type { PlacesRatingFloor } from '../utils/placesFilter' +/** The part of the world the trip's plan map shows, as its last move left it. */ +export interface PlanMapViewport { + tripId: number + south: number + west: number + north: number + east: number +} + export interface TripStoreState extends PlacesSlice, AssignmentsSlice, @@ -69,6 +78,9 @@ export interface TripStoreState // Minimum average stars. Shared for the same reason: the map markers and the // phone's list follow the floor the desktop list sets, and back (#1435). placesRatingFilter: PlacesRatingFloor + // Where the plan map is looking, so the place search can look there too + // (#2620). Null while no plan map is on screen. + planMapViewport: PlanMapViewport | null isLoading: boolean error: string | null @@ -76,6 +88,7 @@ export interface TripStoreState setPlacesFilter: (filter: string) => void setPlacesCategoryFilter: (categoryIds: Set) => void setPlacesRatingFilter: (floor: PlacesRatingFloor) => void + setPlanMapViewport: (viewport: PlanMapViewport | null) => void /** Lifts the pool, category and rating filters at once. */ resetPlacesFilters: () => void handleRemoteEvent: (event: WebSocketEvent) => void @@ -105,6 +118,7 @@ export const useTripStore = create((set, get) => ({ placesFilter: 'all', placesCategoryFilter: new Set(), placesRatingFilter: 'all', + planMapViewport: null, isLoading: false, error: null, @@ -112,6 +126,7 @@ export const useTripStore = create((set, get) => ({ setPlacesFilter: (filter: string) => set({ placesFilter: filter }), setPlacesCategoryFilter: (categoryIds: Set) => set({ placesCategoryFilter: categoryIds }), setPlacesRatingFilter: (floor: PlacesRatingFloor) => set({ placesRatingFilter: floor }), + setPlanMapViewport: (viewport: PlanMapViewport | null) => set({ planMapViewport: viewport }), resetPlacesFilters: () => set({ placesFilter: 'all', placesCategoryFilter: new Set(), placesRatingFilter: 'all' }), handleRemoteEvent: (event: WebSocketEvent) => handleRemoteEvent(set, get, event), @@ -134,6 +149,7 @@ export const useTripStore = create((set, get) => ({ placesFilter: 'all', placesCategoryFilter: new Set(), placesRatingFilter: 'all', + planMapViewport: null, error: null, }), diff --git a/client/tests/unit/mobile/trip/MMapArea.test.tsx b/client/tests/unit/mobile/trip/MMapArea.test.tsx index 1dd2d9465..f1d0b5627 100644 --- a/client/tests/unit/mobile/trip/MMapArea.test.tsx +++ b/client/tests/unit/mobile/trip/MMapArea.test.tsx @@ -17,7 +17,7 @@ import { openLeg } from '../../../helpers/legAlternatives' import { RT_ALT_BAR_LIFT } from '../../../../src/mobile/screens/trip/roadtrip/useMRtAlternatives' import { corePoiCategories, pluginPoiCategories } from '../../../../src/components/Map/usePoiCategories' -// FE-MOB-MAPAREA-001 to FE-MOB-MAPAREA-049 +// FE-MOB-MAPAREA-001 to FE-MOB-MAPAREA-050 // // The stage's pins come out of the trip store rather than the planner's map list, so the // stage fixtures seed the store and leave `mapPlaces` to stand for what the plan tab shows. @@ -990,3 +990,17 @@ describe('MMapArea — places filter', () => { expect(screen.queryByTestId('places-filter-pill')).not.toBeInTheDocument() }) }) + +describe('MMapArea — viewport', () => { + it('FE-MOB-MAPAREA-050: a moved map feeds both the POI bar and the place search, and leaves nothing behind (#2620)', () => { + const bounds = { south: 34.96, west: 135.7, north: 35.06, east: 135.82 } + const { unmount } = renderArea() + + act(() => (mocks.props.onViewportChange as (b: typeof bounds) => void)(bounds)) + expect(mocks.poi.onViewportChange).toHaveBeenCalledWith(bounds) + expect(useTripStore.getState().planMapViewport).toEqual({ tripId: 1, ...bounds }) + + unmount() + expect(useTripStore.getState().planMapViewport).toBeNull() + }) +}) diff --git a/client/tests/unit/mobile/trip/MPlaceEditSheet.test.tsx b/client/tests/unit/mobile/trip/MPlaceEditSheet.test.tsx index 1a5df245c..b4fba5836 100644 --- a/client/tests/unit/mobile/trip/MPlaceEditSheet.test.tsx +++ b/client/tests/unit/mobile/trip/MPlaceEditSheet.test.tsx @@ -437,7 +437,7 @@ describe('MPlaceEditSheet', () => { * carried. The hint comes from useLocationBias, which reads the trip store, * not the planner prop, so both are seeded the way the running app has them. */ - async function capturedBias(places: Place[], day?: { id: number; placeIds: number[] }) { + async function capturedBias(places: Place[], day?: { id: number; placeIds: number[] }, extra: Record = {}) { const bodies: Record[] = [] server.use(http.post('/api/maps/autocomplete', async ({ request }) => { bodies.push(await request.json() as Record) @@ -447,6 +447,7 @@ describe('MPlaceEditSheet', () => { places, assignments: day ? { [String(day.id)]: day.placeIds.map(id => ({ place_id: id })) } : {}, selectedDayId: day?.id ?? null, + ...extra, }) setup({ places }) fireEvent.change(screen.getByPlaceholderText('places.mapsSearchPlaceholder'), { target: { value: 'ueno' } }) @@ -477,6 +478,18 @@ describe('MPlaceEditSheet', () => { }) }) + it('FE-MOB-PLEDIT-029c: biases on the visible map area first, even for a trip too wide for one region (#2620)', async () => { + const places = [ + { id: 1, name: 'Tokyo', lat: 35.68, lng: 139.76 }, + { id: 2, name: 'Kyoto', lat: 35.01, lng: 135.77 }, + ] as unknown as Place[] + // The map is zoomed in on Kyoto. The trip alone would send nothing at all. + expect(await capturedBias(places, undefined, { + trip: { id: 1 }, + planMapViewport: { tripId: 1, south: 34.96, west: 135.7, north: 35.06, east: 135.82 }, + })).toEqual({ low: { lat: 34.96, lng: 135.7 }, high: { lat: 35.06, lng: 135.82 } }) + }) + it('FE-MOB-PLEDIT-030: drops the bias for a trip that outgrows one region', async () => { // Tokyo to Nagoya, 264km across: inside the old 500km diagonal rule, outside // the 60km radius one. A box that wide has its centre in open country.