// ==UserScript==
// @name OE2 Survey Scan Tracker
// @namespace https://game.dev.outerempires.net/
// @version 1.2
// @description Track survey scan jobs vs cargo scans via API + WebSocket
// @match https://game.dev.outerempires.net/*
// @icon https://outerempires.net/favicon.ico
// @grant GM_xmlhttpRequest
// @connect oe2-pub-api-dev.azure-api.net
// ==/UserScript==
(function () {
'use strict';
const BASE_URL = 'https://oe2-pub-api-dev.azure-api.net';
const APP_ID = 'e0315d43-df72-4cf5-8fef-aff4f94e6c0c';
const CLIENT_ID = '76561199402618688';
const CLIENT_SECRET = 'VJlLZd5+5rSl9w9M4ZFJ2FApPoPqUH/Q/zj9WKLK6b0=';
// ── WebSocket interceptor (addEventListener only — no constructor override) ──
(function () {
var _origAdd = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function (type, listener, options) {
if (type === 'message' && this instanceof WebSocket) {
var self = this;
var wrapped = function (e) {
if (typeof e.data === 'string') tryWSMessage(e.data);
if (typeof listener === 'function') return listener.apply(self, arguments);
else if (listener && typeof listener.handleEvent === 'function') return listener.handleEvent(e);
};
return _origAdd.call(this, type, wrapped, options);
}
return _origAdd.apply(this, arguments);
};
function tryWSMessage(text) {
try { var p = JSON.parse(text); } catch (e) { return; }
var msgs = Array.isArray(p) ? p : [p];
for (var i = 0; i < msgs.length; i++) {
var m = msgs[i];
if (m.message_type === 'GameUpdate' && m.message) {
handleGameUpdate(m.message);
}
}
}
})();
function handleGameUpdate(msg) {
var action = msg.action;
var payload = msg.payload;
if (!action || !payload) return;
if (action === 'ScanData') {
var cargo = payload.cargo;
if (cargo && cargo.typeC === 'Sc') {
// Dedup by id
var exists = false;
for (var xi = 0; xi < cargoScans.length; xi++) {
if (cargoScans[xi].id === cargo.id) { exists = true; break; }
}
if (!exists) {
cargoScans.push(cargo);
lastCargoFetch = Date.now();
onCargoChanged();
}
}
return;
}
// Log unknown actions for discovery (skip noisy ShipPartsUpdate)
if (action !== 'ShipPartsUpdate') {
console.log('[Survey WS] GameUpdate action:', action, payload);
}
}
function onCargoChanged() {
if (isPanelVisible) renderPanel();
highlightStellarBodies();
highlightJumpLanes();
highlightOrbitals();
}
var panelEl = null;
var reopenBtn = null;
var isPanelVisible = false;
var isDragging = false, dragOffX = 0, dragOffY = 0;
var panelPosKey = 'oe2-survey-pos';
// Data
var jobsCache = []; // parsed survey jobs from DOM
var cargoScans = []; // scan items from cargo API
var lastCargoFetch = 0;
var lastJobScrape = 0;
function getContainer() {
return document.querySelector('#ui-component') || document.body;
}
// ── Styles (same rp-* as rank tracker) ────────────────
function ensureStyles() {
if (document.getElementById('oe2-survey-st')) return;
var el = document.createElement('style');
el.id = 'oe2-survey-st';
el.textContent = [
'#oe2-survey-panel{position:fixed;z-index:200;top:50%;right:64px;transform:translateY(-50%);background:rgba(6,12,22,0.35);padding:4px 0;width:390px;border-radius:4px;pointer-events:auto;cursor:move;user-select:none;text-shadow:0 0 8px #000,0 1px 4px #000;font-family:Rajdhani,"Segoe UI",sans-serif;color:#c8d6e5;font-size:14px;max-height:80vh;display:flex;flex-direction:column;}',
'#oe2-survey-panel .rp-hdr{display:flex;align-items:center;justify-content:space-between;padding:4px 8px;cursor:move;flex-shrink:0;}',
'#oe2-survey-panel .rp-title{font-size:12px;font-weight:700;color:#7ecfff;letter-spacing:.5px;}',
'#oe2-survey-panel .rp-close{cursor:pointer;color:#546e7a;font-size:14px;line-height:1;opacity:.6;}',
'#oe2-survey-panel .rp-close:hover{opacity:1;color:#ef5350;}',
'#oe2-survey-panel .rp-refresh{cursor:pointer;color:#546e7a;font-size:13px;line-height:1;opacity:.6;margin-right:4px;}',
'#oe2-survey-panel .rp-refresh:hover{opacity:1;color:#4dd0e1;}',
'#oe2-survey-panel .rp-meta{font-size:10px;color:#546e7a;padding:0 8px 4px;flex-shrink:0;}',
'#oe2-survey-panel .rp-scroll{overflow-y:auto;flex:1;padding:0 8px;}',
'#oe2-survey-panel .rp-empty{color:#546e7a;font-size:12px;padding:8px;text-align:center;}',
'#oe2-survey-panel .rp-footer{font-size:9px;color:#37474f;padding:2px 8px 4px;text-align:right;flex-shrink:0;}',
'#oe2-survey-panel .rp-row{display:flex;align-items:center;padding:3px 0;gap:4px;font-size:13px;font-weight:600;border-bottom:1px solid rgba(255,255,255,.03);}',
'#oe2-survey-panel .rp-name{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}',
'#oe2-survey-panel .rp-r{width:36px;text-align:right;font-size:11px;color:#78909c;font-weight:400;}',
'#oe2-survey-panel .rp-detail{font-size:11px;padding:0 0 6px 12px;color:#78909c;}',
'#oe2-survey-panel .rp-detail .rp-drow{display:flex;gap:6px;padding:1px 0;}',
'#oe2-survey-panel .rp-detail .rp-dt{color:#546e7a;width:60px;flex-shrink:0;}',
'#oe2-survey-panel .rp-detail .rp-dv{color:#c8d6e5;}',
'#oe2-survey-panel .rp-done{color:#4dd0e1;}',
'#oe2-survey-panel .rp-pending{color:#ef5350;}',
'#oe2-survey-panel .rp-progress{font-size:10px;color:#546e7a;padding:2px 0;}',
'#oe2-survey-panel .rp-bar-wrap{display:flex;align-items:center;gap:2px;margin:4px 0;}',
'#oe2-survey-panel .rp-bar-seg{height:8px;border-radius:2px;flex:1;}',
'#oe2-survey-panel .rp-bar-done{background:#4dd0e1;}',
'#oe2-survey-panel .rp-bar-pending{background:#37474f;}',
'.oe-survey-click{cursor:pointer;padding:0 2px;border-radius:2px;}',
'.oe-survey-click:hover{outline:1px solid rgba(255,255,255,0.3);}',
'.oe-survey-body-needs-scan{background:rgba(239,83,80,0.25)!important;border-radius:3px;box-shadow:0 0 6px rgba(239,83,80,0.3);}',
'@keyframes oe-survey-pulse{0%,100%{opacity:1;}50%{opacity:.4;}}',
'.oe-survey-body-scanned{background:rgba(77,208,225,0.2)!important;border-radius:3px;box-shadow:0 0 6px rgba(77,208,225,0.25);animation:oe-survey-pulse 1.2s ease-in-out infinite;}',
'.oe-survey-body-done{background:rgba(77,208,225,0.08)!important;border-radius:3px;}',
'.oe-survey-jump-match{background:rgba(77,208,225,0.2)!important;border-radius:3px;box-shadow:0 0 8px rgba(77,208,225,0.35);}',
'.oe-survey-jump-match .SystemExplorer_ObjectName{color:#4dd0e1!important;}',
'.oe-survey-station-match{background:rgba(77,208,225,0.2)!important;border-radius:3px;box-shadow:0 0 8px rgba(77,208,225,0.35);}',
'.oe-survey-station-match .SystemExplorer_ObjectName{color:#4dd0e1!important;}',
'#oe2-survey-reopen{position:fixed;z-index:200;top:calc(50% + 40px);right:16px;width:32px;height:32px;border-radius:50%;background:rgba(6,12,22,0.35);border:1px solid rgba(77,208,225,0.3);color:#4dd0e1;font-size:14px;cursor:pointer;box-shadow:0 0 12px rgba(77,208,225,0.1);display:flex;align-items:center;justify-content:center;transition:all .2s;user-select:none;}',
'#oe2-survey-reopen:hover{border-color:#7ecfff;box-shadow:0 0 16px rgba(0,229,255,0.2)!important;}',
].join('');
document.head.appendChild(el);
}
// ── Panel controls ────────────────────────────────────
function createReopenBtn() {
if (reopenBtn) { reopenBtn.style.display = 'flex'; return; }
ensureStyles();
reopenBtn = document.createElement('div');
reopenBtn.id = 'oe2-survey-reopen';
reopenBtn.textContent = '\u25B6';
reopenBtn.title = 'Survey Tracker';
reopenBtn.addEventListener('click', showPanel);
getContainer().appendChild(reopenBtn);
}
function hidePanel() {
if (panelEl) panelEl.style.display = 'none';
isPanelVisible = false;
createReopenBtn();
}
function showPanel() {
if (reopenBtn) reopenBtn.style.display = 'none';
if (!panelEl) createPanel();
panelEl.style.display = 'flex';
isPanelVisible = true;
refreshAll();
}
function togglePanel() {
if (isPanelVisible && panelEl && panelEl.style.display !== 'none') hidePanel();
else showPanel();
}
function createPanel() {
ensureStyles();
panelEl = document.createElement('div');
panelEl.id = 'oe2-survey-panel';
var saved = localStorage.getItem(panelPosKey);
if (saved) {
try { var p = JSON.parse(saved); panelEl.style.transform = 'none'; panelEl.style.top = p.y + 'px'; panelEl.style.right = p.x + 'px'; } catch (e) {}
}
panelEl.innerHTML = [
'
\u25B6 SURVEYS\u21BB\u2715
',
'',
'',
'',
].join('');
panelEl.querySelector('.rp-close').addEventListener('click', hidePanel);
panelEl.querySelector('.rp-refresh').addEventListener('click', refreshAll);
panelEl.addEventListener('mousedown', function (e) {
if (e.target.closest('.rp-close') || e.target.closest('.rp-refresh')) return;
isDragging = true;
var r = panelEl.getBoundingClientRect();
dragOffX = e.clientX - r.left;
dragOffY = e.clientY - r.top;
panelEl.style.transform = 'none';
panelEl.style.right = (window.innerWidth - r.right) + 'px';
panelEl.style.top = r.top + 'px';
});
getContainer().appendChild(panelEl);
}
document.addEventListener('mousemove', function (e) {
if (!isDragging || !panelEl) return;
panelEl.style.left = (e.clientX - dragOffX) + 'px';
panelEl.style.top = (e.clientY - dragOffY) + 'px';
panelEl.style.right = '';
});
document.addEventListener('mouseup', function () {
if (isDragging && panelEl) {
isDragging = false;
panelEl.style.cursor = '';
var r = panelEl.getBoundingClientRect();
localStorage.setItem(panelPosKey, JSON.stringify({ y: r.top, x: window.innerWidth - r.right }));
}
});
// ── Click-to-search (borrowed from Jobs QoL) ──────────
var lastTargetedInput = null;
var pendingClearHandler = null;
var armedAt = 0;
function findSearchInput() {
var vpMid = window.innerWidth / 2;
var all = document.querySelectorAll('input[type="text"], input[type="search"]');
var candidates = [];
for (var i = 0; i < all.length; i++) {
var el = all[i];
if (el.offsetParent === null) continue;
if (el.id === 'system-input') continue;
var ph = (el.placeholder || '').toLowerCase();
if (ph.indexOf('search') === -1 && ph.indexOf('filter') === -1) continue;
candidates.push(el);
}
if (candidates.length === 0) return null;
// Prefer input on the right side (system explorer)
var rightSide = candidates.filter(function (el) {
var r = el.getBoundingClientRect();
return (r.left + r.width / 2) >= vpMid;
});
return (rightSide.length ? rightSide : candidates)[0];
}
function nativeSetValue(input, value) {
var proto = Object.getPrototypeOf(input);
var desc = Object.getOwnPropertyDescriptor(proto, 'value')
|| Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
if (desc && desc.set) desc.set.call(input, value);
else input.value = value;
}
function fireKey(input, type, key) {
input.dispatchEvent(new KeyboardEvent(type, {
key: key, code: key === 'Enter' ? 'Enter' : 'Key' + key.toUpperCase(),
keyCode: key === 'Enter' ? 13 : key.charCodeAt(0),
which: key === 'Enter' ? 13 : key.charCodeAt(0),
bubbles: true, cancelable: true
}));
}
function fireInputEvents(input) {
input.dispatchEvent(new Event('input', { bubbles: true }));
input.dispatchEvent(new Event('change', { bubbles: true }));
}
function clearSearch() {
var candidates = [];
if (lastTargetedInput && document.contains(lastTargetedInput)) candidates.push(lastTargetedInput);
var input = findSearchInput();
if (input && candidates.indexOf(input) === -1) candidates.push(input);
var seen = new Set();
for (var ci = 0; ci < candidates.length; ci++) {
var inp = candidates[ci];
if (!inp || seen.has(inp) || inp.value === '') continue;
seen.add(inp);
nativeSetValue(inp, '');
fireKey(inp, 'keydown', 'Backspace');
fireInputEvents(inp);
fireKey(inp, 'keyup', 'Backspace');
}
}
function cancelPendingClear() {
if (pendingClearHandler) {
document.removeEventListener('click', pendingClearHandler, true);
pendingClearHandler = null;
}
}
function scheduleClearOnNextClick() {
cancelPendingClear();
armedAt = performance.now();
pendingClearHandler = function (ev) {
if (ev.button !== 0) return;
if (performance.now() - armedAt < 50) return;
if (ev.target && ev.target.closest && ev.target.closest('.oe-survey-click')) return;
cancelPendingClear();
setTimeout(clearSearch, 0);
};
document.addEventListener('click', pendingClearHandler, true);
}
function pasteToSearch(text) {
var input = findSearchInput();
if (!input) return;
lastTargetedInput = input;
input.focus();
nativeSetValue(input, '');
fireKey(input, 'keydown', 'Backspace');
fireInputEvents(input);
fireKey(input, 'keyup', 'Backspace');
nativeSetValue(input, text);
var lastChar = text.slice(-1) || 'a';
fireKey(input, 'keydown', lastChar);
fireInputEvents(input);
fireKey(input, 'keyup', lastChar);
fireKey(input, 'keydown', 'Enter');
fireKey(input, 'keypress', 'Enter');
fireKey(input, 'keyup', 'Enter');
setTimeout(function () {
if (input.value !== text) return;
nativeSetValue(input, text + ' ');
fireKey(input, 'keydown', ' ');
fireInputEvents(input);
fireKey(input, 'keyup', ' ');
nativeSetValue(input, text);
fireKey(input, 'keydown', 'Backspace');
fireInputEvents(input);
fireKey(input, 'keyup', 'Backspace');
}, 0);
scheduleClearOnNextClick();
}
// ── Auth token ────────────────────────────────────────
function getToken() {
return new Promise(function (resolve, reject) {
GM_xmlhttpRequest({
method: 'POST',
url: BASE_URL + '/v1/auth/token',
headers: { 'Content-Type': 'application/json' },
data: JSON.stringify({
appId: APP_ID,
clientId: CLIENT_ID,
secret: CLIENT_SECRET,
grantType: 'client_credentials'
}),
onload: function (resp) {
try {
var body = JSON.parse(resp.responseText);
if (body.success) resolve(body.data.accessToken);
else reject(body.returnString || 'Auth failed');
} catch (e) { reject(e); }
},
onerror: reject
});
});
}
// ── Cargo API ─────────────────────────────────────────
function fetchCargo() {
return getToken().then(function (token) {
return new Promise(function (resolve, reject) {
GM_xmlhttpRequest({
method: 'GET',
url: BASE_URL + '/v1/ship/cargo',
headers: {
'Authorization': 'Bearer ' + token,
'X-App-Id': APP_ID
},
onload: function (resp) {
try {
var body = JSON.parse(resp.responseText);
if (body.success) {
var items = body.data.cargo || [];
cargoScans = items.filter(function (item) { return item.typeC === 'Sc'; });
lastCargoFetch = Date.now();
resolve(cargoScans);
} else {
reject(body.returnString);
}
} catch (e) { reject(e); }
},
onerror: reject
});
});
});
}
// ── Job scraper ───────────────────────────────────────
function scrapeJobs() {
var list = document.getElementById('JobListAccepted');
if (!list) return false;
// Empty job tab → clear cache
if (list.querySelector('.JobNotAvailable')) {
jobsCache = [];
try { localStorage.removeItem(jobsStorageKey); } catch (e) {}
return false;
}
var items = list.querySelectorAll('.JobItem[id^="availableJob_"]');
if (items.length === 0) return false;
var parsed = [];
for (var i = 0; i < items.length; i++) {
var item = items[i];
// Check if it's a Survey contract
var nameEl = item.querySelector('.JobItem_Detail_Name');
var contractText = nameEl ? nameEl.textContent.trim() : '';
if (contractText.indexOf('Survey') === -1 && contractText.indexOf('scan to') === -1) continue;
// Get job ID
var idMatch = item.id.match(/availableJob_(\d+)/);
var jobId = idMatch ? parseInt(idMatch[1], 10) : 0;
// Get job type (Pri, Pub, Mil)
var typeEl = item.querySelector('.JobLeftType');
var jobType = typeEl ? typeEl.textContent.trim() : '';
// Get job status
var statusEl = item.querySelector('.JobStatus .ui_text_yellow_light');
var status = statusEl ? statusEl.textContent.trim() : '';
// Parse target from description .oe-loc elements
var descEl = item.querySelector('.text_justified');
var locs = descEl ? descEl.querySelectorAll('.oe-loc') : [];
var targetMoon = locs.length > 0 ? locs[0].textContent.trim() : '';
var targetSystem = locs.length > 1 ? locs[1].textContent.trim() : '';
var deliverStation = locs.length > 2 ? locs[2].textContent.trim() : '';
var deliverSystem = locs.length > 3 ? locs[3].textContent.trim() : '';
if (!targetMoon) continue;
parsed.push({
jobId: jobId,
type: jobType,
status: status,
targetMoon: targetMoon,
targetSystem: targetSystem,
deliverStation: deliverStation,
deliverSystem: deliverSystem,
isScanned: status.indexOf('scanned') !== -1 || status.indexOf('Deliver') !== -1
});
}
if (parsed.length === 0) return false;
jobsCache = parsed;
lastJobScrape = Date.now();
saveJobsCache();
return true;
}
window.scrapeJobs = scrapeJobs;
window.jobsCacheRef = function () { return jobsCache; };
// ── Matching logic ────────────────────────────────────
function countScansForTarget(moon, system) {
var prefix = moon + ', ' + system;
var count = 0;
for (var i = 0; i < cargoScans.length; i++) {
var name = cargoScans[i].resourceName || '';
if (name.indexOf(prefix) === 0) count++;
}
return count;
}
// ── Aggregate unique targets ──────────────────────────
function aggregateTargets() {
var groups = {};
for (var i = 0; i < jobsCache.length; i++) {
var job = jobsCache[i];
var key = job.targetMoon + '|' + job.targetSystem;
if (!groups[key]) {
groups[key] = {
targetMoon: job.targetMoon,
targetSystem: job.targetSystem,
deliverStation: job.deliverStation,
deliverSystem: job.deliverSystem,
needed: 0,
jobs: []
};
}
groups[key].needed++;
groups[key].jobs.push(job);
}
return groups;
}
// ── Render panel ──────────────────────────────────────
function renderPanel() {
if (!panelEl || panelEl.style.display === 'none') return;
var scrollEl = panelEl.querySelector('.rp-scroll');
var metaEl = panelEl.querySelector('.rp-meta');
var footerEl = panelEl.querySelector('.rp-footer');
if (jobsCache.length === 0 && cargoScans.length === 0) {
scrollEl.innerHTML = 'Open accepted jobs to scan surveys\u2026
';
if (metaEl) metaEl.textContent = '';
if (footerEl) footerEl.textContent = '';
return;
}
var groups = aggregateTargets();
var keys = Object.keys(groups);
if (keys.length === 0) {
scrollEl.innerHTML = 'No survey contracts found in accepted jobs.
';
if (metaEl) metaEl.textContent = 'No survey jobs';
if (footerEl) footerEl.textContent = '';
return;
}
var totalNeeded = 0;
var totalCompleted = 0;
// Sort: by completion status (incomplete first), then by name
keys.sort(function (a, b) {
var ga = groups[a], gb = groups[b];
var ca = countScansForTarget(ga.targetMoon, ga.targetSystem);
var cb = countScansForTarget(gb.targetMoon, gb.targetSystem);
var aDone = ca >= ga.needed;
var bDone = cb >= gb.needed;
if (aDone !== bDone) return aDone ? 1 : -1;
return ga.targetMoon.localeCompare(gb.targetMoon);
});
var html = '';
for (var ki = 0; ki < keys.length; ki++) {
var group = groups[keys[ki]];
var completed = countScansForTarget(group.targetMoon, group.targetSystem);
var needed = group.needed;
totalNeeded += needed;
totalCompleted += Math.min(completed, needed);
var allDone = completed >= needed;
var statusIcon = allDone ? '\u2713' : '\u25A1';
// Progress bar segments
var barHtml = '';
for (var si = 0; si < needed; si++) {
var done = si < completed;
barHtml += '
';
}
barHtml += '
';
html += '';
html += '' + statusIcon + ' ' + esc(group.targetMoon) + '';
html += '' + completed + '/' + needed + '';
html += '
';
html += '';
html += '
System' + esc(group.targetSystem) + '
';
if (group.deliverStation) html += '
Deliver to' + esc(group.deliverStation) + ' (' + esc(group.deliverSystem) + ')
';
html += barHtml;
html += '
';
}
scrollEl.innerHTML = html;
// Delegate clicks on .oe-survey-click to paste into search
scrollEl.querySelectorAll('.oe-survey-click').forEach(function (el) {
el.addEventListener('click', function (e) {
e.stopPropagation();
var q = el.getAttribute('data-search');
if (q) pasteToSearch(q);
});
});
if (metaEl) {
metaEl.textContent = totalCompleted + '/' + totalNeeded + ' scans | ' + cargoScans.length + ' in cargo';
}
if (footerEl) {
var pct = totalNeeded > 0 ? Math.round(totalCompleted / totalNeeded * 100) : 0;
footerEl.textContent = totalCompleted >= totalNeeded ? '\u2713 ALL COMPLETE' : pct + '% complete';
}
}
function esc(s) {
var d = document.createElement('div');
d.textContent = s;
return d.innerHTML;
}
// ── Load cached jobs from localStorage ────────────────
var jobsStorageKey = 'oe2-survey-jobs';
function saveJobsCache() {
try { localStorage.setItem(jobsStorageKey, JSON.stringify({ jobs: jobsCache, time: Date.now() })); } catch (e) {}
}
function loadJobsFromCache() {
try {
var data = JSON.parse(localStorage.getItem(jobsStorageKey));
if (data && Array.isArray(data.jobs) && data.jobs.length > 0) {
jobsCache = data.jobs;
lastJobScrape = data.time || Date.now();
return true;
}
} catch (e) {}
return false;
}
// ── Refresh ───────────────────────────────────────────
function refreshAll() {
scrapeJobs();
if (jobsCache.length === 0) loadJobsFromCache();
fetchCargo().then(function () { renderPanel(); }).catch(function () { renderPanel(); });
}
// ── DOM observer for jobs tab ─────────────────────────
function watchJobsPanel() {
var list = document.getElementById('JobListAccepted');
if (!list) { setTimeout(watchJobsPanel, 2000); return; }
// Initial scrape
scrapeJobs();
// Observe changes — re-scrape jobs when DOM changes
new MutationObserver(function () {
scrapeJobs();
if (isPanelVisible) renderPanel();
}).observe(list, { childList: true, subtree: true });
// Periodic re-render (cargo updates via WS)
setInterval(function () {
if (!isPanelVisible) return;
renderPanel();
}, 30000);
}
// ── Watch JOBS hex button for instant refresh ─────────
function watchJobsHex() {
var btn = document.getElementById('ui_jobs_hex');
if (!btn) { setTimeout(watchJobsHex, 2000); return; }
var prev = btn.classList.contains('active');
new MutationObserver(function () {
var now = btn.classList.contains('active');
if (now && !prev) {
scrapeJobs();
if (isPanelVisible) renderPanel();
}
prev = now;
}).observe(btn, { attributes: true, attributeFilter: ['class'] });
}
// ── Stellar body highlighter ──────────────────────────
function highlightStellarBodies() {
var container = document.getElementById('SystemExplorer_StellarBodies_Expanded');
if (!container || container.style.display === 'none') return;
var items = container.querySelectorAll('.SystemExplorer_Item');
if (items.length === 0) return;
// Clear previous highlights
for (var ci = 0; ci < items.length; ci++) {
items[ci].classList.remove('oe-survey-body-needs-scan', 'oe-survey-body-scanned', 'oe-survey-body-done');
}
if (jobsCache.length === 0) return;
// Build lookup: for each target, check scan status
var lookup = {};
for (var ji = 0; ji < jobsCache.length; ji++) {
var job = jobsCache[ji];
var key = (job.targetMoon + '|' + job.targetSystem).toLowerCase();
if (!lookup[key]) lookup[key] = { needed: 0, completed: 0 };
lookup[key].needed++;
}
// Count completed
for (var ji = 0; ji < jobsCache.length; ji++) {
var job = jobsCache[ji];
var completed = countScansForTarget(job.targetMoon, job.targetSystem);
var key = (job.targetMoon + '|' + job.targetSystem).toLowerCase();
if (lookup[key]) lookup[key].completed = Math.min(completed, lookup[key].needed);
}
for (var i = 0; i < items.length; i++) {
var nameEl = items[i].querySelector('.SystemExplorer_ObjectName');
if (!nameEl) continue;
var bodyName = nameEl.textContent.trim();
// Check if this body matches any survey target
var cls = null;
var keys = Object.keys(lookup);
for (var ki = 0; ki < keys.length; ki++) {
var parts = keys[ki].split('|');
var moon = parts[0];
var bodyLower = bodyName.toLowerCase();
var moonLower = moon.toLowerCase();
if (bodyLower === moonLower) {
var data = lookup[keys[ki]];
if (data.completed >= data.needed) { break; } // done in cargo, no highlight
if (data.completed > 0) cls = 'oe-survey-body-scanned';
else cls = 'oe-survey-body-needs-scan';
break;
}
}
if (cls) items[i].classList.add(cls);
}
}
// ── Jump lane highlighter ────────────────────────────
function highlightJumpLanes() {
var container = document.getElementById('SystemExplorer_JumpLanes_Expanded');
if (!container || container.offsetParent === null) return;
var items = container.querySelectorAll('.SystemExplorer_Item');
if (items.length === 0) return;
// Clear
for (var ci = 0; ci < items.length; ci++) {
items[ci].classList.remove('oe-survey-jump-match');
}
if (jobsCache.length === 0) return;
// Collect deliver systems from available jobs only
var relevantSystems = {};
for (var ji = 0; ji < jobsCache.length; ji++) {
var job = jobsCache[ji];
if (job.isScanned) continue;
if (job.deliverSystem) relevantSystems[job.deliverSystem.toLowerCase()] = true;
}
for (var i = 0; i < items.length; i++) {
var nameEl = items[i].querySelector('.SystemExplorer_ObjectName');
if (!nameEl) continue;
// Extract system name (first text node before the JAS-code span)
var sysName = '';
if (nameEl.firstChild && nameEl.firstChild.nodeType === 3) {
sysName = nameEl.firstChild.textContent.trim();
}
if (!sysName) {
var tip = nameEl.getAttribute('data-ui-tooltip') || '';
sysName = tip.replace(/^#/, '').replace(/\s*\(.*?\)\s*$/, '').trim();
}
if (sysName && relevantSystems[sysName.toLowerCase()]) {
items[i].classList.add('oe-survey-jump-match');
}
}
}
// ── Orbital / station highlighter ─────────────────────
function highlightOrbitals() {
var container = document.getElementById('SystemExplorer_Orbitals_Expanded');
if (!container || container.offsetParent === null) return;
var items = container.querySelectorAll('.SystemExplorer_Item');
if (items.length === 0) return;
// Clear
for (var ci = 0; ci < items.length; ci++) {
items[ci].classList.remove('oe-survey-station-match');
}
if (jobsCache.length === 0) return;
// Collect deliver stations from available jobs
var stations = {};
for (var ji = 0; ji < jobsCache.length; ji++) {
var job = jobsCache[ji];
if (job.isScanned) continue;
if (job.deliverStation) stations[job.deliverStation.toLowerCase()] = true;
}
if (Object.keys(stations).length === 0) return;
for (var i = 0; i < items.length; i++) {
var nameEl = items[i].querySelector('.SystemExplorer_ObjectName');
if (!nameEl) continue;
var stationName = nameEl.textContent.trim().toLowerCase();
if (stations[stationName]) {
items[i].classList.add('oe-survey-station-match');
}
}
}
// ── Watch system explorer ─────────────────────────────
function watchSystemExplorer() {
var c1 = document.getElementById('SystemExplorer_StellarBodies_Expanded');
var c2 = document.getElementById('SystemExplorer_JumpLanes_Expanded');
var c3 = document.getElementById('SystemExplorer_Orbitals_Expanded');
if (!c1 && !c2 && !c3) { setTimeout(watchSystemExplorer, 2000); return; }
if (c1) {
highlightStellarBodies();
new MutationObserver(function () {
highlightStellarBodies();
}).observe(c1, { childList: true, subtree: true });
}
if (c2) {
highlightJumpLanes();
new MutationObserver(function () {
highlightJumpLanes();
}).observe(c2, { childList: true, subtree: true });
}
if (c3) {
highlightOrbitals();
new MutationObserver(function () {
highlightOrbitals();
}).observe(c3, { childList: true, subtree: true });
}
// Re-highlight when cargo data refreshes
setInterval(function () {
if (c1) highlightStellarBodies();
if (c2) highlightJumpLanes();
if (c3) highlightOrbitals();
}, 3000);
}
// ── Init ──────────────────────────────────────────────
setTimeout(function () {
if (document.body) createReopenBtn();
}, 3000);
watchJobsPanel();
watchJobsHex();
watchSystemExplorer();
})();