Skip to content

The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.

JavaScript
21.3 KB
Raw Blame
/**
 * The map engine's boundary.
 *
 * Tools talk to the map through this façade and never to the engine, so
 * replacing the engine is a rewrite of `engine.js` rather than of the tools
 * above it. Two rules keep that promise:
 *
 * - **Nothing engine-shaped crosses the boundary.** A screen point is
 *   `{ x, y }`, a position is `{ lat, lon }`, an extent is
 *   `{ north, south, east, west }`. No LngLat, no Point, no layer.
 * - **Events are named for what happened to the view**, not for what the
 *   engine calls it. `view-settled` is "the camera came to rest", whichever
 *   engine event that turns out to be.
 *
 * Three translations are the whole reason this file exists, and each one is a
 * number that would otherwise be wrong in a request or on disk:
 *
 * - **Zoom.** MapLibre counts zoom on 512 px tiles and counts it continuously.
 *   The app speaks the XYZ view zoom — one level deeper — in whole levels:
 *   `zoom: int` on every route, one level of pixels per raster basemap, one
 *   number recorded on a capture.
 * - **Bearing.** The app's bearing turns the map *clockwise*. MapLibre's is the
 *   compass direction that is up, which is the same turn counted the other way.
 * - **Longitude.** An engine keeps counting past ±180° when the analyst pans
 *   across the date line, every route bounds it to ±180, and an unwrapped
 *   centre answered 422 over the Pacific.
 *
 * Nothing in this file imports the engine, so the translations are exercised
 * against a stub map instead of a browser (`facade.test.js`).
 */
import { wrapLon } from '../coords.js';
import { haversine } from '../measure.js';

/** What happened to the view → the engine events that say so. */
const EVENTS = {
  // MapLibre fires move events for any camera change, a zoom included, so one
  // name covers what used to take two.
  'view-settled': ['moveend'],
  // Every frame of a movement, for what is drawn over the map in the page
  // rather than in the engine and has to be placed again as the ground moves.
  'view-move': ['move'],
  rotate: ['rotate'],
  // a tilt, which only the 3D view takes
  pitch: ['pitch'],
  click: ['click'],
  // the pointer over the map, for a line that follows it while it is drawn
  'pointer-move': ['mousemove'],
  // The engine only fires it for a right-click that did not drag, and stops
  // the browser's own menu once anything listens for it.
  contextmenu: ['contextmenu'],
};

/**
 * How much deeper the app's zoom counts than the engine's.
 *
 * MapLibre's zoom is defined on 512 px tiles, XYZ zoom on 256 px ones, so the
 * same view is one number apart. Everything the app says about zoom — provider
 * ceilings, tile URLs, capture provenance, a saved place's view — is XYZ.
 */
const ZOOM_OFFSET = 1;

/**
 * The engine's zoom as the app says it: whole levels.
 *
 * The engine settles on a level (`engine.js`) so this rounds nothing the
 * analyst can see; what it protects against is a read taken mid-gesture
 * reaching a route as 16.37.
 */
export function viewZoom(engineZoom) {
  return Math.round(engineZoom + ZOOM_OFFSET);
}

/** …and back, for anything handed to the camera. */
export function engineZoom(zoom) {
  return zoom - ZOOM_OFFSET;
}

/**
 * The same reading unrounded, for whatever has to follow the camera itself
 * rather than say a number about it — the Google widget basemap under the map,
 * which would visibly jump a whole level otherwise.
 */
export function exactViewZoom(zoom) {
  return zoom + ZOOM_OFFSET;
}

/** 0–360, whatever the caller typed, dragged or read off a saved row. */
export function normalizeBearing(deg) {
  const value = Number(deg);
  if (!Number.isFinite(value)) return 0;
  return ((value % 360) + 360) % 360;
}

/**
 * The compass direction up the screen of a map turned by the app's `bearing`:
 * the way an eye stood on it and looking up the map faces. The app turns the
 * map clockwise, so it is the same turn counted the other way, and the bearing
 * that puts a heading up is found the same way.
 */
export function headingUp(bearing) {
  return normalizeBearing(-Number(bearing));
}

/**
 * The engine events one neutral name stands for.
 *
 * Throws on anything else: a typo that silently stopped delivering would read
 * as a map that quietly went dead.
 */
