Files
dune-dashboard/templates/base.html
T
2026-12-04 09:35:24 +00:00

647 lines
34 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}Dune Awakening Server Dashboard{% endblock %}</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='themes.css') }}">
<script>
const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
async function csrfFetch(url, options = {}) {
options.headers = options.headers || {};
options.headers['X-CSRFToken'] = csrfToken;
return fetch(url, options);
}
</script>
{% block head_extra %}{% endblock %}
</head>
<body>
<button class="nav-toggle" id="navToggle" title="Toggle nav layout" onclick="toggleNavLayout()">☰</button>
<nav>
<div class="brand">DUNE DASHBOARD</div>
<!-- Horizontal: use grouped nav -->
<div class="nav-links-h">
{% for item in nav_groups %}
{% if item|length == 2 and item[1] is string %}
{# Simple link #}
<a href="{{ item[0] }}" class="{% if current_path == item[0] %}active{% endif %}">{{ item[1] }}</a>
{% else %}
{# Dropdown group: item[0] is label, item[1] is list of (href, label) #}
<div class="nav-dropdown">
<a class="nav-dropdown-toggle {% for ih, il in item[1] %}{% if current_path == ih %}active{% endif %}{% endfor %}">{{ item[0] }} ▾</a>
<div class="nav-dropdown-content">
{% for ih, il in item[1] %}
<a href="{{ ih }}" class="{% if current_path == ih %}active{% endif %}">{{ il }}</a>
{% endfor %}
</div>
</div>
{% endif %}
{% endfor %}
</div>
<!-- Vertical nav links (flat list) -->
<div class="nav-links-v">
{% for href, label in nav_pages %}
<a href="{{ href }}" class="{% if current_path == href %}active{% endif %}">{{ label }}</a>
{% endfor %}
</div>
<div class="spacer"></div>
<div class="nav-stats-h" id="nav-stats-h" style="display:none;">
<span class="ns-item"><span class="conn-dot" id="ns-dot-h"></span><strong id="ns-online-h">–</strong>&nbsp;online</span>
<span class="ns-item">CPU <canvas id="ns-cpu-h" width="64" height="18"></canvas> <span id="ns-cpuv-h">–</span></span>
<span class="ns-item">RAM <canvas id="ns-mem-h" width="64" height="18"></canvas> <span id="ns-memv-h">–</span></span>
</div>
<div class="nav-stats-v" id="nav-stats-v" style="display:none;">
<div class="ns-vrow"><span class="conn-dot" id="ns-dot-v"></span><strong id="ns-online-v">–</strong><span class="ns-vlabel">players online</span></div>
<div class="ns-vrow ns-vgraph"><span class="ns-vlabel">CPU</span><canvas id="ns-cpu-v" width="168" height="28"></canvas><span id="ns-cpuv-v">–</span></div>
<div class="ns-vrow ns-vgraph"><span class="ns-vlabel">RAM</span><canvas id="ns-mem-v" width="168" height="28"></canvas><span id="ns-memv-v">–</span></div>
</div>
<div class="nav-tools">
<div class="theme-dropdown">
<button class="theme-btn" title="Theme">🎨</button>
<div class="theme-dropdown-content">
<div class="theme-grid">
<div class="theme-row" data-family="default">
<span class="theme-row-label">Classic Dune</span>
<span class="theme-swatch default" data-theme="default" onclick="setTheme('default')" title="Classic Dune Light"></span>
<span class="theme-swatch default-dark active-theme" data-theme="default-dark" onclick="setTheme('default-dark')" title="Classic Dune Dark"></span>
</div>
<div class="theme-row" data-family="atreides">
<span class="theme-row-label">House Atreides</span>
<span class="theme-swatch atreides" data-theme="atreides" onclick="setTheme('atreides')" title="House Atreides Light"></span>
<span class="theme-swatch atreides-dark" data-theme="atreides-dark" onclick="setTheme('atreides-dark')" title="House Atreides Dark"></span>
</div>
<div class="theme-row" data-family="harkonnen">
<span class="theme-row-label">House Harkonnen</span>
<span class="theme-swatch harkonnen-light" data-theme="harkonnen-light" onclick="setTheme('harkonnen-light')" title="House Harkonnen Light"></span>
<span class="theme-swatch harkonnen" data-theme="harkonnen" onclick="setTheme('harkonnen')" title="House Harkonnen Dark"></span>
</div>
<div class="theme-row" data-family="fremen">
<span class="theme-row-label">Fremen</span>
<span class="theme-swatch fremen" data-theme="fremen" onclick="setTheme('fremen')" title="Fremen Light"></span>
<span class="theme-swatch fremen-dark" data-theme="fremen-dark" onclick="setTheme('fremen-dark')" title="Fremen Dark"></span>
</div>
<div class="theme-row" data-family="bene-gesserit">
<span class="theme-row-label">Bene Gesserit</span>
<span class="theme-swatch bene-gesserit" data-theme="bene-gesserit" onclick="setTheme('bene-gesserit')" title="Bene Gesserit Light"></span>
<span class="theme-swatch bene-gesserit-dark" data-theme="bene-gesserit-dark" onclick="setTheme('bene-gesserit-dark')" title="Bene Gesserit Dark"></span>
</div>
<div class="theme-row" data-family="spacing-guild">
<span class="theme-row-label">Spacing Guild</span>
<span class="theme-swatch spacing-guild-light" data-theme="spacing-guild-light" onclick="setTheme('spacing-guild-light')" title="Spacing Guild Light"></span>
<span class="theme-swatch spacing-guild" data-theme="spacing-guild" onclick="setTheme('spacing-guild')" title="Spacing Guild Dark"></span>
</div>
<div class="theme-row" data-family="emperor">
<span class="theme-row-label">Emperor</span>
<span class="theme-swatch emperor-light" data-theme="emperor-light" onclick="setTheme('emperor-light')" title="Emperor Light"></span>
<span class="theme-swatch emperor" data-theme="emperor" onclick="setTheme('emperor')" title="Emperor Dark"></span>
</div>
<div class="theme-row" data-family="corrino">
<span class="theme-row-label">House Corrino</span>
<span class="theme-swatch corrino" data-theme="corrino" onclick="setTheme('corrino')" title="House Corrino Light"></span>
<span class="theme-swatch corrino-dark" data-theme="corrino-dark" onclick="setTheme('corrino-dark')" title="House Corrino Dark"></span>
</div>
<div class="theme-row" data-family="mentat">
<span class="theme-row-label">Mentat</span>
<span class="theme-swatch mentat" data-theme="mentat" onclick="setTheme('mentat')" title="Mentat Light"></span>
<span class="theme-swatch mentat-dark" data-theme="mentat-dark" onclick="setTheme('mentat-dark')" title="Mentat Dark"></span>
</div>
<div class="theme-row" data-family="sardaukar">
<span class="theme-row-label">Sardaukar</span>
<span class="theme-swatch sardaukar" data-theme="sardaukar" onclick="setTheme('sardaukar')" title="Sardaukar Light"></span>
<span class="theme-swatch sardaukar-dark" data-theme="sardaukar-dark" onclick="setTheme('sardaukar-dark')" title="Sardaukar Dark"></span>
</div>
<div class="theme-row" data-family="tleilax">
<span class="theme-row-label">Bene Tleilax</span>
<span class="theme-swatch tleilax-light" data-theme="tleilax-light" onclick="setTheme('tleilax-light')" title="Bene Tleilax Light"></span>
<span class="theme-swatch tleilax" data-theme="tleilax" onclick="setTheme('tleilax')" title="Bene Tleilax Dark"></span>
</div>
<div class="theme-row" data-family="ordos">
<span class="theme-row-label">House Ordos</span>
<span class="theme-swatch ordos" data-theme="ordos" onclick="setTheme('ordos')" title="House Ordos Light"></span>
<span class="theme-swatch ordos-dark" data-theme="ordos-dark" onclick="setTheme('ordos-dark')" title="House Ordos Dark"></span>
</div>
<div class="theme-row" data-family="ix">
<span class="theme-row-label">Ix</span>
<span class="theme-swatch ix" data-theme="ix" onclick="setTheme('ix')" title="Ix Light"></span>
<span class="theme-swatch ix-dark" data-theme="ix-dark" onclick="setTheme('ix-dark')" title="Ix Dark"></span>
</div>
<div class="theme-row" data-family="choam">
<span class="theme-row-label">CHOAM</span>
<span class="theme-swatch choam" data-theme="choam" onclick="setTheme('choam')" title="CHOAM Light"></span>
<span class="theme-swatch choam-dark" data-theme="choam-dark" onclick="setTheme('choam-dark')" title="CHOAM Dark"></span>
</div>
</div>
</div>
</div>
<div class="update-banner" id="update-banner" style="display:none;"></div>
</div>
<span class="nav-conn">
<span class="conn-dot {% if conn_ok %}online{% else %}offline{% endif %}"></span>
{{ 'Connected' if conn_ok else 'Disconnected' }}
</span>
{% if current_user and current_user.is_authenticated %}
<a href="/logout" class="nav-logout">Logout</a>
{% endif %}
</nav>
<main class="container">
{% block content %}{% endblock %}
</main>
<footer class="site-footer">
<span>This is a fan-made project and is not affiliated with, endorsed by, or connected to Funcom, Legendary Entertainment, or any official Dune rights holders. All game assets, trademarks, and intellectual property belong to their respective owners.</span>
</footer>
<script>
// Theme System
function setTheme(themeName) {
document.documentElement.setAttribute('data-theme', themeName);
localStorage.setItem('dune-theme', themeName);
updateThemeUI(themeName);
}
function updateThemeUI(themeName) {
document.querySelectorAll('.theme-row .theme-swatch').forEach(sw => {
sw.classList.toggle('active-theme', sw.getAttribute('data-theme') === themeName);
});
}
function initTheme() {
const savedTheme = localStorage.getItem('dune-theme') || 'default-dark';
document.documentElement.setAttribute('data-theme', savedTheme);
updateThemeUI(savedTheme);
}
// Nav Layout System (experimental vertical toggle)
function toggleNavLayout() {
const body = document.body;
const isMobile = window.innerWidth <= 768;
if (isMobile) {
document.querySelector('nav').classList.toggle('nav-open');
return;
}
const current = body.getAttribute('data-nav-layout') || 'horizontal';
const next = current === 'horizontal' ? 'vertical' : 'horizontal';
body.setAttribute('data-nav-layout', next);
localStorage.setItem('dune-nav-layout', next);
if (typeof applyNavStatsLayout === 'function') applyNavStatsLayout();
}
function initNavLayout() {
const isMobile = window.innerWidth <= 768;
if (isMobile) {
document.body.setAttribute('data-nav-layout', 'vertical');
localStorage.removeItem('dune-nav-layout');
} else {
const saved = localStorage.getItem('dune-nav-layout') || 'horizontal';
document.body.setAttribute('data-nav-layout', saved);
}
}
window.addEventListener('resize', function() {
const isMobile = window.innerWidth <= 768;
const current = document.body.getAttribute('data-nav-layout');
if (isMobile && current !== 'vertical') {
document.body.setAttribute('data-nav-layout', current);
}
if (typeof applyNavStatsLayout === 'function') applyNavStatsLayout();
});
initTheme();
initNavLayout();
// Update banner (channel-aware self updates)
function escHtml(s) {
return String(s == null ? '' : s)
.replace(/&/g, '&amp;').replace(/</g, '&lt;')
.replace(/>/g, '&gt;').replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}
// Update widget: always-visible bell. Expands into a panel with a
// channel dropdown, manual check, patch notes overlay, update and
// silence controls. Auto-expands only for a new, non-silenced update.
let ubData = null;
let ubViewChannel = null; // channel shown in the panel; null = own channel
let ubViewVersion = null; // version picked in the dropdown; null = newest
let ubExpanded = false;
function ubChannelLatest(channel) {
if (!ubData) return null;
if (channel === ubData.channel) {
return ubData.latest ? { ...ubData.latest, available: ubData.available } : null;
}
const other = ubData.other_channel;
if (other && other.channel === channel) {
return other.latest ? { ...other.latest, available: other.available } : null;
}
return null;
}
// All known releases for a channel, newest first. Falls back to the
// single latest entry when the server payload predates release lists.
function ubChannelReleases(channel) {
if (!ubData) return [];
const lists = ubData.releases || {};
if (Array.isArray(lists[channel]) && lists[channel].length) {
return lists[channel];
}
const entry = ubChannelLatest(channel);
return entry ? [entry] : [];
}
// Numeric version compare mirroring the server's compare_versions:
// compares the X.Y.Z numbers only, so stable and experimental versions
// are comparable across channels. Returns -1, 0 or 1.
function ubCmpVer(a, b) {
const parse = (v) => {
const m = /^v?(\d+)\.(\d+)\.(\d+)(?:-([A-Za-z0-9]+))?$/.exec(String(v || '').trim());
return m ? [parseInt(m[1], 10), parseInt(m[2], 10), parseInt(m[3], 10)] : null;
};
const pa = parse(a), pb = parse(b);
if (!pa && !pb) return 0;
if (!pa) return -1;
if (!pb) return 1;
for (let i = 0; i < 3; i++) {
if (pa[i] < pb[i]) return -1;
if (pa[i] > pb[i]) return 1;
}
return 0;
}
function ubHasNews() {
if (!ubData || ubData.silence_all) return false;
if (ubData.preview) return true;
const silenced = ubData.silenced_versions || [];
const cur = ubChannelLatest(ubData.channel);
if (cur && cur.available && !silenced.includes(cur.version)) return true;
const other = ubData.other_channel;
if (other && other.available && other.latest && !silenced.includes(other.latest.version)) return true;
return false;
}
async function refreshUpdateBanner(keepOpen) {
const el = document.getElementById('update-banner');
if (!el) return;
try {
const resp = await fetch('/api/update/status');
ubData = await resp.json();
} catch (e) { return; } // leave whatever is shown
if (!ubData || !ubData.success) return;
if (!ubViewChannel) ubViewChannel = ubData.channel;
// Auto-expand for fresh news unless permanently muted.
if (!keepOpen && !ubExpanded && ubHasNews()) ubExpanded = true;
renderUpdateBanner();
}
// Notes cache keyed by version (versions are server-validated to
// digits/dots/dashes only, so they are safe inside onclick quotes).
let ubNotesCache = {};
function ubSafeVer(v) {
return /^[0-9A-Za-z.\-]+$/.test(v || '') ? v : '';
}
function renderUpdateBanner() {
const el = document.getElementById('update-banner');
if (!el || !ubData) return;
if (!ubExpanded) {
const dot = ubHasNews() ? '<span class="ub-dot"></span>' : '';
const bell = ubData.silence_all ? '🔕' : '🔔';
el.style.display = 'block';
el.innerHTML = `<span class="ub-bellwrap" title="Updates"><button class="theme-btn" onclick="toggleUpdatePanel(true)">${bell}${dot}</button></span>`;
return;
}
const data = ubData;
const channels = [data.channel];
if (data.other_channel && data.other_channel.channel &&
!channels.includes(data.other_channel.channel)) {
channels.push(data.other_channel.channel);
}
const viewing = ubViewChannel || data.channel;
const entry = ubChannelLatest(viewing);
const silenced = data.silenced_versions || [];
const isSilenced = !!(entry && silenced.includes(entry.version));
const canUpdate = !!(entry && entry.available && !isSilenced);
// Per-version picker: every known release on the viewed channel,
// newest first. Older than the running version cannot be installed;
// same-numbered is a reinstall (works across channels); newer is
// an update. Settings and protected paths are preserved either way.
const releases = ubChannelReleases(viewing);
let picked = null;
if (releases.length) {
picked = releases.find(r => r.version === ubViewVersion) || releases[0];
if (!ubViewVersion || !releases.some(r => r.version === ubViewVersion)) {
ubViewVersion = picked.version;
}
}
const cmp = picked ? ubCmpVer(picked.version, data.current_version) : 0;
const pickedSilenced = !!(picked && silenced.includes(picked.version));
const pickedCanInstall = !!(picked && cmp >= 0 && !pickedSilenced);
let opts = '';
channels.forEach(ch => {
const label = ch === data.channel ? `${ch} (yours)` : ch;
opts += `<option value="${escHtml(ch)}"${ch === viewing ? ' selected' : ''}>${escHtml(label)}</option>`;
});
let body = `<div class="ub-sub">You are on ${escHtml(data.current_version)} (${escHtml(data.channel)})</div>`;
body += `<div class="ub-row"><label>Channel: <select id="ub-channel" onchange="ubViewChannel=this.value;ubViewVersion=null;renderUpdateBanner();">${opts}</select></label>` +
`<button onclick="checkUpdatesNow()">Check now</button></div>`;
if (releases.length) {
let vopts = '';
releases.forEach(r => {
const c = ubCmpVer(r.version, data.current_version);
const tag = c < 0 ? ' — Older' : (c === 0 ? ' — Current (reinstall)' : ' — Update available');
vopts += `<option value="${escHtml(r.version)}"${picked && r.version === picked.version ? ' selected' : ''}>${escHtml(r.version)}${escHtml(tag)}</option>`;
});
body += `<div class="ub-row"><label>Version: <select id="ub-version" onchange="ubViewVersion=this.value;renderUpdateBanner();">${vopts}</select></label></div>`;
}
if (data.preview && ubSafeVer(data.preview.version)) {
ubNotesCache[data.preview.version] = data.preview.notes || '';
body += `<div class="ub-title">${escHtml(data.preview.version)} <span class="ub-preview-tag">preview</span></div>` +
`<div class="ub-actions"><button class="ub-ghost" onclick="openNotesOverlay('${data.preview.version}')">Patch notes</button>` +
`<button class="ub-ghost" onclick="clearPreview()">Clear preview</button></div>`;
}
if (picked && ubSafeVer(picked.version)) {
ubNotesCache[picked.version] = picked.notes || '';
const isCurrent = cmp === 0;
const stateLine = cmp < 0
? `<div class="ub-sub">${escHtml(picked.version)} is older than your current version — cannot install.</div>`
: (!pickedCanInstall && pickedSilenced)
? `<div class="ub-sub">${escHtml(picked.version)} silenced - a newer version will show again.</div>`
: isCurrent
? `<div class="ub-title">Reinstall: ${escHtml(picked.version)} (same as current)</div>`
: `<div class="ub-title">Update available: ${escHtml(picked.version)}</div>`;
body += stateLine;
body += '<div class="ub-actions">' +
(picked.notes ? `<button class="ub-ghost" onclick="openNotesOverlay('${picked.version}')">Patch notes</button>` : '') +
(pickedCanInstall ? (isCurrent
? `<button onclick="applyUpdate('${picked.version}')">Reinstall ${escHtml(picked.version)}</button>`
: `<button onclick="applyUpdate('${picked.version}')">Update to ${escHtml(picked.version)}</button>`) : '') +
(cmp > 0 && !pickedSilenced ? `<button class="ub-ghost" onclick="silenceUpdateVersion('${picked.version}')">Silence this version</button>` : '') +
'</div>';
} else if (entry && ubSafeVer(entry.version)) {
ubNotesCache[entry.version] = entry.notes || '';
const stateLine = !entry.available
? `<div class="ub-sub">${escHtml(viewing)} is up to date at ${escHtml(entry.version)}.</div>`
: isSilenced
? `<div class="ub-sub">${escHtml(entry.version)} silenced - a newer version will show again.</div>`
: `<div class="ub-title">Update available: ${escHtml(entry.version)}</div>`;
body += stateLine;
body += '<div class="ub-actions">' +
(entry.notes ? `<button class="ub-ghost" onclick="openNotesOverlay('${entry.version}')">Patch notes</button>` : '') +
(canUpdate ? `<button onclick="applyUpdate('${entry.version}')">Update to ${escHtml(entry.version)}</button>` : '') +
(entry.available && !isSilenced ? `<button class="ub-ghost" onclick="silenceUpdateVersion('${entry.version}')">Silence this version</button>` : '') +
'</div>';
} else if (!data.preview) {
body += `<div class="ub-sub">No ${escHtml(viewing)} releases found yet.</div>`;
}
body += `<label class="ub-mute"><input type="checkbox"${data.silence_all ? ' checked' : ''} onchange="setUpdateMute(this.checked)"> Don't remind me again</label>` +
'<div class="ub-status" id="ub-status"></div>';
el.style.display = 'block';
const bellIcon = data.silence_all ? '🔕' : '🔔';
el.innerHTML = `<span class="ub-bellwrap" title="Updates"><button class="theme-btn" onclick="toggleUpdatePanel(false)">${bellIcon}</button></span>` +
`<div class="ub-panel"><div class="ub-panel-head">Updates</div>` + body + `</div>`;
}
function toggleUpdatePanel(open) {
ubExpanded = open;
renderUpdateBanner();
}
async function checkUpdatesNow() {
const st = document.getElementById('ub-status');
if (st) st.textContent = 'Checking...';
try {
await csrfFetch('/api/update/check', { method: 'POST' });
} catch (e) { /* status refresh below reports */ }
refreshUpdateBanner(true);
}
function openNotesOverlay(version) {
closeNotesOverlay();
const notes = ubNotesCache[version] || '';
const ov = document.createElement('div');
ov.id = 'ub-overlay';
const box = document.createElement('div');
box.className = 'ub-overlay-box';
const head = document.createElement('div');
head.className = 'ub-overlay-head';
const title = document.createElement('strong');
title.textContent = 'Patch notes - ' + version;
const close = document.createElement('button');
close.textContent = 'Close';
close.onclick = closeNotesOverlay;
head.appendChild(title);
head.appendChild(close);
const pre = document.createElement('pre');
pre.textContent = notes || 'No notes for this version.';
box.appendChild(head);
box.appendChild(pre);
ov.appendChild(box);
ov.onclick = function(e) { if (e.target === ov) closeNotesOverlay(); };
document.body.appendChild(ov);
}
function closeNotesOverlay() {
const ov = document.getElementById('ub-overlay');
if (ov) ov.remove();
}
async function clearPreview() {
await csrfFetch('/api/update/preview', { method: 'DELETE' });
refreshUpdateBanner(true);
}
async function applyUpdate(version) {
const isReinstall = ubData && version === ubData.current_version;
const action = isReinstall ? 'Reinstall' : 'Update to';
if (!confirm(`${action} ${version}? Settings and protected files are preserved. The dashboard backs itself up, installs, then restarts. Players will be briefly disconnected from the panel (not the game).`)) return;
const st = document.getElementById('ub-status');
if (st) st.textContent = 'Updating - the panel will restart...';
try {
const resp = await csrfFetch('/api/update/apply', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ version })
});
const data = await resp.json();
if (st) st.textContent = data.success ? (data.message || 'Updating...') : ('Error: ' + (data.message || data.error || 'unknown'));
} catch (e) {
if (st) st.textContent = 'Error: ' + e.message;
}
}
async function silenceUpdateVersion(version) {
await csrfFetch('/api/update/silence', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'silence', version })
});
refreshUpdateBanner();
}
async function setUpdateMute(on) {
await csrfFetch('/api/update/silence', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: on ? 'mute' : 'unmute' })
});
refreshUpdateBanner();
}
async function unmuteUpdates() {
await csrfFetch('/api/update/silence', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action: 'unmute' })
});
refreshUpdateBanner();
}
refreshUpdateBanner();
setInterval(refreshUpdateBanner, 10 * 60 * 1000);
// Sidebar/topbar live stats: CPU + RAM sparklines and online count.
// History persists across page changes in localStorage (30 points,
// roughly 5 minutes at the 10s poll rate) and doubles as seed data
// for the big Server charts.
const NS_MAX = 30;
const NS_INTERVAL = 10000;
function nsLoad(key) {
try {
const arr = JSON.parse(localStorage.getItem(key) || '[]');
if (!Array.isArray(arr)) return [];
// Same freshness rule as the big charts: drop anything older
// than 6 minutes so a restart/refresh starts clean instead of
// replaying stale history the big graphs have discarded.
const cutoff = Date.now() - 6 * 60 * 1000;
return arr.filter(p => p && typeof p.v === 'number'
&& typeof p.t === 'number' && p.t >= cutoff).slice(-NS_MAX);
} catch (e) { return []; }
}
let nsCpu = nsLoad('dune-metrics-cpu');
let nsMem = nsLoad('dune-metrics-mem');
function nsSave() {
try {
localStorage.setItem('dune-metrics-cpu', JSON.stringify(nsCpu.slice(-NS_MAX)));
localStorage.setItem('dune-metrics-mem', JSON.stringify(nsMem.slice(-NS_MAX)));
} catch (e) { /* storage full or unavailable - keep memory-only */ }
}
function nsCssVar(name, fallback) {
const v = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
return v || fallback;
}
// Memory total (GiB), latched once like the big charts so the scale
// never moves. Persisted so minis open correctly scaled on load.
let nsMemTotal = parseFloat(localStorage.getItem('dune-mem-total') || '0') || 0;
function drawSpark(canvas, values, color, ymax) {
if (!canvas) return;
const dpr = window.devicePixelRatio || 1;
const w = canvas.clientWidth || canvas.width, h = canvas.clientHeight || canvas.height;
if (!w || !h) return;
canvas.width = w * dpr;
canvas.height = h * dpr;
const ctx = canvas.getContext('2d');
ctx.scale(dpr, dpr);
ctx.clearRect(0, 0, w, h);
if (!values.length) return;
const min = 0, max = (ymax > 0) ? ymax : 100;
const step = values.length > 1 ? w / (NS_MAX - 1) : 0;
const x0 = w - step * (values.length - 1);
ctx.beginPath();
values.forEach((p, i) => {
const v = (typeof p === 'number') ? p : p.v;
const x = x0 + step * i;
const y = h - 2 - ((Math.min(Math.max(v, min), max) - min) / (max - min)) * (h - 4);
if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
});
ctx.strokeStyle = color;
ctx.lineWidth = 1.5;
ctx.stroke();
ctx.lineTo(x0 + step * (values.length - 1), h);
ctx.lineTo(x0, h);
ctx.closePath();
ctx.fillStyle = color + '33';
ctx.fill();
}
// Last known values so layout switches re-render instantly
// instead of waiting for the next poll.
let nsLast = { cpu: '–', mem: '–', online: null };
function applyNavStatsLayout() {
const h = document.getElementById('nav-stats-h');
const v = document.getElementById('nav-stats-v');
const layout = document.body.getAttribute('data-nav-layout') || 'horizontal';
if (h) h.style.display = (layout === 'horizontal') ? '' : 'none';
if (v) v.style.display = (layout === 'vertical') ? '' : 'none';
}
function renderNavStats(cpuStr, memStr, online) {
nsLast = { cpu: cpuStr, mem: memStr, online: online };
const onlineTxt = (online === null || online === undefined) ? '–' : String(online);
const cpuColor = nsCssVar('--primary', '#c9a24e');
const memColor = nsCssVar('--success', '#27ae60');
[['h'], ['v']].forEach(([sfx]) => {
const on = document.getElementById('ns-online-' + sfx);
const cv = document.getElementById('ns-cpuv-' + sfx);
const mv = document.getElementById('ns-memv-' + sfx);
if (on) on.textContent = onlineTxt;
if (cv) cv.textContent = cpuStr;
if (mv) mv.textContent = memStr;
const dot = document.getElementById('ns-dot-' + sfx);
if (dot) dot.className = 'conn-dot ' + ((online > 0) ? 'online' : 'offline');
drawSpark(document.getElementById('ns-cpu-' + sfx), nsCpu.map(p => p.v), cpuColor, 100);
// Pre-GiB entries have no g: skip them rather than plotting
// percent values on a GiB scale.
drawSpark(document.getElementById('ns-mem-' + sfx),
nsMem.filter(p => typeof p.g === 'number').map(p => p.g), memColor,
nsMemTotal > 0 ? Math.ceil(nsMemTotal) : 100);
});
applyNavStatsLayout();
}
async function pollNavStats() {
if (document.hidden) return; // save the server while tab is backgrounded
try {
const resp = await fetch('/server/metrics');
const data = await resp.json();
const now = Date.now();
if (typeof data.cpu_num === 'number') {
nsCpu.push({ t: now, v: data.cpu_num });
nsCpu = nsCpu.slice(-NS_MAX);
}
// Percent only for the graph scale; GiB rides along so the big
// Server charts can seed from this same history.
if (typeof data.memory_pct_num === 'number') {
const gib = (typeof data.memory_gib === 'number') ? data.memory_gib : null;
nsMem.push({ t: now, v: data.memory_pct_num, g: gib });
nsMem = nsMem.slice(-NS_MAX);
// Latch the RAM total once, then only re-latch when the
// machine itself actually changed (implied total moved
// >5%): per-sample rounding wobble never moves the ruler.
if (data.memory_pct_num > 0 && gib > 0) {
const implied = gib / (data.memory_pct_num / 100);
if (!nsMemTotal || Math.abs(implied - nsMemTotal) / nsMemTotal > 0.05) {
nsMemTotal = implied;
try { localStorage.setItem('dune-mem-total', String(nsMemTotal)); } catch (e) {}
}
}
}
// Drop stale points on every poll (not just at load) so a
// wake-from-sleep recovers on the next poll instead of
// replaying old history for minutes.
const freshCutoff = Date.now() - 6 * 60 * 1000;
nsCpu = nsCpu.filter(p => p && p.t >= freshCutoff);
nsMem = nsMem.filter(p => p && p.t >= freshCutoff);
nsSave();
renderNavStats(data.cpu || '–', data.memory || '–',
(data.online === null || data.online === undefined) ? null : data.online);
} catch (e) { /* keep last values on failure */ }
}
pollNavStats();
setInterval(pollNavStats, NS_INTERVAL);
</script>
{% block scripts %}{% endblock %}
<style>
.site-footer { text-align: center; padding: 16px 20px; font-size: 11px; color: var(--text-muted); border-top: 1px solid var(--border); margin-top: 24px; }
</style>
</body>
</html>