Files
alkane-os/src/ui.rs
T
noah 13b1787e1a Square corners, a full-screen mobile drawer, and populated settings
The design system retired every radius step on 2026-07-14 (tokens/radius.json
resolves xs..pill to 0), so the cards, buttons, inputs, pills and code blocks
lose their rounded corners.

Below 901px the rail is now the design's mobile menu: a full-screen drawer on
the page background with the brand and a close control in its head, rows split
by 1px dividers. It closes by the X, the backdrop, Escape, or picking a
destination; without a script the :target fragment still opens it.

Settings stops being a bare list: System now groups Identity, Network and
Updates the way the Warden console does, and Drivers groups Chains and
Firmware. Verified on the bench S21 Pro at port 80.
2026-11-04 14:06:24 -06:00

737 lines
34 KiB
Rust

// SPDX-License-Identifier: MIT
//! On-box web UI: navigation, pages, and the editable dashboard document.
//!
//! The shape follows the Warden/FLARE console: a fixed sidebar of groups and
//! items, hash-routed pages, and dashboards that are a JSON document an operator
//! edits in place. The document is stored on the box, has a default template per
//! deck, and is capped server-side so a bad save cannot grow without bound.
//!
//! The JSON API remains the interface of record: every value the pages show is
//! also available at an `/api/...` route, and the page never becomes the only
//! way to see or change the machine.
use serde_json::{json, Value};
/// Blocks a dashboard may hold. Docker rows count too, so a tidy layout cannot
/// cost an operator a widget.
pub const BLOCK_CAP: usize = 32;
/// Characters allowed in a dashboard name.
pub const NAME_MAX: usize = 120;
/// One navigable destination.
pub struct Item {
pub path: &'static str,
pub label: &'static str,
}
/// A sidebar group.
pub struct Group {
pub label: &'static str,
pub items: &'static [Item],
}
const DASHBOARD: [Item; 1] = [Item {
path: "/",
label: "Dashboard",
}];
const MINING: [Item; 4] = [
Item {
path: "/mining",
label: "Overview",
},
Item {
path: "/mining/hashboards",
label: "Hashboards",
},
Item {
path: "/mining/power",
label: "Power Supply",
},
Item {
path: "/mining/fans",
label: "Fans",
},
];
const SETTINGS: [Item; 8] = [
Item {
path: "/settings/system",
label: "System",
},
Item {
path: "/settings/drivers",
label: "Drivers",
},
Item {
path: "/settings/security",
label: "Security",
},
Item {
path: "/settings/services",
label: "Services",
},
Item {
path: "/settings/monitor",
label: "Monitor",
},
Item {
path: "/settings/logs",
label: "Logs",
},
Item {
path: "/settings/files",
label: "Files",
},
Item {
path: "/settings/terminal",
label: "Terminal",
},
];
pub const NAV: [Group; 3] = [
Group {
label: "Overview",
items: &DASHBOARD,
},
Group {
label: "Mining",
items: &MINING,
},
Group {
label: "Settings",
items: &SETTINGS,
},
];
/// The dashboard a deck starts with. Every deck has one, so a fresh box is never
/// an empty page.
pub fn default_deck(deck: &str) -> Value {
match deck {
"overview" => json!({
"version": 1,
"name": "Mining overview",
"blocks": [
{"id": "status", "kind": "status", "span": 1, "title": "State", "source": "status"},
{"id": "accepted", "kind": "metric", "span": 1, "title": "Accepted", "source": "accepted", "unit": "shares"},
{"id": "rejected", "kind": "metric", "span": 1, "title": "Rejected", "source": "rejected", "unit": "shares"},
{"id": "elapsed", "kind": "metric", "span": 1, "title": "Uptime", "source": "elapsed", "unit": "s"},
{"id": "chains", "kind": "metric", "span": 1, "title": "Active chains", "source": "active_chains", "unit": ""},
{"id": "frequency", "kind": "metric", "span": 1, "title": "Frequency", "source": "frequency", "unit": "MHz"},
{"id": "voltage", "kind": "metric", "span": 1, "title": "Voltage", "source": "voltage", "unit": "mV"},
{"id": "target", "kind": "metric", "span": 1, "title": "Target", "source": "target", "unit": ""},
{"id": "chains_table", "kind": "table", "span": 4, "title": "Hashboards", "source": "chains"}
]
}),
_ => json!({
"version": 1,
"name": "Dashboard",
"blocks": [
{"id": "status", "kind": "status", "span": 2, "title": "Miner", "source": "status"},
{"id": "accepted", "kind": "metric", "span": 1, "title": "Accepted", "source": "accepted", "unit": "shares"},
{"id": "rejected", "kind": "metric", "span": 1, "title": "Rejected", "source": "rejected", "unit": "shares"},
{"id": "hardware", "kind": "kv", "span": 2, "title": "Hardware", "source": "hardware"},
{"id": "fans", "kind": "table", "span": 2, "title": "Fan map", "source": "fans"}
]
}),
}
}
/// Validate a dashboard document the client wants to store.
///
/// Returns the parsed document, or a sentence naming the rule that failed. The
/// rules are the same ones the page enforces, so a save that the UI allowed is
/// never rejected here for a reason the operator cannot see.
pub fn validate_deck(text: &str) -> Result<Value, String> {
let doc: Value =
serde_json::from_str(text).map_err(|_| "document is not valid JSON".to_string())?;
let object = doc.as_object().ok_or("document must be an object")?;
let version = object
.get("version")
.and_then(Value::as_u64)
.ok_or("version must be a number")?;
if version != 1 {
return Err(format!("unsupported version {version}"));
}
if let Some(name) = object.get("name") {
let name = name.as_str().ok_or("name must be a string")?;
if name.chars().count() > NAME_MAX {
return Err(format!("name is longer than {NAME_MAX} characters"));
}
}
let blocks = object
.get("blocks")
.and_then(Value::as_array)
.ok_or("blocks must be a list")?;
if blocks.len() > BLOCK_CAP {
return Err(format!("more than {BLOCK_CAP} blocks"));
}
for block in blocks {
let block = block.as_object().ok_or("each block must be an object")?;
let id = block
.get("id")
.and_then(Value::as_str)
.ok_or("block id must be a string")?;
if id.is_empty() || id.len() > 64 {
return Err("block id must be 1..=64 characters".to_string());
}
let kind = block
.get("kind")
.and_then(Value::as_str)
.ok_or("block kind must be a string")?;
if !["metric", "status", "kv", "table", "text"].contains(&kind) {
return Err(format!("unknown block kind {kind}"));
}
let span = block.get("span").and_then(Value::as_u64).unwrap_or(1);
if !(1..=4).contains(&span) {
return Err("block span must be 1..=4".to_string());
}
}
Ok(doc)
}
/// Render one page inside the shell.
///
/// The rail follows the FLARE/Warden console: a 232px navy column with a 44px
/// head, one native `<details>` per group so the tree opens and closes with no
/// script, and the current page marked with `aria-current` rather than a class
/// alone. Below 901px it slides off-canvas and comes back as a `:target`
/// fragment, which is the one disclosure a locked-down page can still use.
pub fn page(active: &str, title: &str, body: &str) -> String {
format!(
"<!doctype html>\n<html lang=\"en\"><head><meta charset=\"utf-8\">\
<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\
<title>{title} - Alkane</title><style>{CSS}</style></head>\
<body class=\"shell\"><aside class=\"rail\" id=\"rail\">{rail_head}{nav}</aside><div class=\"rail-backdrop\" id=\"rail-backdrop\"></div>\
<main class=\"content\"><header class=\"appbar\">\
<a class=\"appbar__menu\" href=\"#rail\" aria-label=\"Open menu\">Menu</a>\
<h1 class=\"page-title\">{title}</h1><span id=\"live\" class=\"pill\">connecting</span></header>\
<div class=\"frame\">{body}</div></main>\
<script>{JS}</script></body></html>",
title = escape(title),
rail_head = rail_head(),
nav = sidebar(active),
)
}
fn rail_head() -> String {
"<div class=\"rail__head\"><span class=\"rail__brand\">Alkane</span>\
<button class=\"rail__toggle\" type=\"button\" aria-label=\"Collapse sidebar\" title=\"Collapse sidebar\">&#9776;</button>\
<a class=\"rail__close\" href=\"#\" aria-label=\"Close menu\" title=\"Close menu\">&#10005;</a></div>"
.to_string()
}
/// An 18px stroke icon for a destination, matching the rail's icon column.
fn icon(path: &str) -> &'static str {
let body = match path {
"/" => "<rect x=\"3\" y=\"3\" width=\"7\" height=\"7\" rx=\"1\"/><rect x=\"14\" y=\"3\" width=\"7\" height=\"7\" rx=\"1\"/><rect x=\"3\" y=\"14\" width=\"7\" height=\"7\" rx=\"1\"/><rect x=\"14\" y=\"14\" width=\"7\" height=\"7\" rx=\"1\"/>",
"/mining" => "<path d=\"M4 20V10M10 20V4M16 20v-7M22 20H2\"/>",
"/mining/hashboards" => "<rect x=\"5\" y=\"5\" width=\"14\" height=\"14\" rx=\"2\"/><path d=\"M9 2v3M15 2v3M9 19v3M15 19v3M2 9h3M2 15h3M19 9h3M19 15h3\"/>",
"/mining/power" => "<path d=\"M13 2 4 14h7l-1 8 9-12h-7z\"/>",
"/mining/fans" => "<circle cx=\"12\" cy=\"12\" r=\"2\"/><path d=\"M12 10c0-4 1-7 4-7 2 0 3 2 3 4 0 3-3 5-7 5M14 12c4 0 7 1 7 4 0 2-2 3-4 3-3 0-5-3-5-7M12 14c0 4-1 7-4 7-2 0-3-2-3-4 0-3 3-5 7-5M10 12c-4 0-7-1-7-4 0-2 2-3 4-3 3 0 5 3 5 7\"/>",
"/settings/system" => "<rect x=\"3\" y=\"4\" width=\"18\" height=\"6\" rx=\"1\"/><rect x=\"3\" y=\"14\" width=\"18\" height=\"6\" rx=\"1\"/><path d=\"M7 7h.01M7 17h.01\"/>",
"/settings/drivers" => "<rect x=\"4\" y=\"4\" width=\"16\" height=\"16\" rx=\"2\"/><path d=\"M9 9h6v6H9z\"/>",
"/settings/security" => "<rect x=\"4\" y=\"10\" width=\"16\" height=\"10\" rx=\"2\"/><path d=\"M8 10V7a4 4 0 0 1 8 0v3\"/>",
"/settings/services" => "<circle cx=\"12\" cy=\"12\" r=\"9\"/><path d=\"M10 8l6 4-6 4z\"/>",
"/settings/monitor" => "<path d=\"M2 12h4l3-8 4 16 3-8h6\"/>",
"/settings/logs" => "<path d=\"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z\"/><path d=\"M14 2v6h6M8 13h8M8 17h5\"/>",
"/settings/files" => "<path d=\"M3 7a2 2 0 0 1 2-2h5l2 2h7a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z\"/>",
"/settings/terminal" => "<rect x=\"3\" y=\"4\" width=\"18\" height=\"16\" rx=\"2\"/><path d=\"M7 9l3 3-3 3M13 15h4\"/>",
_ => "<circle cx=\"12\" cy=\"12\" r=\"9\"/>",
};
// The strings above are static markup, never user input.
let html = format!(
"<svg class=\"rail__icon\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" \
stroke-width=\"1.7\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\">{body}</svg>"
);
Box::leak(html.into_boxed_str())
}
fn group_icon_svg(label: &str) -> &'static str {
let body = match label {
"Mining" => "<rect x=\"5\" y=\"5\" width=\"14\" height=\"14\" rx=\"2\"/><path d=\"M9 2v3M15 2v3M9 19v3M15 19v3M2 9h3M2 15h3M19 9h3M19 15h3\"/>",
"Settings" => "<circle cx=\"12\" cy=\"12\" r=\"3\"/><path d=\"M19.4 15a1.7 1.7 0 0 0 .3 1.9l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.9-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.9.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.9 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1A1.7 1.7 0 0 0 4.6 9a1.7 1.7 0 0 0-.3-1.9l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.9.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.9-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.9V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z\"/>",
_ => "",
};
if body.is_empty() {
return "";
}
let html = format!(
"<svg class=\"rail__icon\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" \
stroke-width=\"1.7\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\">{body}</svg>"
);
Box::leak(html.into_boxed_str())
}
fn sidebar(active: &str) -> String {
let mut out = String::from("<nav class=\"rail__nav\">");
let mut first = true;
for group in NAV.iter() {
// A one-item group is a plain link, exactly as the FLARE rail renders
// Dashboard: a disclosure around a single leaf is a control that only
// hides the thing it names.
if group.items.len() == 1 {
let item = &group.items[0];
out.push_str(&rail_link(item, active, "rail__link"));
} else {
let open = group.items.iter().any(|item| item.path == active);
out.push_str(&format!(
"<details class=\"tree\"{open}>\
<summary class=\"rail__link tree__summary\">{icon}<span class=\"rail__label\">{label}</span><span class=\"rail__chevron\" aria-hidden=\"true\"></span></summary>\
<ul class=\"tree__list\">",
open = if open { " open" } else { "" },
label = escape(group.label),
icon = group_icon_svg(group.label),
));
for item in group.items {
out.push_str(&rail_link(item, active, "rail__link tree__leaf"));
}
out.push_str("</ul></details>");
}
first = false;
}
let _ = first;
out.push_str("</nav>");
out
}
fn rail_link(item: &Item, active: &str, class: &str) -> String {
let current = if item.path == active {
" aria-current=\"page\""
} else {
""
};
format!(
"<a class=\"{class}\" href=\"#{path}\"{current}>{icon}<span class=\"rail__label\">{label}</span></a>",
class = class,
path = item.path,
label = escape(item.label),
icon = icon(item.path),
)
}
/// A dashboard page: the editor chrome plus the document the client loads.
pub fn dashboard_page(deck: &str, editable: bool) -> String {
let deck = escape(deck);
format!(
"<div class=\"bar\">\
<label>Template <select id=\"deck-name\"></select></label>\
<button id=\"save\"{disabled}>Save</button>\
<button id=\"reset\"{disabled}>Reset to template</button>\
<button id=\"add\"{disabled}>Add block</button>\
<span id=\"edit-msg\" class=\"muted\"></span></div>\
<div id=\"grid\" class=\"grid\" data-deck=\"{deck}\" data-editable=\"{editable}\"></div>",
disabled = if editable { "" } else { " disabled" },
editable = if editable { "1" } else { "0" },
)
}
/// Escape text for HTML. Every user-visible string goes through this.
pub fn escape(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for ch in text.chars() {
match ch {
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
'\'' => out.push_str("&#39;"),
other => out.push(other),
}
}
out
}
/// A definition-list page for key/value data (settings pages).
pub fn kv_page(rows: &[(&str, String)]) -> String {
let mut out = String::from("<table class=\"kv\"><tbody>");
for (key, value) in rows {
out.push_str(&format!(
"<tr><th>{}</th><td>{}</td></tr>",
escape(key),
escape(value)
));
}
out.push_str("</tbody></table>");
out
}
/// Several titled sections in one page: the settings pages' shape in the
/// Warden console, where each group (Identity, Network, ...) is its own block.
pub fn sections_page(sections: &[(&str, String)]) -> String {
let mut out = String::new();
for (title, body) in sections {
out.push_str(&format!(
"<section class=\"section\"><h2 class=\"section__title\">{}</h2>{}</section>",
escape(title),
body
));
}
out
}
/// A table page with a header row.
pub fn table_page(headers: &[&str], rows: &[Vec<String>]) -> String {
let mut out = String::from("<table><thead><tr>");
for header in headers {
out.push_str(&format!("<th>{}</th>", escape(header)));
}
out.push_str("</tr></thead><tbody>");
for row in rows {
out.push_str("<tr>");
for cell in row {
out.push_str(&format!("<td>{}</td>", escape(cell)));
}
out.push_str("</tr>");
}
if rows.is_empty() {
out.push_str(&format!(
"<tr><td colspan=\"{}\" class=\"muted\">nothing to show</td></tr>",
headers.len().max(1)
));
}
out.push_str("</tbody></table>");
out
}
const CSS: &str = r#"
:root{
color-scheme:dark;
/* FLARE tokens: navy scale, cyan action, the same steps portal.css uses. */
--navy-900:#070D1D; --navy-800:#0B1020; --navy-700:#192858; --navy-600:#1E4E90;
--cyan-400:#3ABCF8; --cyan-500:#31A2D6; --orange-500:#F26522;
--text:#FFFFFF; --text-muted:#BABABA;
--border:#192858;
--space-1:4px; --space-2:8px; --space-3:12px; --space-4:16px; --space-6:24px;
--font-display:'Creato Display','Sora','Segoe UI','Selawik',system-ui,-apple-system,sans-serif;
--font-body:'Segoe UI','Selawik',system-ui,-apple-system,sans-serif;
--text-xs:12px; --text-sm:14px; --text-base:16px;
}
*{box-sizing:border-box}
body.shell{margin:0;display:flex;min-height:100vh;background:var(--navy-900);color:var(--text);
font:var(--text-sm)/1.45 var(--font-body)}
a{color:var(--cyan-400);text-decoration:none}
:focus-visible{outline:2px solid var(--cyan-400);outline-offset:2px}
/* --- rail: the Warden console's sidebar ------------------------------- */
.rail{flex:none;width:232px;background:var(--navy-700);border-right:1px solid #1E2A4E;
display:flex;flex-direction:column;position:sticky;top:0;height:100vh;overflow-y:auto;
overscroll-behavior:contain}
.rail__head{display:flex;align-items:center;gap:var(--space-2);min-height:44px;
padding:0 var(--space-3);border-bottom:1px solid #1E2A4E}
.rail__brand{font-family:var(--font-display);font-weight:700;font-size:var(--text-base);
letter-spacing:.02em}
.rail__nav{padding:var(--space-2) 0;display:flex;flex-direction:column}
.rail__link{display:flex;align-items:center;gap:var(--space-3);min-height:36px;
padding:var(--space-2) var(--space-4);color:#E6ECF5;font-size:var(--text-sm);font-weight:600;
border-left:2px solid transparent;min-width:0}
.rail__link:hover{background:rgba(255,255,255,.06)}
.rail__link[aria-current='page']{border-left-color:var(--cyan-400);color:var(--cyan-400);
background:rgba(255,255,255,.06)}
.tree>summary{list-style:none;cursor:pointer}
.tree>summary::-webkit-details-marker{display:none}
.rail__chevron{margin-left:auto;width:0;height:0;border-left:4px solid transparent;
border-right:4px solid transparent;border-top:5px solid #9AA5BB}
.tree[open]>summary .rail__chevron{transform:rotate(180deg)}
.tree__list{list-style:none;margin:0;padding:0}
.tree__leaf{font-weight:400;color:#9AA5BB;min-height:32px;
padding-left:calc(var(--space-4) + var(--space-3))}
.tree__leaf:hover{color:#E6ECF5}
.tree__leaf[aria-current='page']{color:var(--cyan-400);font-weight:600}
.rail a:focus-visible,.rail summary:focus-visible{outline-offset:-2px}
.rail__icon{width:18px;height:18px;flex:none}
.rail__label{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.rail__toggle{margin-left:auto;background:transparent;border:0;color:#9AA5BB;cursor:pointer;
padding:4px;font-size:14px;line-height:1}
.rail__toggle:hover{color:#E6ECF5}
/* Collapsed: icons only, and only where the rail is docked. Labels are clipped
rather than removed so they keep their accessible name. */
@media (min-width:901px){
.shell--collapsed .rail{width:41px}
.shell--collapsed .rail__label,
.shell--collapsed .rail__brand{position:absolute;width:1px;height:1px;overflow:hidden;
clip-path:inset(50%);white-space:nowrap}
.shell--collapsed .tree__list,
.shell--collapsed .rail__chevron{display:none}
.shell--collapsed .rail__link{justify-content:center;padding-left:0;padding-right:2px}
.shell--collapsed .rail__head{justify-content:center;padding-inline:0}
}
/* --- content column ---------------------------------------------------- */
.content{flex:1;min-width:0;display:flex;flex-direction:column}
.appbar{display:flex;align-items:center;gap:var(--space-4);min-height:44px;
padding:0 var(--space-6);border-bottom:1px solid var(--border);
position:sticky;top:0;z-index:40;background:var(--navy-900)}
.page-title{font-family:var(--font-display);font-size:22px;font-weight:700;line-height:1.1;
margin:0;letter-spacing:-.01em}
.appbar__menu{display:none;font-size:var(--text-sm);color:var(--cyan-400)}
.pill{border-radius:0;margin-left:auto;font-size:var(--text-xs);padding:3px 9px;
background:var(--navy-800);color:var(--text-muted);border:1px solid var(--border)}
.pill.ok{color:#7EE787;border-color:#1F4D2C}
.pill.bad{color:#FF9B9B;border-color:#552323}
.frame{padding:var(--space-6);display:flex;flex-direction:column;gap:var(--space-6)}
/* --- blocks ------------------------------------------------------------ */
.bar{display:flex;gap:var(--space-3);align-items:center;flex-wrap:wrap}
h2,.card h2{font-family:var(--font-display);font-size:11px;font-weight:600;line-height:1.15;
text-transform:uppercase;letter-spacing:2px;color:var(--text-muted);margin:0 0 var(--space-2)}
button{border-radius:0;font:inherit;cursor:pointer;padding:7px 12px;
background:var(--navy-700);color:var(--text);border:1px solid #1E2A4E}
button:hover:not(:disabled){background:var(--navy-600)}
button:disabled{opacity:.4;cursor:default}
select,input[type=text]{border-radius:0;font:inherit;color:var(--text);background:var(--navy-900);
border:1px solid #1E2A4E;padding:6px 8px}
input[type=text]{min-width:320px;padding:8px 10px}
.grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:var(--space-4)}
.card{background:var(--navy-800);border:1px solid var(--border);border-radius:0;
padding:var(--space-4);min-height:96px}
.card.drag{outline:1px dashed var(--cyan-400);outline-offset:2px}
.card .big{font-family:var(--font-display);font-size:28px;font-weight:700;letter-spacing:-.5px}
.card .unit{font-size:var(--text-xs);color:var(--text-muted);margin-left:var(--space-1)}
.span2{grid-column:span 2}.span3{grid-column:span 3}.span4{grid-column:span 4}
table{width:100%;border-collapse:collapse;font-size:var(--text-sm)}
th,td{text-align:left;padding:8px 10px;border-bottom:1px solid #14203C}
th{font-family:var(--font-display);font-size:11px;font-weight:600;text-transform:uppercase;
letter-spacing:2px;color:var(--text-muted)}
table.kv th{width:220px;color:var(--text-muted);font-weight:600;text-transform:none;
letter-spacing:0;font-family:var(--font-body);font-size:var(--text-sm)}
.muted{color:var(--text-muted)}
.section{display:flex;flex-direction:column;gap:var(--space-2)}
.section__title{font-family:var(--font-display);font-size:11px;font-weight:600;line-height:1.15;
text-transform:uppercase;letter-spacing:2px;color:var(--text-muted);margin:0;
padding-bottom:var(--space-2);border-bottom:1px solid var(--border)}
pre{background:var(--navy-900);border:1px solid var(--border);border-radius:0;
padding:var(--space-4);overflow:auto;max-height:60vh;
font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}
/* Off-canvas below 901px, reopened by the fragment so it works without a
script, exactly as portal.css does it. */
.rail__close{display:none;margin-left:var(--space-2);background:transparent;border:0;
color:#9AA5BB;font-size:16px;line-height:1;padding:6px;cursor:pointer}
.rail__close:hover{color:#E6ECF5}
.rail-backdrop{display:none}
@media (max-width:900px){
.shell{display:block}
/* Full-screen drawer, as the design's mobile menu: page background, its own
top bar with the brand and a close, rows split by 1px dividers. */
.rail{position:fixed;inset:0;width:100%;max-width:none;transform:translateX(-100%);
z-index:60;background:var(--navy-900);border-right:0}
.rail:target{transform:none}
body.drawer-open .rail{transform:none}
body.drawer-open{overflow:hidden}
body.drawer-open .rail-backdrop{display:block;position:fixed;inset:0;background:rgba(0,0,0,.6);z-index:55}
.rail__head{min-height:56px;padding:0 var(--space-4);border-bottom:1px solid var(--border)}
.rail__brand{font-size:18px}
.rail__toggle{display:none}
.rail__close{display:inline-flex}
.rail__link{padding:var(--space-4);border-bottom:1px solid var(--border);border-left:0}
.rail__link[aria-current='page']{border-left:0;background:rgba(255,255,255,.06)}
.tree__leaf{padding:var(--space-4) var(--space-4) var(--space-4) calc(var(--space-4) * 2);min-height:48px}
.appbar__menu{display:inline-flex}
.appbar{padding:0 var(--space-4)}
.frame{padding:var(--space-4)}
.grid{grid-template-columns:1fr}
.span2,.span3,.span4{grid-column:span 1}
}
"#;
const JS: &str = r#"
(function(){
"use strict";
function $(id){return document.getElementById(id)}
function esc(s){return String(s).replace(/[&<>"']/g,function(c){return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]})}
function route(){var p=location.hash.slice(1)||"/";return p}
function go(){location.hash=route()}
// Live status pill: the page is a convenience over the JSON API.
function poll(){fetch("/api/summary").then(function(r){return r.json()}).then(function(d){
var el=$("live"); if(!el)return; var m=(d.miner||d); el.textContent=(m.state||"up"); el.className="pill ok";
}).catch(function(){var el=$("live"); if(el){el.textContent="offline"; el.className="pill bad"}})}
setInterval(poll,5000); poll();
// Mobile drawer. The rail is full-screen below 901px; Menu opens it and the
// close control, the backdrop or Escape puts it away. Without a script the
// :target fragment still opens it, which is why the Menu link is an anchor.
(function(){
var body=document.body;
var menu=document.querySelector(".appbar__menu");
var close=document.querySelector(".rail__close");
var backdrop=document.getElementById("rail-backdrop");
function open(){body.classList.add("drawer-open")}
function shut(){body.classList.remove("drawer-open")}
if(menu)menu.addEventListener("click",function(e){e.preventDefault();open()});
if(close)close.addEventListener("click",function(e){e.preventDefault();shut()});
if(backdrop)backdrop.addEventListener("click",shut);
document.addEventListener("keydown",function(e){if(e.key==="Escape")shut()});
document.querySelectorAll(".rail__link").forEach(function(link){
link.addEventListener("click",function(){shut()});
});
})();
// Rail collapse. The state is remembered so a reload keeps the operator's
// choice; the button is the only control that needs a script.
(function(){
var key="alkane.rail.collapsed";
try{if(localStorage.getItem(key)==="1")document.body.classList.add("shell--collapsed")}catch(e){}
var toggle=document.querySelector(".rail__toggle");
if(toggle)toggle.addEventListener("click",function(){
var on=document.body.classList.toggle("shell--collapsed");
try{localStorage.setItem(key,on?"1":"0")}catch(e){}
});
})();
var grid=$("grid");
if(grid){
var deck=grid.dataset.deck, editable=grid.dataset.editable==="1", doc=null, dragId=null;
var METRICS={hashrate:["TH/s",1],power_w:["W",1],chains:["",0],chip_temp_c:["C",0],fans:["",0]};
function render(){
grid.innerHTML="";
(doc.blocks||[]).forEach(function(b){
var card=document.createElement("div");
card.className="card span"+(b.span||1);
card.draggable=editable;
card.addEventListener("dragstart",function(){dragId=b.id;card.classList.add("drag")});
card.addEventListener("dragend",function(){card.classList.remove("drag")});
card.addEventListener("dragover",function(e){e.preventDefault()});
card.addEventListener("drop",function(e){e.preventDefault(); if(!dragId||dragId===b.id)return;
var from=doc.blocks.findIndex(function(x){return x.id===dragId});
var to=doc.blocks.findIndex(function(x){return x.id===b.id});
if(from<0||to<0)return; var moved=doc.blocks.splice(from,1)[0]; doc.blocks.splice(to,0,moved); render(); msg("unsaved changes")});
var h=document.createElement("h2"); h.textContent=b.title||b.id; card.appendChild(h);
if(b.kind==="metric"||b.kind==="status"){
var big=document.createElement("div"); big.className="big"; big.textContent="--";
big.dataset.source=b.source||""; card.appendChild(big);
if(b.unit){var u=document.createElement("span"); u.className="unit"; u.textContent=b.unit; card.appendChild(u)}
} else if(b.kind==="table"){
var t=document.createElement("table");
t.dataset[b.source==="fans"?"fans":"table"]=b.source||"";
t.innerHTML="<tbody><tr><td class='muted'>loading</td></tr></tbody>";
card.appendChild(t);
} else {
var p=document.createElement("div"); p.className="muted"; p.dataset.kv=b.source||""; p.textContent="loading"; card.appendChild(p);
}
grid.appendChild(card);
});
}
function msg(text){var el=$("edit-msg"); if(el)el.textContent=text}
function fill(){
var hw=null, sm=null;
function paint(){
if(!hw||!sm)return;
var s=(sm.SUMMARY||[{}])[0];
var src={
status:(s.Status||"unknown"),
accepted:(s.Accepted||0),
rejected:(s.Rejected||0),
elapsed:(s.Elapsed||0),
active_chains:(hw.active_chains||[]).length,
frequency:(hw.frequency_mhz||0),
voltage:((hw.operating_point||{}).voltage_mv||0),
target:(hw.target||"-")
};
document.querySelectorAll("[data-source]").forEach(function(el){
var v=src[el.dataset.source];
if(v===undefined||v===null){el.textContent="not reported"; el.classList.add("muted"); return}
el.textContent=String(v);
});
document.querySelectorAll("[data-table]").forEach(function(t){
var rows=(hw.chains||[]).map(function(c){return [c.index,c.chip,c.chips_found,JSON.stringify(c.eeprom),c.response_per_mille]});
if(!rows.length){t.innerHTML="<tbody><tr><td class='muted'>no chains reported</td></tr></tbody>";return}
t.innerHTML="<thead><tr><th>#</th><th>chip</th><th>chips</th><th>eeprom</th><th>response</th></tr></thead><tbody>"+
rows.map(function(r){return "<tr>"+r.map(function(c){return "<td>"+esc(c)+"</td>"}).join("")+"</tr>"}).join("")+"</tbody>";
});
document.querySelectorAll("[data-kv]").forEach(function(el){
var rows=[["profile",hw.profile||"-"],["chip",hw.chip||"-"],["psu",hw.psu||"-"],["target",hw.target||"-"],["stopped",hw.stopped?hw.stopped:"no"]];
el.innerHTML=rows.map(function(r){return "<div><span class='muted'>"+esc(r[0])+"</span> "+esc(r[1])+"</div>"}).join("");
});
document.querySelectorAll("[data-fans]").forEach(function(t){
var rows=(hw.fan_zones||[]).map(function(z){return [z.fan,(z.zones||[]).join(", ")]});
if(!rows.length){t.innerHTML="<tbody><tr><td class='muted'>not mapped yet</td></tr></tbody>";return}
t.innerHTML="<thead><tr><th>fan</th><th>zones</th></tr></thead><tbody>"+
rows.map(function(r){return "<tr><td>"+esc(r[0])+"</td><td>"+esc(r[1])+"</td></tr>"}).join("")+"</tbody>";
});
}
fetch("/api/hardware").then(function(r){return r.json()}).then(function(h){hw=h;paint()}).catch(function(){msg("hardware unavailable")});
fetch("/api/summary").then(function(r){return r.json()}).then(function(s){sm=s;paint()}).catch(function(){});
}
fetch("/api/dashboard?deck="+encodeURIComponent(deck)).then(function(r){return r.json()}).then(function(d){doc=d;render();fill()});
if(editable){
$("save").onclick=function(){fetch("/api/dashboard?deck="+encodeURIComponent(deck),{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(doc)}).then(function(r){if(r.ok){msg("saved")}else{r.text().then(msg)}})};
$("reset").onclick=function(){fetch("/api/dashboard?deck="+encodeURIComponent(deck)+"&reset=1",{method:"PUT",headers:{"Content-Type":"application/json"},body:"{}"}).then(function(r){return r.json()}).then(function(d){doc=d;render();fill();msg("template restored")})};
$("add").onclick=function(){
if(doc.blocks.length>=32){msg("32 blocks is the limit");return}
var id="block"+(doc.blocks.length+1);
doc.blocks.push({id:id,kind:"metric",span:1,title:"New block",source:"power_w",unit:"W"});render();msg("unsaved changes")};
}
}
})();
"#;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_sidebar_item_has_a_page() {
for group in NAV.iter() {
for item in group.items {
assert!(item.path.starts_with('/'), "{} has no path", item.label);
assert!(!item.label.is_empty());
}
}
assert_eq!(NAV.iter().map(|g| g.items.len()).sum::<usize>(), 13);
}
#[test]
fn default_decks_are_valid() {
for deck in ["dashboard", "overview"] {
let doc = default_deck(deck);
let text = doc.to_string();
assert!(validate_deck(&text).is_ok(), "{deck} default rejected");
}
}
#[test]
fn the_block_cap_is_enforced() {
let mut blocks = Vec::new();
for i in 0..=BLOCK_CAP {
blocks.push(json!({"id": format!("b{i}"), "kind": "metric", "span": 1}));
}
let doc = json!({"version": 1, "blocks": blocks});
assert!(validate_deck(&doc.to_string()).is_err());
}
#[test]
fn malformed_documents_are_rejected_with_a_reason() {
assert!(validate_deck("not json").is_err());
assert!(validate_deck("{}").is_err());
assert!(validate_deck(r#"{"version":2,"blocks":[]}"#).is_err());
assert!(
validate_deck(r#"{"version":1,"blocks":[{"id":"x","kind":"evil","span":1}]}"#).is_err()
);
assert!(
validate_deck(r#"{"version":1,"blocks":[{"id":"x","kind":"metric","span":9}]}"#)
.is_err()
);
}
#[test]
fn sidebar_marks_the_active_page_and_opens_its_group() {
let html = page("/mining/fans", "Fans", "");
assert!(html.contains("href=\"#/mining/fans\" aria-current=\"page\""));
// Exactly the group holding the current page is open; the other is not.
assert_eq!(html.matches("<details class=\"tree\" open>").count(), 1);
assert!(html.contains("Power Supply"));
assert!(html.contains("href=\"#/settings/terminal\""));
// A one-item group is a plain link, not a disclosure around a leaf.
assert!(html.contains("class=\"rail__link\" href=\"#/\""));
}
#[test]
fn user_text_is_escaped() {
assert_eq!(escape("<script>"), "&lt;script&gt;");
let html = kv_page(&[("note", "<b>x</b>".to_string())]);
assert!(!html.contains("<b>x</b>"));
assert!(html.contains("&lt;b&gt;"));
}
}