Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

38.1 KB
Raw Blame
// FE-COMP-JMAPGL-001 to FE-COMP-JMAPGL-050, FE-COMP-JMAPGL-2453, FE-COMP-JMAPGL-2910

type Spy = ReturnType<typeof vi.fn>

interface MarkerStub {
  element: HTMLElement
  lngLat: [number, number]
  setLngLat: Spy
  addTo: Spy
  remove: Spy
  getElement: Spy
  getLngLat: Spy
}

interface PopupStub {
  options: Record<string, unknown>
  element: HTMLElement
  setLngLat: Spy
  setHTML: Spy
  setOffset: Spy
  getElement: Spy
  addTo: Spy
  remove: Spy
}

interface BoundsStub {
  points: [number, number][]
  extend: Spy
  getCenter: Spy
}

const gl = vi.hoisted(() => {
  const map = {
    on: vi.fn(),
    off: vi.fn(),
    once: vi.fn(),
    loaded: vi.fn(() => true),
    // Container pixels, ten per degree. The layers must not group by them: they
    // shift with every pan (#2889).
    project: vi.fn(),
    remove: vi.fn(),
    resize: vi.fn(),
    flyTo: vi.fn(),
    easeTo: vi.fn(),
    fitBounds: vi.fn(),
    getZoom: vi.fn(() => 10),
    addSource: vi.fn(),
    addLayer: vi.fn(),
    getSource: vi.fn((): unknown => null),
    // The satellite imagery (#2594) asks for its layer and for the style's layers to slide under.
    getLayer: vi.fn((): unknown => undefined),
    getStyle: vi.fn((): unknown => ({ layers: [] })),
    setTerrain: vi.fn(),
    setConfigProperty: vi.fn(),
    setLayoutProperty: vi.fn(),
  }
  const markers: MarkerStub[] = []
  const popups: PopupStub[] = []
  const boundsList: BoundsStub[] = []

  function createMarker(options: { element?: HTMLElement }): MarkerStub {
    const marker: MarkerStub = {
      element: options?.element ?? document.createElement('div'),
      lngLat: [0, 0],
      setLngLat: vi.fn((ll: [number, number]) => { marker.lngLat = ll; return marker }),
      addTo: vi.fn(() => marker),
      remove: vi.fn(),
      getElement: vi.fn(() => marker.element),
      getLngLat: vi.fn(() => marker.lngLat),
    }
    markers.push(marker)
    return marker
  }

  function createPopup(options: Record<string, unknown>): PopupStub {
    const popup: PopupStub = {
      options: options ?? {},
      element: document.createElement('div'),
      setLngLat: vi.fn(() => popup),
      setHTML: vi.fn(() => popup),
      setOffset: vi.fn(() => popup),
      getElement: vi.fn(() => popup.element),
      addTo: vi.fn(() => popup),
      remove: vi.fn(),
    }
    popups.push(popup)
    return popup
  }

  function createBounds(): BoundsStub {
    const bounds: BoundsStub = {
      points: [],
      extend: vi.fn((p: [number, number]) => { bounds.points.push(p); return bounds }),
      getCenter: vi.fn(() => ({ lng: 5, lat: 45 })),
    }
    boundsList.push(bounds)
    return bounds
  }

  return { map, markers, popups, boundsList, createMarker, createPopup, createBounds }
})

const glModule = vi.hoisted(() => () => ({
  default: {
    accessToken: '',
    Map: vi.fn(function () { return gl.map }),
    Marker: vi.fn(function (options: { element?: HTMLElement }) { return gl.createMarker(options) }),
    Popup: vi.fn(function (options: Record<string, unknown>) { return gl.createPopup(options) }),
    LngLatBounds: vi.fn(function () { return gl.createBounds() }),
  },
}))

vi.mock('mapbox-gl', glModule)
// maplibre-gl 6 has no default export: the same fakes, as named exports.
vi.mock('maplibre-gl', () => glModule().default)
vi.mock('mapbox-gl/dist/mapbox-gl.css', () => ({}))
vi.mock('maplibre-gl/dist/maplibre-gl.css', () => ({}))

vi.mock('../Map/mapboxSetup', () => ({
  isStandardFamily: vi.fn(() => false),
  supportsCustom3d: vi.fn(() => false),
  wantsTerrain: vi.fn(() => false),
  addCustom3dBuildings: vi.fn(),
  addTerrainAndSky: vi.fn(),
}))

import React from 'react'
import mapboxgl from 'mapbox-gl'
import * as maplibregl from 'maplibre-gl'
import { render, screen, act } from '../../../tests/helpers/render'
import { resetAllStores, seedStore } from '../../../tests/helpers/store'
import { useSettingsStore } from '../../store/settingsStore'
import { isStandardFamily, supportsCustom3d, wantsTerrain, addCustom3dBuildings, addTerrainAndSky } from '../Map/mapboxSetup'
import JourneyMapGLWithEngine from './JourneyMapGL'
import type { JourneyMapGLHandle } from './JourneyMapGL'

// The engine is a prop now, not a module import — that is what keeps mapbox-gl and
// maplibre-gl in separate chunks. This shim preserves the suite's existing call
// shape and makes the same choice glLazy.tsx makes in production, so the vi.mock
// factories below still stand in for the right SDK.
const JourneyMapGL = React.forwardRef(function JourneyMapGLShim(
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  props: any,
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  ref: any
) {
  return (
    <JourneyMapGLWithEngine
      ref={ref}
      {...props}
      gl={props.glProvider === 'maplibre-gl' ? maplibregl : mapboxgl}
    />
  )
})

