const API = "/api";
// The globe surface's violet tint (see onGlobeReady below) — reused as the
// civilian-flight color so those icons read as "part of the globe" rather
// than a separate alert layer, per the flights-overlay color spec.
const GLOBE_TINT_HEX = 0x6a3fd9;
const MILITARY_FLIGHT_HEX = 0xff33ff;
// News icons used to gradient violet->pink by corroborating-source count;
// flattened to a single bright magenta so they stay legible against the
// (also violet) globe tint — size still scales with source/article count.
const NEWS_ICON_HEX = 0xff33ff;
// Must match INCIDENT_MERGE_HOURS in backend/app/markets.py — display label only.
const INCIDENT_MERGE_HOURS_LABEL = "1h";
let config = { weather_enabled: false, conflict_enabled: false };
let clusters = []; // raw, server-side ~11km-grid clusters
let displayedClusters = []; // zoom-adaptive regrouping of `clusters`, currently on screen
let conflictEvents = [];
let clickRings = [];
let weatherMeshes = {}; // layer -> THREE.Mesh (built lazily, cached)
let activeWeatherLayer = null;
let currentAltitude = 2.2;
// ---------------------------------------------------------------- globe --
const globe = Globe()(document.getElementById("globeViz"))
.globeImageUrl("https://unpkg.com/three-globe/example/img/earth-blue-marble.jpg")
.bumpImageUrl("https://unpkg.com/three-globe/example/img/earth-topology.png")
.backgroundColor("#0f0d16")
.objectLat("lat")
.objectLng("lon")
.objectAltitude(0.014)
.objectThreeObject(buildGlobeObject)
.objectLabel(objectLabelFor)
.onObjectClick(onGlobeObjectClick)
.onZoom(({ altitude }) => {
currentAltitude = altitude;
scheduleRegroup();
})
.ringLat("lat")
.ringLng("lon")
.ringColor((d) => (t) =>
d.kind === "conflict" ? `rgba(245,5,5,${1 - t})` : `rgba(228,0,70,${1 - t})`
)
.ringMaxRadius((d) => d.maxR)
.ringPropagationSpeed(3)
.ringRepeatPeriod((d) => d.repeatPeriod);
// Degrees-of-arc -> scene units, so icon sprite sizes can be specified in
// the same "degrees" unit pointRadiusFor/declutter already use, and stay
// visually consistent with them.
const sceneUnitsPerDeg = (2 * Math.PI * globe.getGlobeRadius()) / 360;
const HELMET_ICON_DEG = 1.6;
globe.pointOfView({ lat: 20, lng: 20, altitude: 2.2 }, 0);
// Tint the globe surface (blue-marble texture) into the theme's violet
// range by multiplying it against the material's diffuse color, rather
// than a CSS filter on the whole canvas — that would also hue-shift the
// point/ring accent colors set below, which need to stay true to the
// palette. Must wait for onGlobeReady: three-globe (re)builds the mesh's
// material once the texture has loaded, which would otherwise orphan a
// tint applied immediately after construction.
globe.onGlobeReady(() => {
const globeMaterial = globe.globeMaterial();
globeMaterial.color = new THREE.Color(GLOBE_TINT_HEX);
globeMaterial.emissive = new THREE.Color(0x1a0e33);
globeMaterial.emissiveIntensity = 0.25;
});
// National border overlay: transparent fill (so it doesn't obscure the globe
// texture or news points) with a bright themed stroke. Natural Earth's
// admin-0 country polygons, served as a static asset from three-globe's own
// npm package via unpkg.
globe
.polygonAltitude(0.001)
.polygonCapColor(() => "rgba(0,0,0,0)")
.polygonSideColor(() => "rgba(0,0,0,0)")
.polygonStrokeColor(() => "#c9a6ff")
.polygonLabel((d) => escapeHtml(d.properties.ADMIN || d.properties.NAME || ""));
fetch("https://unpkg.com/three-globe@2.32.0/example/country-polygons/ne_110m_admin_0_countries.geojson")
.then((res) => res.json())
.then((geo) => globe.polygonsData(geo.features))
.catch((e) => console.warn("Could not load country borders", e));
function resizeGlobe() {
const el = document.getElementById("globeViz");
globe.width(el.clientWidth).height(el.clientHeight);
}
window.addEventListener("resize", resizeGlobe);
setTimeout(resizeGlobe, 0);
// ---- globe icon sprites (news clusters + conflict events) --------------
//
// Both are white-on-transparent alpha-mask canvases so a SpriteMaterial's
// `color` can tint them per-datum (news: the violet->pink gradient above;
// conflict: magenta) without needing separate colored art assets — same
// technique as the flight-plane icon further down.
let _newspaperIconTexture = null;
function newspaperIconTexture() {
if (_newspaperIconTexture) return _newspaperIconTexture;
const size = 64;
const canvas = document.createElement("canvas");
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "#ffffff";
ctx.beginPath();
ctx.moveTo(8, 8);
ctx.lineTo(46, 8);
ctx.lineTo(58, 20);
ctx.lineTo(58, 58);
ctx.lineTo(8, 58);
ctx.closePath();
ctx.fill();
ctx.globalCompositeOperation = "destination-out"; // cut "text line" gaps into the page
ctx.fillRect(14, 16, 30, 4);
ctx.fillRect(14, 26, 38, 3);
ctx.fillRect(14, 33, 38, 3);
ctx.fillRect(14, 40, 34, 3);
ctx.fillRect(14, 47, 28, 3);
ctx.globalCompositeOperation = "source-over";
_newspaperIconTexture = new THREE.CanvasTexture(canvas);
return _newspaperIconTexture;
}
let _helmetIconTexture = null;
function helmetIconTexture() {
if (_helmetIconTexture) return _helmetIconTexture;
const size = 64;
const canvas = document.createElement("canvas");
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "#ffffff";
ctx.beginPath();
ctx.arc(32, 30, 21, Math.PI, 0, false); // dome
ctx.lineTo(53, 36);
ctx.quadraticCurveTo(53, 43, 45, 43); // brim, right
ctx.lineTo(19, 43);
ctx.quadraticCurveTo(11, 43, 11, 36); // brim, left
ctx.closePath();
ctx.fill();
_helmetIconTexture = new THREE.CanvasTexture(canvas);
return _helmetIconTexture;
}
function makeIconSprite(texture, colorHex, scale) {
const material = new THREE.SpriteMaterial({
map: texture,
color: colorHex,
transparent: true,
depthWrite: false,
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(scale, scale, 1);
return sprite;
}
function buildGlobeObject(d) {
if (d.kind === "conflict") {
return makeIconSprite(helmetIconTexture(), MILITARY_FLIGHT_HEX, HELMET_ICON_DEG * sceneUnitsPerDeg);
}
return makeIconSprite(newspaperIconTexture(), NEWS_ICON_HEX, pointRadiusFor(d) * sceneUnitsPerDeg * 2.4);
}
function objectLabelFor(d) {
if (d.kind === "conflict") {
return `
`;
loadWikiSummary(cluster.location_name || cluster.country);
if (cluster.country) loadParliament(cluster.country);
loadClusterArticles(cluster.cluster_keys || [cluster.cluster_key]);
}
async function loadClusterArticles(clusterKeys) {
const el = document.getElementById("articleList");
try {
const results = await Promise.all(
clusterKeys.map((key) => fetch(`${API}/clusters/${encodeURIComponent(key)}/articles`).then((r) => r.json()))
);
const seen = new Set();
const articles = results
.flat()
.filter((a) => (seen.has(a.id) ? false : (seen.add(a.id), true)))
.sort((a, b) => new Date(b.published_at) - new Date(a.published_at));
el.innerHTML = articles.map(articleItemHtml).join("");
} catch (e) {
el.textContent = "Could not load stories.";
}
}
// Decorative publisher favicon, derived from the article's own URL so it
// works for any source without hand-curating logo assets (and without
// hotlinking an outlet's actual trademarked logo — favicons are the
// standard low-risk "site icon" browsers/RSS readers already show).
function faviconFor(url) {
try {
const host = new URL(url).hostname;
return `https://www.google.com/s2/favicons?sz=32&domain=${encodeURIComponent(host)}`;
} catch (e) {
return "";
}
}
function faviconImgHtml(a) {
const src = faviconFor(a.url);
if (!src) return "";
return ``;
}
function articleItemHtml(a) {
return `
`;
})
.join("");
el.querySelectorAll(".market-item").forEach((item) => {
item.onclick = () => toggleMarketDetail(item.dataset.symbol, item.dataset.idx);
});
rows.forEach((r, i) => loadSparkline(r.symbol, i));
} catch (e) {
console.error("Failed to load markets", e);
}
}
// 7-day price history as a small inline line+area chart, with a hover
// crosshair/tooltip (per dataviz interaction guidance: line charts ship
// hover by default). Single series per instrument, so no legend — the
// stroke reuses the theme's existing up/down status colors rather than
// introducing a new categorical hue.
async function loadSparkline(symbol, idx) {
const container = document.getElementById(`spark-${idx}`);
if (!container) return;
try {
const res = await fetch(`${API}/markets/history?symbol=${encodeURIComponent(symbol)}&hours=168`);
const history = await res.json();
mountSparkline(container, history);
} catch (e) {
console.error("Failed to load sparkline for", symbol, e);
}
}
function mountSparkline(container, history) {
container.innerHTML = "";
if (!history || history.length < 2) {
container.innerHTML = `
not enough history yet
`;
return;
}
const width = 280;
const height = 44;
const pad = 3;
const prices = history.map((h) => h.price);
const min = Math.min(...prices);
const max = Math.max(...prices);
const span = max - min || Math.abs(prices[0]) * 0.001 || 1;
const up = prices[prices.length - 1] >= prices[0];
const color = up ? "var(--c-green)" : "var(--c-red)";
const pts = history.map((h, i) => ({
x: pad + (i / (history.length - 1)) * (width - 2 * pad),
y: height - pad - ((h.price - min) / span) * (height - 2 * pad),
price: h.price,
t: h.recorded_at,
}));
const svgNS = "http://www.w3.org/2000/svg";
const svg = document.createElementNS(svgNS, "svg");
svg.setAttribute("viewBox", `0 0 ${width} ${height}`);
svg.setAttribute("preserveAspectRatio", "none");
svg.classList.add("spark");
const linePath = pts.map((p, i) => `${i === 0 ? "M" : "L"}${p.x.toFixed(1)},${p.y.toFixed(1)}`).join(" ");
const areaPath = `${linePath} L${pts[pts.length - 1].x.toFixed(1)},${height - pad} L${pts[0].x.toFixed(1)},${height - pad} Z`;
const area = document.createElementNS(svgNS, "path");
area.setAttribute("d", areaPath);
area.setAttribute("fill", color);
area.setAttribute("fill-opacity", "0.14");
area.setAttribute("stroke", "none");
svg.appendChild(area);
const line = document.createElementNS(svgNS, "path");
line.setAttribute("d", linePath);
line.setAttribute("fill", "none");
line.setAttribute("stroke", color);
line.setAttribute("stroke-width", "2");
line.setAttribute("stroke-linecap", "round");
line.setAttribute("stroke-linejoin", "round");
svg.appendChild(line);
const crosshair = document.createElementNS(svgNS, "line");
crosshair.setAttribute("y1", "0");
crosshair.setAttribute("y2", String(height));
crosshair.setAttribute("stroke", "var(--c-text-muted)");
crosshair.setAttribute("stroke-width", "1");
crosshair.setAttribute("stroke-dasharray", "2,2");
crosshair.style.display = "none";
svg.appendChild(crosshair);
const dot = document.createElementNS(svgNS, "circle");
dot.setAttribute("r", "2.6");
dot.setAttribute("fill", color);
dot.style.display = "none";
svg.appendChild(dot);
container.appendChild(svg);
const tooltip = document.createElement("div");
tooltip.className = "spark-tooltip hidden";
container.appendChild(tooltip);
svg.addEventListener("mousemove", (ev) => {
const rect = svg.getBoundingClientRect();
const relX = ((ev.clientX - rect.left) / rect.width) * width;
let nearest = 0;
let bestDist = Infinity;
pts.forEach((p, i) => {
const d = Math.abs(p.x - relX);
if (d < bestDist) {
bestDist = d;
nearest = i;
}
});
const p = pts[nearest];
crosshair.setAttribute("x1", p.x.toFixed(1));
crosshair.setAttribute("x2", p.x.toFixed(1));
crosshair.style.display = "";
dot.setAttribute("cx", p.x.toFixed(1));
dot.setAttribute("cy", p.y.toFixed(1));
dot.style.display = "";
tooltip.textContent = `${p.price.toLocaleString(undefined, { maximumFractionDigits: 2 })} · ${new Date(p.t).toLocaleString()}`;
tooltip.classList.remove("hidden");
const leftPct = p.x / width;
tooltip.style.left = `${Math.min(70, Math.max(0, leftPct * 100 - 30))}%`;
});
svg.addEventListener("mouseleave", () => {
crosshair.style.display = "none";
dot.style.display = "none";
tooltip.classList.add("hidden");
});
}
// "Likely factors": the words that recur most across every headline
// published in a spike's window (backend textutil.py — stopword-filtered
// word frequency, no AI/LLM). A hint worth reading the linked articles
// over, not an explanation, so it's labeled as such wherever it's shown.
function keywordTagsHtml(keywords) {
if (!keywords || !keywords.length) return "";
const tags = keywords.map(([word, count]) => `${escapeHtml(word)} · ${count}`).join("");
return `
Likely factors (common words in this window): ${tags}
`;
}
async function toggleMarketDetail(symbol, idx) {
const el = document.getElementById(`market-detail-${idx}`);
const wasHidden = el.classList.contains("hidden");
document.querySelectorAll(".market-detail").forEach((d) => d.classList.add("hidden"));
if (!wasHidden) return;
el.classList.remove("hidden");
el.innerHTML = `
Loading recent moves…
`;
try {
const res = await fetch(`${API}/markets/spikes?symbol=${encodeURIComponent(symbol)}&hours=720`);
const spikes = await res.json();
if (!spikes.length) {
el.innerHTML = `
`;
}
}
// An "incident" is one or more spikes merged because they landed within an
// hour of each other (backend: markets.merge_spikes_into_incidents) — e.g.
// WTI and Brent crude spiking together shows as one incident, not two.
function econIncidentHtml(inc) {
const fmtHour = (iso) =>
new Date(iso).toLocaleString(undefined, {
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
});
const instrumentsHtml = inc.instruments
.map((i) => {
const dir = i.pct_change > 0 ? "up" : "down";
const arrow = i.pct_change > 0 ? "▲" : "▼";
return `${escapeHtml(i.label)} ${arrow} ${i.pct_change.toFixed(2)}%`;
})
.join("");
const articlesHtml = inc.candidate_articles.length
? inc.candidate_articles.map(articleItemHtml).join("")
: `
No stories found published in that window.
`;
return `
${instrumentsHtml}
${fmtHour(inc.window_start)} – ${fmtHour(inc.window_end)}
· ${inc.candidate_articles.length} stor${inc.candidate_articles.length === 1 ? "y" : "ies"} in window
${inc.instruments.length > 1 ? ` · ${inc.instruments.length} instruments moved within ${INCIDENT_MERGE_HOURS_LABEL} of each other` : ""}
${keywordTagsHtml(inc.top_keywords)}
${articlesHtml}
`;
}
// -------------------------------------------------------------- flights --
//
// Rendered as a single THREE.Points cloud (not three-globe's per-datum
// pointsData/objectsData layers, already used by news clusters) since a
// live global snapshot can be several thousand aircraft — one draw call
// keeps that cheap. The tradeoff: point sprites all face the camera and
// don't support per-instance rotation, so icons aren't heading-aligned.
// Military classification is a best-effort heuristic from the backend (see
// backend/app/data/military_ranges.yaml); color is the only encoding
// (magenta = flagged military, globe-tint purple = everything else) and
// isn't itself a claim of certainty — the hover tooltip states as much.
let flightsPoints = null;
let flightsData = [];
let flightsPollTimer = null;
let flightsPollSeconds = 300;
const flightRaycaster = new THREE.Raycaster();
flightRaycaster.params.Points.threshold = 2.5;
function altitudeForFlight(f) {
const m = f.altitude_m || 0;
return 0.02 + Math.min(1, m / 12000) * 0.03;
}
// A small top-down airplane silhouette, drawn once as a white-on-transparent
// alpha mask so PointsMaterial's vertexColors can tint it per-aircraft
// (military vs civilian) without needing separate red/gray sprite sheets.
let _planeIconTexture = null;
function planeIconTexture() {
if (_planeIconTexture) return _planeIconTexture;
const size = 64;
const canvas = document.createElement("canvas");
canvas.width = size;
canvas.height = size;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "#ffffff";
ctx.beginPath();
ctx.moveTo(32, 3); // nose
ctx.lineTo(36, 24);
ctx.lineTo(61, 39); // right wingtip
ctx.lineTo(61, 45);
ctx.lineTo(37, 38);
ctx.lineTo(35, 50);
ctx.lineTo(47, 59); // right tailtip
ctx.lineTo(47, 63);
ctx.lineTo(32, 57); // tail center
ctx.lineTo(17, 63); // left tailtip
ctx.lineTo(17, 59);
ctx.lineTo(29, 50);
ctx.lineTo(27, 38);
ctx.lineTo(3, 45); // left wingtip
ctx.lineTo(3, 39);
ctx.lineTo(28, 24);
ctx.closePath();
ctx.fill();
_planeIconTexture = new THREE.CanvasTexture(canvas);
return _planeIconTexture;
}
function buildFlightsPoints(flights) {
const geometry = new THREE.BufferGeometry();
const positions = new Float32Array(flights.length * 3);
const colors = new Float32Array(flights.length * 3);
const milColor = new THREE.Color(MILITARY_FLIGHT_HEX);
const civColor = new THREE.Color(GLOBE_TINT_HEX);
flights.forEach((f, i) => {
const { x, y, z } = globe.getCoords(f.lat, f.lon, altitudeForFlight(f));
positions[i * 3] = x;
positions[i * 3 + 1] = y;
positions[i * 3 + 2] = z;
const c = f.is_military ? milColor : civColor;
colors[i * 3] = c.r;
colors[i * 3 + 1] = c.g;
colors[i * 3 + 2] = c.b;
});
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
geometry.setAttribute("color", new THREE.BufferAttribute(colors, 3));
const material = new THREE.PointsMaterial({
size: 4,
map: planeIconTexture(),
alphaTest: 0.3,
vertexColors: true,
sizeAttenuation: true,
transparent: true,
depthWrite: false,
});
return new THREE.Points(geometry, material);
}
async function loadFlights() {
try {
const res = await fetch(`${API}/flights`);
flightsData = await res.json();
renderFlights();
} catch (e) {
console.error("Failed to load flights", e);
}
}
// Rebuilds the points cloud from the last-fetched snapshot, applying the
// "Military only" filter — kept separate from loadFlights so toggling the
// filter is instant and doesn't wait on a network round-trip.
let flightsRendered = []; // the array actually backing the current geometry (post-filter), for hover lookups
function renderFlights() {
if (flightsPoints) {
globe.scene().remove(flightsPoints);
flightsPoints.geometry.dispose();
flightsPoints.material.dispose();
flightsPoints = null;
}
if (!document.getElementById("toggleFlights").checked) return;
const militaryOnly = document.getElementById("toggleMilitaryOnly").checked;
flightsRendered = militaryOnly ? flightsData.filter((f) => f.is_military) : flightsData;
flightsPoints = buildFlightsPoints(flightsRendered);
globe.scene().add(flightsPoints);
const milCount = flightsData.filter((f) => f.is_military).length;
document.getElementById("flightCount").textContent = flightsData.length
? militaryOnly
? `${milCount} military-flagged (of ${flightsData.length})`
: `${flightsData.length} aircraft · ${milCount} military-flagged`
: "no data yet";
}
function setFlightsVisible(visible) {
if (visible) {
loadFlights();
flightsPollTimer = setInterval(loadFlights, Math.max(15, flightsPollSeconds) * 1000);
} else {
if (flightsPollTimer) clearInterval(flightsPollTimer);
flightsPollTimer = null;
if (flightsPoints) {
globe.scene().remove(flightsPoints);
flightsPoints.geometry.dispose();
flightsPoints.material.dispose();
flightsPoints = null;
}
document.getElementById("flightCount").textContent = "";
document.getElementById("flightTooltip").classList.add("hidden");
}
}
const flightTooltip = document.getElementById("flightTooltip");
document.getElementById("globeViz").addEventListener("mousemove", (ev) => {
if (!flightsPoints) return;
const el = document.getElementById("globeViz");
const rect = el.getBoundingClientRect();
const mouse = new THREE.Vector2(
((ev.clientX - rect.left) / rect.width) * 2 - 1,
-((ev.clientY - rect.top) / rect.height) * 2 + 1
);
flightRaycaster.setFromCamera(mouse, globe.camera());
const hits = flightRaycaster.intersectObject(flightsPoints);
const f = hits.length ? flightsRendered[hits[0].index] : null;
if (!f) {
flightTooltip.classList.add("hidden");
return;
}
flightTooltip.innerHTML = `
${escapeHtml(f.callsign || f.icao24)}${f.is_military ? ' MIL (heuristic)' : ""}
${escapeHtml(f.origin_country || "")}
${f.altitude_m != null ? Math.round(f.altitude_m) + " m" : ""}${
f.velocity_ms != null ? " · " + Math.round(f.velocity_ms * 3.6) + " km/h" : ""
}
`;
flightTooltip.style.left = ev.clientX + 12 + "px";
flightTooltip.style.top = ev.clientY + 12 + "px";
flightTooltip.classList.remove("hidden");
});
// --------------------------------------------------------------- wiring --
document.getElementById("refreshBtn").onclick = async () => {
await fetch(`${API}/refresh`, { method: "POST" });
setTimeout(loadClusters, 1500);
setTimeout(loadNewsFeed, 1500);
};
document.getElementById("toggleWeather").onchange = (ev) => {
activeWeatherLayer = ev.target.checked ? document.getElementById("weatherLayer").value : null;
setWeatherLayer(activeWeatherLayer);
};
document.getElementById("weatherLayer").onchange = (ev) => {
if (document.getElementById("toggleWeather").checked) setWeatherLayer(ev.target.value);
};
document.getElementById("toggleConflict").onchange = () => {
if (!conflictEvents.length) loadConflictEvents();
else {
syncRings();
syncGlobeObjects();
}
};
document.getElementById("toggleFlights").onchange = (ev) => setFlightsVisible(ev.target.checked);
document.getElementById("toggleMilitaryOnly").onchange = () => {
if (document.getElementById("toggleFlights").checked) renderFlights();
};
async function init() {
try {
config = await (await fetch(`${API}/config`)).json();
} catch (e) {
console.warn("Could not load config; assuming weather/conflict disabled", e);
}
document.getElementById("toggleWeather").disabled = !config.weather_enabled;
document.getElementById("toggleConflict").disabled = !config.conflict_enabled;
flightsPollSeconds = config.flights_poll_seconds || 300;
await loadClusters();
await loadNewsFeed();
await loadMarkets();
await loadConflictEvents();
resizeGlobe();
setInterval(loadClusters, 60_000);
setInterval(loadNewsFeed, 60_000);
setInterval(loadMarkets, 5 * 60_000);
setInterval(loadConflictEvents, 10 * 60_000);
}
init();