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
44.9 KB
Raw Blame
<script>
  /**
   * Detect: watch an area of Copernicus Sentinel-2 or Sentinel-1 over time.
   *
   * It stands on its own rather than inside Compare, because it is a different
   * job: Compare reads two pictures side by side, while this one sweeps ground
   * and comes back to it. One map is enough for that — the evidence for a
   * candidate is the before/after picture the panel shows, not a second
   * surface — so the map here is the ground you draw on and the pass you are
   * about to read, and the column beside it holds the work.
   *
   * Nothing here fetches imagery on its own beyond the basemap the map shows.
   * Starting a run, and looking a pass up, are the acts that reach Copernicus.
   *
   * The ruler over the map is for the thing on it: how long a hull is, how far
   * a wake runs. Its measures are a scratch aid, gone with the session.
   */
  import { onMount, tick, untrack } from 'svelte';
  import { api } from '../lib/api.js';
  import { caseState, dismissToast, fmtCoords, prefs, prefsReady, reloadCase, toast, uiState } from '../lib/state.svelte.js';
  import { assignFolder } from '../lib/filing.js';
  import { createFireKey } from '../lib/map/fireKey.svelte.js';
  import { createLayerSet } from '../lib/map/layerSet.svelte.js';
  import { addedLayers } from '../lib/map/addedLayersState.svelte.js';
  import { createMapLayerMemory } from '../lib/map/layerMemory.js';
  import { savedRow } from '../lib/geoTree.js';
  import { copyText } from '../lib/clipboard.js';
  import { marksToZones, sourceLabel, viewZone, zoneMarks, zoneRing } from '../lib/map/analyzers.js';
  import { blinkable } from '../lib/map/detectReview.js';
  import { ADVISED_MAXCC } from '../lib/map/detectWhen.js';
  import { DEFAULT_MAXCC } from '../lib/sentinel.js';
  import { DEFAULT_BLINK_INTERVAL } from '../lib/map/compare.js';
  import { createImageryState } from './satellite/state/imagery.svelte.js';
  import { createSentinelState } from './satellite/state/sentinel.svelte.js';
  import { createRadarState } from './satellite/state/radar.svelte.js';
  import { RADAR_ID, passLabel } from '../lib/radar.js';
  import { copernicusNeed } from '../lib/copernicusSetup.js';
  import { actionsFor, otherMapTools } from '../lib/map/contextMenu.js';
  import { lookFrom, openMapAt } from '../lib/navigate.js';
  import { headingUp } from '../lib/map/facade.js';
  import { followFullscreen, toggleFullscreen } from '../lib/fullscreen.js';
  import { shareView } from '../lib/map/sharedView.js';
  import { COMPARE_SOURCES, comparePair } from '../lib/map/comparePair.js';
  import CopernicusNeeded from '../components/CopernicusNeeded.svelte';
  import MapSurface from './satellite/MapSurface.svelte';
  import MapContextMenu from './satellite/MapContextMenu.svelte';
  import PlaceSearch from './satellite/PlaceSearch.svelte';
  import ImageryChip from './satellite/ImageryChip.svelte';
  import LayerMenu from '../components/LayerMenu.svelte';
  import AddedLayersOverlay from './satellite/AddedLayersOverlay.svelte';
  import LayerGeometry from './satellite/LayerGeometry.svelte';
  import PersonalLayerPanel from './satellite/PersonalLayerPanel.svelte';
  import { personalLayers, personalPlaceDeletion } from '../lib/map/personalLayers.svelte.js';
  import SavedOverlay from './satellite/SavedOverlay.svelte';
  import { createSavedState } from './satellite/state/saved.svelte.js';
  import Compass from '../components/Compass.svelte';
  import TurnGuide from '../components/TurnGuide.svelte';
  import Icon from '../components/Icon.svelte';
  import { createWaybackState } from './satellite/state/wayback.svelte.js';
  import { turnFromKey, turnFromPress } from '../lib/map/gestures.js';
  import AnnotationCanvas from './compare/AnnotationCanvas.svelte';
  import AnalysisOverlay from './detect/AnalysisOverlay.svelte';
  import DetectAreas from './detect/DetectAreas.svelte';
  import DetectPanel from './detect/DetectPanel.svelte';
  import CheckBench from './detect/CheckBench.svelte';
  import CheckMarks from './detect/CheckMarks.svelte';
  import RuleLayers from './detect/RuleLayers.svelte';
  import RuleProbe from './detect/RuleProbe.svelte';
  import SecondPass from './detect/SecondPass.svelte';
  import './mapdock.css';

  const SENTINEL = 'sentinel2';
  const imagery = createImageryState({ api });

  let home = $state(null);
  let view = $state({ lat: 0, lon: 0, zoom: 2 });
  let bearing = $state(0);
  let engine = $state(null);
  let element = $state(null);
  let ready = $state(false);
  let refused = $state(false);
  let dated = $state(null);
  let providerId = $state('esri-world-imagery');
  let chosenBasemap = $state('esri-world-imagery');
  let collapsed = $state(false);
  let dockWidth = $state(380);
  let savedDockWidth = $state(380);
  let toolEl = $state(null);
  let fullscreen = $state(false);
  // on at every visit, like the watched areas: what the case already found is
  // the first thing to see over the map
  let savedVisible = $state(true);
  let readingPass = $state(false);
  let layersOpen = $state(false);
  let prefsLoaded = $state(false);
  const wayback = createWaybackState({ api, place: () => view });
  const s1 = createRadarState({ api, place: () => view, onBilled: () => imagery.refreshUsage() });
  const shown = $derived(imagery.displayed(providerId, view.zoom, { ...s2.variant, release: wayback.release, pass: s1.shownPass }));
  /** The metered archives. Any of them can be put on the map from its chip, with
   *  its Copernicus layer and day, but none is remembered as the basemap: Detect
   *  opens on free imagery every time. */
  const PASSES = [SENTINEL, RADAR_ID];
  /** Whether the fire layer can be used, read from our own backend. */
  const fireKey = createFireKey({ api });
  /** What a case that never said otherwise opens Detect's map on. */
  const DETECT_LAYERS = ['boundaries'];
  /**
   * The map's layers, every one the catalogue offers (lib/map/layerSet). The
   * fires and the night lights start on the day of the picture on screen, which
   * is a pass's own day when one is read.
   */
  const mapLayers = createLayerSet({
    fireKey,
    initial: DETECT_LAYERS,
    follow: "Picture's day",
    pictureDay: () => dated?.date ?? '',
    imagery: () => imagery.find(providerId)?.imagery ?? true,
    onsettings: () => {
      uiState.settingsTab = 'imagery';
      uiState.tool = 'settings';
    },
  });
  // Each case opens on the layers it was left on (lib/map/layerMemory), kept
  // under the case the switches were set for.
  const switchMemory = createMapLayerMemory('detect', DETECT_LAYERS);
  let layersFor;
  $effect(() => {
    const id = caseState.current?.id ?? null;
    if (id === layersFor) return;
    layersFor = id;
    mapLayers.restore(switchMemory.recall(id));
  });
  $effect(() => switchMemory.keep(layersFor, mapLayers.ids));
  // The case's saved places, captures and located files, as the other maps draw
  // them. Off at first: Detect opens on its own findings.
  const savedWork = createSavedState({ api, notify: toast, assignFolder, reloadCase });
  $effect(() => savedWork.load(caseState.current?.id ?? null));
  $effect(() => savedWork.loadMode(caseState.current?.id, caseState.rev));
  // the position picked under the layer's row, Media first as on the Map
  const savedItems = $derived(savedWork.shown);
  const myLayers = addedLayers.scope('detect');
  // a FIRMS key pasted into Settings, or tested back to life there
  $effect(() => {
    if (uiState.tool === 'detect') void fireKey.load();
  });
  $effect(() => () => fireKey.destroy());
  // a snapshot filed from these findings ("Add to the SAT layers") reaches this
  // menu with the reload that follows it
  $effect(() => addedLayers.load(caseState.current?.id ?? null, caseState.rev));
  const layerRows = $derived([
    ...mapLayers.rows({
      saved: savedRow(savedWork, mapLayers.has('saved')),
    }),
    // Detect's own, under the case's: what its runs found, and where it watches
    { id: 'detections', group: 'case', label: 'Saved detections', title: 'What saved runs found, drawn over the map',
      on: savedVisible, toggle: () => (savedVisible = !savedVisible) },
    { id: 'areas', group: 'case', label: 'Watched areas', title: 'The areas your routines watch',
      on: showZones, toggle: () => (showZones = !showZones) },
  ]);
  let searchText = $state('');
  let searching = $state(false);
  let panel = $state(null);
  let opening = $state(null);

  const s2 = createSentinelState({
    place: () => ({ lat: view.lat, lon: view.lon }),
    onBilled: () => imagery.refreshUsage(),
    notify: toast,
    api,
  });

  // What the column owns and the map draws.
  let zones = $state([]);
  let drawing = $state('select');
  let selectedZone = $state(null);
  let layers = $state([]);
  let focusedRunId = $state(null);
  // Reviewing a run temporarily isolates it. The saved eye states stay intact
  // and return as soon as the review closes.
  const visibleRunLayers = $derived(focusedRunId
    ? layers.filter((layer) => layer.id === focusedRunId).map((layer) => ({ ...layer, visible: true }))
    : layers);
  let showZones = $state(true);
  let selectedResult = $state(null);
  let resultMarkers = $state(true);
  let resultOutlines = $state(true);
  let areaGroups = $state([]);
  let highlight = $state([]);
  let manual = $state(null);
  let manualTool = $state('select');
  // An analyzer of your own being built (AnalyzerBuilder): the bench it keeps
  // (lib/map/bench.svelte.js), which says what the map shows. The map is its
  // bench while it is open, so saved work and watched areas step aside.
  let builder = $state(null);
  // The builder offers the configuration's Copernicus layers by name; the list
  // is the app's own catalogue until the instance has been asked, so reading
  // it spends nothing.
  let layersAsked = false;
  $effect(() => {
    if (!builder || layersAsked || s2.layers.length) return;
    layersAsked = true;
    untrack(() => s2.loadLayers(false, true));
  });
  // A basemap with no date sends no mosaicking window, and Sentinel Hub then
  // blends the whole archive pixel by pixel. Detect pins a date whenever it
  // shows a pass; this covers the map before a run, so the ground an analyst
  // draws a zone on is one acquisition like everything that follows it.
  $effect(() => {
    if (!engine || shown.provider?.id !== SENTINEL) return;
    view.lat;
    view.lon;
    s2.maxcc;
    clearTimeout(s2LatestTimer);
    s2LatestTimer = setTimeout(() => s2.resolveLatest().catch(() => {}), s2.resolved ? 900 : 0);
    return () => clearTimeout(s2LatestTimer);
  });
  $effect(() => {
    if (!engine || shown.provider?.id !== RADAR_ID) return;
    view.lat;
    view.lon;
    clearTimeout(s1LatestTimer);
    s1LatestTimer = setTimeout(() => s1.resolveLatest().catch(() => {}), s1.resolved ? 900 : 0);
    return () => clearTimeout(s1LatestTimer);
  });
  let s2LatestTimer;
  let s1LatestTimer;

  // What the last test found, outlined and pinned on the ground it judged.
  const previewLayer = $derived(builder?.detail ? [{
    id: 'builder-preview', visible: true,
    input: { recipe: { colour: builder.recipe.colour, style: builder.recipe.style } },
    results: builder.detail.candidates.map((row) => ({ ...row, review: 'new', phenomenon: builder.recipe.phenomenon })),
  }] : []);
  const paintedRules = $derived(builder ? builder.recipe.rules.map((_, i) => builder.painted(i)) : []);
  /** The pin the reading card was opened on, if it was opened on one. */
  const probedPin = $derived.by(() => {
    const at = builder?.probe?.pin;
    const mark = at === null || at === undefined ? null : builder.marks[at];
    return mark ? { number: at + 1, expect: mark.expect } : null;
  });
  // The passes the bench asks for go under the pins: the before pass (or the
  // only one) on this map, the after pass on a second one laid over it.
  $effect(() => {
    const intent = builder?.imagery;
    if (!intent) return;
    untrack(() => {
      if (intent.mode === 'basemap') leavePass();
      else showDate(intent.mode === 'swipe' ? intent.a : intent.b);
    });
  });
  const building = $derived(!!builder);
  $effect(() => {
    if (!building) return;
    return () => untrack(() => leavePass());
  });
  let secondEngine = $state(null);
  let secondElement = $state(null);
  $effect(() => { manualTool = manual?.kind === 'polygon' ? 'polygon' : 'select'; });

  // The ruler: measures drawn over the map, one armed at a time.
  let measures = $state([]);
  let measureTool = $state('select');
  let selectedMeasure = $state(null);
  let measureCanvas = $state(null);
  /** A measure started from the right-click menu, which only wants its far end. */
  let trailing = $state(false);
  const measuring = $derived(measureTool === 'measure');
  $effect(() => { if (!measuring) trailing = false; });
  // One tool holds the pointer at a time: drawing an area or a candidate puts
  // the ruler down, and taking the ruler up lets go of both.
  $effect(() => {
    if (drawing !== 'select' || manual) untrack(() => { measureTool = 'select'; });
  });

  // The review's eye and blink. The eye takes what the detection draws off the
  // imagery; the blink lays pass A over pass B in the same map and flips it at
  // Compare's normal speed, both pictures loaded, so nothing reloads mid-blink.
  let bare = $state(false);
  let blinking = $state(false);
  let reviewPair = $state(null);
  let showingA = $state(false);
  const blinkPair = $derived(blinking && blinkable(reviewPair) ? reviewPair : null);
  const alternate = $derived.by(() => {
    if (!blinkPair) return null;
    const { a } = blinkPair;
    const other = a.provider === RADAR_ID
      ? imagery.displayed(RADAR_ID, view.zoom, { pass: { date: a.date, time: a.time ?? '', orbit: a.orbit ?? '' } })
      : imagery.displayed(SENTINEL, view.zoom, { ...s2.variant, from: a.date, to: a.date });
    // Zoomed out of the archive, or past the month's budget, both sides fall
    // back to the same stand-in, and blinking that against itself says nothing.
    return other.provider && other.provider.id === shown.provider?.id ? other : null;
  });
  $effect(() => {
    const pair = blinkPair;
    if (!pair) return;
    untrack(() => showDate(pair.b));
    const timer = setInterval(() => (showingA = !showingA), DEFAULT_BLINK_INTERVAL);
    return () => {
      clearInterval(timer);
      showingA = false;
    };
  });

  const marks = $derived(zoneMarks(zones));
  const mapDate = $derived(s2.day);
  const passChip = $derived(providerId === RADAR_ID ? passLabel(s1.shownPass) : mapDate);
  let passCloud = $state(null);
  let passContext = $state(null);
  const cloudyPass = $derived(providerId !== RADAR_ID && passCloud > ADVISED_MAXCC);
  /**
   * What Detect needs before a run can fetch anything: a Copernicus key, which
   * Sentinel-2 lists once it is in Settings. Said in the middle of the map,
   * where the work would be. Not a lock: the panel still opens on the
   * detections already saved.
   */
  const needs = $derived(imagery.providers.length ? copernicusNeed(imagery.providers) : '');

  onMount(() => {
    let gone = false;
    const fitDock = () => (dockWidth = clampDock(savedDockWidth));
    window.addEventListener('resize', fitDock);
    void (async () => {
      imagery.refreshUsage();
      await prefsReady;
      if (gone) return;
      const saved = prefs.detectView;
      collapsed = saved?.collapsed ?? false;
      savedDockWidth = Math.max(300, Math.min(720, saved?.width ?? 380));
      fitDock();
      chosenBasemap = saved?.basemap && !PASSES.includes(saved.basemap) ? saved.basemap : 'esri-world-imagery';
      providerId = chosenBasemap;
      prefsLoaded = true;
      home = { ...prefs.homeView };
      // Where the other map tabs left the window, when they share a camera.
      const shared = share.opening();
      view = shared ? { lat: shared.lat, lon: shared.lon, zoom: shared.zoom } : { ...home };
      bearing = shared?.bearing ?? 0;
      try {
        await imagery.loadProviders();
      } catch {
        /* the panel still opens on local state; the map says what it cannot show */
      }
      if (gone) return;
      if (!imagery.find(providerId)) providerId = 'esri-world-imagery';
    })();
    return () => { gone = true; window.removeEventListener('resize', fitDock); };
  });

  function dockMaximum() {
    const available = toolEl?.clientWidth || window.innerWidth;
    return Math.max(300, Math.min(720, available - 320));
  }
  function clampDock(width) { return Math.max(300, Math.min(dockMaximum(), Math.round(width))); }
  function commitDockWidth() { savedDockWidth = dockWidth; }

  $effect(() => {
    if (!PASSES.includes(providerId)) chosenBasemap = providerId;
  });
  let lastPrefs = '';
  $effect(() => {
    if (!prefsLoaded) return;
    const value = { collapsed, width: savedDockWidth, basemap: chosenBasemap };
    const key = JSON.stringify(value);
    if (!lastPrefs) { lastPrefs = key; return; }
    if (key === lastPrefs) return;
    lastPrefs = key;
    prefs.detectView = value;
    void api.put('/api/settings/prefs', { detect_view: value }).catch(() => toast('Could not save the Detect preferences', 'danger'));
  });
  $effect(() => {
    collapsed;
    fullscreen;
    dockWidth;
    void tick().then(() => engine?.resize());
  });

  // The panel comes along to the whole screen, since the review is worked from
  // it; `]` still folds it away for the map alone.
  $effect(() => {
    if (toolEl) return followFullscreen(toolEl, (on) => (fullscreen = on));
  });
  function switchFullscreen() {
    toggleFullscreen(toolEl).catch(() => toast('Full screen is not available', 'danger'));
  }

  // The same turn as Satellite and Compare: a middle-drag, or shift and the
  // left button, turns the map about the point that was grabbed.
  let rotating = $state(null);
  $effect(() => {
    if (!element || !engine) return;
    const surfaces = [[engine, element], ...(secondEngine && secondElement ? [[secondEngine, secondElement]] : [])];
    const releases = surfaces.map(([surfaceEngine, surface]) => {
      const down = (event) =>
        turnFromPress(surfaceEngine, event, {
          onPivot: (point) => (rotating = point),
          onEnd: () => (rotating = null),
        });
      surface.addEventListener('mousedown', down, true);
      return () => surface.removeEventListener('mousedown', down, true);
    });
    return () => releases.forEach((release) => release());
  });
  function onKey(event) {
    if (uiState.tool !== 'detect') return;
    // held down, the turn keeps going
    if (turnFromKey(engine, event)) return;
    if (event.key === 'Escape' && builder?.escape()) { event.preventDefault(); return; }
    if (event.repeat || event.ctrlKey || event.metaKey || event.altKey
      || event.target?.closest?.('input, textarea, select, [contenteditable="true"]')) return;
    if (event.key === ']') collapsed = !collapsed;
    else if (event.key.toLowerCase() === 'm') toggleMeasure();
    else if ((event.key === 'Delete' || event.key === 'Backspace') && selectedMeasure) dropMeasure(selectedMeasure);
    else return;
    event.preventDefault();
  }

  /** A click on either map: a candidate to add, a pin to drop, or a point to read the rules at. */
  function onMapClick({ lon, lat }) {
    if (personalLayers.armed) return;
    if (manual?.kind === 'point') void panel?.addManual({ type: 'Point', coordinates: [lon, lat] });
    else if (builder?.pinning && !measuring) builder.dropPin({ lon, lat });
    else if (builder && !measuring) void builder.probeAt({ lon, lat });
  }

  function armMeasure() {
    drawing = 'select';
    manual = null;
    measureTool = 'measure';
  }
  function toggleMeasure() {
    personalLayers.stop();
    if (measuring) measureTool = 'select';
    else armMeasure();
  }
  function dropMeasure(id) {
    measures = measures.filter((mark) => mark.id !== id);
    if (selectedMeasure === id) selectedMeasure = null;
  }
  function clearMeasures() {
    measures = [];
    selectedMeasure = null;
  }

  // --- the right-click menu: acts on the point under the cursor -------------
  //
  // Satellite's menu, cut down to what Detect can honour: there is no sun panel
  // and no imagery history here, and a place is kept by pinning a candidate. A
  // run under review adds a candidate where the point falls in one of its
  // areas, which is how a hull the detector missed joins the queue.
  let pointMenu = $state(null); // { lat, lon, x, y, frame, lookup, areaId }
  let pointLookupSeq = 0;
  const compareSources = $derived(
    COMPARE_SOURCES.filter((source) => !source.provider || imagery.find(source.provider))
  );
  const pointActions = $derived(
    // a layer being edited owns the clicks on the map, so no measure is armed under it
    actionsFor((pointMenu?.areaId ? ['lookup', 'candidate', 'measure', 'horizon', 'centre'] : ['lookup', 'measure', 'horizon', 'centre'])
      .filter((id) => !personalLayers.editor || id !== 'measure'))
  );
  const pointTools = otherMapTools('detect');

  /** A saved item picked on the map: the map goes to it. */
  function flyToSaved(row) {
    if (row.lat == null || row.lon == null || !engine) return;
    engine.setView({ lat: Number(row.lat), lon: Number(row.lon) }, Math.max(engine.getZoom(), Number(row.zoom) || 13));
  }

  function onMapContextMenu(at) {
    pointLookupSeq += 1;
    pointMenu = {
      ...at,
      frame: { width: element?.clientWidth ?? 0, height: element?.clientHeight ?? 0 },
      lookup: null,
      areaId: panel?.candidateAreaAt(at) ?? null,
    };
  }

  /**
   * A right-click on a candidate, an area or a measure is a right-click on the
   * ground under it. Those are drawn over the map rather than in it, so the
   * engine never hears the press, and the browser's own menu opened instead,
   * right where a hull under review sits.
   */
  function onOverlayMenu(event) {
    if (!engine || !element || !event.target?.closest?.('.analysis-overlay, .detect-areas, .annotation-canvas')) return;
    event.preventDefault();
    const box = element.getBoundingClientRect();
    const x = event.clientX - box.left;
    const y = event.clientY - box.top;
    const at = engine.containerPointToLatLng({ x, y });
    onMapContextMenu({ lat: at.lat, lon: ((at.lon + 540) % 360) - 180, x, y });
  }

  function closePointMenu() {
    pointLookupSeq += 1;
    pointMenu = null;
  }

  async function onPointMenu(id, value) {
    const at = pointMenu;
    if (!at || !engine) return;
    const point = { lat: at.lat, lon: at.lon };
    if (id === 'lookup') return lookUpPoint(point);
    closePointMenu();
    if (id === 'copy') {
      await copyText(value);
    } else if (id === 'candidate') {
      await panel?.addCandidate(at.areaId, { type: 'Point', coordinates: [point.lon, point.lat] });
    } else if (id === 'measure') {
      armMeasure();
      await tick();
      measureCanvas?.startFrom([point.lon, point.lat]);
      trailing = true;
    } else if (id === 'centre') {
      engine.setView(point, engine.getZoom());
    } else if (id === 'horizon') {
      // a turned map faces somewhere: the eye faces the way up the screen
      lookFrom({ ...point, heading: headingUp(bearing) });
    } else if (id === 'compare') {
      await comparePoint(point, value);
    } else if (id === 'goto') {
      openMapAt(value, { ...point, zoom: engine.getZoom() });
    }
  }

  /** "What is here?": the geocoder's name for the point, shown in the menu itself. */
  async function lookUpPoint(point) {
    const mine = ++pointLookupSeq;
    pointMenu = { ...pointMenu, lookup: { busy: true } };
    try {
      const answer = await api.get(`/api/geo/reverse?lat=${point.lat}&lon=${point.lon}`);
      if (mine !== pointLookupSeq || !pointMenu) return;
      pointMenu = { ...pointMenu, lookup: { text: answer.display_name || 'No name for this point' } };
    } catch (error) {
      if (mine !== pointLookupSeq || !pointMenu) return;
      pointMenu = { ...pointMenu, lookup: { error: `Lookup failed: ${error.message}` } };
    }
  }

  /** Open Compare on the last two pictures of this point, as Satellite's menu does. */
  async function comparePoint(point, source) {
    const name = COMPARE_SOURCES.find((entry) => entry.id === source)?.label ?? 'the archive';
    const waiting = toast(`Asking ${name} for the last two pictures…`, 'info', 0);
    try {
      const zoom = engine.getZoom();
      const pair = await comparePair(api, source, { ...point, zoom });
      uiState.compareAt = { ...point, zoom, ...pair };
      uiState.tool = 'compare';
    } catch (error) {
      toast(error.message, 'warn', 6000);
    } finally {
      dismissToast(waiting);
    }
  }

  // The menu is pinned to a screen point, so a zoom or a pan leaves it pointing
  // at somewhere else. A drag already closes it by pressing outside; the wheel
  // does not, so the settled view does.
  $effect(() => {
    if (!engine || !pointMenu) return;
    return engine.on('view-settled', closePointMenu);
  });
  function leavePass() {
    blinking = false;
    readingPass = false;
    passContext = null;
    providerId = chosenBasemap;
  }

  // A saved item asked for from elsewhere: the case sidebar, or the top bar
  // while a run was working (lib/detectRuns.svelte.js).
  $effect(() => {
    const requested = uiState.openAnalyzer;
    if (!requested) return;
    untrack(() => {
      opening = requested;
      uiState.openAnalyzer = null;
    });
  });

  /** The camera as a rectangle to sweep: the one place the map decides what a
   *  run covers, after which the area is fixed and the camera is free again. */
  function useCurrentView() {
    const bounds = engine?.viewBounds?.();
    if (!bounds) return;
    zones = [...zones, viewZone(bounds, `Area ${zones.length + 1}`)];
    showZones = true;
    drawing = 'select';
  }

  /** Go to a point of the work. A candidate under review asks to be close
   *  enough to read; a saved place only asks to be on screen. */
  function focus([lon, lat], closest = 13) {
    engine?.setView({ lon, lat }, Math.max(engine.getZoom(), closest));
  }

  /** A framing asked for before the map engine existed, run once it does: the
   *  case's areas usually arrive first. Likewise one asked for while another tab
   *  shows, as a new case's areas are: a hidden map has no size to fit them to,
   *  and the landing is for the analyst arriving here, so it waits for that. */
  let waitingFrame = $state(null);
  $effect(() => {
    if (!engine || !waitingFrame || uiState.tool !== 'detect') return;
    const { shapes, landing } = waitingFrame;
    untrack(() => { waitingFrame = null; frame(shapes, { landing }); });
  });

  /**
   * The camera this window's map tabs share (`lib/map/sharedView.js`), taken
   * when this tab shows, including while a candidate is under review.
   */
  const share = shareView('detect', { state: uiState, enabled: () => prefs.mapSync });

  $effect(() => {
    uiState.mapView;
    if (uiState.tool !== 'detect' || !ready) return;
    untrack(() => {
      const next = share.pending(engine.camera());
      if (next) engine.setCamera(next);
    });
  });

  /** Where the map is, for Coordinates, and where the window looks: hidden
   *  too, when a pan's glide ends after a switch of tab. */
  function onSettled(camera) {
    uiState.mapPoint = { lat: camera.lat, lon: camera.lon, zoom: camera.zoom };
    share.settled(camera, engine?.maxZoom());
  }

  /**
   * A point another map tab asked Detect to look at. It wins over the case's
   * landing frame, which can arrive after it: the analyst came here for that
   * point, not for the areas the case happens to watch.
   */
  let pointAsked = false;
  $effect(() => {
    caseState.current?.id;
    pointAsked = false;
  });
  $effect(() => {
    const asked = uiState.lookAt;
    if (uiState.tool !== 'detect' || asked?.tool !== 'detect' || !engine) return;
    untrack(() => {
      uiState.lookAt = null;
      pointAsked = true;
      engine.setView({ lat: asked.lat, lon: asked.lon }, Number.isFinite(asked.zoom) ? asked.zoom : engine.getZoom());
    });
  });

  /** Frame a whole set of areas: opening a routine should show all of it. */
  function frame(shapes, { landing = false } = {}) {
    // The case's landing gives way to a point asked for, and to a camera another
    // map tab left the window on: arriving from there, that is the ground in hand.
    if (landing && (pointAsked || share.ledElsewhere())) return;
    if (!engine?.fitBounds || uiState.tool !== 'detect') { waitingFrame = { shapes, landing }; return; }
    const points = shapes.flatMap((zone) => zoneRing(zone));
    if (!points.length) return;
    const xs = points.map(([lon]) => lon);
    const ys = points.map(([, lat]) => lat);
    engine.fitBounds(
      { west: Math.min(...xs), east: Math.max(...xs), south: Math.min(...ys), north: Math.max(...ys) },
      { padding: 60, maxZoom: 15 }
    );
  }

  /**
   * Put a pass on the map, so the picture is the one the work is about. A day is
   * shown whole, as a run reads it: under the run's ceiling Sentinel Hub would
   * drop a cloudier tile and leave the map black. Its cloud, when the lookup
   * knows it, rides on the chip.
   */
  function showDate({ provider, date, time, layer, cloud = null, area = null, side = '' }) {
    if (!date) { leavePass(); return; }
    passContext = area && side ? { name: area.name, side } : null;
    if (area) frame([area]);
    passCloud = provider === RADAR_ID || !Number.isFinite(cloud) ? null : cloud;
    if (provider === RADAR_ID) {
      // A radar pass is shown by the radar basemap, once Settings has its layer.
      if (!imagery.find(RADAR_ID)) return;
      readingPass = true;
      providerId = RADAR_ID;
      s1.pick({ date, time });
      return;
    }
    if (!imagery.find(SENTINEL)) return;
    readingPass = true;
    providerId = SENTINEL;
    if (layer) s2.layer = layer;
    s2.setMaxcc(DEFAULT_MAXCC);
    s2.date = date ?? '';
  }

  async function goTo() {
    const text = searchText.trim();
    if (!text || searching || !engine) return;
    searching = true;
    try {
      try {
        const parsed = await api.post('/api/geo/parse', { text });
        engine.setView(parsed, Math.max(engine.getZoom(), 16));
        return;
      } catch {
        /* not coordinates: ask the geocoder below */
      }
      const place = await api.get(`/api/geo/geocode?q=${encodeURIComponent(text)}`);
      engine.setView(place, Math.max(engine.getZoom(), 13));
      if (place.display_name) toast(place.display_name, 'info', 5000);
    } catch {
      toast('No match. Try coordinates, DMS, MGRS, a plus code or a place name', 'danger');
    } finally {
      searching = false;
    }
  }