const entries = [
  { id: 'e1', lat: 48.8566, lng: 2.3522, title: 'Louvre', location_name: 'Paris, France', entry_date: '2025-06-01', dayColor: '#ff0055', dayLabel: 2 },
  { id: 'e2', lat: 52.52, lng: 13.405, title: 'Museumsinsel', location_name: 'Berlin, Germany', entry_date: '2025-06-02' },
]

const singleEntry = [entries[0]]

function withToken(extra: Record<string, unknown> = {}) {
  seedStore(useSettingsStore, {
    settings: { ...useSettingsStore.getState().settings, mapbox_access_token: 'pk.test_token', ...extra },
  })
}

function mapOptions(): Record<string, unknown> {
  const call = vi.mocked(mapboxgl.Map).mock.calls[0]
  return call[0] as unknown as Record<string, unknown>
}

function popupHtml(index = 0): string {
  return String(gl.popups[index].setHTML.mock.calls[0][0])
}

beforeEach(() => {
  resetAllStores()
  vi.clearAllMocks()
  gl.markers.length = 0
  gl.popups.length = 0
  gl.boundsList.length = 0
  gl.map.on.mockImplementation((event: string, handler: () => void) => {
    if (event === 'load') handler()
    return gl.map
  })
  gl.map.getZoom.mockReturnValue(10)
  gl.map.project.mockImplementation(([lng, lat]: [number, number]) => ({ x: lng * 10, y: lat * 10 }))
  gl.map.getSource.mockReturnValue(null)
  gl.map.getLayer.mockReturnValue(undefined)
  gl.map.getStyle.mockReturnValue({ layers: [] })
  vi.mocked(isStandardFamily).mockReturnValue(false)
  vi.mocked(supportsCustom3d).mockReturnValue(false)
  vi.mocked(wantsTerrain).mockReturnValue(false)
  document.getElementById('trek-journey-popup-style')?.remove()
})

