Add the on-box web UI: sidebar, editable dashboards, settings pages
The UI follows the Warden/FLARE console shape rather than inventing one: a fixed sidebar of groups and items, hash-routed pages, and dashboards that are a JSON document an operator edits in place, with a default template per deck and server-side caps on what a save may contain. Sections: Dashboard and Mining/Overview are editable dashboards (drag to reorder, add a block, save, reset). Mining also serves Hashboards, Power Supply and Fans from the hardware document. Settings serves System, Drivers, Security, Services, Monitor, Logs, Files and Terminal. Files and Terminal are gated on a token at /var/lib/alkane/ui-token so a shared network cannot use them. Served on port 80 of the miner's own address (8080 if 80 cannot be bound), and started from the runlevel so the page is up without an operator. The JSON API remains the interface of record: every value shown is also at /api/, and nothing is reachable only through the page. Verified: 165 tests, clippy clean, all 13 pages answering, and on the bench S21 Pro the UI answers on port 80 after an unattended reboot.
This commit is contained in:
@@ -0,0 +1,497 @@
|
||||
// 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.
|
||||
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>\
|
||||
<nav class=\"side\">{nav}</nav><main><header><h1>{title}</h1><span id=\"live\" class=\"pill\">connecting</span></header>{body}</main>\
|
||||
<script>{JS}</script></body></html>",
|
||||
title = escape(title),
|
||||
nav = sidebar(active),
|
||||
)
|
||||
}
|
||||
|
||||
fn sidebar(active: &str) -> String {
|
||||
let mut out = String::from("<div class=\"brand\">Alkane</div>");
|
||||
for group in NAV.iter() {
|
||||
out.push_str(&format!(
|
||||
"<div class=\"group\">{}</div><ul>",
|
||||
escape(group.label)
|
||||
));
|
||||
for item in group.items {
|
||||
let class = if item.path == active {
|
||||
" class=\"on\""
|
||||
} else {
|
||||
""
|
||||
};
|
||||
out.push_str(&format!(
|
||||
"<li><a href=\"#{}\"{class}>{}</a></li>",
|
||||
item.path,
|
||||
escape(item.label)
|
||||
));
|
||||
}
|
||||
out.push_str("</ul>");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 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("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' => out.push_str("""),
|
||||
'\'' => out.push_str("'"),
|
||||
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
|
||||
}
|
||||
|
||||
/// 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}*{box-sizing:border-box}
|
||||
body{margin:0;display:grid;grid-template-columns:220px 1fr;min-height:100vh;background:#0d1117;color:#e6edf3;font:14px/1.45 system-ui,-apple-system,Segoe UI,Roboto,sans-serif}
|
||||
.side{background:#11161d;border-right:1px solid #222c37;padding:14px 0;position:sticky;top:0;height:100vh;overflow:auto}
|
||||
.brand{font-weight:700;font-size:17px;padding:0 16px 12px;letter-spacing:.3px}
|
||||
.group{padding:14px 16px 4px;font-size:11px;text-transform:uppercase;letter-spacing:.8px;color:#7d8b9a}
|
||||
.side ul{list-style:none;margin:0;padding:0}
|
||||
.side a{display:block;padding:7px 16px;color:#c3cfdb;text-decoration:none;border-left:2px solid transparent}
|
||||
.side a:hover{background:#161d26;color:#fff}
|
||||
.side a.on{background:#161d26;color:#fff;border-left-color:#3b82f6;font-weight:600}
|
||||
main{padding:18px 22px;min-width:0}
|
||||
header{display:flex;align-items:center;gap:12px;margin-bottom:14px}
|
||||
h1{font-size:19px;margin:0;font-weight:650}
|
||||
.pill{font-size:11px;padding:3px 9px;border-radius:999px;background:#1c2530;color:#9fb0c0;border:1px solid #263241}
|
||||
.pill.ok{color:#7ee787;border-color:#1f4d2c;background:#10231a}
|
||||
.pill.bad{color:#ff9b9b;border-color:#552323;background:#261013}
|
||||
.bar{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin-bottom:14px}
|
||||
button{background:#1b2431;color:#dbe6f1;border:1px solid #2a3949;border-radius:7px;padding:7px 11px;font:inherit;cursor:pointer}
|
||||
button:hover:not(:disabled){background:#233043}
|
||||
button:disabled{opacity:.4;cursor:default}
|
||||
select{background:#1b2431;color:#dbe6f1;border:1px solid #2a3949;border-radius:7px;padding:6px 8px;font:inherit}
|
||||
.grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px}
|
||||
.card{background:#11161d;border:1px solid #222c37;border-radius:10px;padding:12px 14px;min-height:96px}
|
||||
.card.drag{outline:1px dashed #3b82f6}
|
||||
.card h2{font-size:12px;margin:0 0 8px;color:#8fa2b5;font-weight:600;text-transform:uppercase;letter-spacing:.6px}
|
||||
.card .big{font-size:28px;font-weight:650;letter-spacing:-.5px}
|
||||
.card .unit{font-size:12px;color:#7d8b9a;margin-left:4px}
|
||||
table{width:100%;border-collapse:collapse;font-size:13px}
|
||||
th,td{text-align:left;padding:7px 9px;border-bottom:1px solid #1d2733}
|
||||
th{color:#8fa2b5;font-weight:600;font-size:11px;text-transform:uppercase;letter-spacing:.5px}
|
||||
table.kv th{width:220px}
|
||||
.muted{color:#7d8b9a}
|
||||
.span2{grid-column:span 2}.span3{grid-column:span 3}.span4{grid-column:span 4}
|
||||
pre{background:#0b0f14;border:1px solid #1d2733;border-radius:8px;padding:12px;overflow:auto;max-height:60vh;font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}
|
||||
input[type=text]{background:#0b0f14;border:1px solid #2a3949;border-radius:7px;color:#e6edf3;padding:8px 10px;font:inherit;min-width:320px}
|
||||
"#;
|
||||
|
||||
const JS: &str = r#"
|
||||
(function(){
|
||||
"use strict";
|
||||
function $(id){return document.getElementById(id)}
|
||||
function esc(s){return String(s).replace(/[&<>"']/g,function(c){return {'&':'&','<':'<','>':'>','"':'"',"'":'''}[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();
|
||||
|
||||
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() {
|
||||
let html = page("/mining/fans", "Fans", "");
|
||||
assert!(html.contains("href=\"#/mining/fans\" class=\"on\""));
|
||||
assert!(html.contains("Power Supply"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_text_is_escaped() {
|
||||
assert_eq!(escape("<script>"), "<script>");
|
||||
let html = kv_page(&[("note", "<b>x</b>".to_string())]);
|
||||
assert!(!html.contains("<b>x</b>"));
|
||||
assert!(html.contains("<b>"));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user