export function engineEvents(name) {
  const events = EVENTS[name];
  if (!events) throw new Error(`unknown map event: ${name}`);
  return events;
}

/** The smallest box holding every point, or null if there is nothing to hold. */
export function pointsExtent(points) {
  const usable = (points ?? []).filter(
    (point) => Number.isFinite(point?.lat) && Number.isFinite(point?.lon)
  );
  if (!usable.length) return null;
  const lats = usable.map((point) => point.lat);
  const lons = usable.map((point) => point.lon);
  return {
    north: Math.max(...lats),
    south: Math.min(...lats),
    east: Math.max(...lons),
    west: Math.min(...lons),
  };
}

/**
 * Frame padding as the engine wants it, from the `[x, y]` pair callers write.
 *
 * A number is the same on all four sides; a pair is horizontal then vertical,
 * which is how a caller thinks about leaving room beside a box.
 */
export function framePadding(padding) {
  if (padding == null) return 0;
  if (typeof padding === 'number') return padding;
  const [x, y] = padding;
  return { left: x, right: x, top: y, bottom: y };
}

/**
 * The paint properties that make each kind of layer see-through, for a picture
 * taken without it (`snapshot`'s `keep`). A layer with none of its own stays.
 */
const SEE_THROUGH = {
  raster: ['raster-opacity'],
  fill: ['fill-opacity'],
  line: ['line-opacity'],
  circle: ['circle-opacity', 'circle-stroke-opacity'],
  symbol: ['icon-opacity', 'text-opacity'],
  heatmap: ['heatmap-opacity'],
  'fill-extrusion': ['fill-extrusion-opacity'],
};

/** A copy of what the map's canvas holds this instant, which only the frame just drawn has. */
function copyOf(source, into = null) {
  const copy = into ?? document.createElement('canvas');
  const fresh = copy.width !== source.width || copy.height !== source.height;
  if (fresh) {
    copy.width = source.width;
    copy.height = source.height;
  }
  const context = copy.getContext('2d');
  if (!context) throw new Error('this browser cannot capture the map');
  if (!fresh) context.clearRect(0, 0, copy.width, copy.height);
  context.drawImage(source, 0, 0);
  return copy;
}

/** The operators that read a feature, which make an expression data-driven. */
const FEATURE_READS = new Set(['get', 'has', 'properties', 'feature-state', 'geometry-type', 'id']);

/** Whether a paint value is worked out per feature, and so built into the tiles. */
function readsFeatures(value) {
  return Array.isArray(value) && (FEATURE_READS.has(value[0]) || value.some(readsFeatures));
}

/**
 * The map drawn without the layers `keep` turns down, copied, then put back.
 *
 * Drawn and read in one task, the frame without them never reaches the screen.
 * A layer is made see-through with no transition, both ways, so nothing fades
 * back in once the copy is taken, and no tile is cut again. One whose opacity is
 * read off each feature has it built into its tiles, where only hiding it takes
 * effect at once.
 */
function drawnWithout(map, keep) {
  const faded = []; // [id, property, value, transition]
  const hidden = []; // [id, visibility]
  for (const id of map.getLayersOrder()) {
    if (keep(id) || map.getLayoutProperty(id, 'visibility') === 'none') continue;
    const properties = SEE_THROUGH[map.getLayer(id)?.type] ?? [];
    const values = properties.map((property) => map.getPaintProperty(id, property));
    if (values.some(readsFeatures)) {
      hidden.push([id, map.getLayoutProperty(id, 'visibility')]);
      map.setLayoutProperty(id, 'visibility', 'none');
      continue;
    }
    properties.forEach((property, index) => {
      faded.push([id, property, values[index], map.getPaintProperty(id, `${property}-transition`)]);
      map.setPaintProperty(id, `${property}-transition`, { duration: 0, delay: 0 });
      map.setPaintProperty(id, property, 0);
    });
  }
  try {
    map.redraw();
    return copyOf(map.getCanvas());
  } finally {
    if (faded.length || hidden.length) {
      for (const [id, property, value] of faded) map.setPaintProperty(id, property, value);
      for (const [id, visibility] of hidden) map.setLayoutProperty(id, 'visibility', visibility ?? 'visible');
      map.redraw();
      for (const [id, property, , transition] of faded) map.setPaintProperty(id, `${property}-transition`, transition);
    }
  }
}

