Skip to content

A spy satellite simulator in your browser, except the data is real. Live open source spatial intelligence on a photorealistic 3D globe.

7.2 KB
Raw Blame
import { mapillaryImageUrl } from './policy.js';

/**
 * @typedef {object} StreetPose
 * @property {string} imageId
 * @property {{lon: number, lat: number}} position
 * @property {number|null} bearing
 * @property {number|null} altitude
 * @property {boolean} isPano
 * @property {number|null} capturedAt   Epoch milliseconds.
 * @property {string|null} creator
 * @property {string|null} sequenceId
 * @property {string} externalUrl      Deep link to the image on mapillary.com.
 */

/**
 * The source's Graph endpoint as an absolute URL ending in `/`, as MapillaryJS
 * resolves its lookup paths against it; '' when the source has none.
 */
export function graphEndpointUrl(source) {
  if (!source?.graphEndpoint) return '';
  const url = new URL(
    source.graphEndpoint,
    globalThis.location?.href || 'http://localhost/',
  );
  url.pathname = url.pathname.replace(/\/*$/, '/');
  return url.href;
}

/**
 * The panel's photo viewer: loads MapillaryJS on the first `mount` and emits
 * a pose on every image, view or position change.
 */
export function createMapillaryViewer({ source, render } = {}) {
  let viewer = null;
  let Library = null;
  let container = null;
  /** The viewer being built for a host: a second mount joins it, not a twin. */
  let building = null;
  let pendingOpen = null;
  /** Bumped by `unmount`, so a construction it overtook builds nothing. */
  let generation = 0;
  let renderMode = 'letterbox';
  /** Metadata of the image on screen; pov/position events reuse it. */
  let current = null;
  /** The pose listener (the viewer host); one at a time. */
  let poseListener = null;

  function requestRender() {
    render?.governorRequestRender?.('mapillary-viewer');
  }

  function libraryRenderMode(mode) {
    const { RenderMode } = Library || {};
    if (!RenderMode) return undefined;
    return mode === 'fill' ? RenderMode.Fill : RenderMode.Letterbox;
  }

  async function ensureLibrary() {
    if (Library) return Library;
    // Lazy CSS: Vite applies it before the import resolves, so the viewer is
    // styled from its first frame without ~90 KB of render-blocking CSS.
    const [library] = await Promise.all([
      import('mapillary-js'),
      import('mapillary-js/dist/mapillary.css'),
    ]);
    Library = library;
    return Library;
  }

  function emit(pose) {
    try {
      poseListener?.(pose);
    } catch {
      /* listener errors are the core's to log */
    }
  }

  /** Read MapillaryJS image metadata into the pose shape. */
  function describe(image) {
    return {
      imageId: String(image.id),
      isPano: image.cameraType === 'spherical',
      capturedAt: image.capturedAt ?? null,
      sequenceId: image.sequenceId ?? null,
      altitude: Number.isFinite(image.computedAltitude)
        ? image.computedAltitude
        : Number.isFinite(image.originalAltitude)
          ? image.originalAltitude
          : null,
      creator: image.creatorUsername || null,
    };
  }

  async function publishPose(image) {
    if (!viewer) return;
    try {
      const [lngLat, pov] = await Promise.all([
        viewer.getPosition(),
        viewer.getPointOfView(),
      ]);
      // Closed (or never opened) while the pose was in flight: a late
      // `image` event must not bring the photo back.
      if (pendingOpen === null) return;
      if (image) current = describe(image);
      if (!current || !viewer) return;
      emit({
        ...current,
        position: { lon: lngLat.lng, lat: lngLat.lat },
        bearing: Number.isFinite(pov?.bearing) ? pov.bearing : null,
        externalUrl: mapillaryImageUrl(current.imageId),
      });
      requestRender();
    } catch {
      /* viewer torn down mid-flight */
    }
  }

  function ensureViewer(host) {
    if (viewer && container === host) return Promise.resolve(viewer);
    if (building?.host === host) return building.promise;
    const promise = buildViewer(host).finally(() => {
      if (building?.promise === promise) building = null;
    });
    building = { host, promise };
    return promise;
  }

  async function buildViewer(host) {
    const built = generation;
    destroyViewer();
    const { Viewer, GraphDataProvider } = await ensureLibrary();
    // Unmounted (layer off) while the library loaded: a viewer built now
    // would hold a WebGL context nobody releases.
    if (built !== generation) throw new Error('Mapillary viewer was unmounted');
    const endpoint = graphEndpointUrl(source);
    viewer = new Viewer({
      // A source with its own Graph endpoint (which adds the token itself)
      // answers the viewer's lookups, sent without a token; otherwise
      // MapillaryJS calls the Graph API with the client token.
      ...(endpoint
        ? { dataProvider: new GraphDataProvider({ endpoint }) }
        : { accessToken: source.token }),
      container: host,
      component: {
        cover: false,
        bearing: true,
        zoom: true,
        attribution: true,
      },
      // The panel's ResizeObserver resizes the viewer, and skips it while it
      // is hidden (0x0); MapillaryJS's own window tracking would resize a
      // hidden viewer and ask for a tile at z=NaN.
      trackResize: false,
      renderMode: libraryRenderMode(renderMode),
    });
    container = host;
    viewer.on('image', (event) => publishPose(event.image));
    viewer.on('pov', () => publishPose(null));
    viewer.on('position', () => publishPose(null));
    return viewer;
  }

  function destroyViewer() {
    if (viewer) {
      try {
        viewer.remove();
      } catch {
        /* already removed */
      }
    }
    viewer = null;
    container = null;
    current = null;
  }

  return {
    async mount(host) {
      if (!host) throw new Error('Street Level viewer has no host element');
      await ensureViewer(host);
    },

    /** Resolves once the image is on screen and its first pose was emitted. */
    async open(imageId) {
      const id = String(imageId);
      if (!container) throw new Error('Mapillary viewer is not mounted');
      pendingOpen = id;
      const instance = await ensureViewer(container);
      if (pendingOpen !== id) return;
      const image = await instance.moveTo(id);
      if (pendingOpen !== id) return;
      await publishPose(image);
    },

    close() {
      pendingOpen = null;
      current = null;
      // A playing sequence would keep stepping through (and downloading)
      // images in the hidden viewer.
      try {
        viewer?.getComponent('sequence')?.stop();
      } catch {
        /* sequence component not available */
      }
    },

    unmount() {
      pendingOpen = null;
      // A build still waiting for the library gives up when it arrives.
      generation++;
      building = null;
      destroyViewer();
    },

    resize() {
      try {
        viewer?.resize();
      } catch {
        /* no-op */
      }
    },

    /** Show the whole image ('letterbox') or crop it to the frame ('fill'). */
    setRenderMode(mode) {
      renderMode = mode === 'fill' ? 'fill' : 'letterbox';
      try {
        const value = libraryRenderMode(renderMode);
        if (viewer && value !== undefined) viewer.setRenderMode(value);
      } catch {
        /* viewer not ready */
      }
    },

    onPose(listener) {
      poseListener = listener;
      return () => {
        if (poseListener === listener) poseListener = null;
      };
    },
  };
}