</script>

<svelte:window onkeydown={onKey} />
<div class="detect-tool" bind:this={toolEl}>
  <div class="stage">
    <!-- svelte-ignore a11y_no_static_element_interactions -->
    <div class="surface-shell" oncontextmenu={onOverlayMenu}>
    <div class="search cmp-glass" data-bar-obstacle>
      <PlaceSearch
        bind:value={searchText}
        centre={{ lat: view.lat, lon: view.lon }}
        units={prefs.units}
        {searching}
        listId="detect-suggestions"
        onsubmit={goTo}
        onpick={(place) => { searchText = place.label ?? searchText; goTo(); }}
      />
    </div>
    <div class="map-choices">
      <!-- The passes under an analyzer being built are its check's (the console), so the provider is not offered. -->
      {#if !builder}<ImageryChip {imagery} bind:providerId {s2} {wayback} {s1} {shown} />{/if}
      <LayerMenu
        rows={layerRows}
        added={myLayers.rows}
        ontoggleadded={(layer) => myLayers.toggle(caseState.current?.id, layer)}
        onmanage={() => (uiState.tool = 'satellite')}
        oneditadded={(row) => { layersOpen = false; personalLayers.open(row); }}
        onnewpersonal={() => { layersOpen = false; personalLayers.newLayer(); }}
        ondownloadadded={(row) => { layersOpen = false; personalLayers.download(row); }}
        buttonClass="layers-chip cmp-glass"
        align="right"
        bind:open={layersOpen}
      />
      <!-- While an analyzer is built, the console over the map holds its passes. -->
      {#if blinkPair && !builder}
        <!-- Which of the two is on screen, in Compare's letters and colours. -->
        <div class="pass-chip blink-chip cmp-glass" role="group" aria-label="Blinking A and B">
          <span class="cmp-letter" class:a={showingA} class:b={!showingA}>{showingA ? 'A' : 'B'}</span>
          <span class="mono">{sourceLabel(showingA ? blinkPair.a : blinkPair.b)}</span>
          <button class="cmp-icon" title="Stop blinking" aria-label="Stop blinking" onclick={() => (blinking = false)}><Icon name="x" size={12} /></button>
        </div>
      {:else if readingPass && !builder}
        <button class="pass-chip cmp-glass" title="Return to your basemap" aria-label="Leave pass imagery" onclick={leavePass}>
          {#if passContext}<strong>{passContext.name} · {passContext.side?.toUpperCase()}</strong>{/if}{passChip}
          {#if cloudyPass}<span class="cloudy" title="Ground under cloud is left out of a run">{Math.round(passCloud)}% cloud</span>{/if}
          <Icon name="x" size={12} /></button>
      {/if}
      <!-- Which way is up: the same reading every other map in the app shows,
           which Detect lost when it turned the surface's own chrome off. -->
      <Compass {bearing} onbearing={(deg) => engine?.setBearing(deg)} />
    </div>
    <!-- Under the search and over the zoom buttons, which `controlsTop` pushes down to make room. -->
    <div class="ruler cmp-glass">
      <button class="cmp-icon" class:on={measuring} aria-pressed={measuring} aria-label="Measure"
        title="Measure a length (M)" onclick={toggleMeasure}><Icon name="ruler" size={15} /></button>
      {#if measures.length}
        <button class="cmp-icon" aria-label="Clear measures" title="Clear measures" onclick={clearMeasures}><Icon name="trash" size={14} /></button>
      {/if}
    </div>
      {#if home}
        <MapSurface
          bind:engine
          bind:element
          bind:view
          bind:bearing
          bind:ready
          bind:refused
          bind:dated
          bind:providerId
          {imagery}
          {s2}
          {wayback}
          {s1}
          overlays={mapLayers.overlays}
          chrome={false}
          {home}
          resetToHome={false}
          imperial={prefs.units === 'imperial'}
          armed={personalLayers.armed ? 'selecting' : measuring ? 'measuring' : drawing !== 'select' || builder?.pinning ? 'selecting' : null}
          onclick={onMapClick}
          controlsTop={108}
          {alternate}
          alternateOn={showingA}
          onusage={() => imagery.refreshUsage()}
          onviewsettled={onSettled}
          oncontextmenu={onMapContextMenu}
          onimageryfallback={() => builder ? builder.setBasemap(true) : leavePass()}
        />
        <!-- The case's own layers, under Detect's findings. Drawn only while this
             tab is on screen, and inert while a tool holds the pointer, so a pin
             or an area is never a card opened instead. -->
        <LayerGeometry engine={ready ? engine : null} controller={personalLayers} active={uiState.tool === 'detect'} onmenu={onMapContextMenu} />
        <AddedLayersOverlay
          engine={ready ? engine : null}
          caseId={caseState.current?.id ?? ''}
          layers={uiState.tool === 'detect' && !bare ? myLayers.drawn : []}
          drawing={addedLayers.drawing}
          watch={myLayers.watch}
          onmenu={onMapContextMenu}
          interactive={!personalLayers.armed && !measuring && drawing === 'select' && !manual && !builder?.pinning}
          onedit={async (row, key) => { if (personalLayers.editor?.name !== row.name) await personalLayers.open(row); personalLayers.select(key); }}
          onremovefeature={(row, key) => personalLayers.remove(key, row)} ondeleteplace={personalPlaceDeletion.open}
          oncopyfeature={(row, feature, anchor) => personalLayers.copy(row, feature, anchor)}
        />
        {#if mapLayers.has('saved') && !bare && caseState.current && !personalLayers.armed}
          <SavedOverlay
            engine={ready ? engine : null}
            items={savedItems}
            caseId={caseState.current.id}
            coords={(item) => fmtCoords(item.lat, item.lon)}
            onopen={flyToSaved}
            onrefresh={reloadCase}
          />
        {/if}
        {#if builder?.split}
          <SecondPass {imagery} primary={engine} source={builder.imagery.b} {view} {bearing} {home} overlays={mapLayers.overlays}
            imperial={prefs.units === 'imperial'} armed={measuring ? 'measuring' : builder.pinning ? 'selecting' : null}
            divider={builder.divider} bind:engine={secondEngine} bind:element={secondElement}
            onsplit={(percent) => builder.setDivider(percent)} onclick={onMapClick} oncontextmenu={onMapContextMenu}
            onusage={() => imagery.refreshUsage()} onimageryfallback={() => builder.setBasemap(true)} />
        {/if}
        {#if builder}
          {#if !builder.hideOverlays}
            <RuleLayers {engine} {element} detail={builder.detail} rules={builder.recipe.rules} shown={paintedRules}
              hover={builder.hovered} colours={builder.colours} split={builder.split} divider={builder.divider}
              live={builder.live} stale={builder.staleToDraw} />
          {/if}
          {#if previewLayer.length && !builder.hideOverlays}
            <AnalysisOverlay {engine} layers={previewLayer} markers={builder.markers} outlines={builder.outlines}
              interactive={!personalLayers.armed && !builder.pinning && !measuring} onpick={(_, id) => {
              const row = builder.detail.candidates.find((candidate) => candidate.id === id);
              if (row) void builder.probeAt({ lon: row.coordinates[0], lat: row.coordinates[1] });
            }} />
          {/if}
          {#if builder.checkPins && !builder.hideOverlays}
            <CheckMarks {engine} pins={builder.pins} armed={!!builder.pinning || personalLayers.armed} selected={builder.probe?.pin ?? null}
              onpick={(index) => builder.probePin(index)} />
          {/if}
          {#if builder.probe && !personalLayers.armed}
            <RuleProbe {engine} probe={builder.probe} rules={builder.recipe.rules} colours={builder.colours} single={builder.single}
              width={element?.clientWidth ?? 0} height={(element?.clientHeight ?? 0) - builder.reach} onclose={() => builder.closeProbe()}
              onmark={(expect) => builder.markProbe(expect)} pin={probedPin}
              onturn={() => { builder.flipPin(builder.probe.pin); builder.closeProbe(); }}
              onremove={() => { builder.removePin(builder.probe.pin); builder.closeProbe(); }} />
          {/if}
        {:else if !bare && (focusedRunId || savedVisible) && visibleRunLayers.some((layer) => layer.visible)}
          <AnalysisOverlay {engine} layers={visibleRunLayers} selected={selectedResult} active={!manual}
            markers={resultMarkers} outlines={resultOutlines}
            interactive={!personalLayers.armed && !measuring && drawing === 'select'}
            onpick={(run, result) => panel?.pick(run, result)} />
        {/if}
        {#if areaGroups.length && !manual && !bare && !builder && !personalLayers.armed}
          <DetectAreas {engine} groups={areaGroups} {highlight} onpick={(id) => panel?.openArea(id)} />
        {/if}
        {#if manual?.kind === 'polygon'}
          <AnnotationCanvas annotations={[]} {engine} letter="a" bind:tool={manualTool} colour="#ffffff"
            onchange={(next) => {
              const polygon = marksToZones(next, [])[0];
              if (polygon) {
                const ring = zoneRing(polygon);
                void panel?.addManual({ type: 'Polygon', coordinates: [[...ring, ring[0]]] });
              }
            }} />
        {:else if showZones && !manual && !bare && !builder}
          <AnnotationCanvas annotations={marks} {engine} letter="a" editVertices={true} edgeOnly={true}
            active={!personalLayers.armed}
            bind:tool={drawing} bind:selectedId={selectedZone} colour="#38bdf8" fillOpacity={0.08}
            onchange={(next) => (zones = marksToZones(next, zones))} />
        {/if}
        <!-- Over the areas, so a measure started inside one takes the press. -->
        <AnnotationCanvas bind:this={measureCanvas} annotations={measures} {engine} letter="a" units={prefs.units}
          active={!personalLayers.armed}
          editVertices={true} bind:tool={measureTool} bind:selectedId={selectedMeasure} colour="#f5a623"
          strokeWidth={2} stampSize={14} onchange={(next) => (measures = next)} />
        {#if pointMenu}
          <MapContextMenu
            at={pointMenu}
            frame={pointMenu.frame}
            zoom={view.zoom}
            format={prefs.coordFormat}
            actions={pointActions}
            tools={pointTools}
            lookup={pointMenu.lookup}
            {compareSources}
            {fullscreen}
            onpick={onPointMenu}
            onclose={closePointMenu}
          />
        {/if}
      {:else}
        <div class="loading">Reading your preferences…</div>
      {/if}
      {#if rotating}
        <TurnGuide x={rotating.x} y={rotating.y} />
      {/if}
      {#if builder}
        <CheckBench bench={builder} />
      {/if}
      {#if needs && !personalLayers.editor}
        <div class="need-over">
          <CopernicusNeeded need={needs} tool="Detect" />
        </div>
      {/if}
      {#if measuring}
        <div class="manual-chip cmp-glass">{trailing ? 'Click the far end' : 'Drag from one end to the other'}
          <button class="cmp-icon" aria-label="Stop measuring" title="Stop measuring (Esc)" onclick={() => (measureTool = 'select')}><Icon name="x" size={13} /></button>
        </div>
      {/if}
      {#if manual}
        <div class="manual-chip cmp-glass">{manual.kind === 'point' ? 'Click the candidate on the map' : 'Click corners; Enter finishes'}
          <button class="cmp-icon" aria-label="Cancel adding candidate" title="Cancel adding candidate" onclick={() => (manual = null)}><Icon name="x" size={13} /></button>
        </div>
      {/if}
    </div>

    <DetectPanel
      bind:this={panel}
      bind:collapsed
      {dockWidth}
      maxDockWidth={dockMaximum}
      onwidth={(value) => (dockWidth = clampDock(value))}
      onwidthend={commitDockWidth}
      {fullscreen}
      onfullscreen={switchFullscreen}
      bind:manual
      caseId={caseState.current?.id}
      bind:zones
      bind:drawing
      bind:selectedZone
      bind:layers
      bind:focusedRunId
      bind:showZones
      bind:selectedResult
      bind:markers={resultMarkers}
      bind:outlines={resultOutlines}
      bind:areaGroups
      bind:highlight
      bind:bare
      bind:blinking
      onpair={(pair) => (reviewPair = pair)}
      {opening}
      onopened={() => (opening = null)}
      onfocus={focus}
      onframe={frame}
      onusecurrentview={useCurrentView}
      onshow={showDate}
      onleavepass={leavePass}
      bind:builder
      viewBounds={() => engine?.viewBounds?.() ?? null}
      passLayers={s2.layers}
      passLayerState={s2}
      onfly={({ lon, lat, zoom, bounds }) => (bounds ? engine?.fitBounds(bounds, { padding: 40 }) : engine?.setView({ lon, lat }, zoom))}
    />
  </div>
  <PersonalLayerPanel tool="detect" scope={myLayers} {engine}
    onarm={() => { drawing = 'select'; manual = null; measureTool = 'select'; if (builder?.pinning) builder.escape(); }} />
</div>

<style>
  .detect-tool {
    position: relative;
    display: flex;
    flex-direction: column;
    height: 100%;
    min-height: 0;
    background: var(--bg-0);
  }
  /* one over the chips under it, so the suggestions open over the ruler */
  .search { position: absolute; top: 12px; left: 12px; z-index: 651; display: flex; width: min(280px, 42%); padding: 4px; }
  .search :global(.place-search) { flex: 1; }
  .map-choices { position: absolute; top: 12px; right: 12px; z-index: 650; display: grid; justify-items: end; gap: 8px; }
  /* the closed menu is as tall as the imagery chip over it */
  .map-choices :global(.layers-chip) { display: flex; align-items: center; gap: 6px; height: 30px; box-sizing: border-box;
    padding: 0 10px; font-size: var(--fs-xs); cursor: pointer; }
  .map-choices :global(.layers-chip:hover), .map-choices :global(.layers-chip.active) { color: var(--accent); }
  .ruler { position: absolute; top: 66px; left: 12px; z-index: 650; display: flex; padding: 2px; }
  .blink-chip { padding: 2px 2px 2px 4px; }
  .blink-chip .cmp-icon { width: 22px; height: 22px; }
  .pass-chip { display: flex; align-items: center; gap: 8px; padding: 4px 8px; font-size: var(--fs-xs); }
  .pass-chip .cloudy { color: var(--warn, #e2a03f); }
  /* Over the map and under its own controls, which stay usable around it. */
  .need-over {
    position: absolute;
    inset: 0;
    z-index: 640;
    display: grid;
    place-items: center;
    padding: 16px;
    background: rgb(0 0 0 / 0.35);
  }
  .manual-chip { position: absolute; bottom: 36px; left: 12px; z-index: 650; display: flex; align-items: center; padding: 4px 8px; font-size: var(--fs-xs); }
  /* The point a turn is happening about, drawn as Satellite and Compare draw it. */
  .stage { display: flex; flex: 1; min-height: 0; }
  /* The surface itself is a flex child (`.map-wrap`), so this has to be a flex
     container or the map lands with no height at all. */
  .surface-shell {
    position: relative;
    display: flex;
    flex: 1;
    min-width: 0;
    min-height: 0;
    overflow: hidden;
    background: var(--bg-0);
  }
  .loading {
    display: grid;
    place-items: center;
    height: 100%;
    color: var(--text-3);
    font-size: var(--fs-sm);
  }
</style>