In this section
- Seethrough interaction · cosmic / tools/explore/theme/seethrough.js lines 1–212
- Seethrough Index render · cosmic / tools/explore/theme/seethrough_index.py lines 1–332
Seethrough
A JavaScript file in the theme folder of Cosmic covering substations and uses data from the kuiper-belt repository. It opens sub (`openSub`) and opens repo (`openRepo`).
interactioncosmic / tools/explore/theme/seethrough.js · lines 1–212 of 212 · Not reached from any entry point (candidate for review) · pattern sectionPage (shared by 2 files)
- What it does
- It draws substations. Defines 20 functions or classes, including el, ring, hashFor, close, onKey. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain terms in the code: substations.
- Inputs & outputs
- In: data source: kuiper-belt data; JSON file index.json.
- What it achieves
- The See Through mode for Explore Code (PERISCOPE-64). It responds to keydown, load and ide 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, ring, hashFor, close, onKey, shell, frame, smallScreen, openSub, openRepo, choose, modeButton
- Defines here
- el, ring, hashFor, close, onKey, shell, frame, smallScreen, openSub, openRepo, choose, modeButton, fileButton, go, sectionPage, repoPage, attach, whenChromeReady, go, start
- 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/seethrough.js:1-212 · blob 92d1775922d0fc2d63bfd708fbea764073f7e993 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, network · domain stage: unknown · users: none · canonical: unreached_review
/* seethrough.js: the See Through mode for Explore Code (PERISCOPE-64).
* Opens the owner's live See Through app (https://ventusltd.github.io/kuiper-belt/see-through/) by its own deep links:
* a file that names a substation -> #sub=<name>&view=3d (the name exactly as See Through holds it)
* a repository page -> #repo=<repos.tsv name>&view=kuiper
* in a full-screen overlay with a close button, plus an "Open in new tab" link (the fallback when the frame struggles).
* Data: <root>seethrough/index.json, written by theme/seethrough_index.py from See Through's own grid-data.js names
* and each file's source line. Nothing is guessed: no index entry, no button.
* Hooks (agreed through the Neural Link outbox): a button in HOTBAR-36's .ide-modes and .ide-head on section pages,
* a button in ARCADE-36's [data-pl-slot=modes] HUD slot on repo pages, else a floating button of its own.
* Every node added carries data-st; the page's own text and structure are never changed. */
(function () {
'use strict';
if (window.ExploreSeeThrough) return;
var D = document;
var me = D.currentScript || D.querySelector('script[src*="theme/seethrough.js"]');
var src = me ? me.getAttribute('src') : '../theme/seethrough.js';
var ROOT = src.replace(/theme\/seethrough\.js(?:\?.*)?$/, '');
var API = window.ExploreSeeThrough = { root: ROOT, index: null, open: openSub, openRepo: openRepo, close: close };
function el(tag, attrs, kids) {
var e = D.createElement(tag);
e.setAttribute('data-st', '');
if (attrs) Object.keys(attrs).forEach(function (k) {
var v = attrs[k];
if (v == null) return;
if (k === 'text') e.textContent = v;
else if (k === 'on') Object.keys(v).forEach(function (ev) { e.addEventListener(ev, v[ev]); });
else e.setAttribute(k, v);
});
(kids || []).forEach(function (c) { if (c != null) e.appendChild(typeof c === 'string' ? D.createTextNode(c) : c); });
return e;
}
function ring() { var r = el('span', { class: 'st-ring', 'aria-hidden': 'true' }); return r; }
function hashFor(fields) {
return '#' + Object.keys(fields).map(function (k) { return k + '=' + encodeURIComponent(fields[k]); }).join('&');
}
var IDX = null, lastFocus = null, overlay = null, timer = 0;
// ---------------------------------------------------------------- overlay
function close() {
if (!overlay) return;
clearTimeout(timer);
overlay.remove(); overlay = null;
D.documentElement.classList.remove('st-open');
D.removeEventListener('keydown', onKey, true);
Array.prototype.forEach.call(D.querySelectorAll('.st-mode'), function (b) { b.setAttribute('aria-pressed', 'false'); });
if (lastFocus && lastFocus.focus) try { lastFocus.focus(); } catch (e) {}
}
function onKey(e) {
if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); close(); }
else if (e.key === 'Tab' && overlay) { // keep focus inside the dialog
var f = overlay.querySelectorAll('button, a[href], iframe');
if (!f.length) return;
var first = f[0], last = f[f.length - 1];
if (e.shiftKey && D.activeElement === first) { e.preventDefault(); last.focus(); }
else if (!e.shiftKey && D.activeElement === last) { e.preventDefault(); first.focus(); }
}
}
function shell(nameText, whereNode, tabUrl) {
close();
lastFocus = D.activeElement;
overlay = el('div', { class: 'st-overlay', role: 'dialog', 'aria-modal': 'true', 'aria-label': 'See Through: ' + nameText });
var x = el('button', { type: 'button', class: 'st-x', title: 'Close See Through (Esc)', 'aria-label': 'Close See Through', on: { click: close } }, ['Close']);
var hud = el('div', { class: 'st-hud' }, [
ring(),
el('div', { class: 'st-title' }, [el('span', { class: 'st-name', text: nameText }), whereNode]),
tabUrl ? el('a', { class: 'st-tab', href: tabUrl, target: '_blank', rel: 'noopener', title: 'Open See Through in a new tab' }, ['New tab']) : null,
x
]);
overlay.appendChild(hud);
D.body.appendChild(overlay);
D.documentElement.classList.add('st-open');
D.addEventListener('keydown', onKey, true);
Array.prototype.forEach.call(D.querySelectorAll('.st-mode'), function (b) { b.setAttribute('aria-pressed', 'true'); });
x.focus();
return overlay;
}
function frame(url, label) {
var note = el('div', { class: 'st-note', role: 'status' }, [el('p', { text: 'Opening See Through…' })]);
var ifr = el('iframe', { src: url, title: label, allow: 'fullscreen; accelerometer; gyroscope', referrerpolicy: 'no-referrer-when-downgrade' });
var box = el('div', { class: 'st-frame' }, [ifr, note]);
ifr.addEventListener('load', function () { clearTimeout(timer); note.hidden = true; });
timer = setTimeout(function () { // the frame struggles: offer the new tab instead
note.textContent = '';
note.appendChild(el('p', { text: 'See Through is slow to open here. It needs the internet for its map, imagery and terrain.' }));
note.appendChild(el('a', { class: 'st-btn', href: url, target: '_blank', rel: 'noopener' }, ['Open in a new tab']));
note.hidden = false;
}, 15000);
overlay.appendChild(box);
}
function smallScreen() { return Math.min(window.innerWidth, window.innerHeight) < 360; }
function openSub(m, fileKey) {
if (!IDX || !m) return;
var name = m[0], line = m[1];
var url = IDX.base + hashFor({ sub: name, view: '3d' });
if (smallScreen()) { window.open(url, '_blank', 'noopener'); return; }
var where = line ? fileKey + ':' + line : fileKey + ' (build graph)';
var twins = IDX.twins && IDX.twins[name];
var w = el('span', { class: 'st-where' }, ['mentioned in ', el('code', { text: where }),
twins ? ' · See Through holds ' + twins + ' sites with this name and opens the first' : null]);
w.title = m[3] || '';
shell(name, w, url);
frame(url, 'See Through: ' + name);
}
function openRepo(repo) {
if (!IDX) return;
var tsv = IDX.repos && IDX.repos[repo];
if (!tsv) return;
var url = IDX.base + hashFor({ repo: tsv, view: 'kuiper' });
if (smallScreen()) { window.open(url, '_blank', 'noopener'); return; }
shell(tsv + ' stars', el('span', { class: 'st-where' }, ['the stars of repository ', el('code', { text: tsv }), ' on the Kuiper']), url);
frame(url, 'See Through: stars of ' + tsv);
}
// several substations: a chooser first, each with the line it comes from
function choose(groups, title) {
var total = groups.reduce(function (a, g) { return a + g.m.length; }, 0);
if (total === 1) { openSub(groups[0].m[0], groups[0].k); return; }
shell(title, el('span', { class: 'st-where', text: total + ' substations named in this code · choose one' }), null);
var list = el('div', { class: 'st-list' });
groups.forEach(function (g) {
list.appendChild(el('h3', { text: g.k + (g.n > g.m.length ? ' · ' + g.m.length + ' of ' + g.n + ' names shown' : '') }));
var ul = el('ul');
g.m.forEach(function (m) {
ul.appendChild(el('li', null, [el('button', { type: 'button', class: 'st-pick', on: { click: function () { openSub(m, g.k); } } }, [
el('b', { text: m[0] }),
el('span', { text: 'mentioned in ' + g.k + (m[1] ? ':' + m[1] : ' (build graph)') + ' · ' + m[2] + ' match' }),
el('code', { text: m[3] })
])]));
});
list.appendChild(ul);
});
overlay.appendChild(list);
}
// ---------------------------------------------------------------- page hooks
function modeButton(label, title, onClick) {
// ARCADE-36's HUD slot first (HOTBAR-36 moves its modes there and hides .ide-modes), else the IDE rail's group
var slot = D.querySelector('[data-pl-slot="modes"]') || D.querySelector('.ide-modes');
if (D.querySelector('.st-mode, .st-fab')) return;
if (slot) {
var cls = slot.classList.contains('ide-modes') ? 'ide-mode st-mode' : 'pl-mode st-mode';
slot.appendChild(el('button', { type: 'button', class: cls, 'data-mode': 'seethrough', 'data-st-mode': '', 'aria-pressed': 'false', title: title, on: { click: onClick } }, [ring(), label]));
} else {
D.body.appendChild(el('button', { type: 'button', class: 'st-fab st-mode', 'data-st-mode': '', 'aria-pressed': 'false', title: title, on: { click: onClick } }, [ring(), label]));
}
}
function fileButton(sec, rec) {
if (sec.querySelector('[data-st-file]')) return;
var first = rec.m[0][0];
var label = 'See Through · ' + first;
var go = function () { choose([rec], 'Substations in ' + rec.k.split('/').pop()); };
var head = sec.querySelector('.ide-head');
if (head) {
head.appendChild(el('button', { type: 'button', class: 'ide-btn st-btn', 'data-st-file': '', title: 'Open ' + first + ' in See Through', on: { click: go } }, [rec.m.length > 1 ? 'See Through (' + rec.n + ')' : 'See Through']));
return;
}
var row = el('div', { class: 'st-row', 'data-st-file': '' }, [
el('button', { type: 'button', class: 'st-btn', title: 'Open in See Through, mentioned at ' + rec.k + (rec.m[0][1] ? ':' + rec.m[0][1] : ''), on: { click: go } }, [ring(), label]),
rec.n > 1 ? el('span', { class: 'st-more', text: '+' + (rec.n - 1) + ' more named in this file' }) : null
]);
var h2 = sec.querySelector(':scope > h2');
if (h2 && h2.nextSibling) sec.insertBefore(row, h2.nextSibling); else sec.appendChild(row);
}
function sectionPage(sec) {
var ids = IDX.sections[String(sec)];
if (!ids || !ids.length) return;
var groups = [];
ids.forEach(function (id) {
var rec = IDX.files[String(id)];
if (!rec) return;
rec.id = id;
var s = D.getElementById('f' + rec.b);
if (s) fileButton(s, rec);
groups.push(rec);
});
if (!groups.length) return;
modeButton('See Through', 'See Through: fly to the substations this section names', function () { choose(groups, 'Section ' + sec + ' substations'); });
}
function repoPage(repo) {
if (!IDX.repos || !IDX.repos[repo]) return;
modeButton('See Through', 'See Through: light this repository\'s stars on the Kuiper', function () { openRepo(repo); });
}
function attach() {
var path = location.pathname;
var ms = /\/s\/(\d+)\.html$/.exec(path), mr = /\/repos\/([^\/]+)\.html$/.exec(path);
if (ms) sectionPage(+ms[1]);
else if (mr) repoPage(decodeURIComponent(mr[1]));
}
function whenChromeReady(fn) {
// Wait briefly for the IDE rail (HOTBAR-36) or HUD slot (ARCADE-36); go alone if neither comes.
var hud = D.querySelector('script[src*="theme/play.js"]'), ide = D.querySelector('script[src*="theme/ide.js"]');
var want = hud ? '[data-pl-slot="modes"]' : '.ide-modes';
var expect = hud || ide;
if (D.querySelector(want) || !expect) { fn(); return; }
var done = false, mo;
function go() { if (done) return; done = true; if (mo) mo.disconnect(); fn(); }
D.addEventListener('ide:ready', go); D.addEventListener('pl:hud-ready', go);
if (window.MutationObserver) { mo = new MutationObserver(function () { if (D.querySelector(want)) go(); }); mo.observe(D.body, { childList: true, subtree: true }); }
setTimeout(go, 2500);
}
function start() {
fetch(ROOT + 'seethrough/index.json').then(function (r) { if (!r.ok) throw new Error(r.status); return r.json(); }).then(function (j) {
IDX = API.index = j;
whenChromeReady(attach);
}).catch(function () { /* no index: no See Through buttons, the page is unchanged */ });
}
if (D.readyState === 'loading') D.addEventListener('DOMContentLoaded', start); else start();
})();Seethrough Index
A Python command-line tool in the theme folder of Cosmic that reads build graph and substations from the kuiper-belt repository. It loads names (`load_names`) and loads repos (`load_repos`).
rendercosmic / tools/explore/theme/seethrough_index.py · lines 1–332 of 332 · Entry point · pattern inject (shared by 2 files)
- What it does
- It loads build graph and substations. Defines 15 functions or classes, including newest_folder, load_names, load_repos, Matcher, __init__. Uses libraries __future__, argparse, json, os, re. Side effects: changes the web page (DOM); reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain terms in the code: substations.
- Inputs & outputs
- In: data source: kuiper-belt data; JSON file build_graph.json; command-line arguments. Out: JSON file index.json.
- Downstream impact
- Used directly by 2 files: Extras (cosmic); Test Seethrough (cosmic). Reached from 3 other entry points, including Ship (cosmic); Test Extras (cosmic); Test Ship (cosmic).
- What it achieves
- Post-build step: link Explore Code files to the substations that See Through knows. It accepts `--site`, `--src` and `--seethrough`.
- Why it matters
- Run by Extras. Checked by Test Seethrough.
- Application
- cosmic · tools/explore/theme · Python CLI
- Uses
- Kuiper Belt — See Through Page (estate URL), __future__, argparse, json, os, re, shutil, sys, pathlib
- Used by
- run by Extras (script call), imported by Test Seethrough (import)
- Produces
- newest_folder, load_names, load_repos, Matcher, landing, evidence, build, inject, main
- Defines here
- newest_folder, load_names, load_repos, Matcher, __init__, scan, _shaped, _inside_proper_noun, _joined, _window, landing, evidence, build, inject, main
- 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/seethrough_index.py:1-332 · blob b71ca3637c9caf0f7288ecbc7a8fcf43ba30b793 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""Post-build step: link Explore Code files to the substations that See Through knows.
python tools/explore/theme/seethrough_index.py --site <out>/explore-code \
[--src CLONES] [--seethrough kuiper-belt/see-through] [--base URL] [--inject]
Reads, never invents:
* the substation names from See Through's own data file, <seethrough>/<newest dated folder>/grid-data.js
(window.KGGridData.substations.names, OpenStreetMap, ODbL);
* the repository names from kuiper-belt/cosmos/repos.tsv, which See Through's #repo= link reads;
* <site>/build_graph.json and each file's source at <src>/<repo>/<path> (same commit as the build).
Writes <site>/seethrough/index.json:
{"base": URL, "names": n, "files": {"<file id>": {"s": section, "b": block, "k": "repo/path", "n": total,
"m": [[name, line, kind, evidence], ...]}}, "sections": {"<section>": [file ids]}, "repos": {"repo": "tsv name"}}
kind is "exact" (the name verbatim), "normalised" (same words, case and separators folded) or "suffix" (the name's
own words with its suffix spelt another way: "Cowley GSP" for "Cowley Substation"). line 0 means the match is in
build_graph.json text (evidence names the field). Only names that pass the guards below are linked.
--inject (test copies only) adds the See Through link/script to s/*.html and repos/*.html with the marker
data-ec-seethrough; in the real build theme/inject.py (bonus agent A) loads them.
"""
from __future__ import annotations
import argparse
import json
import os
import re
import shutil
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
LIVE = 'https://ventusltd.github.io/kuiper-belt/see-through/'
MAX_PER_FILE = 40 # matches stored per file (n keeps the total)
WINDOW = 120 # characters either side of a match used for context and evidence
TOKEN = re.compile(r'[A-Za-z0-9]+')
SEP_OK = re.compile(r"^[ \t_\-./']{1,3}$")
VOLT = re.compile(r'^\d+(?:\.\d+)?kv$')
# words that make a name generic, or that are a suffix the same site is written with
GENERIC = {'substation', 'substations', 'sub', 'station', 'grid', 'primary', 'bsp', 'gsp', 'ss', 'supply', 'point',
'kv', 'switching', 'switchyard', 'the', 'for', 'and', 'of', 'a', 'b', 'c', 'new', 'old', 'main', 'unknown'}
SUFFIX_NAME = [('substation',), ('sub', 'station'), ('grid',), ('primary',), ('bsp',), ('gsp',), ('grid', 'supply', 'point')]
SUFFIX_SEEN = {'substation', 'substations', 'gsp', 'bsp', 'grid', 'primary'}
# a one-word name is linked only next to words like these (a town name alone is a place, not a substation)
CONTEXT = re.compile(r'(?i)(?<![A-Za-z])(sub ?stations?|grid|gsp|bsp|primary|\d+ ?kv|transmission|pylons?|feeders?|'
r'busbars?|switchyard|dno|tso|osm|power ?station|transformers?)(?![A-Za-z])')
# words that are ordinary English, places elsewhere, companies or institutions, or that touch on belief: never linked
STOP = set('''
pool close idle flint shin harden malleable tulip greenfield newtown oxbridge mona beal ross university dallas
richmond kingston charleston nissan pfizers mbna srm dlco plangeo stadco sulzers rockware seraphim pilgrim belmont
barrow seaton stockton acton norwood dunston newhall greenhill westgate southgate bramley morley lindley thorne
harwood buckley johnstone castleton easington darley wheatley sowerby flatworth kinver pandy salen dallas
'''.split())
BELIEF = re.compile(r'(?i)\b(church|chapel|abbey|cathedral|temple|priory|minster|mosque|synagogue|vicarage|rectory|'
r'monastery|convent|holy|saint|seraphim|pilgrim|bishop|bishops|parsonage|kirk)\b')
def newest_folder(st: Path) -> Path:
dated = sorted(d for d in st.iterdir() if d.is_dir() and re.fullmatch(r'\d{12}', d.name))
if not dated:
raise SystemExit('no dated folder in %s' % st)
return dated[-1]
def load_names(folder: Path) -> dict[int, str]:
"""Substation index -> name, as See Through's grid-data.js holds them."""
text = (folder / 'grid-data.js').read_text(encoding='utf-8')
i = text.find('"names":')
if i < 0:
raise SystemExit('grid-data.js has no "names"')
obj, _ = json.JSONDecoder().raw_decode(text, i + len('"names":'))
return {int(k): v for k, v in obj.items() if isinstance(v, str) and v.strip()}
def load_repos(cosmos: Path) -> list[str]:
p = cosmos / 'repos.tsv'
if not p.is_file():
return []
out = []
for line in p.read_text(encoding='utf-8').splitlines():
if line and not line.startswith('#'):
parts = line.split('\t')
if len(parts) > 1:
out.append(parts[1])
return out
class Matcher:
"""Exact or normalised matches of See Through names, with guards against ordinary words."""
def __init__(self, names: dict[int, str]):
self.full: dict[str, list] = {} # first token -> [(tokens, name, needs_context)]
self.core: dict[str, list] = {} # first token -> [(core tokens, name)] for suffix variants
self.skipped = {'placeholder': 0, 'generic': 0, 'stop': 0, 'belief': 0}
seen = set()
self.linkable = 0
for idx in sorted(names):
name = names[idx].strip()
if name in seen:
continue
seen.add(name)
toks = tuple(t.lower() for t in TOKEN.findall(name))
if '__' in name or not toks:
self.skipped['placeholder'] += 1
continue
meaning = [t for t in toks if t not in GENERIC and not VOLT.match(t) and not t.isdigit()]
if not meaning:
self.skipped['generic'] += 1
continue
if BELIEF.search(name):
self.skipped['belief'] += 1
continue
if len(meaning) == 1 and (meaning[0] in STOP or len(meaning[0]) < 4):
self.skipped['stop'] += 1
continue
self.linkable += 1
# a name of one meaning word ("Drax", "York Street", "Wakefield B") needs exact case and context
needs = len(meaning) == 1 or len(toks) == 2 and any(t in STOP or len(t) < 3 for t in toks)
self.full.setdefault(toks[0], []).append((toks, name, needs))
for suf in SUFFIX_NAME:
if len(toks) > len(suf) and toks[-len(suf):] == suf:
core = toks[:-len(suf)]
if [t for t in core if t not in GENERIC and not VOLT.match(t)]:
self.core.setdefault(core[0], []).append((core, name))
break
def scan(self, text: str):
"""Yield (name, kind, start, end) for one line: longest matches first, never overlapping."""
spans = [(m.start(), m.end(), m.group(0)) for m in TOKEN.finditer(text)]
low = [s[2].lower() for s in spans]
n = len(spans)
cands = []
for i in range(n):
for toks, name, needs in self.full.get(low[i], ()):
k = len(toks)
if i + k > n or tuple(low[i:i + k]) != toks or not self._joined(text, spans, i, k):
continue
a, b = spans[i][0], spans[i + k - 1][1]
verbatim = text[a:b] == name
if needs and not (verbatim or text[a:b] == name.upper()):
continue
if needs and not CONTEXT.search(self._window(text, a, b, name)):
continue
if not verbatim and not self._shaped(text[a:b]):
continue
cands.append((i, i + k, name, 'exact' if verbatim else 'normalised'))
for core, name in self.core.get(low[i], ()):
k = len(core)
if i + k > n or tuple(low[i:i + k]) != core:
continue
j = i + k
if j < n and VOLT.match(low[j]):
j += 1
if j >= n or low[j] not in SUFFIX_SEEN or not self._joined(text, spans, i, j - i + 1):
continue
if not spans[i][2][:1].isupper():
continue
cands.append((i, j + 1, name, 'suffix'))
cands.sort(key=lambda c: (-(c[1] - c[0]), c[0], c[3] != 'exact'))
taken = [False] * n
for i, j, name, kind in cands:
if any(taken[i:j]) or self._inside_proper_noun(text, spans, i, j):
continue
for t in range(i, j):
taken[t] = True
yield name, kind, spans[i][0], spans[j - 1][1]
@staticmethod
def _shaped(s):
"""A case-folded match counts only as an identifier or in capitals, never as lower-case prose."""
if s.isupper() or not re.search(r'[ \t]', s):
return True
return s[:1].isupper()
@staticmethod
def _inside_proper_noun(text, spans, i, j):
"""Part of a longer name ("Berwick Bank", "Thorpe Marsh Power Station"): a capitalised word joined by one space."""
if i > 0 and text[spans[i - 1][1]:spans[i][0]] == ' ' and spans[i - 1][2][:1].isupper() and len(spans[i - 1][2]) > 1:
return True
if j < len(spans) and text[spans[j - 1][1]:spans[j][0]] == ' ' and spans[j][2][:1].isupper():
return True
return False
@staticmethod
def _joined(text, spans, i, k):
return all(SEP_OK.match(text[spans[j][1]:spans[j + 1][0]] or 'x') for j in range(i, i + k - 1))
@staticmethod
def _window(text, a, b, name):
return text[max(0, a - WINDOW):a] + ' ' + text[b:b + WINDOW]
def landing(names: dict[int, str], want: str) -> str:
"""The name See Through's #sub=<want> lands on: its search keeps the first 200 names that contain the text
(lower case, index order) and prefers an exact one among them (descent.js doSearch / bestMatch)."""
q = want.strip().lower()
hits = []
for i in sorted(names):
if q in names[i].lower():
hits.append(names[i])
if len(hits) == 200:
break
for h in hits:
if h.lower() == q:
return h
return hits[0] if hits else ''
def evidence(text: str, a: int, b: int) -> str:
s = text.strip()
if len(s) <= 2 * WINDOW:
return s
lo, hi = max(0, a - WINDOW // 2), min(len(text), b + WINDOW // 2)
return ('…' if lo else '') + text[lo:hi].strip() + ('…' if hi < len(text) else '')
GRAPH_FIELDS = ('title', 'synopsis', 'achieves', 'why')
def build(site: Path, src: Path, st: Path, base: str) -> dict:
folder = newest_folder(st)
names = load_names(folder)
matcher = Matcher(names)
repos_tsv = load_repos(st.parent / 'cosmos')
g = json.loads((site / 'build_graph.json').read_text(encoding='utf-8'))
files_out: dict[str, dict] = {}
sections: dict[str, list] = {}
all_names = set()
for f in g['files']:
hits, seen = [], set()
p = src / f['repo'] / f['path']
try:
lines = p.read_text(encoding='utf-8', errors='replace').splitlines()
except OSError:
lines = []
for ln, text in enumerate(lines, 1):
for name, kind, a, b in matcher.scan(text):
if name not in seen:
seen.add(name)
hits.append([name, ln, kind, evidence(text, a, b)])
for field in GRAPH_FIELDS:
v = f.get(field)
if isinstance(v, str):
for name, kind, a, b in matcher.scan(v):
if name not in seen:
seen.add(name)
hits.append([name, 0, kind, 'build_graph.json files[%s].%s: %s' % (f['id'], field, evidence(v, a, b))])
if not hits:
continue
all_names.update(seen)
files_out[str(f['id'])] = {'s': f['section'], 'b': f['block'], 'k': '%s/%s' % (f['repo'], f['path']),
'n': len(hits), 'm': hits[:MAX_PER_FILE], '_all': [h[0] for h in hits]}
sections.setdefault(str(f['section']), []).append(f['id'])
# keep only names that #sub= opens as themselves; count names See Through holds more than once
counts: dict[str, int] = {}
for v in names.values():
counts[v.strip()] = counts.get(v.strip(), 0) + 1
wrong = {nm for nm in all_names if landing(names, nm) != nm}
if wrong:
for fid in list(files_out):
rec = files_out[fid]
rec['m'] = [m for m in rec['m'] if m[0] not in wrong]
rec['n'] = sum(1 for nm in rec['_all'] if nm not in wrong)
if not rec['m']:
del files_out[fid]
sections = {}
for fid, rec in files_out.items():
sections.setdefault(str(rec['s']), []).append(int(fid))
all_names -= wrong
for rec in files_out.values():
rec.pop('_all', None)
twins = {nm: counts[nm] for nm in sorted(all_names) if counts.get(nm, 0) > 1}
by_low = {r.lower(): r for r in repos_tsv}
repo_map = {r['repo']: by_low[r['repo'].lower()] for r in g['repos'] if r['repo'].lower() in by_low}
return {
'schema': 'explore-seethrough-v1',
'base': base,
'source': 'see-through/%s/grid-data.js (window.KGGridData.substations.names, (c) OpenStreetMap contributors, ODbL)' % folder.name,
'cut': g.get('cut'),
'names': len(names), 'linkable': matcher.linkable, 'skipped': matcher.skipped,
'linked_files': len(files_out), 'linked_substations': len(all_names), 'dropped_wrong_landing': sorted(wrong),
'twins': twins,
'files': files_out, 'sections': sections, 'repos': repo_map,
}
INJ_RE = re.compile(r'<(?:link|script)\b[^>]*\bdata-ec-seethrough\b[^>]*>(?:</script>)?')
def inject(site: Path) -> int:
"""Test copies only: load seethrough.css/js on section and repo pages (marker data-ec-seethrough)."""
out = site / 'theme'
out.mkdir(exist_ok=True)
for name in ('seethrough.css', 'seethrough.js'):
shutil.copyfile(HERE / name, out / name)
n = 0
for sub in ('s', 'repos'):
for page in sorted((site / sub).glob('*.html')):
t = page.read_text(encoding='utf-8')
t2 = INJ_RE.sub('', t)
tags = ('<link rel="stylesheet" href="../theme/seethrough.css" data-ec-seethrough>'
'<script defer src="../theme/seethrough.js" data-ec-seethrough></script>')
t2 = t2.replace('</head>', tags + '</head>', 1)
if t2 != t:
page.write_text(t2, encoding='utf-8')
n += 1
return n
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
ap.add_argument('--site', required=True, type=Path)
ap.add_argument('--src', type=Path, default=Path('/home/claude/src'))
ap.add_argument('--seethrough', type=Path, default=None, help='the see-through folder (default <src>/kuiper-belt/see-through)')
ap.add_argument('--base', default=LIVE, help='See Through URL the overlay opens (default the live app)')
ap.add_argument('--inject', action='store_true', help='test copies only: add the tags to s/ and repos/ pages')
a = ap.parse_args(argv)
st = a.seethrough or a.src / 'kuiper-belt' / 'see-through'
idx = build(a.site, a.src, st, a.base)
(a.site / 'seethrough').mkdir(exist_ok=True)
(a.site / 'seethrough' / 'index.json').write_text(json.dumps(idx, ensure_ascii=False, separators=(',', ':')), encoding='utf-8')
print('seethrough: %d names, %d linkable, %d files linked, %d substations linked, %d repos mapped'
% (idx['names'], idx['linkable'], idx['linked_files'], idx['linked_substations'], len(idx['repos'])))
if a.inject:
print('seethrough: injected into %d pages' % inject(a.site))
return 0
if __name__ == '__main__':
sys.exit(main())