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
16.8 KB
Raw Blame
<script>
  import Icon from '../../components/Icon.svelte';
  import CustomLayerForm from '../../components/CustomLayerForm.svelte';
  import { api } from '../../lib/api.js';
  import { toast } from '../../lib/state.svelte.js';
  import {
    clearPreview,
    dataSources,
    previewLayer,
    readCustomLayers,
    saveCustomLayer,
    startForm,
  } from '../../lib/customLayers.js';

  /** `s2` is the store from `state/sentinel.svelte.js`: what has been asked,
   *  what came back, and what is still in flight. The label helpers are pure
   *  (`lib/sentinel.js`) and are handed over so this stays a view. */
  let {
    menuEl = $bindable(),
    s2,
    maxccLabel,
    monthLabel,
    monthGrid,
    cloudClass,
    cloudLabel,
  } = $props();

  // What the tiles are dated: the pinned pass, or the one "most recent" resolved
  // to. Blank only while that lookup is out, or where no pass came back at all.
  const chipDate = $derived(s2.day);

  // The readout tracks the drag; the ceiling only moves on release. Every step
  // in between would be a provider id of its own, and Sentinel-2 tiles are
  // billed — you pay for the number you stopped on, not the ones you passed.
  let dragging = $state(null);
  const shown = $derived(dragging ?? s2.maxcc);

  /**
   * Writing a layer happens here rather than only in Settings because a script
   * is judged on pixels: Preview renders it on this very map, over the date and
   * the ceiling already chosen, before anything is saved. Settings keeps the
   * list; this is where one is made. Both use the same form.
   *
   * **The draft outlives the panel.** Previewing is the reason to close the
   * form — you close it to look at the map — so closing it must not throw away
   * what was typed. The draft is held here until it is saved or discarded, and
   * reopening the panel hands the same one back.
   */
  let open = $state(false); // is the form showing
  let held = $state(null); // the draft, kept while the form is closed
  let writingBusy = $state(false);
  let writingNote = $state('');
  let mine = $state([]); // the saved scripts, read when the form opens
  let scriptMax = $state(4000);
  let bands = $state([]);
  let radarLayer = $state('');
  let before = ''; // the layer to come back to if nothing is kept

  // A script reads the data of a layer the configuration serves — never another
  // script, and never the radar layer, through which Sentinel-2 bands render
  // nothing at all.
  const bases = $derived(dataSources(s2.layers, radarLayer));
  const resuming = $derived(!!held && !held.editing);

  async function openWriting(ident) {
    try {
      const found = await readCustomLayers(api);
      mine = found.layers;
      scriptMax = found.scriptMax;
      bands = found.bands;
      radarLayer = found.radarLayer;
    } catch (error) {
      toast(`Could not read your layers: ${error.message}`, 'danger');
      return;
    }
    // The draft already in hand is handed back, unless this press is about a
    // different layer — then it is that layer's turn and the old draft is gone.
    if (!held || held.editing !== ident) {
      held = startForm({
        layer: ident ? mine.find((row) => row.id === ident) ?? null : null,
        bases: dataSources(s2.layers, radarLayer),
        bands,
        radarLayer,
      });
      writingNote = '';
    }
    before = s2.draft ? before : s2.layer;
    open = true;
  }

  async function preview(draft) {
    writingBusy = true;
    try {
      s2.layer = await previewLayer(api, draft);
      writingNote = 'Drawn on the map. Nothing is saved yet.';
    } catch (error) {
      writingNote = '';
      toast(error.message, 'danger');
    } finally {
      writingBusy = false;
    }
  }

  async function keep(draft) {
    writingBusy = true;
    try {
      const saved = await saveCustomLayer(api, draft);
      await clearPreview(api).catch(() => {});
      s2.rememberLayer(saved);
      s2.layer = saved.id;
      open = false;
      held = null;
      writingNote = '';
      toast(`${draft.id} saved`, 'ok');
    } catch (error) {
      toast(error.message, 'danger');
    } finally {
      writingBusy = false;
    }
  }

  /** Put the form away, keeping the draft and the preview on the map. */
  function setAside() {
    open = false;
  }

  async function discard() {
    open = false;
    held = null;
    writingNote = '';
    // A preview is a layer only this machine knows; dropping the draft forgets
    // it and the map goes back to what was on it.
    if (before) s2.layer = before;
    await clearPreview(api).catch(() => {});
  }