/**
 * Wrap a built map in the façade.
 *
 * @param {object} map the engine's own map object
 * @param {HTMLElement} [container] the element the map was built in
 * @param {string} [mapId] this map's name to the billed-tile guard (`quotaGuard.js`)
 */
export function mapFacade(map, container, mapId = '') {
  // Set while another map's frame is being copied onto this one (`follow`).
  let following = false;
  const settledHandlers = new Set();

  /**
   * Layers that answer their own click.
   *
   * A click on a shape is not also a click on the map underneath: a cell of a
   * search grid cycles its own status, and the map's click handler — which
   * drops a polygon vertex or plants the sky anchor — must not fire behind it.
   * The engine delivers both, so the map's own relay asks first whether a
   * claiming layer was hit. Which layers claim is asked here rather than left
   * to listener order, so the answer does not depend on who registered first.
   */
  const claimed = new Set();

  function shapeUnder(point) {
    for (const claim of claimed) {
      const layers = claim.layers.filter((id) => map.getLayer(id));
      if (!layers.length) continue;
      if (map.queryRenderedFeatures(point, { layers, filter: claim.filter }).length) return true;
    }
    return false;
  }

  /** Where the camera is, in the terms the rest of the app uses. */
  function camera() {
    const centre = map.getCenter();
    return {
      lat: centre.lat,
      lon: wrapLon(centre.lng),
      zoom: viewZoom(map.getZoom()),
      bearing: normalizeBearing(-map.getBearing()),
      // 0 on a flat map: only the 3D view tilts (`lib/globe/globe.js`)
      pitch: Math.round(map.getPitch()),
    };
  }

  function fitBounds({ north, south, east, west }, options = {}) {
    const ceiling = options.maxZoom == null ? map.getMaxZoom() : engineZoom(options.maxZoom);
    const fitted = map.cameraForBounds(
      [
        [west, south],
        [east, north],
      ],
      { padding: framePadding(options.padding), maxZoom: ceiling }
    );
    if (!fitted) return;
    // The shallower whole level, not the nearest: the box has to still fit
    // inside the frame, and a raster basemap only has whole levels of pixels.
    // A box with no extent at all (one point) fits at any zoom, so clamp — the
    // engine's own ceiling is the answer there, never Infinity.
    const zoom = Math.min(ceiling, Math.floor(fitted.zoom));
    map.easeTo(
      {
        center: fitted.center,
        zoom: Math.max(map.getMinZoom(), zoom),
        duration: options.animate ? 420 : 0,
      });
  }

  /** Frame every point handed over. False when none of them was usable. */
  function fitPoints(points, options) {
    const extent = pointsExtent(points);
    if (!extent) return false;
    fitBounds(extent, options);
    return true;
  }

  return {
    camera,
    getZoom: () => viewZoom(map.getZoom()),

    /** The app putting the camera somewhere. */
    setView: ({ lat, lon }, zoom) => map.jumpTo({ center: [lon, lat], zoom: engineZoom(zoom) }),
    /**
     * A whole camera in one jump, turn included: one move and one settle, where
     * `setView` then `setBearing` would settle once on the old heading first.
     * A camera that names no tilt keeps the one the map has; a flat map holds
     * any tilt it is handed at zero. The centre's height a 3D camera carries is
     * the globe's to read (`lib/globe/globe.js`); a flat map has no use for it.
     */
    setCamera: ({ lat, lon, zoom, bearing = 0, pitch }) =>
      map.jumpTo({
        center: [lon, lat],
        zoom: engineZoom(zoom),
        bearing: -normalizeBearing(bearing),
        ...(Number.isFinite(pitch) ? { pitch } : {}),
      }),
    /** The centre's height: a flat map has none, the 3D view answers it (`lib/globe/globe.js`). */
    centreElevation: () => null,
    setZoom: (zoom) => map.setZoom(engineZoom(zoom)),
    /** The app zoom unrounded, for a gesture that eases the zoom (`gestures.js`). */
    exactZoom: () => exactViewZoom(map.getZoom()),
    setBearing: (deg) => map.setBearing(-normalizeBearing(deg)),
    /** Tilt from straight down, in degrees; a flat map holds it at zero. */
    setPitch: (deg) => map.setPitch(Math.max(0, Number(deg) || 0)),
    /** How far this map may lean, in degrees. */
    maxPitch: () => map.getMaxPitch(),
    /** How deep this map goes right now, in app zoom: its basemap's ceiling. */
    maxZoom: () => viewZoom(map.getMaxZoom()),
    /** Never animated: a rotation pans the map once per pointer move. */
    panBy: (dx, dy) => map.panBy([dx, dy], { duration: 0 }),
    /** Whether a drag pans the map: held while the hand paints on it instead (Find's brush). */
    setPanning: (on) => (on ? map.dragPan.enable() : map.dragPan.disable()),
    fitBounds,
    fitPoints,

    containerPointToLatLng({ x, y }) {
      const position = map.unproject([x, y]);
      return { lat: position.lat, lon: wrapLon(position.lng) };
    },

    latLngToContainerPoint({ lat, lon }) {
      const point = map.project([lon, lat]);
      return { x: point.x, y: point.y };
    },

    /**
     * How far the view reaches on the ground, along each of its own sides.
     * What sizes anything drawn in metres — the sky arc is a circle around its
     * anchor, so a radius taken off the diagonal runs off a wide window.
     */
    viewSpanMeters() {
      const bounds = map.getBounds();
      const north = bounds.getNorth();
      const west = bounds.getWest();
      return {
        across: haversine({ lat: north, lon: west }, { lat: north, lon: bounds.getEast() }),
        down: haversine({ lat: north, lon: west }, { lat: bounds.getSouth(), lon: west }),
      };
    },

    /**
     * The ground rectangle the camera is looking at. A turned map reports the
     * box that encloses its corners, which is what a rectangle drawn from the
     * view has to be anyway.
     */
    viewBounds() {
      const bounds = map.getBounds();
      return {
        west: wrapLon(bounds.getWest()),
        south: bounds.getSouth(),
        east: wrapLon(bounds.getEast()),
        north: bounds.getNorth(),
      };
    },

    /** The container changed size; re-read it. */
    resize: () => map.resize(),

    /** Whether a press landed on the drawn map itself, not on a marker or a control over it. */
    onSurface: (target) => Boolean(target) && target === map.getCanvas?.(),

    /**
     * Give the map the keyboard, as a press on it would, and like a press without
     * the ring round the whole map: a browser that last saw a key (the Shift of
     * a turn) would draw one for a focus given from script (`engine.css`). It
     * comes back once the map has lost the keyboard and Tab brings it back.
     */
    focus: () => {
      const canvas = map.getCanvas?.();
      if (!canvas?.focus) return;
      if (canvas.dataset) {
        canvas.dataset.handFocus = '';
        canvas.addEventListener?.('blur', () => delete canvas.dataset.handFocus, { once: true });
      }
      canvas.focus({ preventScroll: true });
    },

    /**
     * The camera exactly as the engine holds it, fractional zoom included. Only
     * a second map copying this one reads it (`cameraLink.js`): anything that
     * states a view uses `camera()`, which speaks whole app zoom levels.
     */
    frame() {
      const centre = map.getCenter();
      return {
        lng: centre.lng,
        lat: centre.lat,
        zoom: map.getZoom(),
        bearing: map.getBearing(),
        pitch: map.getPitch(),
      };
    },

    /**
     * Take another map's frame. While the jump runs this map is only a copy:
     * it does not settle on a level of its own, and it does not report a
     * settled view for each intermediate frame. `settled` marks the leader's
     * last frame, and that one is reported once the jump is done.
     */
    follow(next, { settled = false } = {}) {
      following = true;
      try {
        map.jumpTo({
          center: [next.lng, next.lat],
          zoom: next.zoom,
          bearing: next.bearing,
          ...(Number.isFinite(next.pitch) ? { pitch: next.pitch } : {}),
        });
      } finally {
        following = false;
      }
      if (settled) for (const handler of settledHandlers) handler(camera());
    },

    /** True while `follow` is moving this map. */
    following: () => following,

    /** True while the view moves or has tiles in flight, so a capture now would be partial. */
    tilesLoading: () => map.isMoving() || !map.areTilesLoaded(),

    /**
     * Resolves once the map is at rest with every tile in. Read after the next
     * frame the engine draws, never at once: right after a change nothing new
     * has been asked for yet, so "every tile is in" would hold for that moment.
     */
    idle: () =>
      new Promise((resolve) => {
        const check = () => {
          if (map.isMoving() || !map.areTilesLoaded()) return;
          map.off('render', check);
          resolve();
        };
        map.on('render', check);
        map.triggerRepaint();
      }),

    /**
     * The drawn pixels, once every visible tile is in.
     *
     * WebGL clears its buffer after each frame reaches the screen, so a canvas
     * read at any other moment is transparent. The copy is taken inside the
     * engine's own `render` event, which runs in the same frame as the draw.
     * `complete` is false when the wait gave up with tiles still loading.
     *
     * `keep`, a test on a layer's id, takes the picture with only the layers it
     * passes: Difference reads the ground, not the borders or the case's marks
     * laid over one side.
     *
     * `into`, a canvas an earlier snapshot returned, is drawn over rather than a
     * new one made: a caller taking one at every frame of a move keeps one canvas.
     */
    async snapshot({ timeout = 12000, keep = null, into = null } = {}) {
      const complete = await new Promise((resolve) => {
        if (!map.isMoving() && map.areTilesLoaded()) {
          resolve(true);
          return;
        }
        const timer = setTimeout(() => {
          map.off('idle', idle);
          resolve(false);
        }, timeout);
        const idle = () => {
          clearTimeout(timer);
          resolve(true);
        };
        map.once('idle', idle);
      });
      if (keep) return { canvas: drawnWithout(map, keep), complete };
      const canvas = await new Promise((resolve, reject) => {
        map.once('render', () => {
          try {
            resolve(copyOf(map.getCanvas(), into));
          } catch (error) {
            reject(error);
          }
        });
        map.triggerRepaint();
      });
      return { canvas, complete };
    },

    /**
     * Listen for something happening to the view. Returns the unsubscribe, so
     * a caller cannot hold one half of the pair.
     */
    on(name, handler) {
      const events = engineEvents(name);
      // A pointer event hands over the point; a right-click also where it was
      // pressed, since a menu opens there. A shape that answers its own click
      // answers its own right-click too: a flagged grid cell is not also a menu.
      const relay =
        name === 'pointer-move'
          ? (event) => handler({ lat: event.lngLat.lat, lon: wrapLon(event.lngLat.lng) })
          : name === 'click' || name === 'contextmenu'
          ? (event) => {
              if (shapeUnder(event.point)) return;
              const at = { lat: event.lngLat.lat, lon: wrapLon(event.lngLat.lng) };
              handler(name === 'click' ? at : { ...at, x: event.point.x, y: event.point.y });
            }
          : name === 'view-settled'
            ? () => {
                if (!following) handler(camera());
              }
            : () => handler(camera());
      if (name === 'view-settled') settledHandlers.add(handler);
      for (const event of events) map.on(event, relay);
      return () => {
        settledHandlers.delete(handler);
        for (const event of events) map.off(event, relay);
      };
    },

    /**
     * These layers answer their own clicks; keep the map's relay off them.
     * The filter narrows that to the features that really do — a shape drawn
     * under a mark to say how loosely it is placed answers nothing, and must
     * not swallow the click meant for the map. Returns the release, for a
     * surface that is torn down.
     */
    claimClicks(layers, filter) {
      const claim = { layers: [...layers], filter };
      claimed.add(claim);
      return () => claimed.delete(claim);
    },

    destroy() {
      if (container) delete container.dataset.mapReady;
      map.remove();
    },

    /**
     * The element the map fills. Every engine has one, and the gestures measure
     * and read it, so it crosses the boundary as itself.
     */
    container,

    /** This map's name to the billed-tile guard, which reads its view per tile. */
    mapId,

    /**
     * The engine's own map.
     *
     * The modules in `lib/map` are the engine, plainly: layers, sources and
     * markers are its vocabulary and there is no neutral way to say them.
     * Nothing above the façade may reach for this.
     */
    impl: map,
  };
}