diff --git a/client/src/components/Journey/JourneyMap.test.tsx b/client/src/components/Journey/JourneyMap.test.tsx index e6206a01e..d3d6f7a52 100644 --- a/client/src/components/Journey/JourneyMap.test.tsx +++ b/client/src/components/Journey/JourneyMap.test.tsx @@ -1,4 +1,4 @@ -// FE-COMP-JOURNEYMAP-001 to FE-COMP-JOURNEYMAP-061 +// FE-COMP-JOURNEYMAP-001 to FE-COMP-JOURNEYMAP-062 vi.mock('../../api/websocket', () => ({ connect: vi.fn(), @@ -12,18 +12,38 @@ vi.mock('../../api/websocket', () => ({ // Leaflet does not work in jsdom — mock the entire library vi.mock('leaflet', () => { - // The card a pin binds; `once('add')` is where its element gets its tap. - const mockTooltip = { once: vi.fn().mockReturnThis() }; const domEvent = { on: vi.fn((el: HTMLElement, types: string, fn: (e: Event) => void) => { types.split(' ').forEach(type => el.addEventListener(type, fn)); }), stopPropagation: vi.fn((e: Event) => e.stopPropagation()), + disableClickPropagation: vi.fn((el: HTMLElement) => { + for (const type of ['mousedown', 'touchstart', 'dblclick', 'contextmenu']) el.addEventListener(type, e => e.stopPropagation()); + }), + }; + // The openable card (#2885): one per map, put on and taken off by the map itself. + // Its element is built on the first add, inside a stand-in for the map container. + const cardState = { onMap: false, element: null as HTMLElement | null, onAdd: [] as (() => void)[] }; + const mockCard = { + state: cardState, + once: vi.fn((_type: string, fn: () => void) => { cardState.onAdd.push(fn); }), + setLatLng: vi.fn().mockReturnThis(), + setContent: vi.fn().mockReturnThis(), + getElement: vi.fn(() => cardState.element), + addTo: vi.fn(() => { + if (!cardState.element) { + cardState.element = document.createElement('div'); + cardState.element.innerHTML = '
card
'; + document.createElement('div').appendChild(cardState.element); + } + cardState.onMap = true; + cardState.onAdd.splice(0).forEach(fn => fn()); + }), + remove: vi.fn(() => { cardState.onMap = false; }), }; const mockMarker = { addTo: vi.fn().mockReturnThis(), bindTooltip: vi.fn().mockReturnThis(), - getTooltip: vi.fn(() => mockTooltip), on: vi.fn().mockReturnThis(), setIcon: vi.fn(), setZIndexOffset: vi.fn(), @@ -53,6 +73,7 @@ vi.mock('leaflet', () => { off: vi.fn(), project: vi.fn(() => ({ x: 0, y: 0 })), latLngToContainerPoint: vi.fn(() => ({ x: 0, y: 0 })), + hasLayer: vi.fn((layer: unknown) => (layer === mockCard ? cardState.onMap : true)), }; return { default: { @@ -66,6 +87,7 @@ vi.mock('leaflet', () => { // The map builds its own attribution control so it can collapse to the credit // alone (see the GL twin: the phone lays a carousel over the bottom edge). control: { attribution: vi.fn(() => ({ addTo: vi.fn() })) }, + tooltip: vi.fn(() => mockCard), DomEvent: domEvent, }, map: vi.fn(() => mockMap), @@ -75,6 +97,7 @@ vi.mock('leaflet', () => { divIcon: vi.fn(() => ({})), latLngBounds: vi.fn(() => ({})), control: { attribution: vi.fn(() => ({ addTo: vi.fn() })) }, + tooltip: vi.fn(() => mockCard), DomEvent: domEvent, }; }); @@ -89,6 +112,7 @@ import type { Mock } from 'vitest'; import L from 'leaflet'; import JourneyMap from './JourneyMap'; import type { JourneyMapHandle } from './JourneyMap'; +import type { JourneyMapLayerVisibility } from './journeyMapLayers'; import { mercatorWorldPx } from './journeyMapMarks'; import type { JourneyMapStay } from '@trek/shared'; @@ -194,59 +218,105 @@ describe('JourneyMap', () => { }); describe('the marker card as a way into the entry (#2885)', () => { - /** Builds each card's element the way Leaflet does on its first open, inside the map. */ - function openCards() { - const tooltip = mockedMarker().getTooltip(); - const mapClick = vi.fn(); - const mapPress = vi.fn(); - return vi.mocked(tooltip.once).mock.calls.map(([event, onAdd]: [string, (e: unknown) => void]) => { - expect(event).toBe('add'); - const el = document.createElement('div'); - el.innerHTML = '
card
'; - const map = document.createElement('div'); - map.appendChild(el); - map.addEventListener('click', mapClick); - map.addEventListener('mousedown', mapPress); - onAdd({ target: { getElement: () => el } }); - return { title: el.firstElementChild as HTMLElement, mapClick, mapPress }; - }); + interface MockCard { + state: { onMap: boolean; element: HTMLElement | null; onAdd: (() => void)[] }; + addTo: Mock; + remove: Mock; + setContent: Mock; + } + // The leaflet mock hands every map the same card, so each case starts it unbuilt and off the map. + function mockedCard(): MockCard { + const card = vi.mocked(L.tooltip)() as unknown as MockCard; + vi.mocked(L.tooltip).mockClear(); + return card; } - it('FE-COMP-JOURNEYMAP-059: a tap on a pin's card opens that entry and never reaches the map', () => { - const onMarkerCardClick = vi.fn(); - render(); + beforeEach(() => { + Object.assign(mockedCard().state, { onMap: false, element: null, onAdd: [] }); + }); - expect(mockedMarker().bindTooltip).toHaveBeenCalledWith( - expect.any(String), - expect.objectContaining({ className: 'map-tooltip trek-journey-tooltip is-openable' }), + function renderOpenable(onMarkerCardClick = vi.fn(), visibility?: JourneyMapLayerVisibility) { + const ref = React.createRef(); + const view = render( + , ); - const [first, second] = openCards(); - second.title.click(); - first.title.click(); + return { ...view, ref, onMarkerCardClick }; + } + + function cardTitle(): HTMLElement { + return mockedCard().state.element!.firstElementChild as HTMLElement; + } + + it('FE-COMP-JOURNEYMAP-059: a tap on the card over the active pin opens that entry and never reaches the map', () => { + const { ref, onMarkerCardClick } = renderOpenable(); + act(() => ref.current!.highlightMarker('e2')); + + expect(L.tooltip).toHaveBeenCalledWith(expect.objectContaining({ className: 'map-tooltip trek-journey-tooltip is-openable' })); + const container = mockedCard().state.element!.parentElement!; + const mapClick = vi.fn(); + const mapPress = vi.fn(); + container.addEventListener('click', mapClick); + container.addEventListener('mousedown', mapPress); + + cardTitle().dispatchEvent(new MouseEvent('mousedown', { bubbles: true })); + cardTitle().click(); + act(() => ref.current!.highlightMarker('e1')); + cardTitle().click(); expect(onMarkerCardClick.mock.calls).toEqual([['e2'], ['e1']]); - expect(first.mapClick).not.toHaveBeenCalled(); + expect(mapClick).not.toHaveBeenCalled(); + expect(mapPress).not.toHaveBeenCalled(); }); - it('FE-COMP-JOURNEYMAP-060: pressing the card keeps the focus, so the pin does not close it first', () => { - render(); - const [card] = openCards(); + it('FE-COMP-JOURNEYMAP-060: the pins do not open or close the card, so leaving the pin for the card keeps it', () => { + const { ref } = renderOpenable(); + act(() => ref.current!.highlightMarker('e1')); - const press = new MouseEvent('mousedown', { bubbles: true, cancelable: true }); - card.title.dispatchEvent(press); - - expect(press.defaultPrevented).toBe(true); - expect(card.mapPress).not.toHaveBeenCalled(); + // A bound tooltip is what Leaflet closes on the pin's mouseout and blur, which + // a tap on the card sends first. The pins bind none and listen for the tap alone. + expect(mockedMarker().bindTooltip).not.toHaveBeenCalled(); + expect(vi.mocked(mockedMarker().on).mock.calls.map(([type]) => type)).toEqual(['click', 'click']); + expect(mockedCard().state.onMap).toBe(true); + expect(mockedCard().remove).not.toHaveBeenCalled(); }); - it('FE-COMP-JOURNEYMAP-061: without a handler the card stays a label the map's drags pass through', () => { - render(); + it('FE-COMP-JOURNEYMAP-061: the card follows the active pin and leaves with it or with the pins', () => { + mockedMarkerWithRemove(); + const card = mockedCard(); + const shown = { plan: true, recorded: true, entries: true }; + const onMarkerCardClick = vi.fn(); + const { ref, rerender } = renderOpenable(onMarkerCardClick, shown); + const map = mockedMap(); + + act(() => ref.current!.highlightMarker('e1')); + expect(card.setContent).toHaveBeenLastCalledWith(expect.stringContaining('Paris')); + act(() => ref.current!.highlightMarker('e2')); + expect(card.setContent).toHaveBeenLastCalledWith(expect.stringContaining('Berlin')); + expect(card.addTo).toHaveBeenCalledTimes(1); + + act(() => ref.current!.highlightMarker(null)); + expect(card.state.onMap).toBe(false); + + act(() => ref.current!.highlightMarker('e1')); + map.hasLayer.mockImplementation((layer: unknown) => layer === card && card.state.onMap); + try { + rerender(); + expect(card.state.onMap).toBe(false); + } finally { + map.hasLayer.mockImplementation((layer: unknown) => (layer === card ? card.state.onMap : true)); + } + }); + + it('FE-COMP-JOURNEYMAP-062: without a handler the card stays a hover label on each pin that the drags on the map pass through', () => { + const ref = React.createRef(); + render(); + act(() => ref.current!.highlightMarker('e1')); expect(mockedMarker().bindTooltip).toHaveBeenCalledWith( expect.any(String), expect.objectContaining({ className: 'map-tooltip trek-journey-tooltip' }), ); - expect(mockedMarker().getTooltip().once).not.toHaveBeenCalled(); + expect(L.tooltip).not.toHaveBeenCalled(); }); }); diff --git a/client/src/components/Journey/JourneyMap.tsx b/client/src/components/Journey/JourneyMap.tsx index 7c227dca7..2e3d90165 100644 --- a/client/src/components/Journey/JourneyMap.tsx +++ b/client/src/components/Journey/JourneyMap.tsx @@ -69,7 +69,8 @@ interface Props { * Open the entry a marker card names when the card itself is tapped. * * On a phone the card is what a tap on a pin brings up, so it has to lead - * somewhere (#2885). Wiring it is what makes the card take the pointer; without + * somewhere (#2885). Wiring it is what makes the card take the pointer, and the + * card then stands over the active pin, as the GL popup does; without * it the card stays a label the map's drags pass through, as on desktop, where * it is a hover card the mouse cannot reach. */ @@ -185,26 +186,46 @@ function panToMarker(map: L.Map, marker: L.Marker): void { } /** - * Let a tap on a marker card open its entry (#2885). - * - * Handled on the card's own element rather than through Leaflet's interactive - * tooltip, and kept away from the map. A press that reaches the map container - * has Leaflet's keyboard handler focus it, which blurs the pin that opened the - * card, and Leaflet closes a pin's card on blur, so the card was gone before its - * click landed. Holding the mouse press back from the browser's focus change - * matters for the same reason; a touch press is left alone, since cancelling it - * would cancel the click as well. + * The same card the GL renderer shows, from the same builder: which map engine a + * reader happens to have selected should not change what a marker tells them + * (discussion #2299). The builder escapes everything that came from a person, + * which matters most here, since this map is what the public journey page renders. */ -function makeCardOpenEntry(el: HTMLElement, open: () => void): void { - L.DomEvent.on(el, 'mousedown', (ev) => { - L.DomEvent.stopPropagation(ev) - ev.preventDefault() +function entryCardHtml(item: MapMarkerItem): string { + return journeyPopupHtml({ + title: item.label || item.locationName || 'Entry', + place: item.label ? item.locationName : '', + date: formatMarkerDate(item.time), + photoUrls: item.photoUrls, }) - L.DomEvent.on(el, 'touchstart pointerdown', L.DomEvent.stopPropagation) - L.DomEvent.on(el, 'click', (ev) => { - L.DomEvent.stopPropagation(ev) - open() +} + +const ENTRY_CARD_OPTIONS: L.TooltipOptions = { direction: 'top', offset: [0, -MARKER_H] } + +/** + * The card that opens its entry when tapped (#2885), one per map like the GL + * popup, shown above the active pin. + * + * It is deliberately not bound to the pins. A bound tooltip is opened and closed + * by Leaflet on the pin's hover and focus, and a tap on the card is, to a phone, + * the pointer leaving the pin: the pin's mouseout closed the card between the + * tap and its click. Driven by the active pin alone, nothing but a change of + * entry takes it away. + */ +function createEntryCard(open: () => void): L.Tooltip { + const card = L.tooltip({ ...ENTRY_CARD_OPTIONS, className: 'map-tooltip trek-journey-tooltip is-openable' }) + // The element is built on the first open and kept for every later one. + card.once('add', () => { + const el = card.getElement() + if (!el) return + // A press on the card is not the start of a drag or a tap on the map. + L.DomEvent.disableClickPropagation(el) + L.DomEvent.on(el, 'click', (ev) => { + L.DomEvent.stopPropagation(ev) + open() + }) }) + return card } const EMPTY_TRAIL: { lat: number; lng: number }[] = [] @@ -279,6 +300,33 @@ function JourneyMap( plannedRef.current = plannedEntryIds }) + const entryCardRef = useRef(null) + const cardEntryIdRef = useRef(null) + + /** Puts the openable card over the active pin while that pin is on the map, and takes it off otherwise. */ + const syncEntryCard = useCallback(() => { + const map = mapRef.current + const id = highlightedRef.current + const marker = id ? markersRef.current.get(id) : undefined + const item = id ? itemsRef.current.find(i => i.id === id) : undefined + if (!onMarkerCardClickRef.current || !map || !marker || !item || !map.hasLayer(marker)) { + entryCardRef.current?.remove() + cardEntryIdRef.current = null + return + } + ensureJourneyPopupStyle() + let card = entryCardRef.current + if (!card) { + card = createEntryCard(() => { + if (cardEntryIdRef.current) onMarkerCardClickRef.current?.(cardEntryIdRef.current) + }) + entryCardRef.current = card + } + cardEntryIdRef.current = item.id + card.setLatLng(marker.getLatLng()).setContent(entryCardHtml(item)) + if (!map.hasLayer(card)) card.addTo(map) + }, []) + const highlightMarker = useCallback((id: string | null) => { const prev = highlightedRef.current highlightedRef.current = id @@ -287,7 +335,8 @@ function JourneyMap( ) if (prev && prev !== id) paint(prev, false) if (id) paint(id, true) - }, []) + syncEntryCard() + }, [syncEntryCard]) /** * Bring an entry's marker under the reader without changing how far out they are. @@ -445,32 +494,11 @@ function JourneyMap( allCoords.push(pos) const marker = place('entries', L.marker(pos, { icon: entryIcon(item, false, plannedRef.current.has(item.id)) })) - // The same card the GL renderer shows, from the same builder: which map - // engine a reader happens to have selected should not change what a marker - // tells them (discussion #2299). The builder escapes everything that came - // from a person, which matters most here — this map is what the public - // journey page renders. - ensureJourneyPopupStyle() - const openable = !!onMarkerCardClickRef.current - marker.bindTooltip( - journeyPopupHtml({ - title: item.label || item.locationName || 'Entry', - place: item.label ? item.locationName : '', - date: formatMarkerDate(item.time), - photoUrls: item.photoUrls, - }), - { - direction: 'top', - offset: [0, -MARKER_H], - className: `map-tooltip trek-journey-tooltip${openable ? ' is-openable' : ''}`, - }, - ) - // The card's element is built on its first open and kept for every later one. - if (openable) { - marker.getTooltip()?.once('add', (e: L.LeafletEvent) => { - const el = (e.target as L.Tooltip).getElement() - if (el) makeCardOpenEntry(el, () => onMarkerCardClickRef.current?.(item.id)) - }) + // A host that opens the entry from its card gets the one card that follows + // the active pin instead (see syncEntryCard). + if (!onMarkerCardClickRef.current) { + ensureJourneyPopupStyle() + marker.bindTooltip(entryCardHtml(item), { ...ENTRY_CARD_OPTIONS, className: 'map-tooltip trek-journey-tooltip' }) } marker.on('click', () => { @@ -517,7 +545,8 @@ function JourneyMap( // A switch puts its layer back on the map or takes it off, exactly as drawn. useEffect(() => { shownRef.current = switchLeafletLayers(mapRef.current, drawnRef.current, shownRef.current, layerVisibility) - }, [layerVisibility]) + syncEntryCard() + }, [layerVisibility, syncEntryCard]) // The plan's check on an entry pin follows the plan layer without redrawing the map. useEffect(() => {