fix(journey): hold the client gates on the journey map changes

The phone card logic moves out of JourneyMap into useEntryCard, which brings
the component back under the line limit. The new card tests reach the
card element through a guard instead of non-null assertions, the public
hook test reads the hook through renderHook, the GL card tests use
mock.lastCall where Array#at is outside the client's lib, and the
complexity baseline drops to the count the branch now holds.
This commit is contained in:
Maurice
2026-10-29 17:39:37 +01:00
parent c14b572038
commit 2dbaf6b029
5 changed files with 77 additions and 61 deletions
+1 -1
View File
@@ -3,7 +3,7 @@
"@typescript-eslint/no-non-null-assertion": 382,
"@typescript-eslint/no-misused-promises": 847,
"no-console": 88,
"complexity": 219,
"complexity": 218,
"@typescript-eslint/no-explicit-any": 146,
"trek/no-swallowed-catch": 129,
"max-params": 32,
@@ -243,16 +243,22 @@ describe('JourneyMap', () => {
return { ...view, ref, onMarkerCardClick };
}
function cardElement(): HTMLElement {
const { element } = mockedCard().state;
if (!element) throw new Error('the card was never built');
return element;
}
function cardTitle(): HTMLElement {
return mockedCard().state.element!.firstElementChild as HTMLElement;
return cardElement().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'));
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 container = cardElement().parentElement as HTMLElement;
const mapClick = vi.fn();
const mapPress = vi.fn();
container.addEventListener('click', mapClick);
@@ -260,7 +266,7 @@ describe('JourneyMap', () => {
cardTitle().dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
cardTitle().click();
act(() => ref.current!.highlightMarker('e1'));
act(() => ref.current?.highlightMarker('e1'));
cardTitle().click();
expect(onMarkerCardClick.mock.calls).toEqual([['e2'], ['e1']]);
@@ -270,7 +276,7 @@ describe('JourneyMap', () => {
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'));
act(() => ref.current?.highlightMarker('e1'));
// 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.
@@ -288,16 +294,16 @@ describe('JourneyMap', () => {
const { ref, rerender } = renderOpenable(onMarkerCardClick, shown);
const map = mockedMap();
act(() => ref.current!.highlightMarker('e1'));
act(() => ref.current?.highlightMarker('e1'));
expect(card.setContent).toHaveBeenLastCalledWith(expect.stringContaining('Paris'));
act(() => ref.current!.highlightMarker('e2'));
act(() => ref.current?.highlightMarker('e2'));
expect(card.setContent).toHaveBeenLastCalledWith(expect.stringContaining('Berlin'));
expect(card.addTo).toHaveBeenCalledTimes(1);
act(() => ref.current!.highlightMarker(null));
act(() => ref.current?.highlightMarker(null));
expect(card.state.onMap).toBe(false);
act(() => ref.current!.highlightMarker('e1'));
act(() => ref.current?.highlightMarker('e1'));
map.hasLayer.mockImplementation((layer: unknown) => layer === card && card.state.onMap);
try {
rerender(<JourneyMap ref={ref} checkins={[]} entries={entriesWithCoords} onMarkerCardClick={onMarkerCardClick} layerVisibility={{ ...shown, entries: false }} />);
@@ -310,7 +316,7 @@ describe('JourneyMap', () => {
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<JourneyMapHandle>();
render(<JourneyMap ref={ref} checkins={[]} entries={entriesWithCoords} />);
act(() => ref.current!.highlightMarker('e1'));
act(() => ref.current?.highlightMarker('e1'));
expect(mockedMarker().bindTooltip).toHaveBeenCalledWith(
expect.any(String),
+49 -32
View File
@@ -1,4 +1,4 @@
import { useEffect, useRef, useImperativeHandle, useCallback, type CSSProperties, type Ref } from 'react'
import { useEffect, useRef, useImperativeHandle, useCallback, type CSSProperties, type Ref, type RefObject } from 'react'
import { clusterPhotos, photoMarkerHtml, type MapPhoto } from './journeyPhotoLayer'
import L from 'leaflet'
import { useSettingsStore } from '../../store/settingsStore'
@@ -228,6 +228,52 @@ function createEntryCard(open: () => void): L.Tooltip {
return card
}
interface PinRefs {
mapRef: RefObject<L.Map | null>
markersRef: RefObject<Map<string, L.Marker>>
itemsRef: RefObject<MapMarkerItem[]>
highlightedRef: RefObject<string | null>
}
/**
* The openable card of a host that wires onMarkerCardClick. `sync` puts it over
* the active pin while that pin is on the map and takes it off otherwise.
*/
function useEntryCard(onMarkerCardClick: ((entryId: string) => void) | undefined, pins: PinRefs) {
const { mapRef, markersRef, itemsRef, highlightedRef } = pins
// Read through a ref: the handler is fixed per surface, and putting it in the
// marker effect's deps would rebuild every marker for nothing.
const onCardClickRef = useRef(onMarkerCardClick)
onCardClickRef.current = onMarkerCardClick
const cardRef = useRef<L.Tooltip | null>(null)
const cardEntryIdRef = useRef<string | null>(null)
const sync = 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 (!onCardClickRef.current || !map || !marker || !item || !map.hasLayer(marker)) {
cardRef.current?.remove()
cardEntryIdRef.current = null
return
}
ensureJourneyPopupStyle()
let card = cardRef.current
if (!card) {
card = createEntryCard(() => {
if (cardEntryIdRef.current) onCardClickRef.current?.(cardEntryIdRef.current)
})
cardRef.current = card
}
cardEntryIdRef.current = item.id
card.setLatLng(marker.getLatLng()).setContent(entryCardHtml(item))
if (!map.hasLayer(card)) card.addTo(map)
}, [mapRef, markersRef, itemsRef, highlightedRef])
return { opensFromCardRef: onCardClickRef, sync }
}
const EMPTY_TRAIL: { lat: number; lng: number }[] = []
const EMPTY_TRACKS: JourneyTrack[] = []
/** Fallback when a track carries no colour of its own, matching the planner's default. */
@@ -246,10 +292,6 @@ function fitOptions(paddingBottom: number | undefined): L.FitBoundsOptions {
function JourneyMap(
{ entries, photos, onPhotoClick, trail, tracks, height = 220, dark, activeMarkerId, onMarkerClick, fullScreen, paddingBottom, cartoApiKey, onMarkerCardClick, layerVisibility = EVERY_LAYER, marks, onMarksPick, plannedEntryIds = NO_PLANNED, ref }: Props,
) {
// Read through a ref: the handler is fixed per surface, and putting it in the
// marker effect's deps would rebuild every marker for nothing.
const onMarkerCardClickRef = useRef(onMarkerCardClick)
onMarkerCardClickRef.current = onMarkerCardClick
const stableTrail = trail || EMPTY_TRAIL
const stableTracks = tracks || EMPTY_TRACKS
const mapTileUrl = useSettingsStore(s => s.settings.map_tile_url)
@@ -300,32 +342,7 @@ function JourneyMap(
plannedRef.current = plannedEntryIds
})
const entryCardRef = useRef<L.Tooltip | null>(null)
const cardEntryIdRef = useRef<string | null>(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 { opensFromCardRef, sync: syncEntryCard } = useEntryCard(onMarkerCardClick, { mapRef, markersRef, itemsRef, highlightedRef })
const highlightMarker = useCallback((id: string | null) => {
const prev = highlightedRef.current
@@ -496,7 +513,7 @@ function JourneyMap(
const marker = place('entries', L.marker(pos, { icon: entryIcon(item, false, plannedRef.current.has(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) {
if (!opensFromCardRef.current) {
ensureJourneyPopupStyle()
marker.bindTooltip(entryCardHtml(item), { ...ENTRY_CARD_OPTIONS, className: 'map-tooltip trek-journey-tooltip' })
}
@@ -520,7 +520,7 @@ describe('JourneyMapGL', () => {
render(<JourneyMapGL ref={ref} checkins={[]} entries={withPhotos} {...props} />)
act(() => { ref.current?.highlightMarker(id) })
const popup = gl.popups[0]
popup.element.innerHTML = String(popup.setHTML.mock.calls.at(-1)?.[0])
popup.element.innerHTML = String(popup.setHTML.mock.lastCall?.[0])
const mapClick = vi.fn()
const host = document.createElement('div')
host.appendChild(popup.element)
@@ -578,7 +578,7 @@ describe('JourneyMapGL', () => {
const { ref, popup } = openCard({ onMarkerCardClick })
act(() => { ref.current?.highlightMarker('e2') })
popup.element.innerHTML = String(popup.setHTML.mock.calls.at(-1)?.[0])
popup.element.innerHTML = String(popup.setHTML.mock.lastCall?.[0])
tap(popup, '.trek-journey-popup-title')
expect(popup.element.classList.contains('is-openable')).toBe(true)
@@ -2,7 +2,7 @@
import { http, HttpResponse } from 'msw';
import { describe, expect, it, vi } from 'vitest';
import { server } from '../../../tests/helpers/msw/server';
import { render, waitFor } from '../../../tests/helpers/render';
import { renderHook, waitFor } from '../../../tests/helpers/render';
import type { PublicEntry } from './journeyPublicModel';
import { useJourneyPublic } from './useJourneyPublic';
@@ -46,13 +46,6 @@ function serveShare(entries: PublicEntry[]): void {
);
}
let latest: ReturnType<typeof useJourneyPublic>;
function Harness() {
latest = useJourneyPublic();
return null;
}
describe('useJourneyPublic', () => {
it('FE-JRN-PUBHOOK-001: the map and the timeline count the stops through the whole journey', async () => {
serveShare([
@@ -62,17 +55,17 @@ describe('useJourneyPublic', () => {
buildEntry({ id: 4, entry_date: '2026-10-24' }),
buildEntry({ id: 5, entry_date: '2026-10-24', sort_order: 1 }),
]);
render(<Harness />);
const { result } = renderHook(() => useJourneyPublic());
await waitFor(() => expect(latest.sidebarMapItems).toHaveLength(5));
expect(latest.sidebarMapItems.map((m) => [m.id, m.dayLabel])).toEqual([
await waitFor(() => expect(result.current.sidebarMapItems).toHaveLength(5));
expect(result.current.sidebarMapItems.map((m) => [m.id, m.dayLabel])).toEqual([
['1', 1],
['2', 2],
['3', 3],
['4', 4],
['5', 5],
]);
expect([...latest.stopNumberById]).toEqual([
expect([...result.current.stopNumberById]).toEqual([
['1', 1],
['2', 2],
['3', 3],
@@ -88,14 +81,14 @@ describe('useJourneyPublic', () => {
buildEntry({ id: 7, location_lat: null, location_lng: null }),
buildEntry({ id: 9, entry_date: '2026-10-24' }),
]);
render(<Harness />);
const { result } = renderHook(() => useJourneyPublic());
await waitFor(() => expect(latest.sidebarMapItems).toHaveLength(3));
expect(latest.sidebarMapItems.map((m) => [m.id, m.dayLabel])).toEqual([
await waitFor(() => expect(result.current.sidebarMapItems).toHaveLength(3));
expect(result.current.sidebarMapItems.map((m) => [m.id, m.dayLabel])).toEqual([
['6', 1],
['8', 2],
['9', 3],
]);
expect(latest.stopNumberById.has('7')).toBe(false);
expect(result.current.stopNumberById.has('7')).toBe(false);
});
});