describe('JourneyMapGL', () => {
  it('FE-COMP-JMAPGL-001: mapbox without a token shows the settings hint instead of a map', () => {
    render(<JourneyMapGL checkins={[]} entries={entries} />)
    expect(screen.getByText(/No Mapbox access token configured/)).toBeInTheDocument()
    expect(screen.getByText('Settings → Map → Mapbox GL')).toBeInTheDocument()
    expect(mapboxgl.Map).not.toHaveBeenCalled()
  })

  it('FE-COMP-JMAPGL-002: a configured token builds the map and is handed to the sdk', () => {
    withToken()
    render(<JourneyMapGL checkins={[]} entries={entries} />)
    expect(mapboxgl.accessToken).toBe('pk.test_token')
    expect(mapboxgl.Map).toHaveBeenCalledTimes(1)
    // Collapsed to its ⓘ rather than a strip of text across the bottom (#2299).
    expect(mapOptions()).toMatchObject({ style: 'mapbox://styles/mapbox/standard', attributionControl: { compact: true } })
  })

  it('FE-COMP-JMAPGL-003: maplibre needs no token and opts out of the around-center rotate', () => {
    render(<JourneyMapGL checkins={[]} entries={entries} glProvider="maplibre-gl" />)
    expect(maplibregl.Map).toHaveBeenCalledTimes(1)
    const options = vi.mocked(maplibregl.Map).mock.calls[0][0] as unknown as Record<string, unknown>
    expect(options.aroundCenter).toBe(false)
    // projection is a mapbox-only option
    expect(options).not.toHaveProperty('projection')
  })

  it('FE-COMP-JMAPGL-004: quality mode turns on the globe projection and antialiasing', () => {
    withToken({ mapbox_quality_mode: true })
    render(<JourneyMapGL checkins={[]} entries={entries} />)
    expect(mapOptions()).toMatchObject({ projection: 'globe', antialias: true })
  })

  it('FE-COMP-JMAPGL-005: entries become bottom-anchored pins carrying their day colour and label', () => {
    withToken()
    render(<JourneyMapGL checkins={[]} entries={entries} />)

    expect(gl.markers).toHaveLength(2)
    expect(vi.mocked(mapboxgl.Marker).mock.calls[0][0]).toMatchObject({ anchor: 'bottom' })
    expect(gl.markers[0].setLngLat).toHaveBeenCalledWith([2.3522, 48.8566])
    const svg = gl.markers[0].element.innerHTML
    expect(svg).toContain('#ff0055')
    expect(svg).toContain('>2<')
    // the second entry has no explicit day meta and falls back to the neutral defaults
    expect(gl.markers[1].element.innerHTML).toContain('#52525B')
    expect(gl.markers[1].element.innerHTML).toContain('>1<')
  })

  it('FE-COMP-JMAPGL-043: a stop without a number (a draft) gets an unnumbered pin', () => {
    withToken()
    render(<JourneyMapGL checkins={[]} entries={[{ ...entries[0], dayLabel: null }]} />)

    expect(gl.markers).toHaveLength(1)
    expect(gl.markers[0].element.innerHTML).toContain('#ff0055')
    expect(gl.markers[0].element.innerHTML).toMatch(/font-weight="700"><\/text>/)
  })

  it('FE-COMP-JMAPGL-006: entries without coordinates never reach the map', () => {
    withToken()
    render(
      <JourneyMapGL
        checkins={[]}
        entries={[{ id: 'nope', lat: 0, lng: 0, title: 'Null Island', entry_date: '2025-06-01' }]}
      />,
    )
    expect(gl.markers).toHaveLength(0)
    expect(gl.map.fitBounds).not.toHaveBeenCalled()
  })

  it('FE-COMP-JMAPGL-007: two or more entries add the dashed route source and layer', () => {
    withToken()
    render(<JourneyMapGL checkins={[]} entries={entries} />)

    expect(gl.map.addSource).toHaveBeenCalledWith('journey-route', expect.objectContaining({ type: 'geojson' }))
    const source = vi.mocked(gl.map.addSource).mock.calls[0][1] as { data: { geometry: { coordinates: number[][][] } } }
    expect(source.data.geometry.coordinates).toEqual([[[2.3522, 48.8566], [13.405, 52.52]]])
    expect(gl.map.addLayer).toHaveBeenCalledWith(expect.objectContaining({
      id: 'journey-route-line',
      source: 'journey-route',
    }))
  })

  it('FE-COMP-JMAPGL-038: a planned GPX track goes on the dashed layer, a recorded route on the solid one (JRN-01)', () => {
    withToken()
    render(
      <JourneyMapGL
        checkins={[]}
        entries={singleEntry}
        tracks={[
          { place_id: 1, trip_id: 1, name: 'Ridge', color: '#aa0000', points: [[47, 11], [47.1, 11.1]] },
          { place_id: -100001, trip_id: 0, name: 'Recorded on 14 May', color: '#00aa00', points: [[47, 11], [47.2, 11.2]], kind: 'day_recording' },
        ]}
      />,
    )

    const source = vi.mocked(gl.map.addSource).mock.calls.find(c => c[0] === 'journey-tracks')?.[1] as
      | { data: { features: Array<{ properties: { planned: boolean } }> } }
      | undefined
    expect(source?.data.features.map(f => f.properties.planned)).toEqual([true, false])
    expect(gl.map.addLayer).toHaveBeenCalledWith(expect.objectContaining({
      id: 'journey-tracks-planned',
      filter: ['==', ['get', 'planned'], true],
      paint: expect.objectContaining({ 'line-dasharray': [2.2, 2] }),
    }))
    expect(gl.map.addLayer).toHaveBeenCalledWith(expect.objectContaining({
      id: 'journey-tracks-line',
      filter: ['!=', ['get', 'planned'], true],
    }))
  })

  it('FE-COMP-JMAPGL-009: a single entry draws no route line', () => {
    withToken()
    render(<JourneyMapGL checkins={[]} entries={singleEntry} />)
    expect(gl.map.addSource).not.toHaveBeenCalled()
    expect(gl.map.addLayer).not.toHaveBeenCalled()
  })

  it('FE-COMP-JMAPGL-037: the fullScreen map draws the route once the entries arrive after mount', () => {
    withToken()
    const { rerender } = render(<JourneyMapGL checkins={[]} entries={[]} fullScreen />)
    expect(gl.map.addSource).not.toHaveBeenCalledWith('journey-route', expect.anything())

    rerender(<JourneyMapGL checkins={[]} entries={entries} fullScreen />)
    expect(gl.map.addSource).toHaveBeenCalledWith('journey-route', expect.objectContaining({ type: 'geojson' }))
    expect(gl.map.addLayer).toHaveBeenCalledWith(expect.objectContaining({ id: 'journey-route-line' }))
  })

  it('FE-COMP-JMAPGL-049: paddingStart widens the fit on the side of the rail', () => {
    withToken()
    render(<JourneyMapGL checkins={[]} entries={entries} paddingBottom={200} paddingStart={100} fullScreen />)
    expect(gl.map.fitBounds).toHaveBeenCalledWith(gl.boundsList[0], expect.objectContaining({
      padding: { top: 50, bottom: 200, left: 150, right: 50 },
    }))
  })

  it('FE-COMP-JMAPGL-010: the camera fits entries and trail with the requested bottom padding', () => {
    withToken()
    render(
      <JourneyMapGL
        checkins={[]}
        entries={entries}
        trail={[{ lat: 50, lng: 8 }]}
        paddingBottom={200}
        fullScreen
      />,
    )

    expect(gl.boundsList[0].points).toEqual([[2.3522, 48.8566], [13.405, 52.52], [8, 50]])
    expect(gl.map.fitBounds).toHaveBeenCalledWith(gl.boundsList[0], expect.objectContaining({
      padding: { top: 50, bottom: 200, left: 50, right: 50 },
      maxZoom: 16,
      pitch: 45,
      duration: 0,
    }))
    // fullScreen + 3D also tilts the opening camera
    expect(mapOptions()).toMatchObject({ pitch: 45, center: { lng: 5, lat: 45 }, zoom: 2 })
  })

  it('FE-COMP-JMAPGL-011: with nothing to show the map opens on the world view', () => {
    withToken()
    render(<JourneyMapGL checkins={[]} entries={[]} />)
    expect(mapOptions()).toMatchObject({ center: [0, 30], zoom: 1 })
    expect(gl.map.fitBounds).not.toHaveBeenCalled()
  })

  it('FE-COMP-JMAPGL-012: clicking a pin reports the entry id and stops the map from handling it', () => {
    withToken()
    const onMarkerClick = vi.fn()
    render(<JourneyMapGL checkins={[]} entries={entries} onMarkerClick={onMarkerClick} />)

    const ev = new MouseEvent('click', { bubbles: true, cancelable: true })
    const stopPropagation = vi.spyOn(ev, 'stopPropagation')
    act(() => { gl.markers[1].element.dispatchEvent(ev) })

    expect(onMarkerClick).toHaveBeenCalledWith('e2')
    expect(stopPropagation).toHaveBeenCalled()
  })

  it('FE-COMP-JMAPGL-013: highlightMarker enlarges the pin and opens a two-line popup', () => {
    withToken()
    const ref = React.createRef<JourneyMapGLHandle>()
    render(<JourneyMapGL ref={ref} checkins={[]} entries={entries} />)

    act(() => { ref.current!.highlightMarker('e1') })

    const inner = gl.markers[0].element.querySelector('.trek-journey-marker-inner') as HTMLElement
    expect(inner.style.transform).toBe('scale(1.2)')
    expect(gl.markers[0].element.style.zIndex).toBe('1000')

    expect(gl.popups).toHaveLength(1)
    expect(gl.popups[0].setLngLat).toHaveBeenCalledWith([2.3522, 48.8566])
    expect(gl.popups[0].addTo).toHaveBeenCalledWith(gl.map)
    const html = popupHtml()
    expect(html).toContain('>Louvre<')
    expect(html).toContain('trek-journey-popup-place')
    expect(html).toContain('trek-journey-popup-chip')
  })

  it('FE-COMP-JMAPGL-014: the popup falls back to the location name when the entry has no title', () => {
    withToken()
    const ref = React.createRef<JourneyMapGLHandle>()
    render(
      <JourneyMapGL
        ref={ref}
        checkins={[]}
        entries={[{ id: 'e1', lat: 1, lng: 2, title: null, location_name: 'Reykjavík', entry_date: '2025-06-01' }]}
      />,
    )

    act(() => { ref.current!.highlightMarker('e1') })

    const html = popupHtml()
    expect(html).toContain('>Reykjavík<')
    // the location moved to the title line, so there is no place chip left below.
    // The date keeps its own chip, which is why only the place one is checked.
    expect(html).not.toContain('trek-journey-popup-place')
  })

  it('FE-COMP-JMAPGL-015: an entry with neither title nor place still gets a heading', () => {
    withToken()
    const ref = React.createRef<JourneyMapGLHandle>()
    render(
      <JourneyMapGL
        ref={ref}
        checkins={[]}
        entries={[{ id: 'e1', lat: 1, lng: 2, entry_date: '' }]}
      />,
    )

    act(() => { ref.current!.highlightMarker('e1') })

    const html = popupHtml()
    expect(html).toContain('>Entry<')
    // empty entry_date yields no subline at all
    expect(html).not.toContain('trek-journey-popup-sub')
  })

  it('FE-COMP-JMAPGL-016: an unparseable entry date is passed through verbatim', () => {
    withToken()
    const ref = React.createRef<JourneyMapGLHandle>()
    render(
      <JourneyMapGL
        ref={ref}
        checkins={[]}
        entries={[{ id: 'e1', lat: 1, lng: 2, title: 'Somewhere', entry_date: 'sometime' }]}
      />,
    )

    act(() => { ref.current!.highlightMarker('e1') })
    expect(popupHtml()).toContain('>sometime<')
  })

  it('FE-COMP-JMAPGL-017: popup text is html-escaped', () => {
    withToken()
    const ref = React.createRef<JourneyMapGLHandle>()
    render(
      <JourneyMapGL
        ref={ref}
        checkins={[]}
        entries={[{ id: 'e1', lat: 1, lng: 2, title: '<img src=x onerror="alert(1)">', location_name: "Tom & Jerry's", entry_date: '2025-06-01' }]}
      />,
    )

    act(() => { ref.current!.highlightMarker('e1') })

    const html = popupHtml()
    expect(html).not.toContain('<img')
    expect(html).toContain('&lt;img src=x onerror=&quot;alert(1)&quot;&gt;')
    expect(html).toContain('Tom &amp; Jerry&#39;s')
  })

  it('FE-COMP-JMAPGL-018: highlighting a second pin reuses the popup and resets the first pin', () => {
    withToken()
    const ref = React.createRef<JourneyMapGLHandle>()
    render(<JourneyMapGL ref={ref} checkins={[]} entries={entries} dark />)

    act(() => { ref.current!.highlightMarker('e1') })
    act(() => { ref.current!.highlightMarker('e2') })

    // only one popup instance is ever constructed
    expect(gl.popups).toHaveLength(1)
    expect(gl.popups[0].setLngLat).toHaveBeenCalledWith([13.405, 52.52])
    expect(gl.popups[0].setOffset).toHaveBeenCalledWith([0, -46])
    expect(gl.popups[0].element.classList.contains('trek-dark')).toBe(true)

    const firstInner = gl.markers[0].element.querySelector('.trek-journey-marker-inner') as HTMLElement
    expect(firstInner.style.transform).toBe('scale(1)')
    expect(gl.markers[0].element.style.zIndex).toBe('1')
  })

  it('FE-COMP-JMAPGL-019: dark mode tags the popup class on creation', () => {
    withToken()
    const ref = React.createRef<JourneyMapGLHandle>()
    render(<JourneyMapGL ref={ref} checkins={[]} entries={entries} dark />)
    act(() => { ref.current!.highlightMarker('e1') })
    expect(gl.popups[0].options.className).toBe('trek-journey-popup trek-dark')
  })

  it('FE-COMP-JMAPGL-020: highlightMarker(null) closes the popup', () => {
    withToken()
    const ref = React.createRef<JourneyMapGLHandle>()
    render(<JourneyMapGL ref={ref} checkins={[]} entries={entries} />)
    act(() => { ref.current!.highlightMarker('e1') })
    act(() => { ref.current!.highlightMarker(null) })
    expect(gl.popups[0].remove).toHaveBeenCalled()
  })

  it('FE-COMP-JMAPGL-021: highlighting an unknown id changes nothing', () => {
    withToken()
    const ref = React.createRef<JourneyMapGLHandle>()
    render(<JourneyMapGL ref={ref} checkins={[]} entries={entries} />)
    act(() => { ref.current!.highlightMarker('ghost') })
    expect(gl.popups).toHaveLength(0)
    expect(gl.markers[0].element.style.zIndex).toBe('1')
  })

  it('FE-COMP-JMAPGL-022: the popup stylesheet is injected exactly once', () => {
    withToken()
    const ref = React.createRef<JourneyMapGLHandle>()
    render(<JourneyMapGL ref={ref} checkins={[]} entries={entries} />)
    act(() => { ref.current!.highlightMarker('e1') })
    act(() => { ref.current!.highlightMarker('e2') })
    expect(document.querySelectorAll('#trek-journey-popup-style')).toHaveLength(1)
  })

  describe('the marker card as a way into the entry (#2885)', () => {
    const withPhotos = [
      { ...entries[0], photoUrls: ['/a.jpg', '/b.jpg'] },
      entries[1],
    ]

    // The stub's setHTML records the markup; the card's content is put in by hand.
    function openCard(props: Record<string, unknown>, id = 'e1') {
      withToken()
      const ref = React.createRef<JourneyMapGLHandle>()
      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.lastCall?.[0])
      const mapClick = vi.fn()
      const host = document.createElement('div')
      host.appendChild(popup.element)
      host.addEventListener('click', mapClick)
      return { ref, popup, mapClick }
    }

    function tap(popup: PopupStub, selector: string) {
      const target = popup.element.querySelector(selector) as HTMLElement
      target.click()
    }

    it('FE-COMP-JMAPGL-044: a tap anywhere on the card opens its entry and stays off the map', () => {
      const onMarkerCardClick = vi.fn()
      const { popup, mapClick } = openCard({ onMarkerCardClick })

      expect(popup.options.className).toContain('is-openable')
      tap(popup, '.trek-journey-popup-title')

      expect(onMarkerCardClick).toHaveBeenCalledWith('e1')
      expect(mapClick).not.toHaveBeenCalled()
    })

    it('FE-COMP-JMAPGL-045: with a photo handler a thumbnail opens the photo, not the entry', () => {
      const onMarkerCardClick = vi.fn()
      const onMarkerPhotoClick = vi.fn()
      const { popup } = openCard({ onMarkerCardClick, onMarkerPhotoClick })

      tap(popup, '[data-shot="1"]')

      expect(onMarkerPhotoClick).toHaveBeenCalledWith('e1', 1)
      expect(onMarkerCardClick).not.toHaveBeenCalled()
    })

    it('FE-COMP-JMAPGL-046: without a photo handler a thumbnail opens the entry like the rest of the card', () => {
      const onMarkerCardClick = vi.fn()
      const { popup } = openCard({ onMarkerCardClick })

      tap(popup, '[data-shot]')

      expect(onMarkerCardClick).toHaveBeenCalledWith('e1')
    })

    it('FE-COMP-JMAPGL-047: without a handler the card stays a label the tap passes through', () => {
      const { popup, mapClick } = openCard({})

      expect(popup.options.className).toBe('trek-journey-popup')
      tap(popup, '.trek-journey-popup-title')

      expect(mapClick).toHaveBeenCalled()
    })

    it('FE-COMP-JMAPGL-048: the reused card opens the entry it shows now', () => {
      const onMarkerCardClick = vi.fn()
      const { ref, popup } = openCard({ onMarkerCardClick })

      act(() => { ref.current?.highlightMarker('e2') })
      popup.element.innerHTML = String(popup.setHTML.mock.lastCall?.[0])
      tap(popup, '.trek-journey-popup-title')

      expect(popup.element.classList.contains('is-openable')).toBe(true)
      expect(popup.element.classList.contains('is-interactive')).toBe(false)
      expect(onMarkerCardClick).toHaveBeenCalledWith('e2')
    })
  })

  it('FE-COMP-JMAPGL-023: focusMarker eases over with the 3D pitch and no zoom of its own', () => {
    withToken()
    const ref = React.createRef<JourneyMapGLHandle>()
    render(<JourneyMapGL ref={ref} checkins={[]} entries={entries} />)

    act(() => { ref.current!.focusMarker('e2') })

    // No zoom in the call at all: stepping through the timeline keeps the frame the
    // reader chose (discussion #2299), same as the Leaflet twin.
    expect(gl.map.easeTo).toHaveBeenCalledWith({
      center: [13.405, 52.52],
      pitch: 45,
      duration: 600,
    })
    expect(gl.map.flyTo).not.toHaveBeenCalled()
  })

  it('FE-COMP-JMAPGL-024: with 3D disabled the camera stays flat', () => {
    withToken({ mapbox_3d_enabled: false })
    const ref = React.createRef<JourneyMapGLHandle>()
    render(<JourneyMapGL ref={ref} checkins={[]} entries={entries} />)

    act(() => { ref.current!.focusMarker('e1') })

    expect(gl.map.easeTo).toHaveBeenCalledWith(expect.objectContaining({ pitch: 0 }))
    expect(addCustom3dBuildings).not.toHaveBeenCalled()
  })

  it('FE-COMP-JMAPGL-025: focusMarker swallows sdk errors while the map is not ready', () => {
    withToken()
    const ref = React.createRef<JourneyMapGLHandle>()
    render(<JourneyMapGL ref={ref} checkins={[]} entries={entries} />)
    gl.map.easeTo.mockImplementationOnce(() => { throw new Error('not ready') })

    expect(() => act(() => { ref.current!.focusMarker('e1') })).not.toThrow()
    expect(gl.map.flyTo).not.toHaveBeenCalled()
  })

  it('FE-COMP-JMAPGL-2453: geotagged photos become clustered thumbnails under the pins and open on a tap', () => {
    withToken()
    const onPhotoClick = vi.fn()
    const photos = [
      { id: 'a', lat: 45, lng: 5, thumbUrl: '/api/photos/1/thumbnail' },
      { id: 'b', lat: 45.1, lng: 5.1, thumbUrl: '/api/photos/2/thumbnail' },
      { id: 'c', lat: 48, lng: 11, thumbUrl: '/api/photos/3/thumbnail' },
    ]
    gl.map.getZoom.mockReturnValue(4)
    render(<JourneyMapGL checkins={[]} entries={entries} photos={photos} onPhotoClick={onPhotoClick} />)
    const thumbs = gl.markers.filter(m => m.element.innerHTML.includes('/api/photos/'))
    // At zoom 4 a and b lie three world pixels apart in one 64px cell, c far off.
    expect(thumbs).toHaveLength(2)
    expect(thumbs[0].element.innerHTML).toContain('>2<')
    thumbs[0].element.click()
    expect(onPhotoClick).toHaveBeenCalledWith(['a', 'b'])
    expect(gl.map.on).toHaveBeenCalledWith('moveend', expect.any(Function))
  })

  it('FE-COMP-JMAPGL-2910: no marker element sets its own position, so the engine keeps it absolute', () => {
    withToken()
    const photos = [{ id: 'a', lat: 45, lng: 5, thumbUrl: '/api/photos/1/thumbnail' }]
    const marks = [{ kind: 'stay', key: 's1', lat: 46, lng: 6, color: '#14b8a6', stay: {} }]
    render(<JourneyMapGL checkins={[]} entries={entries} photos={photos} marks={marks} />)
    expect(gl.markers.some(m => m.element.innerHTML.includes('/api/photos/'))).toBe(true)
    for (const marker of gl.markers) expect(marker.element.style.position).toBe('')
  })

  it('FE-COMP-JMAPGL-2889: panning keeps the photo and mark groups, only a zoom regroups them', () => {
    withToken()
    const photos = [
      { id: 'a', lat: 45, lng: 5, thumbUrl: '/api/photos/1/thumbnail' },
      { id: 'b', lat: 45, lng: 5.1, thumbUrl: '/api/photos/2/thumbnail' },
    ]
    const marks = [
      { kind: 'stay', key: 's1', lat: 45, lng: 5, color: '#14b8a6', stay: {} },
      { kind: 'stay', key: 's2', lat: 45, lng: 5.1, color: '#14b8a6', stay: {} },
    ]
    gl.map.getZoom.mockReturnValue(4)
    render(<JourneyMapGL checkins={[]} entries={entries} photos={photos} marks={marks} />)
    const drawn = () => {
      const shown = gl.markers.filter(m => !m.remove.mock.calls.length)
      return {
        photos: shown.filter(m => m.element.innerHTML.includes('/api/photos/')).map(m => [m.lngLat, m.element.innerHTML]),
        marks: shown.filter(m => m.element.innerHTML.includes('#14b8a6')).map(m => [m.lngLat, m.element.innerHTML]),
      }
    }
    const moveEnd = () => act(() => {
      const gone = new Set(gl.map.off.mock.calls.map(c => c[1]))
      for (const [event, handler] of gl.map.on.mock.calls) if (event === 'moveend' && !gone.has(handler)) (handler as () => void)()
    })
    const before = drawn()
    expect(before.photos).toHaveLength(1)
    expect(before.photos[0][1]).toContain('>2<')
    expect(before.marks).toHaveLength(1)

    // A pan moves every container point; at this offset b crosses a cell edge on screen.
    gl.map.project.mockImplementation(([lng, lat]: [number, number]) => ({ x: lng * 10 - 19, y: lat * 10 }))
    moveEnd()
    expect(drawn()).toEqual(before)

    gl.map.getZoom.mockReturnValue(12)
    moveEnd()
    expect(drawn().photos).toHaveLength(2)
    expect(drawn().marks).toHaveLength(2)
  })

  it('FE-COMP-JMAPGL-026: focusMarker on an unknown id is a no-op', () => {
    withToken()
    const ref = React.createRef<JourneyMapGLHandle>()
    render(<JourneyMapGL ref={ref} checkins={[]} entries={entries} />)
    act(() => { ref.current!.focusMarker('ghost') })
    expect(gl.map.flyTo).not.toHaveBeenCalled()
  })

  it('FE-COMP-JMAPGL-027: invalidateSize resizes the gl canvas', () => {
    withToken()
    const ref = React.createRef<JourneyMapGLHandle>()
    render(<JourneyMapGL ref={ref} checkins={[]} entries={entries} />)
    act(() => { ref.current!.invalidateSize() })
    expect(gl.map.resize).toHaveBeenCalled()
  })

  it('FE-COMP-JMAPGL-028: the activeMarkerId prop highlights and eases over after the settle delay', () => {
    vi.useFakeTimers()
    try {
      withToken()
      render(<JourneyMapGL checkins={[]} entries={entries} activeMarkerId="e2" />)
      expect(gl.map.easeTo).not.toHaveBeenCalled()

      act(() => { vi.advanceTimersByTime(60) })

      expect(gl.popups).toHaveLength(1)
      expect(gl.map.easeTo).toHaveBeenCalledWith(expect.objectContaining({
        center: [13.405, 52.52],
        duration: 500,
      }))
    } finally {
      vi.useRealTimers()
    }
  })

  it('FE-COMP-JMAPGL-029: an activeMarkerId with no pin leaves the camera alone', () => {
    vi.useFakeTimers()
    try {
      withToken()
      render(<JourneyMapGL checkins={[]} entries={entries} activeMarkerId="ghost" />)
      act(() => { vi.advanceTimersByTime(60) })
      expect(gl.map.flyTo).not.toHaveBeenCalled()
    } finally {
      vi.useRealTimers()
    }
  })

  it('FE-COMP-JMAPGL-030: 3D styles get terrain, sky and custom buildings on load', () => {
    withToken({ mapbox_style: 'mapbox://styles/mapbox/outdoors-v12' })
    vi.mocked(wantsTerrain).mockReturnValue(true)
    vi.mocked(supportsCustom3d).mockReturnValue(true)

    render(<JourneyMapGL checkins={[]} entries={entries} dark />)

    expect(addTerrainAndSky).toHaveBeenCalledWith(gl.map)
    expect(addCustom3dBuildings).toHaveBeenCalledWith(gl.map, true)
    // only the Standard style needs its built-in DEM flattened
    expect(gl.map.setTerrain).not.toHaveBeenCalled()
  })

  it('FE-COMP-JMAPGL-031: the Standard basemap is flattened and pinned to the ui language', () => {
    withToken({ language: 'gr' })
    vi.mocked(isStandardFamily).mockReturnValue(true)

    render(<JourneyMapGL checkins={[]} entries={entries} />)

    expect(gl.map.setTerrain).toHaveBeenCalledWith(null)
    expect(gl.map.setConfigProperty).toHaveBeenCalledWith('basemap', 'language', 'el')
    expect(addTerrainAndSky).not.toHaveBeenCalled()
  })

  it('FE-COMP-JMAPGL-031b: switching the ui language repins the labels without rebuilding the map', () => {
    withToken({ language: 'gr' })
    vi.mocked(isStandardFamily).mockReturnValue(true)

    render(<JourneyMapGL checkins={[]} entries={entries} />)
    const builds = vi.mocked(mapboxgl.Map).mock.calls.length
    gl.map.setConfigProperty.mockClear()

    act(() => { withToken({ language: 'fr' }) })

    expect(gl.map.setConfigProperty).toHaveBeenCalledWith('basemap', 'language', 'fr')
    expect(vi.mocked(mapboxgl.Map).mock.calls).toHaveLength(builds)
  })

  it('FE-COMP-JMAPGL-032: sdk failures while configuring the basemap do not break the load', () => {
    withToken()
    vi.mocked(isStandardFamily).mockReturnValue(true)
    gl.map.setTerrain.mockImplementationOnce(() => { throw new Error('no terrain') })
    gl.map.setConfigProperty.mockImplementationOnce(() => { throw new Error('unsupported') })

    expect(() => render(<JourneyMapGL checkins={[]} entries={entries} />)).not.toThrow()
    expect(gl.markers).toHaveLength(2)
  })

  it('FE-COMP-JMAPGL-033: an empty bounds fit is swallowed', () => {
    withToken()
    gl.map.fitBounds.mockImplementationOnce(() => { throw new Error('empty bounds') })
    expect(() => render(<JourneyMapGL checkins={[]} entries={entries} />)).not.toThrow()
  })

  it('FE-COMP-JMAPGL-034: unmounting removes the pins, the popup and the map', () => {
    withToken()
    const ref = React.createRef<JourneyMapGLHandle>()
    const { unmount } = render(<JourneyMapGL ref={ref} checkins={[]} entries={entries} />)
    act(() => { ref.current!.highlightMarker('e1') })

    unmount()

    expect(gl.markers[0].remove).toHaveBeenCalled()
    expect(gl.markers[1].remove).toHaveBeenCalled()
    expect(gl.popups[0].remove).toHaveBeenCalled()
    expect(gl.map.remove).toHaveBeenCalled()
  })

  it('FE-COMP-JMAPGL-035: height 9999 stretches the wrapper to its container', () => {
    withToken()
    const { container } = render(<JourneyMapGL checkins={[]} entries={entries} height={9999} />)
    expect((container.firstChild as HTMLElement).style.height).toBe('100%')
  })

  it('FE-COMP-JMAPGL-036: the token placeholder honours the height prop', () => {
    const { container } = render(<JourneyMapGL checkins={[]} entries={entries} height={9999} />)
    expect((container.firstChild as HTMLElement).style.height).toBe('100%')
  })

  it('FE-COMP-JMAPGL-039: the plan has its own casing, and a layer switched off is added hidden (JRN-04)', () => {
    withToken()
    render(
      <JourneyMapGL
        checkins={[]}
        entries={entries}
        tracks={[{ place_id: 1, trip_id: 1, name: 'Ridge', color: '#aa0000', points: [[47, 11], [47.1, 11.1]] }]}
        layerVisibility={{ plan: false, recorded: true, entries: false }}
      />,
    )

    const layer = (id: string) => vi.mocked(gl.map.addLayer).mock.calls.map(c => c[0] as { id: string; layout: Record<string, unknown>; filter?: unknown }).find(l => l.id === id)
    expect(layer('journey-tracks-planned-casing')?.filter).toEqual(['==', ['get', 'planned'], true])
    expect(layer('journey-tracks-planned-casing')?.layout.visibility).toBe('none')
    expect(layer('journey-tracks-planned')?.layout.visibility).toBe('none')
    expect(layer('journey-tracks-line')?.layout.visibility).toBeUndefined()
    expect(layer('journey-route-line')?.layout.visibility).toBe('none')
    expect(gl.markers.every(m => m.element.style.display === 'none')).toBe(true)
  })

  it('FE-COMP-JMAPGL-040: a switch shows and hides its layers in place, and the check follows the plan', () => {
    withToken()
    const shown = { plan: true, recorded: true, entries: true }
    const { rerender } = render(<JourneyMapGL checkins={[]} entries={entries} layerVisibility={shown} />)
    expect(gl.markers[0].element.innerHTML).not.toContain('#16a34a')

    rerender(<JourneyMapGL checkins={[]} entries={entries} layerVisibility={{ ...shown, recorded: false }} plannedEntryIds={new Set(['e1'])} />)
    expect(gl.map.setLayoutProperty).toHaveBeenCalledWith('journey-tracks-line', 'visibility', 'none')
    expect(gl.map.setLayoutProperty).toHaveBeenCalledWith('journey-tracks-casing', 'visibility', 'none')
    expect(gl.map.setLayoutProperty).not.toHaveBeenCalledWith('journey-tracks-planned', 'visibility', expect.anything())
    expect(gl.markers[0].element.innerHTML).toContain('#16a34a')
    expect(mapboxgl.Map).toHaveBeenCalledTimes(1)
  })

  it('FE-COMP-JMAPGL-041: a recorded day takes the line between its entries off the map, the rest stays (#2888)', () => {
    withToken()
    const days = [
      { id: 'a', lat: 48.1, lng: 11.5, entry_date: '2026-10-29' },
      { id: 'b', lat: 48.2, lng: 11.6, entry_date: '2026-10-29' },
      { id: 'c', lat: 48.3, lng: 11.7, entry_date: '2026-10-30' },
      { id: 'd', lat: 48.4, lng: 11.8, entry_date: '2026-10-30' },
    ]
    render(
      <JourneyMapGL
        checkins={[]}
        entries={days}
        tracks={[{ place_id: -1, trip_id: 0, name: '2026-10-29', color: '#7c3aed', points: [[48.1, 11.5], [48.2, 11.6]], kind: 'dawarich_live', date: '2026-10-29' }]}
      />,
    )

    const data = (id: string) => (vi.mocked(gl.map.addSource).mock.calls.find(c => c[0] === id)?.[1] as { data: { geometry: { coordinates: number[][][] } } }).data.geometry.coordinates
    expect(data('journey-route')).toEqual([[[11.6, 48.2], [11.7, 48.3], [11.8, 48.4]]])
    expect(data('journey-route-covered')).toEqual([[[11.5, 48.1], [11.6, 48.2]]])
    const covered = vi.mocked(gl.map.addLayer).mock.calls.map(c => c[0] as { id: string; layout: Record<string, unknown> }).find(l => l.id === 'journey-route-covered-line')
    expect(covered?.layout.visibility).toBe('none')
  })

  it('FE-COMP-JMAPGL-042: hiding what was recorded brings the covered stretches back while the entries show', () => {
    withToken()
    const shown = { plan: true, recorded: true, entries: true }
    const days = [
      { id: 'a', lat: 48.1, lng: 11.5, entry_date: '2026-10-29' },
      { id: 'b', lat: 48.2, lng: 11.6, entry_date: '2026-10-29' },
    ]
    const tracks = [{ place_id: -1, trip_id: 0, name: 'Day', color: null, points: [[48.1, 11.5], [48.2, 11.6]] as [number, number][], kind: 'day_recording' as const, date: '2026-10-29' }]
    const { rerender } = render(<JourneyMapGL checkins={[]} entries={days} tracks={tracks} layerVisibility={shown} />)
    expect(gl.map.addSource).not.toHaveBeenCalledWith('journey-route', expect.anything())

    rerender(<JourneyMapGL checkins={[]} entries={days} tracks={tracks} layerVisibility={{ ...shown, recorded: false }} />)
    expect(gl.map.setLayoutProperty).toHaveBeenCalledWith('journey-route-covered-line', 'visibility', 'visible')

    rerender(<JourneyMapGL checkins={[]} entries={days} tracks={tracks} layerVisibility={{ ...shown, recorded: false, entries: false }} />)
    expect(gl.map.setLayoutProperty).toHaveBeenLastCalledWith('journey-route-covered-line', 'visibility', 'none')
  })

  it("FE-COMP-JMAPGL-049: a map opened on satellite slides the imagery under the journey's own layers (#2594)", () => {
    withToken()
    gl.map.getStyle.mockReturnValue({ layers: [{ id: 'water' }, { id: 'journey-route-line' }] })
    render(<JourneyMapGL checkins={[]} entries={entries} baseLayer="satellite" />)

    expect(gl.map.addSource).toHaveBeenCalledWith('trip-satellite', expect.objectContaining({ type: 'raster' }))
    // Over the basemap's water, under the line between the entries.
    expect(gl.map.addLayer).toHaveBeenCalledWith(expect.objectContaining({ id: 'trip-satellite-raster' }), 'journey-route-line')
  })

  it('FE-COMP-JMAPGL-050: the switch flips the imagery in place, without rebuilding the map', () => {
    withToken()
    const { rerender } = render(<JourneyMapGL checkins={[]} entries={entries} />)
    expect(gl.map.addLayer).not.toHaveBeenCalledWith(expect.objectContaining({ id: 'trip-satellite-raster' }), expect.anything())

    rerender(<JourneyMapGL checkins={[]} entries={entries} baseLayer="satellite" />)
    expect(gl.map.addLayer).toHaveBeenCalledWith(expect.objectContaining({ id: 'trip-satellite-raster' }), undefined)

    gl.map.getLayer.mockReturnValue({ id: 'trip-satellite-raster' })
    rerender(<JourneyMapGL checkins={[]} entries={entries} baseLayer="default" />)
    expect(gl.map.setLayoutProperty).toHaveBeenLastCalledWith('trip-satellite-raster', 'visibility', 'none')
    expect(mapboxgl.Map).toHaveBeenCalledTimes(1)
  })
})