GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / cosmic / tools/explore/theme

Ide

A JavaScript file in the theme folder of Cosmic that opens map (`openMap`), converts to code (`toCode`) and renders facts (`renderFacts`).

556 lines of JavaScript from cosmic, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1142 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Ide interaction · cosmic / tools/explore/theme/ide.js lines 1–556

Ide

A JavaScript file in the theme folder of Cosmic that opens map (`openMap`), converts to code (`toCode`) and renders facts (`renderFacts`).

interactioncosmic / tools/explore/theme/ide.js · lines 1–556 of 556 · Not reached from any entry point (candidate for review) · pattern palette (shared by 3 files)

What it does
It draws its content. Defines 41 functions or classes, including el, txt, ddFor, fileId, mapURL. Side effects: changes the web page (DOM); makes network requests; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
README: "Section pages (`s/*.html`) also get `ide.css`/`ide.js`, which bonus B (HOTBAR-36) owns."
Inputs & outputs
In: JSON file graph.json; browser storage (getItem). Out: browser storage (setItem); canvas drawing.
What it achieves
It maps URL (`mapURL`), opens map (`openMap`) and copies lines text (`copyLinesText`). Explore Code IDE layer (HOTBAR-36). Progressive enhancement for section pages (`s/NNNN.html`). It reads `../visual/graph.json`. It responds to scroll, click and keydown events.
Why it matters
No other file in the estate was found to import it.
Application
cosmic · tools/explore/theme · script
Uses
none found
Used by
none found
Produces
el, txt, ddFor, fileId, mapURL, openMap, pilotURL, copy, done, fallback, copyLinesText, btn
Defines here
el, txt, ddFor, fileId, mapURL, openMap, pilotURL, copy, done, fallback, copyLinesText, btn, toCode, cloneLinks, renderFacts, buildMiniRows, drawMini, updateMiniVP, scrollToLine, flashLine, setCur, go, bump, visited, showMapPanel, closeMap, setModeButtons, fillSlot, hudSize, setMode
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/theme/ide.js:1-556 · blob 81b4c6bb87d53c935e68b35117eff55b69995673 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, network, storage · domain stage: unknown · users: none · canonical: unreached_review
/* Explore Code IDE layer (HOTBAR-36). Progressive enhancement for section pages (s/NNNN.html).
   Vanilla JS, no network libraries, no CDN. With JS off the page is untouched: this script only ADDS
   UI elements (marked data-ide) and classes on <body>; it never edits page text, links or keys.
   Data comes only from the page itself, plus two optional lazy fetches of files the site already
   publishes: ../visual/graph.json (section+block -> file id, for "Show in map") and ../index.html
   (topic list for the command palette). Look: Solar Design Studio / Energy Transition Simulator HUD. */
