All files / geography/maps/src themedMap.ts

100% Statements 13/13
100% Branches 4/4
100% Functions 4/4
100% Lines 13/13

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                        9x         9x     10x 5x         5x 5x     9x 9x 9x     9x 9x 9x     9x    
import mapboxgl from "mapbox-gl";
import type { MapOptions } from "mapbox-gl";
 
export interface MapTheme {
  lightPreset(): "day" | "night";
  subscribe(listener: () => void): () => void;
}
 
export function createThemedMap(
  options: Omit<MapOptions, "style" | "config">,
  theme: MapTheme
) {
  const map = new mapboxgl.Map({
    ...options,
    style: "mapbox://styles/mapbox/standard",
    config: { basemap: { lightPreset: theme.lightPreset() } }
  });
  let styleReady = false;
 
  function updateTheme() {
    if (styleReady && map.getConfigProperty("basemap", "lightPreset") !== theme.lightPreset()) {
      map.setConfigProperty("basemap", "lightPreset", theme.lightPreset());
    }
  }
 
  function onStyleLoad() {
    styleReady = true;
    updateTheme();
  }
 
  const unsubscribe = theme.subscribe(updateTheme);
  map.on("style.load", onStyleLoad);
  map.on("remove", cleanup);
 
  function cleanup() {
    unsubscribe();
    map.off("style.load", onStyleLoad);
    map.off("remove", cleanup);
  }
 
  return map;
}