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
49.8 KB
Raw Blame
import { describe, expect, it } from 'vitest';
import { readdirSync, readFileSync } from 'node:fs';

const source = readFileSync(new URL('./Satellite.svelte', import.meta.url), 'utf8');
const rail = readFileSync(new URL('./satellite/MapRail.svelte', import.meta.url), 'utf8');
const layers = readFileSync(new URL('./satellite/MapLayers.svelte', import.meta.url), 'utf8');
// the rows themselves, drawn the same in the Map's panel and the other maps' menu
const layerRows = readFileSync(new URL('../components/LayerRows.svelte', import.meta.url), 'utf8');
// a layer's settings, drawn the same under the Map's rows and in the other maps' menu
const controls = readFileSync(new URL('../components/LayerControls.svelte', import.meta.url), 'utf8');
const questions = readFileSync(new URL('../lib/map/eventControls.js', import.meta.url), 'utf8');
// The sky overlay's geometry moved to `lib/skyOverlay.js`, where it is exercised
// against real numbers (`skyOverlay.test.js`); the tool hands it to the map.
const sky = readFileSync(new URL('../lib/skyOverlay.js', import.meta.url), 'utf8');

/** The tool and everything it is made of, keyed by the path a failure names, for
 *  the checks that must hold of all of it. */
function satelliteSources() {
  const files = { 'Satellite.svelte': source };
  const dir = new URL('./satellite/', import.meta.url);
  for (const entry of readdirSync(dir, { recursive: true, withFileTypes: true })) {
    if (!entry.isFile() || entry.name.endsWith('.test.js')) continue;
    const at = `${entry.parentPath}/${entry.name}`;
    const key = at.slice(at.indexOf('/satellite/') + 1).replace(/\/{2,}/g, '/');
    files[key] = readFileSync(at, 'utf8');
  }
  return files;
}

describe('the map rail', () => {
  it('says which of its tools is on, every one of them', async () => {
    // a tool armed with its icon left plain reads as nothing being on: the
    // old Elevation profile seat was, until this was checked
    const { railEntries } = await import('../lib/map/tools.js');
    const block = source.slice(source.indexOf('<MapRail'), source.indexOf('onpick={pickTool}'));
    for (const entry of railEntries()) {
      expect(block, `${entry.id} is in the rail and never shown on`).toMatch(new RegExp(`\\b${entry.id}: \\{\\s*on:`));
    }
  });
});

