// 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 { 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 `
` 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!( "\n\ \ {title} - Alkane\
\
\ Menu\

{title}

connecting
\
{body}
\ ", title = escape(title), rail_head = rail_head(), nav = sidebar(active), ) } fn rail_head() -> String { "
Alkane\ \ ✕
" .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 { "/" => "", "/mining" => "", "/mining/hashboards" => "", "/mining/power" => "", "/mining/fans" => "", "/settings/system" => "", "/settings/drivers" => "", "/settings/security" => "", "/settings/services" => "", "/settings/monitor" => "", "/settings/logs" => "", "/settings/files" => "", "/settings/terminal" => "", _ => "", }; // The strings above are static markup, never user input. let html = format!( "{body}" ); Box::leak(html.into_boxed_str()) } fn group_icon_svg(label: &str) -> &'static str { let body = match label { "Mining" => "", "Settings" => "", _ => "", }; if body.is_empty() { return ""; } let html = format!( "{body}" ); Box::leak(html.into_boxed_str()) } fn sidebar(active: &str) -> String { let mut out = String::from(""); out } fn rail_link(item: &Item, active: &str, class: &str) -> String { let current = if item.path == active { " aria-current=\"page\"" } else { "" }; format!( "{icon}{label}", 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!( "
\ \ \ \ \
\
", 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(""); for (key, value) in rows { out.push_str(&format!( "", escape(key), escape(value) )); } out.push_str("
{}{}
"); 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!( "

{}

{}
", escape(title), body )); } out } /// A table page with a header row. pub fn table_page(headers: &[&str], rows: &[Vec]) -> String { let mut out = String::from(""); for header in headers { out.push_str(&format!("", escape(header))); } out.push_str(""); for row in rows { out.push_str(""); for cell in row { out.push_str(&format!("", escape(cell))); } out.push_str(""); } if rows.is_empty() { out.push_str(&format!( "", headers.len().max(1) )); } out.push_str("
{}
{}
nothing to show
"); 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 {'&':'&','<':'<','>':'>','"':'"',"'":'''}[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="loading"; 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="no chains reported";return} t.innerHTML="#chipchipseepromresponse"+ rows.map(function(r){return ""+r.map(function(c){return ""+esc(c)+""}).join("")+""}).join("")+""; }); 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 "
"+esc(r[0])+" "+esc(r[1])+"
"}).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="not mapped yet";return} t.innerHTML="fanzones"+ rows.map(function(r){return ""+esc(r[0])+""+esc(r[1])+""}).join("")+""; }); } 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::(), 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("
").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("