(function () {
  'use strict';
  if (window.__exploreIDE) return;
  var D = document, W = window;
  var files = Array.prototype.slice.call(D.querySelectorAll('main > section.file[id]'));
  if (!files.length || !D.querySelector('nav a[rel]')) return;
  W.__exploreIDE = true;

  var REDUCED = W.matchMedia && W.matchMedia('(prefers-reduced-motion: reduce)').matches;
  var BEHAV = REDUCED ? 'auto' : 'smooth';
  var MODES = ['read', 'map', 'pilot', 'clarity'];
  var store = { get: function (k, d) { try { var v = localStorage.getItem('ec-ide:' + k); return v == null ? d : v; } catch (e) { return d; } },
                set: function (k, v) { try { localStorage.setItem('ec-ide:' + k, v); } catch (e) {} } };

  function el(tag, attrs, kids) {
    var n = D.createElement(tag);
    if (attrs) Object.keys(attrs).forEach(function (k) {
      if (k === 'text') n.textContent = attrs[k];
      else if (k === 'on') Object.keys(attrs.on).forEach(function (ev) { n.addEventListener(ev, attrs.on[ev]); });
      else n.setAttribute(k, attrs[k]);
    });
    (kids || []).forEach(function (c) { if (c) n.appendChild(typeof c === 'string' ? D.createTextNode(c) : c); });
    return n;
  }
  function txt(n) { return n ? n.textContent.replace(/\s+/g, ' ').trim() : ''; }
  function ddFor(sec, label) {
    var dts = sec.querySelectorAll('dl dt');
    for (var i = 0; i < dts.length; i++) if (txt(dts[i]) === label) return dts[i].nextElementSibling;
    return null;
  }

  // ------------------------------------------------------------------ read the page
  var prevA = D.querySelector('nav a[rel=prev]'), nextA = D.querySelector('nav a[rel=next]');
  var secMatch = /Section (\d+) of (\d+)/.exec(txt(D.querySelector('header')));
  var SEC = secMatch ? +secMatch[1] : +(location.pathname.match(/(\d+)\.html$/) || [0, 0])[1];
  var SECS = secMatch ? +secMatch[2] : 0;
  var crumbs = Array.prototype.slice.call(D.querySelectorAll('header .crumbs a'));
  var topicA = crumbs.filter(function (a) { return /topics\//.test(a.getAttribute('href')); })[0];

  var F = files.map(function (sec, i) {
    var role = ((sec.className.match(/\br-([a-z-]+)/) || [])[1]) || 'other';
    var k = sec.querySelector(':scope > p.k');
    var kt = txt(k);
    var lm = /lines (\d+)\D(\d+)(?: of (\d+))?/.exec(kt);
    var ev = txt(ddFor(sec, 'Evidence'));
    var em = /^(\S+)@([0-9a-f]{40}) (.+):(\d+)-(\d+) · blob ([0-9a-f]{40}|-)/.exec(ev);
    var key = em ? em[1] + '@' + em[2] + ' ' + em[3] + ':' + em[4] + '-' + em[5] + ' ' + em[6] : '';
    var path = em ? em[3] : (kt.split(' · ')[0] || '');
    var badge = sec.querySelector('.badge');
    var colour = badge ? getComputedStyle(badge).backgroundColor : '#4c5a65';
    var state = txt(ddFor(sec, 'State'));
    var unreached = !!sec.querySelector('.flag') && /Not reached/.test(txt(sec.querySelector('.flag')));
    var dup = /canonical: (duplicate|superseded|copy)/.test(state);
    var code = sec.querySelector('pre > code') || sec.querySelector('pre');
    return {
      i: i, sec: sec, id: sec.id, block: +(sec.id.replace(/\D/g, '')) || i + 1,
      title: txt(sec.querySelector('h2')), syn: txt(sec.querySelector(':scope > p.syn')),
      role: role, colour: colour, key: key, repo: em ? em[1] : '', path: path,
      first: lm ? +lm[1] : 1, last: lm ? +lm[2] : 0, total: lm && lm[3] ? +lm[3] : 0,
      uses: ddFor(sec, 'Uses'), usedBy: ddFor(sec, 'Used by'), gh: (ddFor(sec, 'Evidence') || sec).querySelector('a[href*="github.com"]'),
      code: code, pre: code ? code.closest('pre') || code : null,
      aside: unreached ? 'not reached from any entry point' : dup ? 'duplicate candidate' : '',
      fid: sec.getAttribute('data-fid')
    };
  });
  var cur = 0;
  var hashIdx = F.findIndex(function (f) { return '#' + f.id === location.hash; });
  if (hashIdx >= 0) cur = hashIdx;

  // ------------------------------------------------------------------ file id (for the visualiser)
  var graphP = null;
  function fileId(f) {
    if (f.fid != null && f.fid !== '') return Promise.resolve(+f.fid);
    if (!graphP) graphP = fetch('../visual/graph.json').then(function (r) { if (!r.ok) throw 0; return r.json(); })
      .then(function (g) { var m = {}; g.n.sec.forEach(function (s, j) { m[s + ':' + g.n.blk[j]] = j; }); return m; })
      .catch(function () { graphP = null; return null; });
    return graphP.then(function (m) { return m && m[SEC + ':' + f.block] != null ? m[SEC + ':' + f.block] : null; });
  }
  function mapURL(id) { return '../visual/' + (id != null ? '#file=' + id : ''); }
  function openMap(f, inPanel) {
    fileId(f).then(function (id) {
      if (inPanel && W.innerWidth >= 1200) showMapPanel(mapURL(id), f);
      else location.href = mapURL(id);
    });
  }
  function pilotURL(f) { return '../pilot/index.html#sec=' + SEC + '&block=' + f.block; }

  // ------------------------------------------------------------------ copy
  function copy(text, btn) {
    function done(ok) { if (!btn) return; var t = btn.textContent; btn.textContent = ok ? 'Copied' : 'Copy failed'; btn.classList.add('ide-flash'); setTimeout(function () { btn.textContent = t; btn.classList.remove('ide-flash'); }, 1200); }
    if (navigator.clipboard && W.isSecureContext) navigator.clipboard.writeText(text).then(function () { done(true); }, function () { done(fallback()); });
    else done(fallback());
    function fallback() {
      var ta = el('textarea', { 'aria-hidden': 'true', style: 'position:fixed;top:0;left:0;opacity:0;width:1px;height:1px' }); ta.value = text;
      D.body.appendChild(ta); ta.select(); var ok = false; try { ok = D.execCommand('copy'); } catch (e) {} ta.remove(); return ok;
    }
  }
  function copyLinesText(f) {
    if (!f.code) return '';
    var lines = f.code.textContent.split('\n');
    return lines.map(function (l, j) { return (f.first + j) + '\t' + l; }).join('\n');
  }

  // ------------------------------------------------------------------ build the chrome
  var body = D.body;
  body.classList.add('ide');
  var mode = store.get('mode', 'read'); if (MODES.indexOf(mode) < 0 || mode === 'pilot' || mode === 'map') mode = 'read';

  function btn(label, title, fn, cls) { return el('button', { type: 'button', class: 'ide-btn' + (cls ? ' ' + cls : ''), title: title, 'aria-label': title, on: { click: fn } }, [label]); }

  // Gutter with line numbers beside every <pre>, aria-hidden so readers and copy are unaffected.
  F.forEach(function (f) {
    if (!f.pre) return;
    var n = f.code.textContent.replace(/\n$/, '').split('\n').length;
    var wrap = el('div', { class: 'ide-codewrap', 'data-ide': '' });
    var gut = el('div', { class: 'ide-gutter', 'aria-hidden': 'true', 'data-ide': '' });
    var s = []; for (var j = 0; j < n; j++) s.push(f.first + j);
    gut.textContent = s.join('\n');
    f.pre.parentNode.insertBefore(wrap, f.pre);
    wrap.appendChild(gut); wrap.appendChild(f.pre);
    f.wrap = wrap; f.gut = gut; f.nlines = n;
    // keep the gutter aligned when the code scrolls inside itself (phones cap the pre height)
    f.pre.addEventListener('scroll', function () { gut.scrollTop = f.pre.scrollTop; }, { passive: true });
    // sticky per-file head showing the key
    var head = el('div', { class: 'ide-head', 'data-ide': '' }, [
      el('span', { class: 'ide-dot', style: 'background:' + f.colour, 'aria-hidden': 'true' }),
      el('span', { class: 'ide-headkey', title: f.key || f.path, text: f.key || f.path }),
      btn('Copy key', 'Copy the file key', function (e) { copy(f.key || f.path, e.currentTarget); }),
      btn('Copy lines', 'Copy these lines with line numbers', function (e) { copy(copyLinesText(f), e.currentTarget); }),
      btn('Show in map', 'Show this file in the visualiser (v)', function () { openMap(f, true); })
    ]);
    wrap.insertBefore(head, gut);
    // phone card: compact facts above the code
    var card = el('div', { class: 'ide-card', 'data-ide': '' }, [
      el('span', { class: 'ide-role', style: 'border-color:' + f.colour + ';color:' + f.colour, text: f.role }),
      el('span', { class: 'ide-cardt', text: 'File ' + (f.i + 1) + ' of ' + F.length + ' · lines ' + f.first + '–' + (f.last || f.first + n - 1) }),
      f.aside ? el('span', { class: 'ide-aside', text: 'Clarity: ' + f.aside }) : null
    ]);
    f.sec.insertBefore(card, f.sec.querySelector(':scope > p.syn') || f.wrap);
    // clarity fold
    if (f.aside) {
      var chip = el('button', { type: 'button', class: 'ide-fold', 'data-ide': '', on: { click: function () { f.sec.classList.toggle('ide-open'); } } },
        ['Set aside in Clarity mode (' + f.aside + '). Show anyway']);
      f.sec.insertBefore(chip, f.wrap);
      f.sec.classList.add('ide-asideable');
    }
  });

  // Left rail
  var rail = el('aside', { id: 'ide-rail', class: 'ide-panel', 'data-ide': '', 'aria-label': 'Files in this section' });
  var modeBar = el('div', { class: 'ide-modes', role: 'group', 'aria-label': 'Mode' });
  var MODE_LABEL = { read: 'Read', map: 'Map', pilot: 'Pilot', clarity: 'Clarity' };
  MODES.forEach(function (m) {
    modeBar.appendChild(el('button', { type: 'button', class: 'ide-mode', 'data-mode': m, 'aria-pressed': 'false', title: MODE_LABEL[m] + ' mode (' + (MODES.indexOf(m) + 1) + ')', on: { click: function () { setMode(m); } } }, [MODE_LABEL[m]]));
  });
  var lvl = el('div', { class: 'ide-level' }, [
    el('span', { class: 'ide-lvl', text: 'SEC ' + SEC + (SECS ? ' / ' + SECS : '') }),
    el('span', { class: 'ide-xp', 'aria-hidden': 'true' }, [el('i', { style: 'width:' + (SECS ? (100 * SEC / SECS).toFixed(1) : 0) + '%' })])
  ]);
  var list = el('ol', { class: 'ide-files' });
  F.forEach(function (f) {
    var a = el('a', { href: '#' + f.id, 'data-i': f.i, on: { click: function (e) { e.preventDefault(); go(f.i, true); } } }, [
      el('span', { class: 'ide-dot', style: 'background:' + f.colour, 'aria-hidden': 'true' }),
      el('span', { class: 'ide-fn', text: f.title }),
      el('span', { class: 'ide-ln', text: f.nlines ? String(f.nlines) : '' })
    ]);
    if (f.aside) a.classList.add('ide-dim');
    f.railA = a;
    list.appendChild(el('li', null, [a]));
  });
  var secNav = el('div', { class: 'ide-secnav' }, [
    prevA ? el('a', { href: prevA.getAttribute('href'), class: 'ide-btn', title: 'Previous section ([)' }, ['[ ' + txt(prevA).replace('← ', '')]) : null,
    nextA ? el('a', { href: nextA.getAttribute('href'), class: 'ide-btn', title: 'Next section (])' }, [txt(nextA).replace(' →', '') + ' ]']) : null
  ]);
  var trailBox = el('div', { class: 'ide-trail', 'aria-label': 'Trail' });
  rail.appendChild(modeBar); rail.appendChild(lvl);
  rail.appendChild(el('p', { class: 'ide-cap', text: 'FILES · j / k' })); rail.appendChild(list);
  rail.appendChild(el('p', { class: 'ide-cap', text: 'SECTIONS · [ / ]' })); rail.appendChild(secNav);
  if (topicA) rail.appendChild(el('a', { class: 'ide-topic', href: topicA.getAttribute('href') }, [txt(topicA)]));
  rail.appendChild(el('p', { class: 'ide-cap', text: 'TRAIL · Back returns' })); rail.appendChild(trailBox);
  rail.appendChild(el('p', { class: 'ide-hint' }, ['Press ', el('kbd', { text: '?' }), ' for keys, ', el('kbd', { text: 'Ctrl K' }), ' for commands']));

  // Right facts panel
  var facts = el('aside', { id: 'ide-facts', class: 'ide-panel', 'data-ide': '', 'aria-label': 'Facts about the current file', 'aria-live': 'polite' });
  var mini = el('canvas', { id: 'ide-mini', width: '280', height: '200', 'aria-label': 'Minimap of the section code coloured by role. Click to jump.', role: 'img' });
  var miniWrap = el('div', { class: 'ide-miniwrap' }, [mini, el('div', { class: 'ide-minivp', 'aria-hidden': 'true' })]);

  // Top bar (sticky, centre): current file + key
  var top = el('div', { id: 'ide-top', 'data-ide': '' });
  // Bottom bar (phones and tablets)
  var bar = el('div', { id: 'ide-bar', 'data-ide': '', role: 'navigation', 'aria-label': 'File and section controls' }, [
    prevA ? el('a', { href: prevA.getAttribute('href'), class: 'ide-bb', 'aria-label': 'Previous section' }, ['« Sec']) : el('span', { class: 'ide-bb ide-off' }, ['« Sec']),
    btn('‹ File', 'Previous file', function () { go(cur - 1, true); }, 'ide-bb'),
    btn('Go', 'Command palette: files, topics, modes', function () { palette(''); }, 'ide-bb'),
    btn('File ›', 'Next file', function () { go(cur + 1, true); }, 'ide-bb'),
    nextA ? el('a', { href: nextA.getAttribute('href'), class: 'ide-bb', 'aria-label': 'Next section' }, ['Sec »']) : el('span', { class: 'ide-bb ide-off' }, ['Sec »'])
  ]);

  top.setAttribute('role', 'button'); top.setAttribute('tabindex', '0'); top.setAttribute('title', 'Jump to the code of this file');
  function toCode() { var f = F[cur]; var t = f.wrap || f.sec; W.scrollTo({ top: Math.max(0, t.getBoundingClientRect().top + W.scrollY - 60), behavior: BEHAV }); }
  top.addEventListener('click', toCode);
  top.addEventListener('keydown', function (e) { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toCode(); } });
  var main = D.querySelector('main');
  main.insertBefore(top, main.firstChild);
  body.appendChild(rail); body.appendChild(facts); body.appendChild(bar);

  // ------------------------------------------------------------------ facts
  function cloneLinks(dd) {
    var box = el('div', { class: 'ide-links' });
    if (!dd) { box.textContent = 'none found'; return box; }
    var as = dd.querySelectorAll('a');
    if (!as.length) { box.textContent = txt(dd) || 'none found'; return box; }
    Array.prototype.forEach.call(as, function (a, j) {
      if (j >= 12) return;
      box.appendChild(el('a', { href: a.getAttribute('href') }, [txt(a)]));
    });
    if (as.length > 12) box.appendChild(el('span', { class: 'ide-more', text: '+' + (as.length - 12) + ' more in the page' }));
    return box;
  }
  function renderFacts() {
    var f = F[cur];
    facts.textContent = '';
    facts.style.setProperty('--role', f.colour);
    facts.appendChild(el('p', { class: 'ide-cap', text: 'FILE ' + (cur + 1) + ' / ' + F.length }));
    facts.appendChild(el('h2', { class: 'ide-ft', text: f.title }));
    facts.appendChild(el('span', { class: 'ide-role', style: 'border-color:' + f.colour + ';color:' + f.colour, text: f.role }));
    if (f.aside) facts.appendChild(el('span', { class: 'ide-aside', text: 'Clarity: ' + f.aside }));
    if (f.syn) facts.appendChild(el('p', { class: 'ide-syn', text: f.syn }));
    facts.appendChild(el('p', { class: 'ide-cap', text: 'USES · u' })); facts.appendChild(cloneLinks(f.uses));
    facts.appendChild(el('p', { class: 'ide-cap', text: 'USED BY · U' })); facts.appendChild(cloneLinks(f.usedBy));
    facts.appendChild(el('p', { class: 'ide-cap', text: 'KEY' }));
    facts.appendChild(el('code', { class: 'ide-key', text: f.key || f.path }));
    var acts = el('div', { class: 'ide-acts' }, [
      btn('Copy key', 'Copy the file key', function (e) { copy(f.key || f.path, e.currentTarget); }),
      btn('Copy lines', 'Copy these lines with line numbers', function (e) { copy(copyLinesText(f), e.currentTarget); }),
      btn('Show in map', 'Show in the visualiser (v)', function () { openMap(f, true); }),
      el('a', { class: 'ide-btn', href: pilotURL(f), title: 'Fly over places this section mentions' }, ['Pilot'])
    ]);
    if (f.gh) acts.appendChild(el('a', { class: 'ide-btn', href: f.gh.getAttribute('href'), rel: 'noopener' }, ['GitHub']));
    facts.appendChild(acts);
    facts.appendChild(el('p', { class: 'ide-cap', text: 'MINIMAP' }));
    facts.appendChild(miniWrap);
    drawMini();
    top.textContent = '';
    top.appendChild(el('span', { class: 'ide-dot', style: 'background:' + f.colour, 'aria-hidden': 'true' }));
    top.appendChild(el('b', { text: f.title }));
    top.appendChild(el('span', { class: 'ide-topkey', title: f.key, text: f.key || f.path }));
    top.appendChild(el('span', { class: 'ide-topn', text: (cur + 1) + '/' + F.length }));
    F.forEach(function (g) { g.railA.classList.toggle('ide-cur', g.i === cur); if (g.i === cur) g.railA.setAttribute('aria-current', 'true'); else g.railA.removeAttribute('aria-current'); });
  }

  // ------------------------------------------------------------------ minimap
  var miniRows = null;
  function buildMiniRows() {
    miniRows = [];
    F.forEach(function (f) {
      if (!f.code) return;
      f.code.textContent.replace(/\n$/, '').split('\n').forEach(function (l, j) {
        var ind = l.length - l.replace(/^\s+/, '').length;
        miniRows.push({ f: f.i, j: j, a: Math.min(ind, 40), w: Math.min(l.trim().length, 100), c: f.colour });
      });
    });
  }
  function drawMini() {
    if (!miniRows) buildMiniRows();
    var cw = mini.clientWidth || 280, ch = 200;
    var dpr = Math.min(W.devicePixelRatio || 1, 2);
    if (mini.width !== cw * dpr) { mini.width = cw * dpr; mini.height = ch * dpr; }
    var c = mini.getContext('2d'); if (!c) return;
    c.setTransform(dpr, 0, 0, dpr, 0, 0);
    c.fillStyle = '#05070b'; c.fillRect(0, 0, cw, ch);
    var n = miniRows.length || 1, h = ch / n, sx = (cw - 8) / 140;
    miniRows.forEach(function (r, k) {
      if (!r.w) return;
      c.globalAlpha = r.f === cur ? 0.95 : 0.35;
      c.fillStyle = r.c;
      c.fillRect(4 + r.a * sx, k * h, Math.max(1, r.w * sx), Math.max(h * 0.8, 0.6));
    });
    c.globalAlpha = 1;
    updateMiniVP();
  }
  function updateMiniVP() {
    var vp = miniWrap.querySelector('.ide-minivp');
    if (!miniRows || !miniRows.length) return;
    // find visible row range by page position of pres
    var total = miniRows.length, startRow = 0, firstVis = -1, lastVis = -1, k = 0;
    F.forEach(function (f) {
      if (!f.pre) return;
      var r = f.pre.getBoundingClientRect(), lh = f.pre.scrollHeight / (f.nlines || 1);
      for (var j = 0; j < f.nlines; j++) {
        var y = r.top + j * lh;
        if (y + lh > 0 && y < W.innerHeight) { if (firstVis < 0) firstVis = k + j; lastVis = k + j; }
      }
      k += f.nlines;
    });
    if (firstVis < 0) { vp.style.display = 'none'; return; }
    vp.style.display = 'block';
    vp.style.top = (200 * firstVis / total) + 'px';
    vp.style.height = Math.max(4, 200 * (lastVis - firstVis + 1) / total) + 'px';
  }
  mini.addEventListener('click', function (e) {
    if (!miniRows || !miniRows.length) return;
    var r = mini.getBoundingClientRect();
    var row = miniRows[Math.min(miniRows.length - 1, Math.floor((e.clientY - r.top) / r.height * miniRows.length))];
    scrollToLine(F[row.f], row.j);
  });
  function scrollToLine(f, j) {
    if (!f.pre) return;
    if (f.sec.classList.contains('ide-asideable')) f.sec.classList.add('ide-open');
    var lh = f.pre.scrollHeight / (f.nlines || 1);
    var y = f.pre.getBoundingClientRect().top + W.scrollY + j * lh - W.innerHeight / 3;
    W.scrollTo({ top: Math.max(0, y), behavior: BEHAV });
    setCur(f.i); lockUntil = performance.now() + (REDUCED ? 150 : 900);
    flashLine(f, j);
  }
  function flashLine(f, j) {
    var lh = f.pre.scrollHeight / (f.nlines || 1);
    var m = el('div', { class: 'ide-lineflash', 'aria-hidden': 'true', 'data-ide': '', style: 'top:' + (f.pre.offsetTop + j * lh + parseFloat(getComputedStyle(f.pre).paddingTop || 0)) + 'px;height:' + lh + 'px' });
    f.wrap.appendChild(m);
    setTimeout(function () { m.remove(); }, REDUCED ? 1500 : 2200);
  }

  // ------------------------------------------------------------------ navigation
  function setCur(i) { if (i === cur) return; cur = i; renderFacts(); }
  function go(i, push) {
    if (i < 0 || i >= F.length) return bump();
    var f = F[i];
    if (push && location.hash !== '#' + f.id) history.pushState({ ide: i }, '', '#' + f.id);
    cur = i; renderFacts(); lockUntil = performance.now() + (REDUCED ? 150 : 900);
    var y = f.sec.getBoundingClientRect().top + W.scrollY - (W.innerWidth >= 1200 ? 8 : 4);
    W.scrollTo({ top: Math.max(0, y), behavior: BEHAV });
    visited(i);
  }
  function bump() { body.classList.add('ide-bump'); setTimeout(function () { body.classList.remove('ide-bump'); }, 250); }
  W.addEventListener('popstate', function () {
    var i = F.findIndex(function (f) { return '#' + f.id === location.hash; });
    go(i >= 0 ? i : 0, false);
  });
  // Track the file in view while scrolling.
  var ticking = false, lockUntil = 0;
  W.addEventListener('scroll', function () {
    if (ticking) return; ticking = true;
    requestAnimationFrame(function () {
      ticking = false;
      if (performance.now() < lockUntil) { updateMiniVP(); return; }
      var best = cur, line = W.innerHeight * 0.3;
      F.forEach(function (f) { if (f.sec.getBoundingClientRect().top <= line) best = f.i; });
      if (W.scrollY < 40) best = hashIdx >= 0 && W.scrollY > 0 ? best : best;
      if (best !== cur) { cur = best; renderFacts(); visited(best); } else updateMiniVP();
    });
  }, { passive: true });
  W.addEventListener('resize', function () { drawMini(); });

  // visited files (a light progress marker) and the section trail
  var seen = {};
  function visited(i) { seen[i] = 1; F[i].railA.classList.add('ide-seen'); }
  (function trail() {
    var t = [];
    try { t = JSON.parse(sessionStorage.getItem('ec-ide:trail') || '[]'); } catch (e) {}
    var me = { s: SEC, h: location.pathname.split('/').pop(), t: txt(D.querySelector('h1')) };
    t = t.filter(function (x) { return x.s !== SEC; }); t.push(me); t = t.slice(-8);
    try { sessionStorage.setItem('ec-ide:trail', JSON.stringify(t)); } catch (e) {}
    t.forEach(function (x) {
      trailBox.appendChild(x.s === SEC ? el('span', { class: 'ide-here', title: x.t, text: String(x.s) }) : el('a', { href: x.h, title: x.t, text: String(x.s) }));
    });
  })();

  // ------------------------------------------------------------------ modes
  var mapPanel = null;
  function showMapPanel(url, f) {
    if (!mapPanel) {
      mapPanel = el('div', { id: 'ide-map', 'data-ide': '', role: 'dialog', 'aria-label': 'Visualiser' });
      body.appendChild(mapPanel);
    }
    mapPanel.textContent = '';
    mapPanel.appendChild(el('div', { class: 'ide-maphead' }, [
      el('b', { text: 'MAP · ' + f.title }),
      el('a', { class: 'ide-btn', href: url }, ['Open full map']),
      btn('Close', 'Close the map (Esc)', function () { closeMap(); })
    ]));
    mapPanel.appendChild(el('iframe', { src: url, title: 'Visualiser showing ' + f.title, loading: 'lazy' }));
    body.classList.add('ide-mapon');
    setModeButtons('map');
  }
  function closeMap() { body.classList.remove('ide-mapon'); if (mapPanel) mapPanel.textContent = ''; setModeButtons(mode); }
  function setModeButtons(m) {
    Array.prototype.forEach.call(D.querySelectorAll('.ide-mode, .pl-mode[data-mode]'), function (b) { b.setAttribute('aria-pressed', String(b.getAttribute('data-mode') === m)); });
  }
  // Shared cockpit HUD (theme/play.js by ARCADE-36): fill its mode slot, and keep clear of its height.
  function fillSlot(slot) {
    if (!slot || slot.getAttribute('data-ide-filled')) return;
    slot.setAttribute('data-ide-filled', '1');
    MODES.forEach(function (m) {
      slot.appendChild(el('button', { type: 'button', class: 'pl-mode', 'data-mode': m, 'data-ide': '', 'aria-pressed': String(m === mode), title: MODE_LABEL[m] + ' mode (' + (MODES.indexOf(m) + 1) + ')', on: { click: function () { setMode(m); } } }, [MODE_LABEL[m]]));
    });
    body.classList.add('ide-hudmodes');
    hudSize();
  }
  function hudSize() {
    var h = D.getElementById('pl-hud');
    var px = h && getComputedStyle(h).position !== 'static' ? h.getBoundingClientRect().height : 0;
    D.documentElement.style.setProperty('--ide-hudh', Math.round(px) + 'px');
  }
  fillSlot(D.querySelector('[data-pl-slot=modes]'));
  D.addEventListener('pl:hud-ready', function (e) { fillSlot((e.detail && e.detail.slot) || D.querySelector('[data-pl-slot=modes]')); });
  W.addEventListener('resize', hudSize);
  function setMode(m) {
    if (m === 'pilot') { location.href = pilotURL(F[cur]); return; }
    if (m === 'map') { openMap(F[cur], true); return; }
    closeMap();
    mode = m; store.set('mode', m);
    body.classList.toggle('ide-clarity', m === 'clarity');
    setModeButtons(m);
    toast(m === 'clarity' ? 'Clarity: ' + F.filter(function (f) { return f.aside; }).length + ' of ' + F.length + ' files set aside (unreached or copies). See what is real.' : 'Read mode');
  }
  var toastEl = null, toastT = 0;
  function toast(s) {
    if (!toastEl) { toastEl = el('div', { id: 'ide-toast', 'data-ide': '', role: 'status' }); body.appendChild(toastEl); }
    toastEl.textContent = s; toastEl.classList.add('on');
    clearTimeout(toastT); toastT = setTimeout(function () { toastEl.classList.remove('on'); }, 2600);
  }

  // ------------------------------------------------------------------ overlays: help and palette
  var overlay = null;
  function closeOverlay() { if (overlay) { overlay.remove(); overlay = null; if (lastFocus && lastFocus.focus) lastFocus.focus(); } }
  var lastFocus = null;
  function openOverlay(node, label) {
    closeOverlay();
    lastFocus = D.activeElement;
    overlay = el('div', { id: 'ide-ov', 'data-ide': '', role: 'dialog', 'aria-modal': 'true', 'aria-label': label, on: { click: function (e) { if (e.target === overlay) closeOverlay(); } } }, [node]);
    body.appendChild(overlay);
  }
  var KEYS = [['j / k', 'next / previous file'], ['[ / ]', 'previous / next section'], ['u / U', 'jump to Uses / Used by'],
    ['/', 'search this section (and the estate)'], ['v', 'open the file in the visualiser'], ['1 2 3 4', 'Read, Map, Pilot, Clarity mode'],
    ['c', 'copy the file key'], ['Ctrl K', 'command palette'], ['Esc', 'close'], ['?', 'this help']];
  function help() {
    var tb = el('table', { class: 'ide-keys' });
    KEYS.forEach(function (k) { tb.appendChild(el('tr', null, [el('td', null, [el('kbd', { text: k[0] })]), el('td', { text: k[1] })])); });
    var box = el('div', { class: 'ide-box' }, [el('p', { class: 'ide-cap', text: 'CONTROLS' }), tb,
      el('p', { class: 'ide-hint', text: 'Back returns along your trail. Pages read the same with JavaScript off.' }), btn('Close', 'Close help', closeOverlay)]);
    openOverlay(box, 'Keyboard help');
    box.querySelector('button').focus();
  }
  var topicsP = null;
  function topics() {
    if (!topicsP) topicsP = fetch('../index.html').then(function (r) { return r.ok ? r.text() : ''; }).then(function (h) {
      var out = [], seenT = {}, re = /<a href="(topics\/[a-z0-9-]+\.html)">(?:<strong>)?([^<]+)/g, m;
      while ((m = re.exec(h))) if (!seenT[m[1]]) { seenT[m[1]] = 1; out.push({ href: '../' + m[1], t: m[2].replace(/&amp;/g, '&').replace(/&#x27;/g, "'") }); }
      return out;
    }).catch(function () { return []; });
    return topicsP;
  }
  function palette(q, searchMode) {
    var inp = el('input', { type: 'search', class: 'ide-pin', placeholder: searchMode ? 'Search code in this section…' : 'Jump to a file, topic or command…', 'aria-label': 'Command', autocomplete: 'off', spellcheck: 'false' });
    var ul = el('ul', { class: 'ide-pres', role: 'listbox' });
    var box = el('div', { class: 'ide-box ide-pal' }, [el('p', { class: 'ide-cap', text: searchMode ? 'SEARCH · Enter to jump' : 'COMMAND PALETTE · Ctrl K' }), inp, ul]);
    openOverlay(box, searchMode ? 'Search' : 'Command palette');
    var items = [], sel = 0, tlist = [];
    topics().then(function (t) { tlist = t; render(); });
    function base() {
      var r = F.map(function (f) { return { k: 'file', t: f.title, s: f.path, c: f.colour, run: function () { closeOverlay(); go(f.i, true); } }; });
      r.push({ k: 'cmd', t: 'Mode: Read', run: function () { closeOverlay(); setMode('read'); } });
      r.push({ k: 'cmd', t: 'Mode: Clarity (see what is real)', run: function () { closeOverlay(); setMode('clarity'); } });
      r.push({ k: 'cmd', t: 'Mode: Map (show in visualiser)', run: function () { closeOverlay(); setMode('map'); } });
      r.push({ k: 'cmd', t: 'Mode: Pilot (fly over the places)', run: function () { closeOverlay(); setMode('pilot'); } });
      r.push({ k: 'cmd', t: 'Copy key of current file', run: function () { closeOverlay(); copy(F[cur].key || F[cur].path); toast('Key copied'); } });
      if (prevA) r.push({ k: 'cmd', t: 'Previous section', run: function () { location.href = prevA.href; } });
      if (nextA) r.push({ k: 'cmd', t: 'Next section', run: function () { location.href = nextA.href; } });
      tlist.forEach(function (t) { r.push({ k: 'topic', t: t.t, run: function () { location.href = t.href; } }); });
      return r;
    }
    function codeHits(qs) {
      var out = [], ql = qs.toLowerCase();
      F.forEach(function (f) {
        if (!f.code) return;
        f.code.textContent.split('\n').forEach(function (l, j) {
          if (out.length < 60 && l.toLowerCase().indexOf(ql) >= 0)
            out.push({ k: 'line', t: f.title + ' :' + (f.first + j), s: l.trim().slice(0, 90), c: f.colour, run: function () { closeOverlay(); scrollToLine(f, j); } });
        });
      });
      return out;
    }
    function render() {
      var qs = inp.value.trim(), ql = qs.toLowerCase();
      items = searchMode ? [] : base().filter(function (x) { return !ql || (x.t + ' ' + (x.s || '')).toLowerCase().indexOf(ql) >= 0; });
      if (qs.length >= 2) items = items.concat(codeHits(qs));
      if (qs) items.push({ k: 'estate', t: 'Search the whole estate for “' + qs + '”', run: function () { location.href = '../search.html?q=' + encodeURIComponent(qs); } });
      sel = Math.min(sel, Math.max(0, items.length - 1));
      ul.textContent = '';
      items.slice(0, 80).forEach(function (x, j) {
        var li = el('li', { role: 'option', 'aria-selected': String(j === sel), class: j === sel ? 'on' : '', on: { click: function () { x.run(); }, mousemove: function () { if (sel !== j) { sel = j; mark(); } } } }, [
          el('span', { class: 'ide-pk', style: x.c ? 'color:' + x.c : '', text: x.k }), el('span', { class: 'ide-ptt', text: x.t }), x.s ? el('span', { class: 'ide-ps', text: x.s }) : null]);
        ul.appendChild(li);
      });
    }
    function mark() { Array.prototype.forEach.call(ul.children, function (li, j) { li.className = j === sel ? 'on' : ''; li.setAttribute('aria-selected', String(j === sel)); if (j === sel) li.scrollIntoView({ block: 'nearest' }); }); }
    inp.addEventListener('input', function () { sel = 0; render(); });
    inp.addEventListener('keydown', function (e) {
      if (e.key === 'ArrowDown') { sel = Math.min(items.length - 1, sel + 1); mark(); e.preventDefault(); }
      else if (e.key === 'ArrowUp') { sel = Math.max(0, sel - 1); mark(); e.preventDefault(); }
      else if (e.key === 'Enter') { if (items[sel]) items[sel].run(); e.preventDefault(); }
      else if (e.key === 'Escape') { closeOverlay(); e.preventDefault(); }
    });
    inp.value = q || ''; render(); inp.focus();
  }

  // ------------------------------------------------------------------ keyboard
  function jumpRow(dd, label) {
    var f = F[cur];
    if (!dd) return toast('No ' + label + ' for this file');
    var row = dd.previousElementSibling;
    var y = row.getBoundingClientRect().top + W.scrollY - W.innerHeight / 3;
    W.scrollTo({ top: Math.max(0, y), behavior: BEHAV });
    dd.classList.add('ide-hl'); setTimeout(function () { dd.classList.remove('ide-hl'); }, 1600);
    var a = dd.querySelector('a'); if (a) a.focus({ preventScroll: true }); else toast(label + ': ' + txt(dd));
  }
  D.addEventListener('keydown', function (e) {
    if ((e.ctrlKey || e.metaKey) && (e.key === 'k' || e.key === 'K')) { e.preventDefault(); if (overlay) closeOverlay(); else palette(''); return; }
    if (e.key === 'Escape') { if (overlay) closeOverlay(); else if (body.classList.contains('ide-mapon')) closeMap(); return; }
    if (overlay || e.ctrlKey || e.metaKey || e.altKey) return;
    var t = e.target, tag = t && t.tagName;
    if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || (t && t.isContentEditable)) return;
    var f = F[cur];
    switch (e.key) {
      case 'j': go(cur + 1, true); break;
      case 'k': go(cur - 1, true); break;
      case ']': if (nextA) location.href = nextA.href; else bump(); break;
      case '[': if (prevA) location.href = prevA.href; else bump(); break;
      case 'u': jumpRow(f.uses, 'Uses'); break;
      case 'U': jumpRow(f.usedBy, 'Used by'); break;
      case '/': palette('', true); break;
      case 'v': openMap(f, false); break;
      case 'c': copy(f.key || f.path); toast('Key copied: ' + (f.key || f.path).slice(0, 60)); break;
      case '?': help(); break;
      case '1': setMode('read'); break;
      case '2': setMode('map'); break;
      case '3': setMode('pilot'); break;
      case '4': setMode('clarity'); break;
      default: return;
    }
    e.preventDefault();
  });

  // ------------------------------------------------------------------ start
  if (mode === 'clarity') body.classList.add('ide-clarity');
  setModeButtons(mode);
  renderFacts();
  visited(cur);
  W.__exploreIDE = { files: F, go: go, setMode: setMode, cur: function () { return cur; }, fileId: fileId, version: 1 };
})();