All files / map element.ts

99.28% Statements 138/139
90.62% Branches 29/32
100% Functions 37/37
99.25% Lines 134/135

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336                                      2x   2x             2x 2x 2x 2x   2x 16x 16x               2x 20x 20x               2x         2x     32x   2x 2x                               14x   14x 14x 14x 14x 14x 1x     14x 14x 14x 14x 14x   1x           14x 14x 13x   14x 14x 14x 14x             29x 29x       1x       14x 14x 14x                 14x       14x   14x         14x       13x 2x 2x 2x 2x   13x 2x 2x     13x 2x 1x     13x 1x 1x   13x 1x 13x 13x 1x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x           29x 10x   19x 19x 19x 19x         21x 19x 19x 19x 19x 19x 19x         19x 19x 18x   1x 1x   1x       19x 19x 17x   2x 2x           19x 19x 17x   2x 2x       1x 1x           19x 19x 19x 15x   4x 4x     4x   3x           1x                             20x 20x 20x 20x                                 20x         21x         2x 28x     1x     3x         2x 16x 1x      
import { Option } from 'effect'
import maplibregl, {
  type Map as MapInstance,
  type MapMouseEvent,
} from 'maplibre-gl'
 
import { Camera, type LatLon } from '../core/domain'
import { wrapLon } from '../core/geo/ellipsoid'
import type { Box } from '../core/geo/geometry'
import { basemapStyles } from './basemaps'
import * as CameraRequest from './cameraRequest'
import { ensureOverlayLayers, setOverlay } from './layers'
import { buildOverlayFrame } from './overlay'
import {
  type MapProperties,
  initialMapProperties,
  mapPropertyNames,
} from './properties'
 
export const MAP_TAG = 'coordkit-map'
 
const DEFAULT_CAMERA: Camera.Camera = {
  center: { lat: 20, lon: 0 },
  zoom: 1.6,
  bearing: 0,
  pitch: 0,
}
 
const FLIGHT_DURATION_MS = 1200
const FLIGHT_MIN_ZOOM = 12
const FIT_PADDING = 120
const FIT_MAX_ZOOM = 14
 
const cameraOf = (map: MapInstance): Camera.Camera => {
  const centre = map.getCenter()
  return {
    center: { lat: centre.lat, lon: wrapLon(centre.lng) },
    zoom: map.getZoom(),
    bearing: map.getBearing(),
    pitch: map.getPitch(),
  }
}
 
const boundsOf = (map: MapInstance): Box => {
  const bounds = map.getBounds()
  return [
    bounds.getWest(),
    bounds.getSouth(),
    bounds.getEast(),
    bounds.getNorth(),
  ]
}
 
const pointOf = (event: MapMouseEvent): LatLon.LatLon => ({
  lat: event.lngLat.lat,
  lon: wrapLon(event.lngLat.lng),
})
 
const requestIdOf = (
  maybeRequest: Option.Option<CameraRequest.CameraRequest>,
): number | undefined =>
  Option.getOrUndefined(Option.map(maybeRequest, ({ id }) => id))
 
const errorReason = (error: unknown): string =>
  error instanceof Error ? error.message : String(error)
 
type Host = Readonly<{ map: MapInstance }>
 
type AppliedKey = 'basemap' | 'projection' | 'camera'
type Applied = { -readonly [K in AppliedKey]?: MapProperties[K] } & {
  cameraRequestId?: number | undefined
}
 
/**
 * `<coordkit-map>`: MapLibre behind a custom element. The view sets its properties
 * from the Model on every render, and the element redraws to match, so the map is a function of
 * the Model and DevTools time travel moves it too. Map events leave as CustomEvents, which the
 * view turns into Messages (see mapEventFields).
 */
export class CoordkitMapElement extends HTMLElement {
  #properties: MapProperties = initialMapProperties
  /** What the map shows now, so each sync applies only what changed. */
  #applied: Applied = {}
  #maybeHost: Option.Option<Host> = Option.none()
  #isStyleReady = false
  #isLoaded = false
  #isSyncQueued = false
  #removeListeners: () => void = () => {}
 
