fix(dawarich): three things a tester on dev1 ran into

The Atlas country check timed out. It asked Dawarich for a year of visited
cities in one request, and Dawarich computes that over every point in the
window with nothing cached, so a dense recorder never got under the 15 s the
server allows. The year is now asked for a month at a time, one request after
another, and folded back together. The windows sit a second apart because
Dawarich reads the bounds as inclusive.

The recorded route only appeared after a reload. Every Dawarich call from the
browser carried the shared 8 s timeout, so the browser gave up while the server
carried on and cached the answer for the next page load. Calls that make the
server talk to Dawarich now wait two minutes, the Atlas four. On the GL
renderers the draw also gave up whenever isStyleLoaded() was false, which it is
while any tile is still loading, and only retried on style.load. It now waits
for idle. The hazard overlay had the same guard and gets the same wait. The
pill shows a ring while the route loads, so a slow first fetch no longer looks
like "done, nothing there".

A collapsed day now takes its recorded route off the map, following the same
folds the planner already applies to places, the road trip sidebar's included.
This commit is contained in:
Maurice
2026-09-14 23:00:57 +02:00
parent 60cbb41d5f
commit c1d55c463c
19 changed files with 703 additions and 37 deletions
@@ -26,15 +26,18 @@ import {
export default function DawarichTrailLayer({
track,
selectedDate,
hiddenDates,
casingPane,
}: {
track: DawarichTrack | null
/** When set, only that local day is drawn. */
selectedDate?: string | null
/** Local dates whose day is folded away in the day plan. */
hiddenDates?: ReadonlySet<string> | null
/** The `trek-track-casing` pane, when the renderer supports panes. */
casingPane?: string
}) {
const segments = useMemo(() => trailSegments(track, selectedDate), [track, selectedDate])
const segments = useMemo(() => trailSegments(track, selectedDate, hiddenDates), [track, selectedDate, hiddenDates])
if (segments.length === 0) return null
return (
@@ -1,5 +1,5 @@
/**
* FE-DAWARICH-TRAILUI-001 to FE-DAWARICH-TRAILUI-007: the recorded-route
* FE-DAWARICH-TRAILUI-001 to FE-DAWARICH-TRAILUI-009: the recorded-route
* toggle that sits with the compass and the layer switcher on the trip map.
*
* The pill is small but it carries the only explanation the user ever gets for
@@ -124,4 +124,26 @@ describe('DawarichTrailPill', () => {
// button to find out why the map is empty.
expect(screen.getByRole('tooltip')).toHaveTextContent('Nothing was recorded on these dates')
})
it('FE-DAWARICH-TRAILUI-008: shows a spinning ring and a busy state while the route loads', () => {
pill({ active: true, status: 'loading' })
// A first fetch from somebody's own server can take a while. With nothing on
// the button it read as "done, no line", and the tester reloaded the page.
expect(screen.getByTestId('dawarich-trail-loading')).toBeInTheDocument()
expect(button()).toHaveAttribute('aria-busy', 'true')
})
it('FE-DAWARICH-TRAILUI-009: drops the ring once there is an answer, and never shows it while the layer is off', () => {
const view = pill({ active: true, status: 'loading' })
view.rerender(<DawarichTrailPill active status="ready" onToggle={vi.fn()} />)
expect(screen.queryByTestId('dawarich-trail-loading')).not.toBeInTheDocument()
expect(button()).toHaveAttribute('aria-busy', 'false')
// Switched off mid-load: the hook still reports its last status, the button
// must not keep spinning for a layer nobody asked for any more.
view.rerender(<DawarichTrailPill active={false} status="loading" onToggle={vi.fn()} />)
expect(screen.queryByTestId('dawarich-trail-loading')).not.toBeInTheDocument()
})
})
@@ -40,10 +40,15 @@ export function DawarichTrailPill({
// A problem worth seeing without reading the tooltip: the layer is on and
// there is nothing to show.
const muted = active && (status === 'empty' || status === 'offline' || status === 'unavailable')
// Loading has to be visible too. A first fetch from somebody's own server can
// take a while, and with nothing on the button it looked exactly like "done,
// but no line", so testers reloaded the page to find out.
const loading = active && status === 'loading'
return (
<div
style={{
position: 'relative',
display: 'inline-flex',
alignItems: 'center',
padding: 4,
@@ -64,6 +69,7 @@ export function DawarichTrailPill({
onClick={onToggle}
aria-label={label}
aria-pressed={active}
aria-busy={loading}
data-testid="dawarich-trail-pill"
style={{
display: 'block',
@@ -88,6 +94,22 @@ export function DawarichTrailPill({
<DawarichIcon fill />
</button>
</Tooltip>
{loading && (
<span
aria-hidden="true"
data-testid="dawarich-trail-loading"
className="motion-safe:animate-spin"
style={{
position: 'absolute',
inset: 2,
borderRadius: 999,
border: '2px solid transparent',
borderTopColor: 'var(--accent)',
borderRightColor: 'var(--accent)',
pointerEvents: 'none',
}}
/>
)}
</div>
)
}
+2
View File
@@ -676,6 +676,7 @@ export const MapView = memo(function MapView({
hazards,
dawarichTrack = null,
dawarichSelectedDate = null,
dawarichHiddenDates = null,
accessLines = [],
onPoiDropOnRoute,
onRouteClick,
@@ -1201,6 +1202,7 @@ export const MapView = memo(function MapView({
<DawarichTrailLayer
track={dawarichTrack}
selectedDate={dawarichSelectedDate}
hiddenDates={dawarichHiddenDates}
casingPane={hasCasingPane ? TRACK_CASING_PANE : undefined}
/>
<ClusteredPois pois={pois} enabled={clusterLoosely} onPoiClick={onPoiClick}>{poiMarkers}</ClusteredPois>
+4 -1
View File
@@ -197,6 +197,8 @@ interface Props {
dawarichTrack?: DawarichTrack | null
/** Draw only this local day of the recording. */
dawarichSelectedDate?: string | null
/** Local dates whose day is collapsed in the day plan; their recording is not drawn. */
dawarichHiddenDates?: ReadonlySet<string> | null
/** Via points to draw as draggable handles, keyed by day (#1797). */
roadtripVias?: Record<number, RoadtripVia[]>
onMoveVia?: (dayId: number, id: number, lat: number, lng: number) => void
@@ -646,6 +648,7 @@ export function MapViewGL({
hazards,
dawarichTrack = null,
dawarichSelectedDate = null,
dawarichHiddenDates = null,
dayOrderMap = NO_DAY_ORDER,
leftWidth = 0,
rightWidth = 0,
@@ -724,7 +727,7 @@ export function MapViewGL({
const hazardPopupFactory = useCallback(() => new gl.Popup({ className: 'map-tooltip trek-hazard-popup', maxWidth: '320px' }), [gl])
useHazardLayerGL(mapRef.current, mapReady, hazards, hazardPopupFactory)
// Beneath the planned route's casing, the GL twin of the Leaflet pane order.
useDawarichTrailGL(mapRef.current, mapReady, dawarichTrack, dawarichSelectedDate, 'trip-route-casing')
useDawarichTrailGL(mapRef.current, mapReady, dawarichTrack, dawarichSelectedDate, 'trip-route-casing', dawarichHiddenDates)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const markersRef = useRef<Map<number, PlacePin>>(new Map())
// Own layer for the hand-positioned place pins (MapLibre path, see makePlacePin).
@@ -1,5 +1,6 @@
/**
* dawarichTrail unit tests: FE-DAWARICH-TRAIL-001 to FE-DAWARICH-TRAIL-008.
* dawarichTrail unit tests: FE-DAWARICH-TRAIL-001 to FE-DAWARICH-TRAIL-008, and
* FE-DAWARICH-TRAIL-030 to FE-DAWARICH-TRAIL-032 for the days folded away.
*
* This module is the whole of what the two map renderers agree on about the
* recorded route: Leaflet turns `trailSegments` into `<Polyline>` elements, the
@@ -32,6 +33,7 @@ import {
DAWARICH_DAY_COLORS,
DAWARICH_TRAIL_CASING,
DAWARICH_TRAIL_COLOR,
collapsedDayDates,
dayColor,
trailDistanceKm,
trailGeoJson,
@@ -227,3 +229,40 @@ describe('trailDistanceKm', () => {
expect(trailDistanceKm([])).toBeNull()
})
})
describe('the days folded away in the day plan', () => {
it('FE-DAWARICH-TRAIL-030: a collapsed day takes its route off the map and leaves the colours of the rest alone', () => {
const all = trailSegments(THREE_DAYS)
const visible = trailSegments(THREE_DAYS, null, new Set(['2026-05-02']))
expect(visible.map(segment => segment.date)).toEqual(['2026-05-01', '2026-05-01', '2026-05-03'])
// Folding day two must not shift day three onto day two's colour.
expect(visible.find(segment => segment.date === '2026-05-03')?.color)
.toBe(all.find(segment => segment.date === '2026-05-03')?.color)
})
it('FE-DAWARICH-TRAIL-031: a picked day that is also folded away draws nothing', () => {
expect(trailSegments(THREE_DAYS, '2026-05-01', new Set(['2026-05-01']))).toEqual([])
expect(trailSegments(THREE_DAYS, '2026-05-01', new Set(['2026-05-03']))).toHaveLength(2)
})
it('FE-DAWARICH-TRAIL-032: follows both folds the places follow, and nothing before the day plan has spoken', () => {
const days = [
{ id: 1, date: '2026-05-03' },
{ id: 2, date: '2026-05-01' },
{ id: 3, date: null },
{ id: 4, date: '2026-05-02' },
]
// Null is "the day plan has not reported yet": the places show, so the
// route shows too.
expect(collapsedDayDates(days, null)).toEqual([])
// Sorted, deduplicated, and a day without a date matches no recording.
expect(collapsedDayDates(days, new Set([4]))).toEqual(['2026-05-01', '2026-05-03'])
// Road trip mode folds days in its own sidebar, on top of the day plan.
expect(collapsedDayDates(days, null, new Set([4]))).toEqual(['2026-05-02'])
expect(collapsedDayDates(days, new Set([1, 2, 3, 4]), new Set([1, 3]))).toEqual(['2026-05-03'])
})
})
+32 -7
View File
@@ -64,20 +64,21 @@ export interface DawarichTrailSegment {
}
/**
* Flatten a fetched track into drawable segments, optionally limited to one day.
* Flatten a fetched track into drawable segments, optionally limited to one day
* and without the days folded away in the day plan.
*
* The day filter is what the timeline scrubber drives: selecting a day on the
* planner should dim the rest of the trip rather than reload it, so the filter
* happens here over data that is already in memory.
* Both filters work on data that is already in memory: selecting or collapsing a
* day changes what is drawn, it does not reload the recording.
*/
export function trailSegments(
track: DawarichTrack | null,
onlyDate?: string | null,
hiddenDates?: ReadonlySet<string> | null,
): DawarichTrailSegment[] {
if (!track) return []
const days: DawarichTrackDay[] = onlyDate
? track.days.filter(day => day.date === onlyDate)
: track.days
const days: DawarichTrackDay[] = track.days.filter(
day => (!onlyDate || day.date === onlyDate) && !hiddenDates?.has(day.date),
)
const out: DawarichTrailSegment[] = []
for (const day of days) {
@@ -108,6 +109,30 @@ export function trailSegments(
return out
}
/**
* The dates whose recording stays off the map because their day is collapsed.
*
* The same rule the planner already applies to places: a collapsed day takes
* its markers off the map, so it takes its route with it. Two folds count, as
* they do for places: the day plan's (`expandedDayIds`, null until the day plan
* has reported its state, and then nothing is hidden by it) and, in road trip
* mode, the road trip sidebar's own. A day without a date has nothing to match a
* recording against. Sorted, so the caller can key a memo on the joined list.
*/
export function collapsedDayDates(
days: ReadonlyArray<{ id: number; date?: string | null }>,
expandedDayIds: ReadonlySet<number> | null,
collapsedDayIds?: ReadonlySet<number> | null,
): string[] {
const dates = new Set<string>()
for (const day of days) {
if (!day.date) continue
const foldedInPlan = !!expandedDayIds && !expandedDayIds.has(day.id)
if (foldedInPlan || collapsedDayIds?.has(day.id)) dates.add(day.date)
}
return [...dates].sort()
}
/** The overlay as a GeoJSON FeatureCollection, for the GL renderer. */
export function trailGeoJson(segments: DawarichTrailSegment[]): {
type: 'FeatureCollection'
@@ -1,5 +1,5 @@
/**
* FE-DAWARICH-TRAILUI-020 to FE-DAWARICH-TRAILUI-029: the recorded-route
* FE-DAWARICH-TRAILUI-020 to FE-DAWARICH-TRAILUI-032: the recorded-route
* overlay on the GL renderer, the imperative twin of `DawarichTrailLayer`.
*
* A declarative overlay that gets its ordering wrong looks wrong. An imperative
@@ -28,6 +28,10 @@
* sources. Both paths are pinned, because which one a refresh takes is the
* difference between a line that blinks every two minutes and one that does
* not.
* - **the wait for `idle`.** `isStyleLoaded()` is false while any tile is
* still in flight, not only before the first style. A draw that gave up
* there and only listened for `style.load` left the line off the map until
* the page was reloaded, which is what a tester on dev1 ran into.
* - **one `style.load` subscription at a time.** The effect re-runs on every
* refresh, and a cleanup that forgot to unsubscribe would add one silent
* redraw per refresh for the life of the map.
@@ -61,6 +65,7 @@ function fakeGlMap({ styleLoaded = true, styleLayers = [] as string[] } = {}) {
const layers = new Map<string, { spec: { id: string; paint?: Record<string, unknown> }; before: string | undefined }>()
for (const id of styleLayers) layers.set(id, { spec: { id }, before: undefined })
const listeners = new Map<string, Set<() => void>>()
const onceListeners = new Map<string, Set<() => void>>()
const state = { styleLoaded }
const map = {
@@ -84,7 +89,15 @@ function fakeGlMap({ styleLoaded = true, styleLayers = [] as string[] } = {}) {
set.add(fn)
listeners.set(type, set)
}),
off: vi.fn((type: string, fn: () => void) => { listeners.get(type)?.delete(fn) }),
once: vi.fn((type: string, fn: () => void) => {
const set = onceListeners.get(type) ?? new Set<() => void>()
set.add(fn)
onceListeners.set(type, set)
}),
off: vi.fn((type: string, fn: () => void) => {
listeners.get(type)?.delete(fn)
onceListeners.get(type)?.delete(fn)
}),
}
return {
@@ -95,6 +108,13 @@ function fakeGlMap({ styleLoaded = true, styleLayers = [] as string[] } = {}) {
state,
styleLoadListeners: () => listeners.get('style.load')?.size ?? 0,
emitStyleLoad: () => { listeners.get('style.load')?.forEach(fn => fn()) },
idleListeners: () => onceListeners.get('idle')?.size ?? 0,
/** A `once` listener is gone before it runs, the way GL's Evented does it. */
emitIdle: () => {
const pending = [...(onceListeners.get('idle') ?? [])]
onceListeners.delete('idle')
pending.forEach(fn => fn())
},
/** What a style rebuild does to the map before `style.load` fires. */
dropStyle: () => { sources.clear(); layers.clear() },
drawn: () => sources.get(SOURCE)?.data as
@@ -109,10 +129,11 @@ interface Props {
track?: DawarichTrack | null
date?: string | null
before?: string
hidden?: ReadonlySet<string> | null
}
const mount = (props: Props) =>
renderHook((p: Props) => useDawarichTrailGL(p.map, p.ready, p.track, p.date, p.before), {
renderHook((p: Props) => useDawarichTrailGL(p.map, p.ready, p.track, p.date, p.before, p.hidden), {
initialProps: props,
})
@@ -314,4 +335,53 @@ describe('useDawarichTrailGL', () => {
// change per refresh, for as long as the map lives.
expect(gl.styleLoadListeners()).toBe(1)
})
it('FE-DAWARICH-TRAILUI-030: a route that lands while tiles are still loading is drawn once they have arrived', () => {
// The tester's case: the overlay switched on, the map still filling in,
// and the line only appearing after a reload.
const gl = fakeGlMap({ styleLoaded: false })
mount({ map: gl.map, ready: true, track: track([DAY_ONE]) })
expect(gl.spies.addSource).not.toHaveBeenCalled()
expect(gl.idleListeners()).toBe(1)
gl.state.styleLoaded = true
gl.emitIdle()
expect(gl.spies.addSource).toHaveBeenCalledTimes(1)
expect(gl.spies.addLayer).toHaveBeenCalledTimes(2)
expect(gl.idleListeners()).toBe(0)
})
it('FE-DAWARICH-TRAILUI-031: waits for idle once however often it is asked, and keeps waiting while the map is busy', () => {
const gl = fakeGlMap({ styleLoaded: false })
const view = mount({ map: gl.map, ready: true, track: track([DAY_ONE]) })
// A style.load that fires while tiles are still in flight is a second draw
// attempt; it must not stack a second wait on the first.
gl.emitStyleLoad()
expect(gl.idleListeners()).toBe(1)
// An idle that arrives before the style is ready (a transition finished,
// another source started) is not the end of the wait.
gl.emitIdle()
expect(gl.spies.addSource).not.toHaveBeenCalled()
expect(gl.idleListeners()).toBe(1)
view.unmount()
expect(gl.idleListeners()).toBe(0)
expect(gl.spies.off).toHaveBeenCalledWith('idle', expect.any(Function))
})
it('FE-DAWARICH-TRAILUI-032: leaves out the days folded away in the day plan without repainting the others', () => {
const gl = fakeGlMap()
const view = mount({ map: gl.map, ready: true, track: track([DAY_ONE, DAY_TWO]) })
const secondColour = gl.drawn()?.features[1]?.properties.color
view.rerender({ map: gl.map, ready: true, track: track([DAY_ONE, DAY_TWO]), hidden: new Set([DAY_ONE.date]) })
expect(gl.drawn()?.features).toHaveLength(1)
expect(gl.drawn()?.features[0]?.properties.date).toBe(DAY_TWO.date)
expect(gl.drawn()?.features[0]?.properties.color).toBe(secondColour)
})
})
@@ -28,14 +28,29 @@ export function useDawarichTrailGL(
selectedDate?: string | null,
/** Insert beneath this layer, so the planned route stays on top. */
beforeId?: string,
/** Local dates whose day is folded away in the day plan. */
hiddenDates?: ReadonlySet<string> | null,
): void {
useEffect(() => {
if (!map || !ready) return
const data = trailGeoJson(trailSegments(track ?? null, selectedDate))
const data = trailGeoJson(trailSegments(track ?? null, selectedDate, hiddenDates))
// `isStyleLoaded()` does not mean "the style has loaded". It is false while
// any source still has tiles in flight, which is the usual state right after
// someone switches the overlay on and the map is still filling in. Giving up
// there left the line undrawn until something rebuilt the style, which in
// practice meant reloading the page. `idle` is the map saying everything it
// was fetching has arrived, so the draw waits for it once and tries again.
let waiting = false
const draw = () => {
if (!map.isStyleLoaded()) return
if (!map.isStyleLoaded()) {
if (!waiting) {
waiting = true
map.once('idle', retry)
}
return
}
const existing = map.getSource(SOURCE) as GeoJSONSource | undefined
if (existing) {
// setData rather than remove-and-add: a rebuilt source flickers, and a
@@ -77,14 +92,20 @@ export function useDawarichTrailGL(
)
}
const retry = () => {
waiting = false
draw()
}
draw()
map.on('style.load', draw)
return () => {
map.off('style.load', draw)
map.off('idle', retry)
for (const layer of [LINE_LAYER, CASING_LAYER]) {
if (map.getLayer(layer)) map.removeLayer(layer)
}
if (map.getSource(SOURCE)) map.removeSource(SOURCE)
}
}, [map, ready, track, selectedDate, beforeId])
}, [map, ready, track, selectedDate, beforeId, hiddenDates])
}
@@ -0,0 +1,107 @@
/**
* FE-ROADTRIP-HAZARDGL-001 to FE-ROADTRIP-HAZARDGL-003: when the hazard overlay
* on the GL renderer actually gets drawn.
*
* It shares a failure with the recorded Dawarich route: `isStyleLoaded()` is
* false while any source still has tiles in flight, not only before the first
* style. A draw that gave up there and waited for `style.load` alone stayed off
* the map until the style was rebuilt, which in practice meant a reload. These
* cases pin the wait for `idle` that replaced it, and that the wait does not
* outlive the component.
*/
import { describe, it, expect, vi } from 'vitest'
import { renderHook } from '@testing-library/react'
import type { Map as MapboxMap, Popup } from 'mapbox-gl'
import type { RoadtripHazard } from '@trek/shared'
import { useHazardLayerGL } from './useHazardLayerGL'
vi.mock('../../i18n/TranslationContext', () => ({ useTranslation: () => ({ t: (key: string) => key }) }))
const SOURCE = 'roadtrip-hazards'
const HAZARD: RoadtripHazard = {
id: 'dwd-1',
source: 'DWD',
title: 'Sturmboeen',
description: 'Boeen bis 85 km/h',
updatedAt: '2026-09-14T10:00:00.000Z',
validUntil: null,
url: 'https://www.dwd.de/warnungen',
geometry: { type: 'Point', coordinates: [13.4, 52.5] },
}
function fakeGlMap(styleLoaded: boolean) {
const sources = new Set<string>()
const layers = new Set<string>()
const once = new Map<string, Set<() => void>>()
const state = { styleLoaded }
const map = {
isStyleLoaded: vi.fn(() => state.styleLoaded),
getSource: vi.fn((id: string) => (sources.has(id) ? {} : undefined)),
addSource: vi.fn((id: string) => { sources.add(id) }),
removeSource: vi.fn((id: string) => { sources.delete(id) }),
getLayer: vi.fn((id: string) => (layers.has(id) ? {} : undefined)),
addLayer: vi.fn((spec: { id: string }) => { layers.add(spec.id) }),
removeLayer: vi.fn((id: string) => { layers.delete(id) }),
on: vi.fn(),
once: vi.fn((type: string, fn: () => void) => {
const set = once.get(type) ?? new Set<() => void>()
set.add(fn)
once.set(type, set)
}),
off: vi.fn((type: string, fn: () => void) => { once.get(type)?.delete(fn) }),
}
return {
map: map as unknown as MapboxMap,
spies: map,
state,
sources,
idleListeners: () => once.get('idle')?.size ?? 0,
emitIdle: () => {
const pending = [...(once.get('idle') ?? [])]
once.delete('idle')
pending.forEach(fn => fn())
},
}
}
const popup = () => ({}) as Popup
describe('useHazardLayerGL', () => {
it('FE-ROADTRIP-HAZARDGL-001: draws straight away into a style that is ready', () => {
const gl = fakeGlMap(true)
renderHook(() => useHazardLayerGL(gl.map, true, [HAZARD], popup))
expect(gl.spies.addSource).toHaveBeenCalledWith(SOURCE, expect.objectContaining({ type: 'geojson' }))
expect(gl.spies.addLayer).toHaveBeenCalledTimes(3)
expect(gl.idleListeners()).toBe(0)
})
it('FE-ROADTRIP-HAZARDGL-002: hazards that arrive while tiles are loading are drawn once the map is idle', () => {
const gl = fakeGlMap(false)
renderHook(() => useHazardLayerGL(gl.map, true, [HAZARD], popup))
expect(gl.spies.addSource).not.toHaveBeenCalled()
expect(gl.idleListeners()).toBe(1)
// Still busy at the first idle: wait again, and only once.
gl.emitIdle()
expect(gl.spies.addSource).not.toHaveBeenCalled()
expect(gl.idleListeners()).toBe(1)
gl.state.styleLoaded = true
gl.emitIdle()
expect(gl.spies.addSource).toHaveBeenCalledTimes(1)
expect(gl.idleListeners()).toBe(0)
})
it('FE-ROADTRIP-HAZARDGL-003: an unmount while waiting takes the wait with it', () => {
const gl = fakeGlMap(false)
const view = renderHook(() => useHazardLayerGL(gl.map, true, [HAZARD], popup))
view.unmount()
expect(gl.idleListeners()).toBe(0)
expect(gl.spies.off).toHaveBeenCalledWith('idle', expect.any(Function))
expect(gl.sources.size).toBe(0)
})
})
+17 -1
View File
@@ -11,8 +11,19 @@ export function useHazardLayerGL(map: Map | null, ready: boolean, hazards: Roadt
const source = 'roadtrip-hazards'
const layers = [`${source}-fill`, `${source}-line`, `${source}-point`]
let detail: Popup | undefined
// Waits for `idle` rather than giving up while tiles are still loading, for
// the reason spelled out in useDawarichTrailGL: `isStyleLoaded()` is false
// for as long as any source has tiles in flight.
let waiting = false
const draw = () => {
if (!map.isStyleLoaded() || map.getSource(source)) return
if (map.getSource(source)) return
if (!map.isStyleLoaded()) {
if (!waiting) {
waiting = true
map.once('idle', retry)
}
return
}
const color = getComputedStyle(document.documentElement).getPropertyValue('--warning').trim()
map.addSource(source, { type: 'geojson', data: { type: 'FeatureCollection', features: hazards.map(hazardFeature) } })
map.addLayer({ id: layers[0], type: 'fill', source, filter: ['!=', ['geometry-type'], 'Point'], paint: { 'fill-color': color, 'fill-opacity': 0.16 } })
@@ -27,12 +38,17 @@ export function useHazardLayerGL(map: Map | null, ready: boolean, hazards: Roadt
detail?.remove()
detail = popup().setLngLat(event.lngLat).setDOMContent(hazardPopup(hazard, t('roadtrip.hazards.note'), t('roadtrip.hazards.point'))).addTo(map)
}
const retry = () => {
waiting = false
draw()
}
draw()
map.on('style.load', draw)
map.on('click', click)
return () => {
detail?.remove()
map.off('style.load', draw)
map.off('idle', retry)
map.off('click', click)
for (const layer of layers) if (map.getLayer(layer)) map.removeLayer(layer)
if (map.getSource(source)) map.removeSource(source)