describe('Satellite saved work', () => {
  // The indexes, the filter, the Locate pass and the row actions are the store's
  // (`satellite/state/saved.svelte.test.js`, which exercises them for real).
  // What is this file's business is that the tool hands them over.
  it('hands one store to the tree, the search and the map overlay', () => {
    expect(source).toContain("import { createSavedState } from './satellite/state/saved.svelte.js'");
    expect(source).toContain('<SavedTree');
    expect(source).toContain('<SavedSearch');
    expect(source).toContain('<SavedOverlay');
    expect(source).toContain('rows={savedWork.shownRows}');
    // the overlay draws the panel's filtered selection, never the whole index
    expect(source).toContain('items={savedWork.shown}');
    expect(source).not.toContain('items={savedWork.rows}');
  });

  it('opens the details dialog when a capture row is edited', () => {
    // Edit on a capture, from the map popup or the panel, sets the row the
    // dialog renders; a call to a helper that no longer exists fails silently.
    const edit = source.slice(source.indexOf('function editSaved'));
    const body = edit.slice(0, edit.indexOf('\n  }'));
    expect(body).toContain("row.kind === 'place'");
    expect(body).toContain('notesItem = row');
    for (const [, name] of body.matchAll(/\b(open\w+)\(/g)) {
      expect(source, `${name} is called but never defined`).toMatch(
        new RegExp(`function ${name}\\b|const ${name}\\b|import \\{[^}]*\\b${name}\\b[^}]*\\}`)
      );
    }
  });

  it('loads and drops every index with the case, through the store', () => {
    // Two stores read the case now: its saved work, which hands back a teardown so
    // a response arriving after the case changed lands nowhere, and the layers the
    // analyst added, shared by every map and read once per reload.
    expect(source).toContain('const stopSaved = savedWork.load(id);');
    expect(source).toContain('stopSaved?.()');
    expect(source).toContain('addedLayers.load(id, caseState.rev);');
    expect(source).toContain('savedWork.loadMode(caseState.current?.id, caseState.rev)');
  });

  it('closes over this case for every row action', () => {
    // a pass or a PATCH must never land in the case the analyst just left
    expect(source).toContain('savedWork.accept(caseState.current.id, row)');
    expect(source).toContain('savedWork.move(caseState.current.id, row, folder)');
    expect(source).toContain('savedWork.runLocate(caseState.current?.id)');
    expect(source).toContain('await savedWork.remove(caseId, row)');
  });

  it('drops the dialogs and the session layers before another case', () => {
    const effect = source.slice(
      source.indexOf('if (openFor !== id)'),
      source.indexOf('return savedWork.load(id);')
    );
    expect(effect).toContain('savedSearchOpen = false');
    expect(effect).toContain('deleteTarget = null');
    expect(effect).toContain('notesItem = null');
    expect(effect).toContain('placeModal = null');
    expect(effect).toContain('temporalMap = null');
    expect(effect).toContain('sheetPoints = null');
  });

  it('opens with the map overlay on, and keeps it out of the case file', () => {
    // a case is opened to be read, and its located work is what a map is read for
    expect(source).toContain('let savedOverlay = $state(true)');
    expect(source).toContain('{#if savedOverlay}');
    // it is a layer, listed with the other layers rather than sitting in the
    // toolbox: nothing about it changes what the pointer does
    expect(source).toContain('toggle: () => (savedOverlay = !savedOverlay)');
    expect(layers).toContain('<LayerRows {rows} />');
    expect(layerRows).toContain('aria-pressed={Boolean(row.on)}');
    // one eye for both states: only its colour says whether the layer is on
    expect(layerRows).toContain('<Icon name="eye" size={13} />');
    expect(layerRows).not.toContain("'ghost'");
    expect(layerRows).toMatch(/\.eye\.on \{\s*color: var\(--accent\);/);
    expect(rail).not.toContain('savedOverlay');
    // nothing about the overlay is written back to the case — session only
    expect(source).not.toContain('savedOverlay:');
  });

  it('shares one hovered id between the panel and the map', () => {
    expect(source).toContain('let hoveredSavedId = $state(null)');
    expect((source.match(/bind:hoveredId=\{hoveredSavedId\}/g) ?? []).length).toBe(3);
  });

  it('queues a saved row as a panel of a new proof', () => {
    expect(source).toContain('function sendToComposer(item)');
    expect(source).toContain('uiState.composeQueue.push(item.path)');
  });

  it('opens a proof already built on the file being played', () => {
    expect(source).toContain('function openProofByName(proof)');
    expect(source).toContain('uiState.openProof = proof.name');
    expect(source).toContain('onproof={openProofByName}');
  });

  it('reveals a capture the case sidebar points at, on the position that lists it', () => {
    expect(source).toContain("savedWork.kind = 'captures'");
    expect(source).toContain("savedWork.query = ''");
    expect(source).toContain('revealSavedId = row.id');
  });
});

describe('Capture extension settings handoff', () => {
  it('opens the extension section from the gate that needs it', () => {
    // There were two: this one, and a line under the panel's list of external
    // maps. That list is gone — the right-click menu already offers those, on
    // the point that was clicked rather than on the map's centre — and the
    // advert went with it rather than being refiled somewhere it reads as an ad.
    expect(source.match(/uiState\.settingsTab = 'extension'/g)).toHaveLength(1);
    expect(source).toContain('<ExtensionGate');
  });
});

describe('filing saved work from its details dialog', () => {
  const captureDialog = readFileSync(
    new URL('./satellite/CaptureDetails.svelte', import.meta.url),
    'utf8'
  );

  it('offers the same folder picker the rest of the app uses, in both dialogs', () => {
    expect(captureDialog).toContain("import FolderSelect from '../../components/FolderSelect.svelte'");
    expect(captureDialog).toContain('bind:value={folder}');
    expect(captureDialog).toContain('emptyLabel="Unfiled"');
    const placeDialog = readFileSync(
      new URL('./satellite/PlaceDialog.svelte', import.meta.url),
      'utf8'
    );
    expect(placeDialog).toContain("import FolderSelect from '../../components/FolderSelect.svelte'");
    expect(placeDialog).toContain('bind:value={draft.folder}');
    expect(placeDialog).toContain('emptyLabel="Unfiled"');
  });

  it('opens each dialog on the folder the item is already in', () => {
    expect(captureDialog).toContain("let folder = $state(row.folder ?? '')");
    expect(source).toContain("folder: row.folder ?? ''");
  });

  it('files a capture in the patch it already sends', () => {
    expect(source).toContain('{ path: notesItem.path, notes, title, folder }');
  });

  it('files a place, whether it is being saved or edited', () => {
    expect(source).toContain("attrs: { notes: m.notes.trim(), folder: m.folder ?? '' }");
    expect(source).toContain('folder: m.folder,');
  });
});

describe('reference windows', () => {
  // When the case is read, where the windows live and how they stack are the
  // store's (`satellite/state/refs.svelte.test.js`); the picker itself is
  // `satellite/RefPicker.svelte`. What is this file's business is that the tool
  // hands one store to all three places the windows are touched.
  it('hands one store to the rail, the picker and the windows', () => {
    expect(source).toContain("import { createRefsState } from './satellite/state/refs.svelte.js'");
    // a rail seat that runs rather than arms: it opens a picker and a window
    expect(source).toContain("if (id === 'reference') return refs.openPicker();");
    expect(source).toContain('on: refs.open.length > 0,');
    // over the map, and in a column on either side of it
    expect(source).toContain('{#each refs.floating as pane (pane.id)}');
    expect(source).toContain('{#each refs.dockedOn(side) as pane (pane.id)}');
    expect(source).toContain("{@render refColumn('left')}");
    expect(source).toContain("{@render refColumn('right')}");
    expect(source).toContain('onpick={(item) => refs.add(item)}');
  });

  it('remeasures the map when a column opens, closes or changes width', () => {
    expect(source).toContain('void refs.dockedOn(side).length;');
    expect(source).toContain('void refs.dockWidth(side);');
    expect(source).toContain('tick().then(() => engine?.resize());');
  });

  it('keeps the windows in the session, never in the case', () => {
    // the store holds no list of its own: it reads and writes the tab's, which
    // is what makes the windows survive a tool switch and die with the tab
    expect(source).toContain('viewers: () => uiState.refViewers');
    expect(source).toContain('setViewers: (windows) => (uiState.refViewers = windows)');
    expect(source).not.toContain('refViewers:');
  });

  it('leaves them out of a screen capture, wherever the crop is taken', () => {
    // the rule is stated once, on the surface that owns the grab
    const surfaces = satelliteSources();
    expect(surfaces['satellite/MapSurface.svelte']).toContain('.map-wrap.grabbing');
  });
});

describe('the saved panel is resizable', () => {
  it('drives the width from the shared panel helpers, with its own key and range', () => {
    expect(source).toContain("import { panelWidth } from '../lib/panelWidth.js'");
    expect(source).toContain("key: 'azimut:satelliteSavedW'");
    expect(source).toContain('let savedW = $state(savedPanel.loadWidth())');
    expect(source).toContain('style={capturesCollapsed ? undefined : `width: ${savedW}px`}');
  });

  it('clamps every width it sets against the live window', () => {
    expect(source).toContain('savedW = savedPanel.clampWidth(w, window.innerWidth)');
    // nothing sets the width past the clamp
    expect((source.match(/savedW = /g) ?? []).length).toBe(2); // the $state, then setSavedWidth
  });

  it('gives the handle a keyboard path and a double-click reset', () => {
    expect(source).toContain('onpointerdown={startSavedResize}');
    expect(source).toContain('ondblclick={resetSavedWidth}');
    expect(source).toContain('onkeydown={onSavedResizeKey}');
    expect(source).toContain('aria-label="Resize the saved panel"');
  });

  it('stores the width once the drag ends, not on every frame', () => {
    expect(source).toContain('savedPanel.saveWidth(savedW); // one write per drag');
  });

  it('leaves the left button to whichever mode is armed for it', () => {
    // shift and the left button turn the map, but the capture marquee and the
    // grid box are both waiting on that same drag
    expect(source).toContain("shift: !capture.armed && grid.drawMode !== 'rect'");
  });

  it('redraws the map for the new size', () => {
    expect(source).toContain('engine?.resize()');
  });

  it('hides the handle when the panel is collapsed to its rail', () => {
    expect(source).toContain('{#if !capturesCollapsed}');
  });
});

describe('filing saved work by dragging it in the panel', () => {
  it('hands the tree both groupings, the case folders and a move handler', () => {
    expect(source).toContain('bind:group={savedWork.group}');
    expect(source).toContain('onmove={moveSaved}');
    expect(source).toContain('folders={caseState.current?.folders ?? []}');
  });

  it('leaves folder browsing out of the search modal', () => {
    const modal = source.slice(source.indexOf('<SavedSearch'));
    expect(modal).not.toContain('onmove');
  });
});

describe('sun and moon mode', () => {
  // Where the path is anchored, what is asked of the backend and what reaches
  // the map are the store's (`satellite/state/sky.svelte.test.js`), and the
  // geometry under it is `lib/skyOverlay.js`, which has its own. What is left
  // here is what the mode means *in this tool*: one map mode among the others.
  it('is a map mode in the rail, exclusive with the others through the registry', () => {
    expect(source).toContain("import { createSkyState } from './satellite/state/sky.svelte.js'");
    // Exclusivity is declared once, not written out per pair: the mode says how
    // to open and close itself and `arm()` closes whatever else was on.
    expect(source).toContain("arm(modes, 'sky')");
    expect(source).toContain('isOn: () => sky.on,');
    expect(source).toContain('close: () => sky.close(),');
    // the pairwise calls this replaced are gone, in both directions
    expect(source).not.toContain('if (capture.armed) toggleSelect()');
    expect(source).not.toContain('if (grid.on) toggleGridMode()');
  });

  it('opens on the moved pin when there is one, else on the view', () => {
    expect(source).toContain('sky.open(markerLatLng ?? { lat: center.lat, lon: center.lon })');
  });

  it('redraws the arc when the view moves, since it is drawn in metres', () => {
    expect(source).toContain("return engine.on('view-settled', () => sky.draw())");
  });

  it('takes the handoff from Coords & Sky into the same mode', () => {
    expect(source).toContain('const handed = uiState.skyAt');
    expect(source).toContain('uiState.skyAt = null'); // consumed once, like gotoCoords
    expect(source).toContain('if (!sky.on) toggleSunMode()');
    // no computed value travels: the store asks for its own
    expect(source).not.toContain('handed.sun');
  });

  it('hands the panel the store, not a copy of its numbers', () => {
    expect(source).toContain('<SunPanel');
    expect(source).toContain('sky={sky.sky}');
    expect(source).toContain('onindex={(value) => sky.setIndex(value)}');
  });
});

describe('the capture button', () => {
  // The frame, the two roads to a filed crop and every refusal are the store's
  // (`satellite/state/capture.svelte.test.js`). What is this file's business is
  // the wiring only it can do: the shared drag outline, the mode exclusivity,
  // and giving the store the map element it does not own.
  it('hands one store to the options popover and both dialogs', () => {
    expect(source).toContain(
      "import {\n    createCaptureState,\n    PRESETS,\n    RATIOS,\n  } from './satellite/state/capture.svelte.js';"
    );
    expect(source).toContain('<CaptureOptions');
    expect(source).toContain('runCapture={() => capture.run()}');
    expect(source).toContain('capturing={capture.busy}');
    expect(source).toContain('{#if capture.shotOpen}');
    expect(source).toContain('{#if capture.extGate}');
  });

  it('asks the surface what drew the pixels, never the provider that was picked', () => {
    // an eco or soft-block fallback means the two differ, and provenance has to
    // name the imagery actually on screen
    expect(source).toContain('provenance: () => surface.provenance()');
  });

  it('shares one live outline with the grid rectangle, since one gesture draws both', () => {
    expect(source).toContain('onRect: (rect) => (selRect = rect)');
    expect(source).toContain('let selRect = $state(null);');
    // …and the grid's own drag writes the same outline
    expect(source).toContain('onChange: (rect) => (selRect = rect)');
  });

  it('cannot be armed at the same time as any other map mode', () => {
    // The marquee is armed from the Capture button rather than from the rail,
    // so it reports in to the registry instead of naming the one other mode it
    // used to know about — which left Grid Search and the sun path open.
    expect(source).toContain("onArm: () => closeOthers(modes, 'capture')");
    expect(source).toContain('capture: {');
    expect(source).toContain('close: () => capture.disarm(),');
    // …and the Measure tool, armed as a mode like the others, puts it away too
    expect(source).toContain('open: () => measure.open(),');
  });

  it('offers a figure on Sentinel-2 only, with the layers it is made of read first', () => {
    // The layer list is read when the date chip is first opened. A figure can be
    // the first thing asked of a session, and one opened before that list came
    // would say the configuration is empty.
    expect(source).toContain('openFigure={isSentinel ? openFigure : null}');
    expect(source).toContain('if (!s2.layers.length) await s2.loadLayers(true, true);');
  });

  it('gives the store the map element rather than reaching for one itself', () => {
    expect(source).toContain('element: () => mapEl');
    expect(source).toContain('function onSelectDrag(e)');
    expect(source).toContain("element.addEventListener('mousedown', onSelectDrag, true)");
    expect(source).toContain("element.removeEventListener('mousedown', onSelectDrag, true)");
  });
});

describe('what is laid over the imagery', () => {
  const surface = readFileSync(new URL('./satellite/MapSurface.svelte', import.meta.url), 'utf8');

  it('hands the surface the list, not one flag per layer', () => {
    // the surface puts overlays on; which are offered is the tool's business,
    // and a second one used to mean a second prop through the same wall
    expect(source).toContain('{overlays}');
    expect(surface).toContain(
      'for (const id of OVERLAY_IDS) basemaps.setOverlay(id, asked.has(id), asked.get(id))'
    );
  });

  it('offers the railways over any basemap and the roads only over imagery', () => {
    // OSM's own street map already draws its roads; it draws a railway as one
    // more line, which is the thing OpenRailwayMap is for
    expect(source).toContain("refLayers.roads && baseIsImagery && 'roads'");
    expect(source).toContain("railOverlay && 'railway'");
    const rows = source.slice(source.indexOf('const layerRows = $derived(['));
    expect(rows).toContain('toggle: () => (railOverlay = !railOverlay)');
  });

  it('lists its layers in the order Compare, Detect, Horizon and the proof map use', () => {
    // the plain references first, then the specialist networks, the dated
    // events, and the case last: the catalogue's order, named as it names them
    const rows = source.slice(source.indexOf('const layerRows = $derived(['), source.indexOf('...(sheetPoints'));
    const ids = [...rows.matchAll(/^ {6}\.\.\.catalogued\('([^']+)'\)/gm)].map((match) => match[1]);
    expect(ids).toEqual([
      'boundaries',
      'placenames',
      'roads',
      'railway',
      'power',
      'seamarks',
      'gpstraces',
      'firms',
      'nightlights',
      'saved',
    ]);
    expect(rows).not.toMatch(/^ {6}label: '/m);
  });

  it('gives the railways no rail seat', () => {
    expect(rail).not.toContain('railOverlay');
  });

  it('has no labels layer: its tiles now ask for a key, and Borders names places', () => {
    expect(source).not.toContain("'labels'");
    expect(source).not.toContain('OSM labels');
  });

  it('fetches no railway tile until it is asked for', () => {
    // local-first: a map that is not showing railways phones nobody
    expect(source).toContain('let railOverlay = $state(false);');
  });

  it('reads what the fire layer can be asked without phoning NASA', () => {
    // our own backend, reading a catalogue and a settings file: safe on mount
    expect(source).toContain("await api.get('/api/firms/sensors')");
    expect(source).toContain('on: false,');
  });

  it('hears about a key pasted into Settings on the way back to the tab', () => {
    // tools stay mounted, so there is no fresh onMount to read it again — and
    // a reload to see a layer light up is a reload nobody should need
    const back = source.slice(source.indexOf('// re-sync providers + prefs when returning to this tab'));
    expect(back.slice(0, 700)).toContain('loadFireSensors()');
  });

  it('offers the layer disabled, with the reason, when the key cannot be used', () => {
    const rows = source.slice(source.indexOf('const layerRows = $derived(['));
    expect(rows).toContain('disabled: !fires.keyed');
    // said on the row, where it can be read without hovering a greyed switch;
    // no key, a key switched off and a refused key each say their own thing
    // (`keyState`, tested in lib/map/firms.test.js)
    expect(rows).toContain("detail: !fires.keyed ? firmsKey.detail : onGlobe ? 'flat map only' : firmsSummary");
    expect(rows).toContain('actions: fires.keyed ? null : [{ label: firmsKey.action, quiet: true, run: openImagerySettings }]');
    expect(source).toContain('const firmsKey = $derived(keyState(fires));');
    expect(source).toContain("uiState.settingsTab = 'imagery';");
  });

  it('rests the fires while the globe draws, whose view to the horizon would spend their allowance', () => {
    const rows = source.slice(source.indexOf('const layerRows = $derived(['));
    expect(rows).toContain('disabled: !fires.keyed || onGlobe');
    expect(source).toContain('bind:onGlobe');
    expect(surface).toContain("exclude: (id) => isGround(id) || id.startsWith('basemap-firms')");
  });

  it('asks its own backend why when a fire tile fails, once for the burst', () => {
    // the map shows nothing for a failed tile, so the row would never hear
    // about a spent allowance or a refused key without this
    expect(source).toContain("onoverlaytrouble={(id) => id === 'firms' && fireTrouble()}");
    const trouble = source.slice(source.indexOf('function fireTrouble()'));
    expect(trouble.slice(0, 200)).toContain('clearTimeout(troubleTimer)');
    expect(trouble.slice(0, 200)).toContain('setTimeout(loadFireSensors');
  });

  it('says a layer is for imagery only when the basemap is not imagery', () => {
    const rows = source.slice(source.indexOf('const layerRows = $derived(['));
    // the roads and the place names, which a street map already draws
    expect(rows.match(/detail: baseIsImagery \? '' : 'imagery only'/g)).toHaveLength(2);
  });

  it('asks for no tile until the choice is one the service can answer', () => {
    // a dated window with no date yet is the normal state of a panel someone
    // just switched, not a request
    expect(source).toContain("fires.on && fires.keyed && firmsAskable && !onGlobe && { id: 'firms'");
    expect(source).toContain('const firmsAskable = $derived(askable(fires))');
  });

  it('asks its two questions in the row rather than in a card over the map', () => {
    expect(source).toContain('controls: fires.on && fires.keyed && !onGlobe ? firmsControls : null');
    expect(layerRows).toContain('{#if row.controls?.length}');
    expect(layerRows).not.toContain('position: absolute');
  });
});

describe('choosing which saved work is drawn', () => {
  it('asks the layer\'s own two questions where the layer is listed', () => {
    // the same state the Saved panel binds, so a map read here and a panel read
    // beside it cannot disagree about what the case holds
    expect(source).toContain('controls: savedOverlay && savedAnything ? savedFilters : null');
    // the kind question is the one every map's Layers menu asks (lib/geoTree.js)
    expect(source).toContain('const rows = [kindControl(savedWork)];');
    expect(source).toContain("pick: (id) => (savedWork.folder = id === 'all' ? null : id)");
  });

  it('offers the folder control only where there is a choice to make', () => {
    expect(source).toContain('if (folders.length > 1)');
  });

  it('picks folders from a list, since the analyst names them and there can be many', () => {
    expect(source).toContain('list: true');
    expect(layerRows).toContain('<LayerControls controls={row.controls} />');
    expect(controls).toContain('{#if control.list}');
    expect(controls).toContain('onchange={(event) => control.pick(event.currentTarget.value)}');
  });

  it('stacks a setting\'s options under their label rather than trailing them', () => {
    // right-aligned wrapping turned a handful of options into a staircase, one
    // per line, in a panel this narrow
    for (const sheet of [layerRows, controls]) {
      expect(sheet).not.toContain('justify-content: flex-end');
      expect(sheet).not.toContain('justify-content: space-between');
    }
  });

  it('counts what is drawn rather than what the case holds', () => {
    expect(source).toContain('detail: savedWork.shown.length ? String(savedWork.shown.length)');
  });

  it('offers the layer on either index, since media is not in the saved one', () => {
    // a case whose footage is placed and whose pins nobody dropped is exactly
    // the case the panel opens on Media for
    expect(source).toContain(
      'const savedAnything = $derived(savedWork.rows.length > 0 || savedWork.media.length > 0)'
    );
    expect(source).toContain('disabled: !savedAnything');
  });
});

describe('tracing a place\'s footprint', () => {
  it('is armed from that place\'s own card, never from the rail', () => {
    expect(source).toContain('ontrace={startTrace}');
    expect(source).toContain("closeOthers(modes, 'footprint')");
    // the registry still has to know it exists, or arming it would leave a
    // second mode waiting for the same click
    expect(source).toContain('footprint: {');
  });

  it('owns the map click while it is tracing', () => {
    expect(source).toContain('if (footprint.addPoint(at)) return;');
  });

  it('gives the panel slot the place it is tracing for', () => {
    expect(source).toContain('<FootprintPanel');
    expect(source).toContain('place={footprint.place}');
    // and whether the shape holds that place's own pin, which is what the panel
    // refuses on: a polygon traced beside the point describes somewhere else
    expect(source).toContain('covers={footprint.covers}');
  });
});

describe('the full editor, reached from the map', () => {
  // The dialog that saves a place asks for what an analyst fills at that moment;
  // everything else a place holds is edited in the panel every other surface opens,
  // so the map hands over to it rather than keeping a second copy of that form.
  const dialog = readFileSync(new URL('./satellite/PlaceDialog.svelte', import.meta.url), 'utf8');

  it('is offered from the place dialog, for a place that exists', () => {
    expect(dialog).toContain('{#if draft.id && ondetails}');
    expect(dialog).toContain('Edit more details');
    expect(source).toContain('ondetails={openPlaceDetails}');
  });

  it('asks before handing over would drop what was typed in the short form', () => {
    expect(dialog).toContain('touched ? (discarding = true) : ondetails()');
    expect(dialog).toContain('<ConfirmDialog');
  });

  it('is the same body the sidebar and the Media Library open', () => {
    expect(source).toContain("import EntityDetails from '../components/EntityDetails.svelte'");
    expect(source).toContain('entityId={detailsEntityId}');
    // its fields wait for Save, so Escape and the backdrop ask first
    expect(source).toContain('bind:dirty={detailsDirty}');
    expect(source).toContain('onclose={closeDetails}');
  });
});

describe('the two acts at the foot of the map', () => {
  it('keeps the marker behind one square rather than across the strip', () => {
    // a full-width select and a Move-pin toggle pushed Save place and Capture
    // onto a second row, which sat on the engine's own scale bracket
    expect(source).toContain('<MarkerMenu bind:style={markerStyle} free={moveMode}');
    expect(source).not.toContain("title=\"Marker style\"");
    expect(source).not.toContain('class="bar-sep"');
  });

  it('leaves the strip the two things that file something', () => {
    const acts = source.slice(source.indexOf('<MapStatusBar'), source.indexOf('</MapStatusBar>'));
    expect(acts).toContain('Save place');
    expect(acts).toContain('<CaptureOptions');
  });
});

describe('accepting a proposed point from the Saved panel', () => {
  it('offers it wherever the panel lists a row', () => {
    // the tree and the search modal read the same index, so both offer it
    expect((source.match(/onaccept=\{acceptSaved\}/g) ?? []).length).toBe(2);
  });
});

describe('Satellite — lifecycle and the date line', () => {
  it('registers a teardown Svelte will actually call', () => {
    // Svelte only honours a cleanup returned from a *synchronous* onMount, and
    // the setup awaits the providers and the saved home view.
    expect(source).toContain('onMount(() => {');
    expect(source).not.toContain('onMount(async () => {');
    expect(source).toContain('async function build()');
    expect(source).toContain('teardown?.();');
  });

  it('takes the centre as the surface hands it over, and never rewraps it', () => {
    // Folding a centre back inside ±180 across the antimeridian is stated once,
    // in lib/map (facade.test.js). A second place reaching for wrapLon would be
    // a second place that guarantee could be got wrong — and now that the map
    // is a component, the tool only ever reads the view it reports.
    const surfaces = satelliteSources();
    expect(surfaces['satellite/MapSurface.svelte']).toContain(
      "engine.on('view-settled', (settled) => {"
    );
    expect(surfaces['satellite/MapSurface.svelte']).toContain(
      'view = { lat: settled.lat, lon: settled.lon, zoom: settled.zoom };'
    );
    for (const [name, text] of Object.entries(surfaces)) {
      expect(text, name).not.toContain('wrapLon');
    }
  });

  it('builds the map in one place, so a second one costs nothing to mount', () => {
    // The engine, its basemap and everything describing the pixels are the
    // surface's; the tool mounts one today and several for Compare.
    const surfaces = satelliteSources();
    expect(surfaces['satellite/MapSurface.svelte']).toContain(
      "import { createMapEngine } from '../../lib/map/engine.js';"
    );
    expect(source).toContain("import MapSurface from './satellite/MapSurface.svelte';");
    expect(source).not.toContain('createMapEngine');
    expect(source).not.toContain('createBasemaps');
  });

  it('goes through the façade for the camera, not through the engine', () => {
    // What must never come back is a tool moving, projecting or measuring the
    // map itself: that is the whole point of `lib/map`, and it is what made
    // replacing the engine a rewrite of five modules instead of a tool.
    for (const [name, text] of Object.entries(satelliteSources())) {
      expect(text, name).not.toContain('map.setView');
      expect(text, name).not.toContain('map.getCenter');
      expect(text, name).not.toContain('map.containerPointToLatLng');
      expect(text, name).not.toContain('map.latLngToContainerPoint');
    }
  });

  it('names no engine at all, not even in a class or a comment', () => {
    // The engine's chrome is dressed in lib/map/engine.css, and a mode armed
    // above the map says so on `.map-surface`, whichever engine drew it. This
    // held across one engine change; it is what will make the next one cheap.
    for (const [name, text] of Object.entries(satelliteSources())) {
      expect(text.toLowerCase(), name).not.toContain('leaflet');
      expect(text.toLowerCase(), name).not.toContain('maplibre');
    }
  });
});

describe('Satellite — the search bar', () => {
  it('is the suggesting combobox, fed by the case and the map centre', () => {
    expect(source).toContain("import PlaceSearch from './satellite/PlaceSearch.svelte';");
    expect(source).toContain('<PlaceSearch');
    expect(source).toContain('savedRows={savedWork.rows}');
    expect(source).toContain('centre={{ lat: center.lat, lon: center.lon }}');
    expect(source).toContain('units={prefs.units}');
    // the plain form it replaces is gone, not left beside it
    expect(source).not.toContain('class="go-form"');
  });

  it('keeps the old Enter behaviour as the fallback', () => {
    // Enter with nothing highlighted still parses or geocodes the raw text
    expect(source).toContain('onsubmit={goTo}');
    expect(source).toContain("await api.get(`/api/geo/geocode?q=");
  });

  it('opens a chosen saved item the way the panel does', () => {
    // same view and bearing as the tree and the modal — one road to a saved place
    expect(source).toContain('function goToSuggestion(item)');
    expect(source).toContain('if (item.row) {\n      openSaved(item.row);');
  });

  it('flies to a proposed point at the zoom that suits what it is', () => {
    expect(source).toContain('engine.setView(item, item.zoom ?? Math.max(engine.getZoom(), 13));');
  });
});

describe('a map in more than one window', () => {
  // The pure halves are `lib/hash.js` and `lib/map/view.js`, each with its own
  // tests. What is this file's business is that the tool opens on what the
  // address says, keeps it there, and can hand it to a second window.
  it('opens on the view in the address rather than the saved home view', () => {
    expect(source).toContain("const opening = splitHash(location.hash)");
    expect(source).toContain('const openingView = readView(opening.params)');
    expect(source).toContain('openingView?.lat != null');
    expect(source).toContain('zoom: openingView.zoom ?? prefs.homeView.zoom,');
    // the surface reads where it opens once, at build, so it has to be handed
    // the same answer the tool gave `center`
    expect(source).toContain('home={opensOn}');
    expect(source).toContain('opensOn = { ...center };');
  });

  it('opens where the other map tabs left the window when the address names no view', () => {
    // the address still wins: a detached window and a reload keep their own view
    expect(source).toContain("const shared = openingView?.lat == null ? share.opening() : null;");
    expect(source).toContain(
      'center = shared ? { lat: shared.lat, lon: shared.lon, zoom: shared.zoom } : { ...openingHome };'
    );
    expect(source).toContain('if (shared) bearing = shared.bearing ?? 0;');
  });

  it('refuses a basemap the catalogue does not hold, since an address is typed', () => {
    expect(source).toContain('if (openingView?.provider && imagery.find(openingView.provider))');
  });

  it('keeps this window\'s view in this window\'s address', () => {
    expect(source).toContain("settlePlace('satellite', params);");
    // panning is not navigating: a back button full of camera positions is worse
    // than no history at all
    expect(source).not.toContain('history.pushState');
    expect(source).not.toContain('navigate: true');
  });

  it('writes nothing while another tool is open, nor while a tilted view waits for its relief', () => {
    const guard = "if (uiState.tool !== 'satellite' || !mapReady || pendingCamera || rotating) return;";
    expect(source).toContain(guard);
    expect(source.slice(source.indexOf(guard)).slice(0, 400)).toContain('viewParams({');
  });

  it('writes the address once a move, not once a degree of a turn or a tilt', () => {
    const guard = "if (uiState.tool !== 'satellite' || !mapReady || pendingCamera || rotating) return;";
    const effect = source.slice(source.indexOf(guard)).slice(0, 600);
    // the turn and the tilt as they stand when the view settles (`center`), never followed step by step
    expect(effect).toContain('const [turn, lean] = untrack(() => [bearing, pitch]);');
    expect(effect).toContain('bearing: turn,');
    expect(effect).toContain('pitch: reliefOn ? lean : null,');
    expect(effect).toContain('lat: center.lat,');
    // a dragged turn says when it ends, which writes it
    expect(source).toContain('onEnd: () => (rotating = false),');
  });

  it('opens a peer tab on the view it is showing, and says when refused', () => {
    // a tab, not a popup window: it can be torn onto the second screen and put
    // back, and it is what a browser does not refuse
    expect(source).toContain("window.open(url, '_blank')");
    expect(source).toContain('params.w = String(nextWindowNumber())');
    expect(source).toContain('params.case = caseState.current.id');
    expect(source).toContain('The browser refused a second tab');
  });

  it('greys the link until there is a second map to link to', () => {
    // a lit button that links one tab to nothing is a button that does nothing
    expect(source).toContain('disabled={!peerMaps}');
    expect(source).toContain("'Open a second map tab or the extension map tools to link the views'");
    // …and a link already on is dropped when the last peer goes
    expect(source).toContain('if (!count) linked = false;');
  });

  it('has no title row: the search floats above the rail, the window buttons beside the imagery', () => {
    // the tab strip already names the tool, and every row above the map is map lost
    expect(source).not.toContain('<div class="tool-header">');
    const bar = source.slice(source.indexOf('<div class="map-bar"'), source.indexOf('<div class="map-tools"'));
    expect(bar).toContain('<PlaceSearch');
    // the rail starts under the search, however tall it renders
    expect(source).toContain('const railTop = $derived(12 + searchHeight + 8);');
    expect(source).toContain('<div class="map-tools" style:top={`${railTop}px`}');
    const beside = source.slice(source.indexOf('{#snippet beside()}'), source.indexOf('{/snippet}', source.indexOf('{#snippet beside()}')));
    for (const label of ['Link the view to the other maps', 'Open in a new tab', 'Toggle fullscreen']) {
      expect(beside).toContain(`aria-label="${label}"`);
    }
    // on the imagery chip's right, where the corner ends
    const row = satelliteSources()['satellite/MapSurface.svelte'];
    const ctl = row.slice(row.indexOf('<div class="ctl-row">'), row.indexOf('</div>', row.indexOf('<div class="ctl-row">')));
    expect(ctl.indexOf('<ImageryChip')).toBeGreaterThan(-1);
    expect(ctl.indexOf('{@render beside()}')).toBeGreaterThan(ctl.indexOf('<ImageryChip'));
  });

  it('dates Sentinel-2 on its chip and again under it, as the radar pass is', () => {
    const surface = satelliteSources()['satellite/MapSurface.svelte'];
    const s2Pill = surface.slice(
      surface.indexOf('{#if s2 && shown.provider?.id === SENTINEL_ID}'),
      surface.indexOf('{:else if s1 && shown.provider?.id === RADAR_ID}')
    );
    // the pill reads the day the window named, and says so rather than naming a
    // pass when the tiles blend the archive
    expect(s2Pill).toContain("{renderedDay ?? (s2.undated ? 'several dates' : 'finding…')}");
    expect(s2Pill).toContain('class:exact={!!renderedDay}');
    expect(s2Pill).toContain('class:undated={!renderedDay && s2.undated}');
  });

  it('opens that tab on the map alone', () => {
    // the rail, the case bar and the tab strip are how you get somewhere else,
    // and a second screen showing one map is already somewhere (lib/hash.js)
    expect(source).toContain("params.solo = '1'");
  });

  it('numbers a detached window, and leaves the first one unnumbered', () => {
    expect(source).toContain('const windowNumber = readWindowLabel(opening.params)');
    expect(source).toContain('{#if windowNumber}<span class="window-no mono" title="This map\'s window">Map {windowNumber}</span>{/if}');
    expect(source).toContain('if (windowNumber) document.title = `Azimut · Map ${windowNumber}`');
  });

  it('keeps saying what the tab is as it rewrites where it is pointed', () => {
    // rewritten without it, the first pan would turn a detached map back into
    // the whole app on the next reload
    expect(source).toContain("if (solo) params.solo = '1';");
    expect(source).toContain('const solo = readSolo(opening.params)');
  });

  it('follows the other tabs only while the link is pressed', () => {
    expect(source).toContain('let linked = $state(false);');
    expect(source).toContain('if (!linked || !engine) return;');
    expect(source).toContain('return { lat: center.lat, lon: center.lon, zoom: center.zoom, bearing };');
    expect(source).toContain('viewLink?.send(linkedView());');
  });

  it('carries the window camera over the link while the map tabs share one', () => {
    // a pan in Compare or Detect reaches the other windows and the extension…
    expect(source).toContain('if (prefs.mapSync && uiState.mapView) return uiState.mapView;');
    // …and what arrives moves the window, so the tab on screen follows it
    expect(source).toContain("uiState.mapView = { ...view, by: 'link' };");
  });

  it('links to the extension panels on other sites as well as to its own tabs', () => {
    expect(source).toContain('relay: mapLinkRelay(),');
  });

  it('lets the channel go with the tool, so a closed map holds no listener', () => {
    expect(source).toContain('viewLink?.close();');
  });

  it('survives a profile that refuses local storage', () => {
    // the numbering is a label; losing it must not cost the window
    const counter = source.slice(source.indexOf('function nextWindowNumber()'));
    expect(counter.slice(0, 400)).toContain('} catch {');
  });
});

describe('one camera for the map tabs', () => {
  it('writes the window camera when this map comes to rest, at its own ceiling', () => {
    expect(source).toContain("const share = shareView('satellite', { state: uiState, enabled: () => prefs.mapSync });");
    expect(source).toContain('onviewsettled={(camera) => share.settled(camera, engine?.maxZoom())}');
  });

  it('takes the window camera in one jump when it shows', () => {
    const taking = source.slice(source.indexOf("if (uiState.tool !== 'satellite' || !mapReady) return;\n    untrack"));
    expect(taking.slice(0, 200)).toContain('const next = share.pending(engine.camera());');
    expect(taking.slice(0, 200)).toContain('if (next) engine.setCamera(next);');
  });
});

describe('the key-less reference layers', () => {
  it('fetches no tile from any of them until its switch is pressed, borders apart', () => {
    // local-first: a map not showing power lines asks nobody about power lines.
    // Borders are the exception and are on from the start: they are map tiles,
    // which is the network a map is opened to use.
    const state = source.slice(
      source.indexOf('const refLayers = $state({'),
      source.indexOf('const night = $state(')
    );
    expect(state).toContain('boundaries: true');
    expect(state).toContain('placenames: false');
    expect(state.replace('boundaries: true', '')).not.toContain('true');
    expect(source).toContain("const night = $state({ on: false, source: 'noaa20', day: lastNight() });");
  });

  it('asks for each by id, and the roads and the place names only over imagery', () => {
    for (const id of ['boundaries', 'power', 'seamarks', 'gpstraces']) {
      expect(source).toContain(`refLayers.${id} && '${id}'`);
    }
    // a street map already names its villages and draws its roads
    for (const id of ['roads', 'placenames']) {
      expect(source).toContain(`refLayers.${id} && baseIsImagery && '${id}'`);
      expect(source).toContain(`if (!baseIsImagery && refLayers.${id}) refLayers.${id} = false;`);
    }
  });

  it('asks GIBS for no night until the choice is one it can answer', () => {
    expect(source).toContain("night.on && nightAskable && { id: 'nightlights', params: nightParams(night) }");
    expect(source).toContain('controls: night.on ? nightControls : null');
  });

  it('warns that a dark night is not an outage by itself', () => {
    expect(source).toContain('Cloud hides lights too, so a dark night is not an outage on its own.');
  });

  it('picks one night from a calendar bounded by the sensor’s record', () => {
    expect(source).toContain('nightQuestions(night, (patch) => Object.assign(night, patch))');
    expect(questions).toContain('min: firstNight(choice.source)');
    expect(questions).toContain('max: lastNight()');
    expect(controls).toContain('{#if control.day}');
  });
});

describe('Esri Wayback', () => {
  it('reads the release list only once the basemap is on screen', () => {
    // local-first: opening the tab names no release
    expect(source).toContain('if (mapReady && shown.provider?.id === WAYBACK_ID) wb.loadReleases();');
  });

  it('reads a history only when asked, at the point the menu names', () => {
    // a moving map never starts the walk: it is dozens of requests to Esri
    expect(source).not.toMatch(/wb\.(follow|watching|here)\b/);
    expect(source).toContain('wb.historyAt({ lat: point.lat, lon: point.lon, zoom });');
  });

  it('puts the release on the id every tile and capture keys on', () => {
    expect(source).toContain('imagery.displayed(providerId, center.zoom, { ...s2.variant, release: wb.release, pass: s1.shownPass })');
    expect(source).toContain('wayback={wb}');
    // …and the radar pass beside it
    expect(source).toContain('{s1}');
  });
});

describe('the right-click menu', () => {
  it('opens on the surface’s own right-click, for the point under the cursor', () => {
    expect(source).toContain('oncontextmenu={onMapContextMenu}');
    expect(source).toContain('<MapContextMenu');
    expect(source).toContain('onpick={onPointMenu}');
  });

  it('is the first thing Escape closes', () => {
    const escape = source.slice(source.indexOf("if (e.key !== 'Escape') return;"));
    expect(escape.slice(0, 200)).toContain('if (pointMenu) return closePointMenu();');
  });

  it('closes when the view moves out from under it', () => {
    expect(source).toContain("return engine.on('view-settled', closePointMenu);");
  });

  it('hands each act the clicked point rather than the map centre', () => {
    const acts = source.slice(source.indexOf('async function onPointMenu(id, value)'));
    const body = acts.slice(0, acts.indexOf('async function lookUpPoint'));
    expect(body).toContain('openNewPlaceAt(point)');
    expect(body).toContain('measure.addPoint(point)');
    expect(body).toContain('sky.handOff({ ...point');
    expect(body).toContain('engine.setView(point');
    expect(body).not.toContain('displayCoords');
  });

  it('offers its own subset of acts, and opens the point in Compare or Detect', () => {
    // while a layer is edited the rail is put away, and with it the acts that arm one of its tools
    expect(source).toContain("actionsFor(myLayers.editor ? ['lookup', 'place', 'horizon', 'history', 'centre']\n    : ['lookup', 'place', 'measure', 'sky', 'horizon', 'history', 'centre'])");
    expect(source).toContain("otherMapTools('satellite')");
    expect(source).toContain('tools={pointTools}');
    const acts = source.slice(source.indexOf('async function onPointMenu(id, value)'));
    const body = acts.slice(0, acts.indexOf('async function comparePoint'));
    expect(body).toContain("openMapAt(value, { ...point, zoom: center.zoom })");
    // Look from here hands the eye the way up the turned map, the bearing counted the other way
    expect(body).toContain('lookFrom({ ...point, heading: headingUp(bearing) })');
  });

  it('drops a lookup answer that arrives after the menu moved on', () => {
    const lookup = source.slice(source.indexOf('async function lookUpPoint(point)'));
    expect(lookup.slice(0, 600)).toContain('if (mine !== pointLookupSeq || !pointMenu) return;');
  });
});

describe('Satellite offers what is open to the Add event bar', () => {
  it('publishes under its own tool id and withdraws on unmount', () => {
    expect(source).toMatch(/offerNote\(\s*'satellite',/);
    expect(source).toContain("onDestroy(() => withdrawNote('satellite'))");
  });
});

describe('the Measure tool on the map', () => {
  it('puts a click on what is there, unless Alt is held', () => {
    expect(source).toContain('if (measure.on) measure.addPoint(measure.snap(at, { free: altHeld }).point);');
    expect(source).toContain("if (e.key === 'Alt') altHeld = true;");
    expect(source).toContain("if (e.type === 'blur' || e.key === 'Alt') altHeld = false;");
  });

  it('takes a point back on Backspace and the measure off on Delete, never while typing', () => {
    expect(source).toContain("if (!typing && measure.on && (e.key === 'Backspace' || e.key === 'Delete')) {");
    expect(source).toContain("(e.key === 'Backspace' && measure.undo()) || measure.removeSelected()");
  });

  it('finishes and lets go of a measure on Escape before the tool itself closes', () => {
    const escape = source.slice(source.indexOf("if (e.key !== 'Escape') return;"));
    expect(escape.indexOf('measure.escape()')).toBeGreaterThan(0);
    expect(escape.indexOf('measure.escape()')).toBeLessThan(escape.indexOf('return disarm(modes)'));
  });

  it('keeps the flat map from zooming on the double click that ends a measure', () => {
    expect(source).toContain("window.addEventListener('dblclick', swallow, true);");
    expect(source).toContain('if (!measure.on || !mapEl) return;');
  });

  it('reads its ground in 3D, where the relief is read anyway, and on its own switch on the flat map', () => {
    expect(source).toContain('relief: () => reliefOn,');
  });
});