</script>

<div class="s2-wrap" bind:this={menuEl}>
  <!-- Opened from a dated chip, as the Wayback and Sentinel-1 pickers are: the
       date is what you look for, and a layers icon hid it behind a click. -->
  <button
    class="chip"
    class:on={s2.menuOpen}
    onclick={s2.toggleMenu}
    title={s2.date ? `Sentinel-2 pass of ${s2.date}` : 'Sentinel-2 layer and date'}
    aria-label="Sentinel-2 layer and date"
    aria-expanded={s2.menuOpen}
  >
    <Icon name="clock" size={13} />
    <span class="mono">{chipDate || 'Most recent'}</span>
  </button>
  {#if s2.menuOpen}
    <div class="s2-menu card" class:writing={open}>
      <div class="menu-row">
        <span class="menu-label">Layer</span>
        <select class="select" aria-label="Sentinel-2 layer" title="What the pass is drawn as: true colour, false colour, a band combination or a layer of yours"
          bind:value={s2.layer} disabled={open}>
          {#each s2.layers as entry (entry.id)}
            <option value={entry.id}>{entry.label}</option>
          {/each}
          {#if s2.draft}
            <option value={s2.layer}>Draft (not saved)</option>
          {/if}
        </select>
      </div>
      {#if s2.layerHint}<div class="menu-hint">{s2.layerHint}</div>{/if}

      {#if !open}
        <div class="menu-hint dim write-row">
          <button class="linkish" onclick={() => openWriting('')}>
            {resuming ? 'Keep writing…' : 'Write a layer…'}
          </button>
          {#if s2.layers.some((entry) => entry.custom && entry.id === s2.layer)}
            <button class="linkish" onclick={() => openWriting(s2.layer)}>Edit this one</button>
          {/if}
          {#if resuming}
            <button class="linkish dismiss" onclick={discard} title="Throw the draft away">
              Discard
            </button>
          {/if}
        </div>
      {:else}
        <CustomLayerForm
          form={held}
          {bases}
          {bands}
          taken={s2.layers
            .filter((entry) => !entry.custom && entry.id !== held.editing)
            .map((entry) => entry.id)}
          {scriptMax}
          busy={writingBusy}
          note={writingNote}
          onpreview={preview}
          onsave={keep}
          oncancel={setAside}
        />
      {/if}
      <!-- Silent when the layers are the configured ones, which is the normal
           case and was a line of panel saying so on every open. -->
      {#if s2.layersSource !== 'instance'}
        <div class="menu-hint dim">
          Could not read your configuration; these are the standard layers.
          <button class="linkish" onclick={() => s2.loadLayers(true)}>Refresh</button>
        </div>
      {/if}

      <div class="menu-sep" aria-hidden="true"></div>

      <div class="menu-row">
        <span class="menu-label">Cloud</span>
        <div class="cc">
          <input
            type="range"
            min="0"
            max="100"
            step="5"
            value={shown}
            oninput={(e) => (dragging = Number(e.currentTarget.value))}
            onchange={(e) => {
              dragging = null;
              s2.setMaxcc(Number(e.currentTarget.value));
            }}
            aria-label="Maximum cloud cover"
            title="Passes cloudier than this drop out of the calendar and the tiles"
          />
          <span class="cc-value mono">{maxccLabel(shown)}</span>
        </div>
      </div>
      <div class="menu-hint dim">Cloudier passes drop out of the calendar.</div>

      <div class="menu-sep" aria-hidden="true"></div>

      <div class="menu-row">
        <span class="menu-label">Date</span>
        <div class="chips">
          <button
            class="chip-opt"
            class:on={!s2.date}
            onclick={s2.clearDate}
            title={s2.undated
              ? 'No pass could be dated here; the tiles blend several dates'
              : 'Show the newest pass over the crosshair'}
          >Most recent{#if !s2.date && s2.latest}<span class="opt-day mono">{s2.latest}</span>{/if}</button>
        </div>
      </div>

      <div class="cal">
        <div class="cal-head">
          <button class="cal-nav" onclick={() => s2.stepMonth(-1)} aria-label="Previous month" title="Previous month">
            <Icon name="chevronLeft" size={13} />
          </button>
          <span class="cal-month">{monthLabel(s2.month)}</span>
          <button class="cal-nav" onclick={() => s2.stepMonth(1)} aria-label="Next month" title="Next month">
            <Icon name="chevronRight" size={13} />
          </button>
        </div>
        <div class="cal-grid" class:busy={s2.passesBusy}>
          {#each ['M', 'T', 'W', 'T', 'F', 'S', 'S'] as entry, index (index)}
            <span class="cal-dow" aria-hidden="true">{entry}</span>
          {/each}
          {#each monthGrid(s2.month) as day, index (day ?? `pad${index}`)}
            {#if !day}
              <span class="cal-pad" aria-hidden="true"></span>
            {:else}
              {@const pass = s2.passes[day]}
              {@const status = s2.dateStatus(day)}
              {@const overCeiling = s2.filtered(day)}
              {@const unavailable = status === false || overCeiling}
              {@const verifying = s2.verifyingDate === day}
              <button
                class="cal-day {pass ? cloudClass(pass.cloud) : ''}"
                class:has={!!pass}
                class:on={s2.date === day}
                class:showing={!s2.date && s2.latest === day}
                class:unavailable
                class:verifying
                disabled={s2.date !== day &&
                  (!pass || s2.stale || s2.passesBusy || unavailable || !!s2.verifyingDate)}
                onclick={() => s2.pickDate(day)}
                title={overCeiling
                  ? `${day}: ${cloudLabel(pass.cloud)}, over the ${s2.maxcc}% ceiling`
                  : unavailable
                    ? `No imagery at the crosshair on ${day}`
                    : verifying
                      ? `Checking imagery for ${day}`
                      : s2.stale
                        ? `Refreshing dates for this location`
                        : pass
                          ? `${day}: ${cloudLabel(pass.cloud) || 'cloud cover unknown'}`
                          : `${day}: no Sentinel-2 pass`}
              >{Number(day.slice(8))}</button>
            {/if}
          {/each}
        </div>
      </div>

      {#if s2.passesBusy}
        <div class="menu-hint dim">Reading this month's passes…</div>
      {:else if s2.passesNote}
        <div class="menu-hint warn">{s2.passesNote}</div>
      {:else if s2.stale}
        <div class="menu-hint">
          <span class="warn">Refreshing dates for this location.</span>
          <button class="linkish" onclick={() => s2.loadPasses(true)}>Refresh</button>
        </div>
      {:else}
        <div class="menu-hint dim">Each date is checked at the crosshair first.</div>
      {/if}
    </div>
  {/if}
</div>

<style>
  .s2-wrap { position: relative; display: flex; }
  /* the same trigger as the Wayback picker, so one date reads like the other */
  .chip {
    display: flex;
    align-items: center;
    gap: 6px;
    height: 30px;
    padding: 0 8px;
    border-radius: var(--radius-1);
    font-size: var(--fs-xs);
    color: var(--text-1);
    background: rgba(24, 24, 24, 0.88);
    backdrop-filter: blur(6px);
    box-shadow: 0 0 0 1px var(--border);
    cursor: pointer;
  }
  .chip:hover,
  .chip.on { color: var(--accent); }
  /* Down and to the left of its button, because the picker now rides in the
     surface's own top-right corner: opening upwards put a calendar off the top
     of the map, where the surface clips it. The height is capped for the same
     reason at the other end — a month of passes must not run off the bottom. */
  .s2-menu {
    position: absolute;
    top: calc(100% + 8px);
    right: 0;
    /* Stated rather than grown: at `max-content` the hint lines set the width,
       the calendar then stretched to fill it, and a month of 40px cells is a
       date picker the size of the thing it is picking on. */
    width: 246px;
    max-height: 70vh;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: 3px;
    padding: 10px;
    background: rgba(24, 24, 24, 0.96);
    backdrop-filter: blur(6px);
    box-shadow: var(--shadow-2);
    z-index: 700;
  }
  /* A script needs room to be read; a date picker does not. The menu widens
     only while one is open, and never past the viewport on a narrow screen. */
  .s2-menu.writing { width: min(620px, calc(100vw - 32px)); }
  .s2-menu .select { max-width: 150px; padding: 4px 6px; font-size: var(--fs-xs); }
  .write-row { display: flex; gap: 10px; }
  .write-row .dismiss { margin-left: auto; color: var(--text-3); }
  .menu-row { display: flex; align-items: center; gap: 10px; justify-content: space-between; }
  .menu-label { font-size: var(--fs-xs); color: var(--text-3); font-weight: 600; }
  .chips { display: flex; gap: 4px; flex-wrap: wrap; justify-content: flex-end; }
  .chip-opt {
    padding: 4px 9px;
    border-radius: var(--r-sm);
    border: 1px solid var(--border);
    background: var(--bg-2);
    color: var(--text-2);
    font-size: var(--fs-xs);
    white-space: nowrap;
    cursor: pointer;
    transition: border-color 0.12s, color 0.12s, background 0.12s;
  }
  .chip-opt:hover { color: var(--text-1); border-color: var(--border-strong); }
  .chip-opt.on { border-color: var(--accent); background: var(--accent-soft); color: var(--accent); }
  .cc { display: flex; align-items: center; gap: 6px; }
  .cc input[type='range'] { width: 96px; accent-color: var(--accent); cursor: pointer; }
  .cc-value { font-size: 10px; color: var(--text-2); min-width: 52px; text-align: right; }
  .menu-hint { font-size: 10px; line-height: 1.35; color: var(--text-3); margin: -1px 0 4px; }
  .menu-hint.dim { opacity: 0.75; }
  .menu-hint .warn, .menu-hint.warn { color: var(--warn, #e2a03f); }
  .menu-sep { height: 1px; background: var(--border); margin: 3px 0 5px; }
  .linkish {
    background: none;
    border: 0;
    padding: 0;
    color: var(--accent);
    font-size: 10px;
    cursor: pointer;
    text-decoration: underline;
  }
  .cal { display: flex; flex-direction: column; gap: 4px; margin: 1px 0 5px; }
  .cal-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
  .cal-month { font-size: var(--fs-xs); font-weight: 600; color: var(--text-1); }
  .cal-nav {
    display: flex;
    padding: 2px 4px;
    border: 1px solid var(--border);
    border-radius: var(--r-sm);
    background: var(--bg-2);
    color: var(--text-2);
    cursor: pointer;
  }
  .cal-nav:hover { color: var(--text-1); border-color: var(--text-3); }
  .cal-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 2px; }
  .cal-grid.busy { opacity: 0.5; pointer-events: none; }
  .cal-dow { text-align: center; font-size: 9px; color: var(--text-3); padding-bottom: 1px; }
  .opt-day { margin-left: 6px; font-size: var(--fs-xs); opacity: 0.7; }
  .cal-day {
    /* a square cell grew with the panel; a stated height keeps the month the
       size of a month whatever else is in here */
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid transparent;
    border-radius: var(--r-sm);
    background: transparent;
    color: var(--text-3);
    font-size: 10px;
    font-family: var(--font-mono);
    cursor: pointer;
  }
  .cal-day:disabled { opacity: 0.28; cursor: default; }
  .cal-day.has { color: var(--text-1); background: var(--bg-2); border-color: var(--border); }
  .cal-day.clear { border-color: color-mix(in srgb, var(--ok, #46a758) 65%, transparent); color: var(--ok, #46a758); }
  .cal-day.part { border-color: color-mix(in srgb, var(--warn, #e2a03f) 55%, transparent); color: var(--warn, #e2a03f); }
  .cal-day.cloudy, .cal-day.unknown { border-color: var(--border); color: var(--text-2); }
  .cal-day.unavailable { text-decoration: line-through; }
  .cal-day.verifying { opacity: 0.55; animation: pulse 0.8s ease-in-out infinite alternate; }
  .cal-day.has:hover { border-color: var(--text-1); }
  .cal-day.on { background: var(--accent); border-color: var(--accent); color: var(--accent-text); font-weight: 700; }
  /* the pass "most recent" resolved to: being rendered, but not chosen */
  .cal-day.showing { box-shadow: inset 0 0 0 1px var(--accent); font-weight: 700; }
  @keyframes pulse { to { opacity: 1; } }
</style>