  connectedCallback(): void {
    try {
      const host = this.#createHost()
      this.#maybeHost = Option.some(host)
      this.#removeListeners = this.#listen(host.map)
      this.#emit('map-moved', cameraOf(host.map))
    } catch (error) {
      this.#emit('map-failed', { reason: errorReason(error) })
    }
  }
 
  // NOTE: Snabbdom removes the element's event listeners before this runs, so nothing is emitted here.
  disconnectedCallback(): void {
    this.#removeListeners()
    if (Option.isSome(this.#maybeHost)) {
      this.#maybeHost.value.map.remove()
    }
    this.#maybeHost = Option.none()
    this.#isStyleReady = false
    this.#isLoaded = false
    this.#applied = {}
  }
 
  setMapProperty<K extends keyof MapProperties>(
    name: K,
    value: MapProperties[K],
  ): void {
    this.#properties = { ...this.#properties, [name]: value }
    this.#queueSync()
  }
 
  getMapProperty<K extends keyof MapProperties>(name: K): MapProperties[K] {
    return this.#properties[name]
  }
 
  #createHost(): Host {
    const properties = this.#properties
    const camera = Option.getOrElse(properties.camera, () => DEFAULT_CAMERA)
    const map = new maplibregl.Map({
      container: this,
      style: basemapStyles[properties.basemap],
      center: [camera.center.lon, camera.center.lat],
      zoom: camera.zoom,
      bearing: camera.bearing,
      pitch: camera.pitch,
      attributionControl: { compact: true },
    })
    map.addControl(
      new maplibregl.NavigationControl({ visualizePitch: true }),
      'top-right',
    )
    map.addControl(new maplibregl.ScaleControl({ unit: 'metric' }), 'top-right')
    // NOTE: the map starts where these properties say, so the first sync must not move it again.
    this.#applied = {
      basemap: properties.basemap,
      camera: properties.camera,
      cameraRequestId: requestIdOf(properties.cameraRequest),
    }
    return { map }
  }
 
  #listen(map: MapInstance): () => void {
    const onStyleLoad = () => {
      this.#isStyleReady = true
      ensureOverlayLayers(map)
      delete this.#applied.projection
      this.#sync()
    }
    const onLoad = () => {
      this.#isLoaded = true
      this.#emit('map-ready', {})
    }
    // NOTE: a tile that fails later is not fatal, but failing before the first load is.
    const onError = (event: { error?: unknown }) => {
      if (!this.#isLoaded) {
        this.#emit('map-failed', { reason: errorReason(event.error) })
      }
    }
    const onMoveEnd = () => {
      this.#renderOverlay()
      this.#emit('map-moved', cameraOf(map))
    }
    const onMouseMove = (event: MapMouseEvent) =>
      this.#emit('cursor-moved', pointOf(event))
    const onMouseOut = () => this.#emit('cursor-left', {})
    const onClick = (event: MapMouseEvent) =>
      this.#emit('map-clicked', pointOf(event))
    map.on('style.load', onStyleLoad)
    map.on('load', onLoad)
    map.on('error', onError)
    map.on('moveend', onMoveEnd)
    map.on('mousemove', onMouseMove)
    map.on('mouseout', onMouseOut)
    map.on('click', onClick)
    return () => {
      map.off('style.load', onStyleLoad)
      map.off('load', onLoad)
      map.off('error', onError)
      map.off('moveend', onMoveEnd)
      map.off('mousemove', onMouseMove)
      map.off('mouseout', onMouseOut)
      map.off('click', onClick)
    }
  }
 
  /** Several properties change in one render; apply them together once it finishes. */
  #queueSync(): void {
    if (this.#isSyncQueued) {
      return
    }
    this.#isSyncQueued = true
    queueMicrotask(() => {
      this.#isSyncQueued = false
      this.#sync()
    })
  }
 
  #sync(): void {
    if (Option.isSome(this.#maybeHost)) {
      const { map } = this.#maybeHost.value
      this.#syncStyle(map)
      this.#syncProjection(map)
      this.#syncCamera(map)
      this.#syncCameraRequest(map)
      this.#renderOverlay()
    }
  }
 
  #syncStyle(map: MapInstance): void {
    const { basemap } = this.#properties
    if (basemap === this.#applied.basemap) {
      return
    }
    this.#applied.basemap = basemap
    this.#isStyleReady = false
    // NOTE: a diffed style swap drops the grid label layer and skips 'style.load', which re-adds it.
    map.setStyle(basemapStyles[basemap], { diff: false })
  }
 
  #syncProjection(map: MapInstance): void {
    const { projection } = this.#properties
    if (!this.#isStyleReady || projection === this.#applied.projection) {
      return
    }
    this.#applied.projection = projection
    map.setProjection({ type: projection === 'Globe' ? 'globe' : 'mercator' })
  }
 
  // NOTE: jump only when the camera property itself changes. While the map pans or flies, the
  // property keeps its last value, so renders during the movement never pull the map back.
  #syncCamera(map: MapInstance): void {
    const { camera } = this.#properties
    if (camera === this.#applied.camera) {
      return
    }
    this.#applied.camera = camera
    if (
      Option.isSome(camera) &&
      !Camera.isSameView(cameraOf(map), camera.value)
    ) {
      const { center, zoom, bearing, pitch } = camera.value
      map.jumpTo({ center: [center.lon, center.lat], zoom, bearing, pitch })
    }
  }
 
  /** Each new request id is one animated move. A copy of the same request, as after a hot reload, does not move the map again. */
  #syncCameraRequest(map: MapInstance): void {
    const { cameraRequest } = this.#properties
    const requestId = requestIdOf(cameraRequest)
    if (requestId === this.#applied.cameraRequestId) {
      return
    }
    this.#applied.cameraRequestId = requestId
    Iif (Option.isNone(cameraRequest)) {
      return
    }
    CameraRequest.CameraTarget.match(cameraRequest.value.target, {
      FlyTo: ({ point }) =>
        map.flyTo({
          center: [point.lon, point.lat],
          zoom: Math.max(map.getZoom(), FLIGHT_MIN_ZOOM),
          duration: FLIGHT_DURATION_MS,
        }),
      FitBox: ({ box: [west, south, east, north] }) =>
        map.fitBounds(
          [
            [west, south],
            [east, north],
          ],
          {
            padding: FIT_PADDING,
            maxZoom: FIT_MAX_ZOOM,
            duration: FLIGHT_DURATION_MS,
          },
        ),
    })
  }
 
  #renderOverlay(): void {
    Eif (Option.isSome(this.#maybeHost)) {
      const { map } = this.#maybeHost.value
      const properties = this.#properties
      const frame = buildOverlayFrame({
        gridToggles: properties.gridToggles,
        isGridLabelsVisible: properties.isGridLabelsVisible,
        bounds: boundsOf(map),
        zoom: map.getZoom(),
        maybeCue: properties.cue,
        options: {
          mgrsPrecision: properties.mgrsPrecision,
          garsPrecision: properties.garsPrecision,
          tileZoom: properties.tileZoom,
        },
        isRangeRingsVisible: properties.isRangeRingsVisible,
        ringSpacing: properties.ringSpacing,
        ringUnit: properties.ringUnit,
        basemap: properties.basemap,
        profile: properties.profile,
      })
      setOverlay(map, frame)
    }
  }
 
  #emit(name: string, detail: unknown): void {
    this.dispatchEvent(new CustomEvent(name, { detail }))
  }
}
 
// NOTE: Snabbdom sets properties by assignment, so each one gets an accessor on the prototype.
mapPropertyNames.forEach(name => {
  Object.defineProperty(CoordkitMapElement.prototype, name, {
    configurable: true,
    get(this: CoordkitMapElement) {
      return this.getMapProperty(name)
    },
    set(this: CoordkitMapElement, value: MapProperties[typeof name]) {
      this.setMapProperty(name, value)
    },
  })
})
 
export const defineMapElement = (): void => {
  if (!customElements.get(MAP_TAG)) {
    customElements.define(MAP_TAG, CoordkitMapElement)
  }
}