Compare commits

..

1 Commits

Author SHA1 Message Date
l5y 858e9fa189 web: render charts with uplot 2026-01-05 14:39:06 +01:00
36 changed files with 1326 additions and 2817 deletions
-1
View File
@@ -20,7 +20,6 @@ on:
pull_request:
branches: [ "main" ]
paths:
- '.github/**'
- 'web/**'
- 'tests/**'
-1
View File
@@ -20,7 +20,6 @@ on:
pull_request:
branches: [ "main" ]
paths:
- '.github/**'
- 'app/**'
- 'tests/**'
-1
View File
@@ -20,7 +20,6 @@ on:
pull_request:
branches: [ "main" ]
paths:
- '.github/**'
- 'data/**'
- 'tests/**'
+1 -2
View File
@@ -20,7 +20,6 @@ on:
pull_request:
branches: [ "main" ]
paths:
- '.github/**'
- 'web/**'
- 'tests/**'
@@ -35,7 +34,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
ruby-version: ['3.4', '4.0']
ruby-version: ['3.3', '3.4']
steps:
- uses: actions/checkout@v5
+116 -314
View File
@@ -24,20 +24,11 @@ use tracing::{error, info};
use crate::config::Config;
use crate::matrix::MatrixAppserviceClient;
use crate::potatomesh::{FetchParams, PotatoClient, PotatoMessage, PotatoNode};
use crate::potatomesh::{FetchParams, PotatoClient, PotatoMessage};
#[derive(Debug, serde::Serialize, serde::Deserialize, Default)]
pub struct BridgeState {
/// Highest message id processed by the bridge.
last_message_id: Option<u64>,
/// Highest rx_time observed; used to build incremental fetch queries.
#[serde(default)]
last_rx_time: Option<u64>,
/// Message ids seen at the current last_rx_time for de-duplication.
#[serde(default)]
last_rx_time_ids: Vec<u64>,
/// Legacy checkpoint timestamp used before last_rx_time was added.
#[serde(default, skip_serializing)]
last_checked_at: Option<u64>,
}
@@ -47,15 +38,7 @@ impl BridgeState {
return Ok(Self::default());
}
let data = fs::read_to_string(path)?;
// Treat empty/whitespace-only files as a fresh state.
if data.trim().is_empty() {
return Ok(Self::default());
}
let mut s: Self = serde_json::from_str(&data)?;
if s.last_rx_time.is_none() {
s.last_rx_time = s.last_checked_at;
}
s.last_checked_at = None;
let s: Self = serde_json::from_str(&data)?;
Ok(s)
}
@@ -66,32 +49,17 @@ impl BridgeState {
}
fn should_forward(&self, msg: &PotatoMessage) -> bool {
match self.last_rx_time {
None => match self.last_message_id {
None => true,
Some(last_id) => msg.id > last_id,
},
Some(last_ts) => {
if msg.rx_time > last_ts {
true
} else if msg.rx_time < last_ts {
false
} else {
!self.last_rx_time_ids.contains(&msg.id)
}
}
match self.last_message_id {
None => true,
Some(last) => msg.id > last,
}
}
fn update_with(&mut self, msg: &PotatoMessage) {
self.last_message_id = Some(msg.id);
if self.last_rx_time.is_none() || Some(msg.rx_time) > self.last_rx_time {
self.last_rx_time = Some(msg.rx_time);
self.last_rx_time_ids = vec![msg.id];
} else if Some(msg.rx_time) == self.last_rx_time && !self.last_rx_time_ids.contains(&msg.id)
{
self.last_rx_time_ids.push(msg.id);
}
self.last_message_id = Some(match self.last_message_id {
None => msg.id,
Some(last) => last.max(msg.id),
});
}
}
@@ -101,7 +69,7 @@ fn build_fetch_params(state: &BridgeState) -> FetchParams {
limit: None,
since: None,
}
} else if let Some(ts) = state.last_rx_time {
} else if let Some(ts) = state.last_checked_at {
FetchParams {
limit: None,
since: Some(ts),
@@ -114,18 +82,34 @@ fn build_fetch_params(state: &BridgeState) -> FetchParams {
}
}
fn update_checkpoint(state: &mut BridgeState, delivered_all: bool, now_secs: u64) -> bool {
if !delivered_all {
return false;
}
if state.last_message_id.is_some() {
state.last_checked_at = Some(now_secs);
true
} else {
false
}
}
async fn poll_once(
potato: &PotatoClient,
matrix: &MatrixAppserviceClient,
state: &mut BridgeState,
state_path: &str,
now_secs: u64,
) {
let params = build_fetch_params(state);
match potato.fetch_messages(params).await {
Ok(mut msgs) => {
// sort by rx_time so we process by actual receipt time
msgs.sort_by_key(|m| m.rx_time);
// sort by id ascending so we process in order
msgs.sort_by_key(|m| m.id);
let mut delivered_all = true;
for msg in &msgs {
if !state.should_forward(msg) {
@@ -136,24 +120,28 @@ async fn poll_once(
if let Some(port) = &msg.portnum {
if port != "TEXT_MESSAGE_APP" {
state.update_with(msg);
if let Err(e) = state.save(state_path) {
error!("Error saving state: {:?}", e);
}
continue;
}
}
if let Err(e) = handle_message(potato, matrix, state, msg).await {
error!("Error handling message {}: {:?}", msg.id, e);
delivered_all = false;
continue;
}
state.update_with(msg);
// persist after each processed message
if let Err(e) = state.save(state_path) {
error!("Error saving state: {:?}", e);
}
}
// Only advance checkpoint after successful delivery and a known last_message_id.
if update_checkpoint(state, delivered_all, now_secs) {
if let Err(e) = state.save(state_path) {
error!("Error saving state: {:?}", e);
}
}
}
Err(e) => {
error!("Error fetching PotatoMesh messages: {:?}", e);
@@ -188,7 +176,12 @@ async fn main() -> Result<()> {
let poll_interval = Duration::from_secs(cfg.potatomesh.poll_interval_secs);
loop {
poll_once(&potato, &matrix, &mut state, state_path).await;
let now_secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
poll_once(&potato, &matrix, &mut state, state_path, now_secs).await;
sleep(poll_interval).await;
}
@@ -206,77 +199,38 @@ async fn handle_message(
// Ensure puppet exists & has display name
matrix.ensure_user_registered(&localpart).await?;
matrix.ensure_user_joined_room(&user_id).await?;
let display_name = display_name_for_node(&node);
matrix.set_display_name(&user_id, &display_name).await?;
matrix.set_display_name(&user_id, &node.long_name).await?;
// Format the bridged message
let preset_short = modem_preset_short(&msg.modem_preset);
let prefix = format!(
"[{freq}][{preset_short}][{channel}]",
freq = msg.lora_freq,
preset_short = preset_short,
channel = msg.channel_name,
);
let (body, formatted_body) = format_message_bodies(&prefix, &msg.text);
let short = node
.short_name
.clone()
.unwrap_or_else(|| node.long_name.clone());
matrix
.send_formatted_message_as(&user_id, &body, &formatted_body)
.await?;
let body = format!(
"[{short}] {text}\n({from_id}{to_id}, {rssi}, {snr}, {chan}/{preset})",
short = short,
text = msg.text,
from_id = msg.from_id,
to_id = msg.to_id,
rssi = msg
.rssi
.map(|v| format!("RSSI {v} dB"))
.unwrap_or_else(|| "RSSI n/a".to_string()),
snr = msg
.snr
.map(|v| format!("SNR {v} dB"))
.unwrap_or_else(|| "SNR n/a".to_string()),
chan = msg.channel_name,
preset = msg.modem_preset,
);
matrix.send_text_message_as(&user_id, &body).await?;
state.update_with(msg);
Ok(())
}
/// Build a compact modem preset label like "LF" for "LongFast".
fn modem_preset_short(preset: &str) -> String {
let letters: String = preset
.chars()
.filter(|ch| ch.is_ascii_uppercase())
.collect();
if letters.is_empty() {
preset.chars().take(2).collect()
} else {
letters
}
}
/// Build plain text + HTML message bodies with inline-code metadata.
fn format_message_bodies(prefix: &str, text: &str) -> (String, String) {
let body = format!("`{}` {}", prefix, text);
let formatted_body = format!("<code>{}</code> {}", escape_html(prefix), escape_html(text));
(body, formatted_body)
}
/// Build the Matrix display name from a node's long/short names.
fn display_name_for_node(node: &PotatoNode) -> String {
match node
.short_name
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
{
Some(short) if short != node.long_name => format!("{} ({})", node.long_name, short),
_ => node.long_name.clone(),
}
}
/// Minimal HTML escaping for Matrix formatted_body payloads.
fn escape_html(input: &str) -> String {
let mut escaped = String::with_capacity(input.len());
for ch in input.chars() {
match ch {
'&' => escaped.push_str("&amp;"),
'<' => escaped.push_str("&lt;"),
'>' => escaped.push_str("&gt;"),
'"' => escaped.push_str("&quot;"),
'\'' => escaped.push_str("&#39;"),
_ => escaped.push(ch),
}
}
escaped
}
#[cfg(test)]
mod tests {
use super::*;
@@ -305,54 +259,6 @@ mod tests {
}
}
fn sample_node(short_name: Option<&str>, long_name: &str) -> PotatoNode {
PotatoNode {
node_id: "!abcd1234".to_string(),
short_name: short_name.map(str::to_string),
long_name: long_name.to_string(),
role: None,
hw_model: None,
last_heard: None,
first_heard: None,
latitude: None,
longitude: None,
altitude: None,
}
}
#[test]
fn modem_preset_short_handles_camelcase() {
assert_eq!(modem_preset_short("LongFast"), "LF");
assert_eq!(modem_preset_short("MediumFast"), "MF");
}
#[test]
fn format_message_bodies_escape_html() {
let (body, formatted) = format_message_bodies("[868][LF]", "Hello <&>");
assert_eq!(body, "`[868][LF]` Hello <&>");
assert_eq!(formatted, "<code>[868][LF]</code> Hello &lt;&amp;&gt;");
}
#[test]
fn escape_html_escapes_quotes() {
assert_eq!(escape_html("a\"b'c"), "a&quot;b&#39;c");
}
#[test]
fn display_name_for_node_includes_short_when_present() {
let node = sample_node(Some("TN"), "Test Node");
assert_eq!(display_name_for_node(&node), "Test Node (TN)");
}
#[test]
fn display_name_for_node_ignores_empty_or_duplicate_short() {
let empty_short = sample_node(Some(""), "Test Node");
assert_eq!(display_name_for_node(&empty_short), "Test Node");
let duplicate_short = sample_node(Some("Test Node"), "Test Node");
assert_eq!(display_name_for_node(&duplicate_short), "Test Node");
}
#[test]
fn bridge_state_initially_forwards_all() {
let state = BridgeState::default();
@@ -362,72 +268,39 @@ mod tests {
}
#[test]
fn bridge_state_tracks_latest_rx_time_and_skips_older() {
fn bridge_state_tracks_highest_id_and_skips_older() {
let mut state = BridgeState::default();
let m1 = sample_msg(10);
let m2 = sample_msg(20);
let m3 = sample_msg(15);
let m1 = PotatoMessage { rx_time: 10, ..m1 };
let m2 = PotatoMessage { rx_time: 20, ..m2 };
let m3 = PotatoMessage { rx_time: 15, ..m3 };
// First message, should forward
assert!(state.should_forward(&m1));
state.update_with(&m1);
assert_eq!(state.last_message_id, Some(10));
assert_eq!(state.last_rx_time, Some(10));
// Second message, higher id, should forward
assert!(state.should_forward(&m2));
state.update_with(&m2);
assert_eq!(state.last_message_id, Some(20));
assert_eq!(state.last_rx_time, Some(20));
// Third message, lower than last, should NOT forward
assert!(!state.should_forward(&m3));
// state remains unchanged
assert_eq!(state.last_message_id, Some(20));
assert_eq!(state.last_rx_time, Some(20));
}
#[test]
fn bridge_state_uses_legacy_id_filter_when_rx_time_missing() {
let state = BridgeState {
last_message_id: Some(10),
last_rx_time: None,
last_rx_time_ids: vec![],
fn bridge_state_update_is_monotonic() {
let mut state = BridgeState {
last_message_id: Some(50),
last_checked_at: None,
};
let older = sample_msg(9);
let newer = sample_msg(11);
let m = sample_msg(40);
assert!(!state.should_forward(&older));
assert!(state.should_forward(&newer));
}
#[test]
fn bridge_state_dedupes_same_timestamp() {
let mut state = BridgeState::default();
let m1 = PotatoMessage {
rx_time: 100,
..sample_msg(10)
};
let m2 = PotatoMessage {
rx_time: 100,
..sample_msg(9)
};
let dup = PotatoMessage {
rx_time: 100,
..sample_msg(10)
};
assert!(state.should_forward(&m1));
state.update_with(&m1);
assert!(state.should_forward(&m2));
state.update_with(&m2);
assert!(!state.should_forward(&dup));
assert_eq!(state.last_rx_time, Some(100));
assert_eq!(state.last_rx_time_ids, vec![10, 9]);
state.update_with(&m); // id is lower than current
// last_message_id must stay at 50
assert_eq!(state.last_message_id, Some(50));
}
#[test]
@@ -438,17 +311,13 @@ mod tests {
let state = BridgeState {
last_message_id: Some(12345),
last_rx_time: Some(99),
last_rx_time_ids: vec![123],
last_checked_at: Some(77),
last_checked_at: Some(99),
};
state.save(path_str).unwrap();
let loaded_state = BridgeState::load(path_str).unwrap();
assert_eq!(loaded_state.last_message_id, Some(12345));
assert_eq!(loaded_state.last_rx_time, Some(99));
assert_eq!(loaded_state.last_rx_time_ids, vec![123]);
assert_eq!(loaded_state.last_checked_at, None);
assert_eq!(loaded_state.last_checked_at, Some(99));
}
#[test]
@@ -459,50 +328,50 @@ mod tests {
let state = BridgeState::load(path_str).unwrap();
assert_eq!(state.last_message_id, None);
assert_eq!(state.last_rx_time, None);
assert!(state.last_rx_time_ids.is_empty());
}
#[test]
fn bridge_state_load_empty_file() {
let tmp_dir = tempfile::tempdir().unwrap();
let file_path = tmp_dir.path().join("empty.json");
let path_str = file_path.to_str().unwrap();
fs::write(path_str, "").unwrap();
let state = BridgeState::load(path_str).unwrap();
assert_eq!(state.last_message_id, None);
assert_eq!(state.last_rx_time, None);
assert!(state.last_rx_time_ids.is_empty());
assert_eq!(state.last_checked_at, None);
}
#[test]
fn bridge_state_migrates_legacy_checkpoint() {
let tmp_dir = tempfile::tempdir().unwrap();
let file_path = tmp_dir.path().join("legacy_state.json");
let path_str = file_path.to_str().unwrap();
fn update_checkpoint_requires_last_message_id() {
let mut state = BridgeState {
last_message_id: None,
last_checked_at: Some(10),
};
fs::write(
path_str,
r#"{"last_message_id":42,"last_checked_at":1710000000}"#,
)
.unwrap();
let saved = update_checkpoint(&mut state, true, 123);
assert!(!saved);
assert_eq!(state.last_checked_at, Some(10));
}
let state = BridgeState::load(path_str).unwrap();
assert_eq!(state.last_message_id, Some(42));
assert_eq!(state.last_rx_time, Some(1_710_000_000));
assert!(state.last_rx_time_ids.is_empty());
#[test]
fn update_checkpoint_skips_when_not_delivered() {
let mut state = BridgeState {
last_message_id: Some(5),
last_checked_at: Some(10),
};
let saved = update_checkpoint(&mut state, false, 123);
assert!(!saved);
assert_eq!(state.last_checked_at, Some(10));
}
#[test]
fn update_checkpoint_sets_when_safe() {
let mut state = BridgeState {
last_message_id: Some(5),
last_checked_at: None,
};
let saved = update_checkpoint(&mut state, true, 123);
assert!(saved);
assert_eq!(state.last_checked_at, Some(123));
}
#[test]
fn fetch_params_respects_missing_last_message_id() {
let state = BridgeState {
last_message_id: None,
last_rx_time: Some(123),
last_rx_time_ids: vec![],
last_checked_at: None,
last_checked_at: Some(123),
};
let params = build_fetch_params(&state);
@@ -514,9 +383,7 @@ mod tests {
fn fetch_params_uses_since_when_safe() {
let state = BridgeState {
last_message_id: Some(1),
last_rx_time: Some(123),
last_rx_time_ids: vec![],
last_checked_at: None,
last_checked_at: Some(123),
};
let params = build_fetch_params(&state);
@@ -528,8 +395,6 @@ mod tests {
fn fetch_params_defaults_to_small_window() {
let state = BridgeState {
last_message_id: Some(1),
last_rx_time: None,
last_rx_time_ids: vec![],
last_checked_at: None,
};
@@ -539,7 +404,7 @@ mod tests {
}
#[tokio::test]
async fn poll_once_leaves_state_unchanged_without_messages() {
async fn poll_once_persists_checkpoint_without_messages() {
let tmp_dir = tempfile::tempdir().unwrap();
let state_path = tmp_dir.path().join("state.json");
let state_str = state_path.to_str().unwrap();
@@ -570,62 +435,18 @@ mod tests {
let mut state = BridgeState {
last_message_id: Some(1),
last_rx_time: Some(100),
last_rx_time_ids: vec![1],
last_checked_at: None,
};
poll_once(&potato, &matrix, &mut state, state_str).await;
poll_once(&potato, &matrix, &mut state, state_str, 123).await;
mock_msgs.assert();
// No new data means state remains unchanged and is not persisted.
assert_eq!(state.last_rx_time, Some(100));
assert_eq!(state.last_rx_time_ids, vec![1]);
assert!(!state_path.exists());
}
#[tokio::test]
async fn poll_once_persists_state_for_non_text_messages() {
let tmp_dir = tempfile::tempdir().unwrap();
let state_path = tmp_dir.path().join("state.json");
let state_str = state_path.to_str().unwrap();
let mut server = mockito::Server::new_async().await;
let mock_msgs = server
.mock("GET", "/api/messages")
.match_query(mockito::Matcher::Any)
.with_status(200)
.with_header("content-type", "application/json")
.with_body(
r#"[{"id":1,"rx_time":100,"rx_iso":"2025-11-27T00:00:00Z","from_id":"!abcd1234","to_id":"^all","channel":1,"portnum":"POSITION_APP","text":"","rssi":-100,"hop_limit":1,"lora_freq":868,"modem_preset":"MediumFast","channel_name":"TEST","snr":0.0,"node_id":"!abcd1234"}]"#,
)
.create();
let http_client = reqwest::Client::new();
let potatomesh_cfg = PotatomeshConfig {
base_url: server.url(),
poll_interval_secs: 1,
};
let matrix_cfg = MatrixConfig {
homeserver: server.url(),
as_token: "AS_TOKEN".to_string(),
server_name: "example.org".to_string(),
room_id: "!roomid:example.org".to_string(),
};
let potato = PotatoClient::new(http_client.clone(), potatomesh_cfg);
let matrix = MatrixAppserviceClient::new(http_client, matrix_cfg);
let mut state = BridgeState::default();
poll_once(&potato, &matrix, &mut state, state_str).await;
mock_msgs.assert();
assert!(state_path.exists());
// Should have advanced checkpoint and saved it.
assert_eq!(state.last_checked_at, Some(123));
let loaded = BridgeState::load(state_str).unwrap();
assert_eq!(loaded.last_checked_at, Some(123));
assert_eq!(loaded.last_message_id, Some(1));
assert_eq!(loaded.last_rx_time, Some(100));
assert_eq!(loaded.last_rx_time_ids, vec![1]);
}
#[tokio::test]
@@ -646,8 +467,6 @@ mod tests {
let node_id = "abcd1234";
let user_id = format!("@potato_{}:{}", node_id, matrix_cfg.server_name);
let encoded_user = urlencoding::encode(&user_id);
let room_id = matrix_cfg.room_id.clone();
let encoded_room = urlencoding::encode(&room_id);
let mock_get_node = server
.mock("GET", "/api/nodes/abcd1234")
@@ -662,29 +481,19 @@ mod tests {
.with_status(200)
.create();
let mock_join = server
.mock(
"POST",
format!("/_matrix/client/v3/rooms/{}/join", encoded_room).as_str(),
)
.match_query(format!("user_id={}&access_token=AS_TOKEN", encoded_user).as_str())
.with_status(200)
.create();
let mock_display_name = server
.mock(
"PUT",
format!("/_matrix/client/v3/profile/{}/displayname", encoded_user).as_str(),
)
.match_query(format!("user_id={}&access_token=AS_TOKEN", encoded_user).as_str())
.match_body(mockito::Matcher::PartialJson(serde_json::json!({
"displayname": "Test Node (TN)"
})))
.with_status(200)
.create();
let http_client = reqwest::Client::new();
let matrix_client = MatrixAppserviceClient::new(http_client.clone(), matrix_cfg);
let room_id = &matrix_client.cfg.room_id;
let encoded_room = urlencoding::encode(room_id);
let txn_id = matrix_client
.txn_counter
.load(std::sync::atomic::Ordering::SeqCst);
@@ -699,12 +508,6 @@ mod tests {
.as_str(),
)
.match_query(format!("user_id={}&access_token=AS_TOKEN", encoded_user).as_str())
.match_body(mockito::Matcher::PartialJson(serde_json::json!({
"msgtype": "m.text",
"body": "`[868][MF][TEST]` Ping",
"format": "org.matrix.custom.html",
"formatted_body": "<code>[868][MF][TEST]</code> Ping",
})))
.with_status(200)
.create();
@@ -717,7 +520,6 @@ mod tests {
assert!(result.is_ok());
mock_get_node.assert();
mock_register.assert();
mock_join.assert();
mock_display_name.assert();
mock_send.assert();
+41 -105
View File
@@ -134,50 +134,12 @@ impl MatrixAppserviceClient {
}
}
/// Ensure the puppet user is joined to the configured room.
pub async fn ensure_user_joined_room(&self, user_id: &str) -> anyhow::Result<()> {
#[derive(Serialize)]
struct JoinReq {}
let encoded_room = urlencoding::encode(&self.cfg.room_id);
let encoded_user = urlencoding::encode(user_id);
let url = format!(
"{}/_matrix/client/v3/rooms/{}/join?user_id={}&{}",
self.cfg.homeserver,
encoded_room,
encoded_user,
self.auth_query()
);
let resp = self.http.post(&url).json(&JoinReq {}).send().await?;
if resp.status().is_success() {
Ok(())
} else {
let status = resp.status();
let body_snip = resp.text().await.unwrap_or_default();
Err(anyhow::anyhow!(
"Matrix join failed for {} in {} with status {} ({})",
user_id,
self.cfg.room_id,
status,
body_snip
))
}
}
/// Send a text message with HTML formatting into the configured room as puppet user_id.
pub async fn send_formatted_message_as(
&self,
user_id: &str,
body_text: &str,
formatted_body: &str,
) -> anyhow::Result<()> {
/// Send a plain text message into the configured room as puppet user_id.
pub async fn send_text_message_as(&self, user_id: &str, body_text: &str) -> anyhow::Result<()> {
#[derive(Serialize)]
struct MsgContent<'a> {
msgtype: &'a str,
body: &'a str,
format: &'a str,
formatted_body: &'a str,
}
let txn_id = self.txn_counter.fetch_add(1, Ordering::SeqCst);
@@ -196,23 +158,24 @@ impl MatrixAppserviceClient {
let content = MsgContent {
msgtype: "m.text",
body: body_text,
format: "org.matrix.custom.html",
formatted_body,
};
let resp = self.http.put(&url).json(&content).send().await?;
if !resp.status().is_success() {
let status = resp.status();
// optional: pull a short body snippet for debugging
let body_snip = resp.text().await.unwrap_or_default();
// Log for observability
tracing::warn!(
"Failed to send formatted message as {}: status {}, body: {}",
"Failed to send message as {}: status {}, body: {}",
user_id,
status,
body_snip
);
// Propagate an error so callers know this message was NOT delivered
return Err(anyhow::anyhow!(
"Matrix send failed for {} with status {}",
user_id,
@@ -395,59 +358,7 @@ mod tests {
}
#[tokio::test]
async fn test_ensure_user_joined_room_success() {
let mut server = mockito::Server::new_async().await;
let user_id = "@test:example.org";
let room_id = "!roomid:example.org";
let encoded_user = urlencoding::encode(user_id);
let encoded_room = urlencoding::encode(room_id);
let query = format!("user_id={}&access_token=AS_TOKEN", encoded_user);
let path = format!("/_matrix/client/v3/rooms/{}/join", encoded_room);
let mock = server
.mock("POST", path.as_str())
.match_query(query.as_str())
.with_status(200)
.create();
let mut cfg = dummy_cfg();
cfg.homeserver = server.url();
cfg.room_id = room_id.to_string();
let client = MatrixAppserviceClient::new(reqwest::Client::new(), cfg);
let result = client.ensure_user_joined_room(user_id).await;
mock.assert();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_ensure_user_joined_room_fail() {
let mut server = mockito::Server::new_async().await;
let user_id = "@test:example.org";
let room_id = "!roomid:example.org";
let encoded_user = urlencoding::encode(user_id);
let encoded_room = urlencoding::encode(room_id);
let query = format!("user_id={}&access_token=AS_TOKEN", encoded_user);
let path = format!("/_matrix/client/v3/rooms/{}/join", encoded_room);
let mock = server
.mock("POST", path.as_str())
.match_query(query.as_str())
.with_status(403)
.create();
let mut cfg = dummy_cfg();
cfg.homeserver = server.url();
cfg.room_id = room_id.to_string();
let client = MatrixAppserviceClient::new(reqwest::Client::new(), cfg);
let result = client.ensure_user_joined_room(user_id).await;
mock.assert();
assert!(result.is_err());
}
#[tokio::test]
async fn test_send_formatted_message_as_success() {
async fn test_send_text_message_as_success() {
let mut server = mockito::Server::new_async().await;
let user_id = "@test:example.org";
let room_id = "!roomid:example.org";
@@ -470,20 +381,45 @@ mod tests {
let mock = server
.mock("PUT", path.as_str())
.match_query(query.as_str())
.match_body(mockito::Matcher::PartialJson(serde_json::json!({
"msgtype": "m.text",
"body": "`[meta]` hello",
"format": "org.matrix.custom.html",
"formatted_body": "<code>[meta]</code> hello",
})))
.with_status(200)
.create();
let result = client
.send_formatted_message_as(user_id, "`[meta]` hello", "<code>[meta]</code> hello")
.await;
let result = client.send_text_message_as(user_id, "hello").await;
mock.assert();
assert!(result.is_ok());
}
#[tokio::test]
async fn test_send_text_message_as_fail() {
let mut server = mockito::Server::new_async().await;
let user_id = "@test:example.org";
let room_id = "!roomid:example.org";
let encoded_user = urlencoding::encode(user_id);
let encoded_room = urlencoding::encode(room_id);
let client = {
let mut cfg = dummy_cfg();
cfg.homeserver = server.url();
cfg.room_id = room_id.to_string();
MatrixAppserviceClient::new(reqwest::Client::new(), cfg)
};
let txn_id = client.txn_counter.load(Ordering::SeqCst);
let query = format!("user_id={}&access_token=AS_TOKEN", encoded_user);
let path = format!(
"/_matrix/client/v3/rooms/{}/send/m.room.message/{}",
encoded_room, txn_id
);
let mock = server
.mock("PUT", path.as_str())
.match_query(query.as_str())
.with_status(500)
.create();
let result = client.send_text_message_as(user_id, "hello").await;
mock.assert();
assert!(result.is_err());
}
}
+9 -13
View File
@@ -213,7 +213,7 @@ module PotatoMesh
#
# @param limit [Integer] maximum number of rows to return.
# @param node_ref [String, Integer, nil] optional node reference to narrow results.
# @param since [Integer] unix timestamp threshold applied in addition to the rolling window for collections.
# @param since [Integer] unix timestamp threshold applied in addition to the rolling window.
# @return [Array<Hash>] compacted node rows suitable for API responses.
def query_nodes(limit, node_ref: nil, since: 0)
limit = coerce_query_limit(limit)
@@ -221,8 +221,7 @@ module PotatoMesh
db.results_as_hash = true
now = Time.now.to_i
min_last_heard = now - PotatoMesh::Config.week_seconds
since_floor = node_ref ? 0 : min_last_heard
since_threshold = normalize_since_threshold(since, floor: since_floor)
since_threshold = normalize_since_threshold(since, floor: min_last_heard)
params = []
where_clauses = []
@@ -284,7 +283,7 @@ module PotatoMesh
# Fetch ingestor heartbeats with optional freshness filtering.
#
# @param limit [Integer] maximum number of ingestors to return.
# @param since [Integer] unix timestamp threshold applied in addition to the rolling window for collections.
# @param since [Integer] unix timestamp threshold applied in addition to the rolling window.
# @return [Array<Hash>] compacted ingestor rows suitable for API responses.
def query_ingestors(limit, since: 0)
limit = coerce_query_limit(limit)
@@ -423,8 +422,7 @@ module PotatoMesh
where_clauses = []
now = Time.now.to_i
min_rx_time = now - PotatoMesh::Config.week_seconds
since_floor = node_ref ? 0 : min_rx_time
since_threshold = normalize_since_threshold(since, floor: since_floor)
since_threshold = normalize_since_threshold(since, floor: min_rx_time)
where_clauses << "COALESCE(rx_time, position_time, 0) >= ?"
params << since_threshold
@@ -472,7 +470,7 @@ module PotatoMesh
#
# @param limit [Integer] maximum number of rows to return.
# @param node_ref [String, Integer, nil] optional node reference to scope results.
# @param since [Integer] unix timestamp threshold applied in addition to the rolling window for collections.
# @param since [Integer] unix timestamp threshold applied in addition to the rolling window.
# @return [Array<Hash>] compacted neighbor rows suitable for API responses.
def query_neighbors(limit, node_ref: nil, since: 0)
limit = coerce_query_limit(limit)
@@ -482,8 +480,7 @@ module PotatoMesh
where_clauses = []
now = Time.now.to_i
min_rx_time = now - PotatoMesh::Config.week_seconds
since_floor = node_ref ? 0 : min_rx_time
since_threshold = normalize_since_threshold(since, floor: since_floor)
since_threshold = normalize_since_threshold(since, floor: min_rx_time)
where_clauses << "COALESCE(rx_time, 0) >= ?"
params << since_threshold
@@ -520,7 +517,7 @@ module PotatoMesh
#
# @param limit [Integer] maximum number of rows to return.
# @param node_ref [String, Integer, nil] optional node reference to scope results.
# @param since [Integer] unix timestamp threshold applied in addition to the rolling window for collections.
# @param since [Integer] unix timestamp threshold applied in addition to the rolling window.
# @return [Array<Hash>] compacted telemetry rows suitable for API responses.
def query_telemetry(limit, node_ref: nil, since: 0)
limit = coerce_query_limit(limit)
@@ -530,8 +527,7 @@ module PotatoMesh
where_clauses = []
now = Time.now.to_i
min_rx_time = now - PotatoMesh::Config.week_seconds
since_floor = node_ref ? 0 : min_rx_time
since_threshold = normalize_since_threshold(since, floor: since_floor)
since_threshold = normalize_since_threshold(since, floor: min_rx_time)
where_clauses << "COALESCE(rx_time, telemetry_time, 0) >= ?"
params << since_threshold
@@ -738,7 +734,7 @@ module PotatoMesh
params = []
where_clauses = []
now = Time.now.to_i
min_rx_time = now - PotatoMesh::Config.trace_neighbor_window_seconds
min_rx_time = now - PotatoMesh::Config.week_seconds
since_threshold = normalize_since_threshold(since, floor: min_rx_time)
where_clauses << "COALESCE(rx_time, 0) >= ?"
params << since_threshold
-7
View File
@@ -158,13 +158,6 @@ module PotatoMesh
7 * 24 * 60 * 60
end
# Rolling retention window in seconds for trace and neighbor API queries.
#
# @return [Integer] seconds in twenty-eight days.
def trace_neighbor_window_seconds
28 * 24 * 60 * 60
end
# Default upper bound for accepted JSON payload sizes.
#
# @return [Integer] byte ceiling for HTTP request bodies.
+10
View File
@@ -7,6 +7,10 @@
"": {
"name": "potato-mesh",
"version": "0.5.9",
"hasInstallScript": true,
"dependencies": {
"uplot": "^1.6.30"
},
"devDependencies": {
"istanbul-lib-coverage": "^3.2.2",
"istanbul-lib-report": "^3.0.1",
@@ -154,6 +158,12 @@
"node": ">=8"
}
},
"node_modules/uplot": {
"version": "1.6.32",
"resolved": "https://registry.npmjs.org/uplot/-/uplot-1.6.32.tgz",
"integrity": "sha512-KIMVnG68zvu5XXUbC4LQEPnhwOxBuLyW1AHtpm6IKTXImkbLgkMy+jabjLgSLMasNuGGzQm/ep3tOkyTxpiQIw==",
"license": "MIT"
},
"node_modules/v8-to-istanbul": {
"version": "9.3.0",
"resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.3.0.tgz",
+4
View File
@@ -4,8 +4,12 @@
"type": "module",
"private": true,
"scripts": {
"postinstall": "node ./scripts/copy-uplot.js",
"test": "mkdir -p reports coverage && NODE_V8_COVERAGE=coverage node --test --experimental-test-coverage --test-reporter=spec --test-reporter-destination=stdout --test-reporter=junit --test-reporter-destination=reports/javascript-junit.xml && node ./scripts/export-coverage.js"
},
"dependencies": {
"uplot": "^1.6.30"
},
"devDependencies": {
"istanbul-lib-coverage": "^3.2.2",
"istanbul-lib-report": "^3.0.1",
@@ -80,13 +80,19 @@ test('initializeChartsPage renders the telemetry charts when snapshots are avail
},
]);
let receivedOptions = null;
const renderCharts = (node, options) => {
let mountedModels = null;
const createCharts = (node, options) => {
receivedOptions = options;
return '<section class="node-detail__charts">Charts</section>';
return { chartsHtml: '<section class="node-detail__charts">Charts</section>', chartModels: [{ id: 'power' }] };
};
const result = await initializeChartsPage({ document: documentStub, fetchImpl, renderCharts });
const mountCharts = (chartModels, options) => {
mountedModels = { chartModels, options };
return [];
};
const result = await initializeChartsPage({ document: documentStub, fetchImpl, createCharts, mountCharts });
assert.equal(result, true);
assert.equal(container.innerHTML.includes('node-detail__charts'), true);
assert.equal(mountedModels.chartModels.length, 1);
assert.ok(receivedOptions);
assert.equal(receivedOptions.chartOptions.windowMs, 604_800_000);
assert.equal(typeof receivedOptions.chartOptions.lineReducer, 'function');
@@ -118,8 +124,8 @@ test('initializeChartsPage shows an error message when fetching fails', async ()
const fetchImpl = async () => {
throw new Error('network');
};
const renderCharts = () => '<section>unused</section>';
const result = await initializeChartsPage({ document: documentStub, fetchImpl, renderCharts });
const createCharts = () => ({ chartsHtml: '<section>unused</section>', chartModels: [] });
const result = await initializeChartsPage({ document: documentStub, fetchImpl, createCharts });
assert.equal(result, false);
assert.equal(container.innerHTML.includes('Failed to load telemetry charts.'), true);
});
@@ -136,8 +142,8 @@ test('initializeChartsPage handles missing containers and empty telemetry snapsh
},
};
const fetchImpl = async () => createResponse(200, []);
const renderCharts = () => '';
const result = await initializeChartsPage({ document: documentStub, fetchImpl, renderCharts });
const createCharts = () => ({ chartsHtml: '', chartModels: [] });
const result = await initializeChartsPage({ document: documentStub, fetchImpl, createCharts });
assert.equal(result, true);
assert.equal(container.innerHTML.includes('Telemetry snapshots are unavailable.'), true);
});
@@ -155,8 +161,8 @@ test('initializeChartsPage shows a status when rendering produces no markup', as
aggregates: { voltage: { avg: 3.9 } },
},
]);
const renderCharts = () => '';
const result = await initializeChartsPage({ document: documentStub, fetchImpl, renderCharts });
const createCharts = () => ({ chartsHtml: '', chartModels: [] });
const result = await initializeChartsPage({ document: documentStub, fetchImpl, createCharts });
assert.equal(result, true);
assert.equal(container.innerHTML.includes('Telemetry snapshots are unavailable.'), true);
});
@@ -113,9 +113,11 @@ test('buildChatTabModel returns sorted nodes and channel buckets', () => {
assert.deepEqual(secondaryChannel.entries.map(entry => entry.message.id), ['iso-ts', 'recent-alt']);
});
test('buildChatTabModel skips channel buckets when there are no messages', () => {
test('buildChatTabModel always includes channel zero bucket', () => {
const model = buildChatTabModel({ nodes: [], messages: [], nowSeconds: NOW, windowSeconds: WINDOW });
assert.equal(model.channels.length, 0);
assert.equal(model.channels.length, 1);
assert.equal(model.channels[0].index, 0);
assert.equal(model.channels[0].entries.length, 0);
});
test('buildChatTabModel falls back to numeric label when no metadata provided', () => {
@@ -27,9 +27,6 @@ test('federation map centers on configured coordinates and follows theme filters
const mapEl = createElement('div', 'map');
registerElement('map', mapEl);
const mapPanel = createElement('div', 'mapPanel');
mapPanel.dataset.legendCollapsed = 'true';
registerElement('mapPanel', mapPanel);
const statusEl = createElement('div', 'status');
registerElement('status', statusEl);
const tableEl = createElement('table', 'instances');
@@ -411,192 +408,15 @@ test('federation table sorting, contact rendering, and legend creation', async (
assert.deepEqual(mapSetViewCalls[0], [[0, 0], 3]);
assert.equal(mapFitBoundsCalls[0][0].length, 3);
assert.equal(legendContainers.length, 2);
const legend = legendContainers.find(container => container.className.includes('legend--instances'));
assert.ok(legend);
assert.ok(legend.className.includes('legend-hidden'));
assert.equal(legendContainers.length, 1);
const legend = legendContainers[0];
assert.ok(legend.className.includes('legend'));
const legendHeader = legend.children.find(child => child.className === 'legend-header');
const legendTitle = legendHeader && Array.isArray(legendHeader.children)
? legendHeader.children.find(child => child.className === 'legend-title')
: null;
assert.ok(legendTitle);
assert.equal(legendTitle.textContent, 'Active nodes');
const legendToggle = legendContainers.find(container => container.className.includes('legend-toggle'));
assert.ok(legendToggle);
} finally {
cleanup();
}
});
test('federation legend toggle respects media query changes', async () => {
const env = createDomEnvironment({ includeBody: true, bodyHasDarkClass: false });
const { document, createElement, registerElement, cleanup } = env;
const mapEl = createElement('div', 'map');
registerElement('map', mapEl);
const mapPanel = createElement('div', 'mapPanel');
mapPanel.setAttribute('data-legend-collapsed', 'false');
registerElement('mapPanel', mapPanel);
const statusEl = createElement('div', 'status');
registerElement('status', statusEl);
const tableEl = createElement('table', 'instances');
const tbodyEl = createElement('tbody');
registerElement('instances', tableEl);
tableEl.appendChild(tbodyEl);
const configPayload = {
mapCenter: { lat: 0, lon: 0 },
mapZoom: 3,
tileFilters: { light: 'none', dark: 'invert(1)' }
};
const configEl = createElement('div');
configEl.setAttribute('data-app-config', JSON.stringify(configPayload));
document.querySelector = selector => {
if (selector === '[data-app-config]') return configEl;
if (selector === '#instances tbody') return tbodyEl;
return null;
};
let mediaQueryHandler = null;
window.matchMedia = () => ({
matches: false,
addListener(handler) {
mediaQueryHandler = handler;
}
});
const legendContainers = [];
const legendButtons = [];
const DomUtil = {
create(tag, className, parent) {
const classSet = new Set(className ? className.split(/\s+/).filter(Boolean) : []);
const el = {
tagName: tag,
className,
classList: {
toggle(name, force) {
const shouldAdd = typeof force === 'boolean' ? force : !classSet.has(name);
if (shouldAdd) {
classSet.add(name);
} else {
classSet.delete(name);
}
el.className = Array.from(classSet).join(' ');
}
},
children: [],
style: {},
textContent: '',
attributes: new Map(),
setAttribute(name, value) {
this.attributes.set(name, String(value));
},
appendChild(child) {
this.children.push(child);
return child;
},
addEventListener(event, handler) {
if (event === 'click') {
this._clickHandler = handler;
}
},
querySelector() {
return null;
}
};
if (parent && parent.appendChild) parent.appendChild(el);
if (className && className.includes('legend-toggle-button')) {
legendButtons.push(el);
}
return el;
}
};
const controlStub = () => {
const ctrl = {
onAdd: null,
container: null,
addTo(map) {
this.container = this.onAdd ? this.onAdd(map) : null;
legendContainers.push(this.container);
return this;
},
getContainer() {
return this.container;
}
};
return ctrl;
};
const markersLayer = {
addLayer() {
return null;
},
addTo() {
return this;
}
};
const leafletStub = {
map() {
return {
setView() {},
on() {},
fitBounds() {}
};
},
tileLayer() {
return {
addTo() {
return this;
},
getContainer() {
return null;
},
on() {}
};
},
layerGroup() {
return markersLayer;
},
circleMarker() {
return {
bindPopup() {
return this;
}
};
},
control: controlStub,
DomUtil,
DomEvent: {
disableClickPropagation() {},
disableScrollPropagation() {}
}
};
const fetchImpl = async () => ({
ok: true,
json: async () => []
});
try {
await initializeFederationPage({ config: configPayload, fetchImpl, leaflet: leafletStub });
const legend = legendContainers.find(container => container.className.includes('legend--instances'));
assert.ok(legend);
assert.ok(!legend.className.includes('legend-hidden'));
assert.equal(legendButtons.length, 1);
legendButtons[0]._clickHandler?.({ preventDefault() {}, stopPropagation() {} });
assert.ok(legend.className.includes('legend-hidden'));
if (mediaQueryHandler) {
mediaQueryHandler({ matches: false });
assert.ok(!legend.className.includes('legend-hidden'));
}
} finally {
cleanup();
}
@@ -1,455 +0,0 @@
/*
* Copyright © 2025-26 l5yth & contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import test from 'node:test';
import assert from 'node:assert/strict';
import { __test__, initializeMobileMenu } from '../mobile-menu.js';
const { createMobileMenuController, resolveFocusableElements } = __test__;
function createClassList() {
const values = new Set();
return {
add(...names) {
names.forEach(name => values.add(name));
},
remove(...names) {
names.forEach(name => values.delete(name));
},
contains(name) {
return values.has(name);
}
};
}
function createElement(tagName = 'div', initialId = '') {
const listeners = new Map();
const attributes = new Map();
if (initialId) {
attributes.set('id', String(initialId));
}
return {
tagName: tagName.toUpperCase(),
attributes,
classList: createClassList(),
dataset: {},
hidden: false,
parentNode: null,
nextSibling: null,
setAttribute(name, value) {
attributes.set(name, String(value));
},
getAttribute(name) {
return attributes.has(name) ? attributes.get(name) : null;
},
addEventListener(event, handler) {
listeners.set(event, handler);
},
dispatchEvent(event) {
const key = typeof event === 'string' ? event : event?.type;
const handler = listeners.get(key);
if (handler) {
handler(event);
}
},
appendChild(node) {
this.lastAppended = node;
return node;
},
insertBefore(node, nextSibling) {
this.lastInserted = { node, nextSibling };
return node;
},
focus() {
globalThis.document.activeElement = this;
},
querySelector() {
return null;
},
querySelectorAll() {
return [];
}
};
}
function createDomStub() {
const originalDocument = globalThis.document;
const registry = new Map();
const documentStub = {
body: createElement('body'),
activeElement: null,
querySelectorAll() {
return [];
},
getElementById(id) {
return registry.get(id) || null;
}
};
globalThis.document = documentStub;
return {
documentStub,
registry,
cleanup() {
globalThis.document = originalDocument;
}
};
}
function createWindowStub(matches = true) {
const listeners = new Map();
const mediaListeners = new Map();
return {
matchMedia() {
return {
matches,
addEventListener(event, handler) {
mediaListeners.set(event, handler);
}
};
},
addEventListener(event, handler) {
listeners.set(event, handler);
},
dispatchEvent(event) {
const key = typeof event === 'string' ? event : event?.type;
const handler = listeners.get(key);
if (handler) {
handler(event);
}
},
dispatchMediaChange() {
const handler = mediaListeners.get('change');
if (handler) {
handler();
}
}
};
}
function createWindowStubWithListener(matches = true) {
const listeners = new Map();
let mediaHandler = null;
return {
matchMedia() {
return {
matches,
addListener(handler) {
mediaHandler = handler;
}
};
},
addEventListener(event, handler) {
listeners.set(event, handler);
},
dispatchMediaChange() {
if (mediaHandler) {
mediaHandler();
}
}
};
}
test('mobile menu toggles open state and aria-expanded', () => {
const { documentStub, registry, cleanup } = createDomStub();
const windowStub = createWindowStub(true);
const menuToggle = createElement('button');
const menu = createElement('div');
const menuPanel = createElement('div');
const closeButton = createElement('button');
const navLink = createElement('a');
menu.hidden = true;
menuPanel.classList.add('mobile-menu__panel');
menu.querySelector = selector => {
if (selector === '.mobile-menu__panel') return menuPanel;
return null;
};
menu.querySelectorAll = selector => {
if (selector === '[data-mobile-menu-close]') return [closeButton];
if (selector === 'a') return [navLink];
return [];
};
menuPanel.querySelectorAll = () => [closeButton, navLink];
registry.set('mobileMenuToggle', menuToggle);
registry.set('mobileMenu', menu);
try {
const controller = createMobileMenuController({
documentObject: documentStub,
windowObject: windowStub
});
controller.initialize();
windowStub.dispatchMediaChange();
menuToggle.dispatchEvent({ type: 'click', preventDefault() {} });
assert.equal(menu.hidden, false);
assert.equal(menuToggle.getAttribute('aria-expanded'), 'true');
assert.equal(documentStub.body.classList.contains('menu-open'), true);
navLink.dispatchEvent({ type: 'click' });
assert.equal(menu.hidden, true);
closeButton.dispatchEvent({ type: 'click' });
assert.equal(menu.hidden, true);
assert.equal(menuToggle.getAttribute('aria-expanded'), 'false');
} finally {
cleanup();
}
});
test('mobile menu closes on escape and route changes', () => {
const { documentStub, registry, cleanup } = createDomStub();
const windowStub = createWindowStub(true);
const menuToggle = createElement('button');
const menu = createElement('div');
const menuPanel = createElement('div');
const closeButton = createElement('button');
menu.hidden = true;
menuPanel.classList.add('mobile-menu__panel');
menu.querySelector = selector => {
if (selector === '.mobile-menu__panel') return menuPanel;
return null;
};
menu.querySelectorAll = selector => {
if (selector === '[data-mobile-menu-close]') return [closeButton];
return [];
};
menuPanel.querySelectorAll = () => [closeButton];
registry.set('mobileMenuToggle', menuToggle);
registry.set('mobileMenu', menu);
try {
const controller = createMobileMenuController({
documentObject: documentStub,
windowObject: windowStub
});
controller.initialize();
menuPanel.dispatchEvent({ type: 'keydown', key: 'Escape', preventDefault() {} });
assert.equal(menu.hidden, true);
menuToggle.dispatchEvent({ type: 'click', preventDefault() {} });
assert.equal(menu.hidden, false);
menuPanel.dispatchEvent({ type: 'keydown', key: 'ArrowDown' });
assert.equal(menu.hidden, false);
menuPanel.dispatchEvent({ type: 'keydown', key: 'Escape', preventDefault() {} });
assert.equal(menu.hidden, true);
menuToggle.dispatchEvent({ type: 'click', preventDefault() {} });
windowStub.dispatchEvent({ type: 'hashchange' });
assert.equal(menu.hidden, true);
menuToggle.dispatchEvent({ type: 'click', preventDefault() {} });
windowStub.dispatchEvent({ type: 'popstate' });
assert.equal(menu.hidden, true);
} finally {
cleanup();
}
});
test('mobile menu traps focus within the panel', () => {
const { documentStub, registry, cleanup } = createDomStub();
const windowStub = createWindowStub(true);
const menuToggle = createElement('button');
const menu = createElement('div');
const menuPanel = createElement('div');
const firstLink = createElement('a');
const lastButton = createElement('button');
menuPanel.classList.add('mobile-menu__panel');
menuPanel.querySelectorAll = () => [firstLink, lastButton];
menu.querySelector = selector => {
if (selector === '.mobile-menu__panel') return menuPanel;
return null;
};
menu.querySelectorAll = () => [];
registry.set('mobileMenuToggle', menuToggle);
registry.set('mobileMenu', menu);
try {
const controller = createMobileMenuController({
documentObject: documentStub,
windowObject: windowStub
});
controller.initialize();
menuToggle.dispatchEvent({ type: 'click', preventDefault() {} });
documentStub.activeElement = lastButton;
menuPanel.dispatchEvent({ type: 'keydown', key: 'Tab', preventDefault() {}, shiftKey: false });
assert.equal(documentStub.activeElement, firstLink);
documentStub.activeElement = firstLink;
menuPanel.dispatchEvent({ type: 'keydown', key: 'Tab', preventDefault() {}, shiftKey: true });
assert.equal(documentStub.activeElement, lastButton);
} finally {
cleanup();
}
});
test('resolveFocusableElements filters out aria-hidden nodes', () => {
const hiddenButton = createElement('button');
hiddenButton.getAttribute = name => (name === 'aria-hidden' ? 'true' : null);
const openLink = createElement('a');
const bareNode = { tagName: 'DIV' };
const container = {
querySelectorAll() {
return [hiddenButton, bareNode, openLink];
}
};
const focusables = resolveFocusableElements(container);
assert.equal(focusables.length, 1);
assert.equal(focusables[0], openLink);
});
test('resolveFocusableElements handles empty containers', () => {
assert.deepEqual(resolveFocusableElements(null), []);
assert.deepEqual(resolveFocusableElements({}), []);
});
test('mobile menu focuses the panel when no focusables exist', () => {
const { documentStub, registry, cleanup } = createDomStub();
const windowStub = createWindowStub(true);
const menuToggle = createElement('button');
const menu = createElement('div');
const menuPanel = createElement('div');
const lastActive = createElement('button');
menuPanel.classList.add('mobile-menu__panel');
menuPanel.querySelectorAll = () => [];
menu.querySelector = selector => {
if (selector === '.mobile-menu__panel') return menuPanel;
return null;
};
menu.querySelectorAll = () => [];
registry.set('mobileMenuToggle', menuToggle);
registry.set('mobileMenu', menu);
documentStub.activeElement = lastActive;
try {
const controller = createMobileMenuController({
documentObject: documentStub,
windowObject: windowStub
});
controller.initialize();
menuToggle.dispatchEvent({ type: 'click', preventDefault() {} });
assert.equal(documentStub.activeElement, menuPanel);
menuToggle.dispatchEvent({ type: 'click', preventDefault() {} });
assert.equal(documentStub.activeElement, lastActive);
} finally {
cleanup();
}
});
test('mobile menu registers legacy media query listeners', () => {
const { documentStub, registry, cleanup } = createDomStub();
const windowStub = createWindowStubWithListener(true);
const menuToggle = createElement('button');
const menu = createElement('div');
const menuPanel = createElement('div');
menuPanel.classList.add('mobile-menu__panel');
menu.querySelector = selector => {
if (selector === '.mobile-menu__panel') return menuPanel;
return null;
};
menu.querySelectorAll = () => [];
registry.set('mobileMenuToggle', menuToggle);
registry.set('mobileMenu', menu);
try {
const controller = createMobileMenuController({
documentObject: documentStub,
windowObject: windowStub
});
controller.initialize();
windowStub.dispatchMediaChange();
assert.equal(menuToggle.getAttribute('aria-expanded'), 'false');
} finally {
cleanup();
}
});
test('mobile menu safely no-ops without required nodes', () => {
const { documentStub, cleanup } = createDomStub();
const windowStub = createWindowStub(true);
try {
const controller = createMobileMenuController({
documentObject: documentStub,
windowObject: windowStub
});
controller.initialize();
controller.openMenu();
controller.closeMenu();
controller.syncLayout();
assert.equal(documentStub.body.classList.contains('menu-open'), false);
} finally {
cleanup();
}
});
test('initializeMobileMenu returns a controller', () => {
const { documentStub, registry, cleanup } = createDomStub();
const windowStub = createWindowStub(true);
const menuToggle = createElement('button');
const menu = createElement('div');
const menuPanel = createElement('div');
menuPanel.classList.add('mobile-menu__panel');
menu.querySelector = selector => {
if (selector === '.mobile-menu__panel') return menuPanel;
return null;
};
menu.querySelectorAll = () => [];
registry.set('mobileMenuToggle', menuToggle);
registry.set('mobileMenu', menu);
try {
const controller = initializeMobileMenu({
documentObject: documentStub,
windowObject: windowStub
});
assert.equal(typeof controller.openMenu, 'function');
} finally {
cleanup();
}
});
@@ -1,207 +0,0 @@
/*
* Copyright © 2025-26 l5yth & contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import test from 'node:test';
import assert from 'node:assert/strict';
import { initializeNodeDetailMapPanel, __testUtils } from '../node-detail-map.js';
const { extractPositionEntries, resolveReferenceId, colorForDay, ROLE_BY_DAY } = __testUtils;
function createClassList() {
const values = new Set();
return {
add(name) {
if (name) values.add(name);
},
remove(name) {
values.delete(name);
},
contains(name) {
return values.has(name);
}
};
}
function createContainer() {
return {
childNodes: [],
insertBefore(node, before) {
const idx = before ? this.childNodes.indexOf(before) : -1;
if (idx >= 0) {
this.childNodes.splice(idx, 0, node);
} else {
this.childNodes.push(node);
}
node.parentNode = this;
},
appendChild(node) {
this.childNodes.push(node);
node.parentNode = this;
}
};
}
function createElement() {
return {
hidden: false,
textContent: '',
classList: createClassList(),
parentNode: null,
nextSibling: null,
};
}
function createRootHarness() {
const section = createElement();
const slot = createContainer();
const status = createElement();
const root = {
querySelector(selector) {
if (selector === '[data-node-map-panel]') return section;
if (selector === '[data-node-map-slot]') return slot;
if (selector === '[data-node-map-status]') return status;
return null;
}
};
return { root, section, slot, status };
}
test('extractPositionEntries filters invalid position entries', () => {
const nowSec = 2_000_000;
const entries = extractPositionEntries([
{ latitude: 10.5, longitude: 20.25, rx_time: nowSec },
{ lat: '42.1', lon: '-71.2', position_time: nowSec - 100 },
{ latitude: 12, longitude: 24, position_time: nowSec - (86_400 * 11) },
{ latitude: null, longitude: 10, rx_time: nowSec },
{ latitude: 'bad', longitude: 10, rx_time: nowSec },
], nowSec);
assert.deepEqual(entries.map(entry => [entry.lat, entry.lon]), [
[10.5, 20.25],
[42.1, -71.2],
]);
});
test('resolveReferenceId prefers node identifiers when present', () => {
assert.equal(resolveReferenceId({ nodeId: '!alpha', nodeNum: 10 }), '!alpha');
assert.equal(resolveReferenceId({ node_num: 12 }), '12');
assert.equal(resolveReferenceId(null), null);
});
test('colorForDay interpolates from red to blue', () => {
const getRoleColor = role => `color:${role}`;
assert.equal(colorForDay(0, getRoleColor), `color:${ROLE_BY_DAY[0]}`);
assert.equal(colorForDay(9, getRoleColor), `color:${ROLE_BY_DAY[9]}`);
});
test('initializeNodeDetailMapPanel hides the panel without shared map data', async () => {
const { root, section, status } = createRootHarness();
status.hidden = false;
section.hidden = false;
const result = await initializeNodeDetailMapPanel(root, { nodeId: '!alpha' }, { fetchImpl: async () => ({ ok: true }) });
assert.equal(result, null);
assert.equal(status.hidden, true);
assert.equal(section.hidden, true);
});
test('initializeNodeDetailMapPanel reuses the shared map and restores it', async () => {
const originalNow = Date.now;
Date.now = () => 1_000_000 * 1000;
try {
const { root, slot, status } = createRootHarness();
const mapPanel = createElement();
const originalParent = createContainer();
originalParent.appendChild(mapPanel);
mapPanel.nextSibling = null;
const calls = { polyline: null, markers: 0, fitBounds: 0 };
const map = {
getCenter() {
return { lat: 1, lng: 2 };
},
getZoom() {
return 6;
},
setView() {},
fitBounds() {
calls.fitBounds += 1;
},
invalidateSize() {}
};
const leaflet = {
layerGroup() {
return {
addTo() {
return this;
},
remove() {}
};
},
polyline(latlngs, options) {
return {
addTo() {
calls.polyline = { latlngs, options };
}
};
},
circleMarker() {
return {
addTo() {
calls.markers += 1;
}
};
}
};
const fitBoundsEl = { checked: true };
const fetchImpl = async () => ({
ok: true,
status: 200,
async json() {
return [
{ latitude: 10, longitude: 20, position_time: 1_000_000 },
{ latitude: 11, longitude: 22, position_time: 1_000_000 - 86_400 },
];
}
});
const cleanup = await initializeNodeDetailMapPanel(root, { nodeId: '!map' }, {
fetchImpl,
mapPanel,
document: {
getElementById(id) {
return id === 'fitBounds' ? fitBoundsEl : null;
}
},
getMapContext: () => ({ map, leaflet }),
getRoleColor: role => `color:${role}`,
});
assert.ok(cleanup);
assert.equal(status.textContent, '2 positions');
assert.equal(mapPanel.parentNode, slot);
assert.equal(mapPanel.classList.contains('map-panel--embedded'), true);
assert.equal(calls.polyline.options.color, 'color:LOST_AND_FOUND');
assert.equal(calls.markers, 2);
assert.equal(fitBoundsEl.checked, false);
assert.deepEqual(calls.polyline.latlngs, [[10, 20], [11, 22]]);
cleanup();
assert.equal(mapPanel.parentNode, originalParent);
assert.equal(fitBoundsEl.checked, true);
} finally {
Date.now = originalNow;
}
});
@@ -111,6 +111,26 @@ test('createNodeDetailOverlayManager renders fetched markup and restores focus',
assert.equal(focusTarget.focusCalled, true);
});
test('createNodeDetailOverlayManager mounts telemetry charts for overlay content', async () => {
const { document, content } = createOverlayHarness();
const chartModels = [{ id: 'power' }];
let mountCall = null;
const manager = createNodeDetailOverlayManager({
document,
fetchNodeDetail: async () => ({ html: '<section class="node-detail">Charts</section>', chartModels }),
mountCharts: (models, options) => {
mountCall = { models, options };
return [];
},
});
assert.ok(manager);
await manager.open({ nodeId: '!alpha' });
assert.equal(content.innerHTML.includes('Charts'), true);
assert.ok(mountCall);
assert.equal(mountCall.models, chartModels);
assert.equal(mountCall.options.root, content);
});
test('createNodeDetailOverlayManager surfaces errors and supports escape closing', async () => {
const { document, overlay, content } = createOverlayHarness();
const errors = [];
@@ -47,7 +47,9 @@ const {
categoriseNeighbors,
renderNeighborGroups,
renderSingleNodeTable,
createTelemetryCharts,
renderTelemetryCharts,
buildUPlotChartConfig,
renderMessages,
renderTraceroutes,
renderTracePath,
@@ -386,23 +388,10 @@ test('renderTelemetryCharts renders condensed scatter charts when telemetry exis
},
};
const html = renderTelemetryCharts(node, { nowMs });
const fmt = new Date(nowMs);
const expectedDate = String(fmt.getDate()).padStart(2, '0');
assert.equal(html.includes('node-detail__charts'), true);
assert.equal(html.includes('Power metrics'), true);
assert.equal(html.includes('Environmental telemetry'), true);
assert.equal(html.includes('Battery (%)'), true);
assert.equal(html.includes('Voltage (V)'), true);
assert.equal(html.includes('Current (A)'), true);
assert.equal(html.includes('Channel utilization (%)'), true);
assert.equal(html.includes('Air util TX (%)'), true);
assert.equal(html.includes('Utilization (%)'), true);
assert.equal(html.includes('Gas resistance (\u03a9)'), true);
assert.equal(html.includes('Air quality'), true);
assert.equal(html.includes('IAQ index'), true);
assert.equal(html.includes('Temperature (\u00b0C)'), true);
assert.equal(html.includes(expectedDate), true);
assert.equal(html.includes('node-detail__chart-point'), true);
assert.equal(html.includes('node-detail__chart-plot'), true);
});
test('renderTelemetryCharts expands upper bounds when overflow metrics exceed defaults', () => {
@@ -433,12 +422,18 @@ test('renderTelemetryCharts expands upper bounds when overflow metrics exceed de
},
},
};
const html = renderTelemetryCharts(node, { nowMs });
assert.match(html, />7\.2<\/text>/);
assert.match(html, />3\.6<\/text>/);
assert.match(html, />45<\/text>/);
assert.match(html, />650<\/text>/);
assert.match(html, />1100<\/text>/);
const { chartModels } = createTelemetryCharts(node, { nowMs });
const powerChart = chartModels.find(model => model.id === 'power');
const environmentChart = chartModels.find(model => model.id === 'environment');
const airChart = chartModels.find(model => model.id === 'airQuality');
const powerConfig = buildUPlotChartConfig(powerChart);
const envConfig = buildUPlotChartConfig(environmentChart);
const airConfig = buildUPlotChartConfig(airChart);
assert.equal(powerConfig.options.scales.voltage.range()[1], 7.2);
assert.equal(powerConfig.options.scales.current.range()[1], 3.6);
assert.equal(envConfig.options.scales.temperature.range()[1], 45);
assert.equal(airConfig.options.scales.iaq.range()[1], 650);
assert.equal(airConfig.options.scales.pressure.range()[1], 1100);
});
test('renderTelemetryCharts keeps default bounds when metrics stay within limits', () => {
@@ -469,11 +464,17 @@ test('renderTelemetryCharts keeps default bounds when metrics stay within limits
},
},
};
const html = renderTelemetryCharts(node, { nowMs });
assert.match(html, />6\.0<\/text>/);
assert.match(html, />3\.0<\/text>/);
assert.match(html, />40<\/text>/);
assert.match(html, />500<\/text>/);
const { chartModels } = createTelemetryCharts(node, { nowMs });
const powerChart = chartModels.find(model => model.id === 'power');
const environmentChart = chartModels.find(model => model.id === 'environment');
const airChart = chartModels.find(model => model.id === 'airQuality');
const powerConfig = buildUPlotChartConfig(powerChart);
const envConfig = buildUPlotChartConfig(environmentChart);
const airConfig = buildUPlotChartConfig(airChart);
assert.equal(powerConfig.options.scales.voltage.range()[1], 6);
assert.equal(powerConfig.options.scales.current.range()[1], 3);
assert.equal(envConfig.options.scales.temperature.range()[1], 40);
assert.equal(airConfig.options.scales.iaq.range()[1], 500);
});
test('renderNodeDetailHtml composes the table, neighbors, and messages', () => {
@@ -551,23 +552,6 @@ test('renderNodeDetailHtml embeds telemetry charts when snapshots are present',
assert.equal(html.includes('Air quality'), true);
});
test('renderNodeDetailHtml includes a map panel when requested', () => {
const node = {
shortName: 'NODE',
nodeId: '!map',
role: 'CLIENT',
rawSources: {
node: { node_id: '!map', role: 'CLIENT', short_name: 'NODE' },
},
};
const html = renderNodeDetailHtml(node, {
renderShortHtml: short => `<span class="short-name">${short}</span>`,
includeMapPanel: true,
});
assert.equal(html.includes('node-detail__map-panel'), true);
assert.equal(html.includes('data-node-map-slot'), true);
});
test('fetchNodeDetailHtml renders the node layout for overlays', async () => {
const reference = { nodeId: '!alpha' };
const calledUrls = [];
@@ -606,17 +590,18 @@ test('fetchNodeDetailHtml renders the node layout for overlays', async () => {
neighbors: [],
rawSources: { node: { node_id: '!alpha', role: 'CLIENT', short_name: 'ALPH' } },
});
const html = await fetchNodeDetailHtml(reference, {
const result = await fetchNodeDetailHtml(reference, {
refreshImpl,
fetchImpl,
renderShortHtml: short => `<span class="short-name">${short}</span>`,
returnState: true,
});
assert.equal(calledUrls.some(url => url.includes('/api/messages/!alpha')), true);
assert.equal(calledUrls.some(url => url.includes('/api/traces/!alpha')), true);
assert.equal(html.includes('Example Alpha'), true);
assert.equal(html.includes('Overlay hello'), true);
assert.equal(html.includes('Traceroutes'), true);
assert.equal(html.includes('node-detail__table'), true);
assert.equal(result.html.includes('Example Alpha'), true);
assert.equal(result.html.includes('Overlay hello'), true);
assert.equal(result.html.includes('Traceroutes'), true);
assert.equal(result.html.includes('node-detail__table'), true);
});
test('fetchNodeDetailHtml hydrates traceroute nodes with API metadata', async () => {
@@ -654,16 +639,17 @@ test('fetchNodeDetailHtml hydrates traceroute nodes with API metadata', async ()
rawSources: { node: { node_id: '!origin', role: 'CLIENT', short_name: 'ORIG' } },
});
const html = await fetchNodeDetailHtml(reference, {
const result = await fetchNodeDetailHtml(reference, {
refreshImpl,
fetchImpl,
renderShortHtml: short => `<span class="short-name">${short}</span>`,
returnState: true,
});
assert.equal(calledUrls.some(url => url.includes('/api/nodes/!relay')), true);
assert.equal(calledUrls.some(url => url.includes('/api/nodes/!target')), true);
assert.equal(html.includes('RLY1'), true);
assert.equal(html.includes('TGT1'), true);
assert.equal(result.html.includes('RLY1'), true);
assert.equal(result.html.includes('TGT1'), true);
});
test('fetchNodeDetailHtml requires a node identifier reference', async () => {
@@ -963,19 +949,13 @@ test('initializeNodeDetailPage reports an error when refresh fails', async () =>
throw new Error('boom');
};
const renderShortHtml = short => `<span>${short}</span>`;
const originalError = console.error;
console.error = () => {};
try {
const result = await initializeNodeDetailPage({
document: documentStub,
refreshImpl,
renderShortHtml,
});
assert.equal(result, false);
assert.equal(element.innerHTML.includes('Failed to load'), true);
} finally {
console.error = originalError;
}
const result = await initializeNodeDetailPage({
document: documentStub,
refreshImpl,
renderShortHtml,
});
assert.equal(result, false);
assert.equal(element.innerHTML.includes('Failed to load'), true);
});
test('initializeNodeDetailPage handles missing reference payloads', async () => {
@@ -0,0 +1,360 @@
/*
* Copyright © 2025-26 l5yth & contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import test from 'node:test';
import assert from 'node:assert/strict';
import { __testUtils } from '../node-page.js';
import { buildMovingAverageSeries } from '../charts-page.js';
const {
createTelemetryCharts,
buildUPlotChartConfig,
mountTelemetryCharts,
mountTelemetryChartsWithRetry,
} = __testUtils;
test('uPlot chart config preserves axes, colors, and tick labels for node telemetry', () => {
const nowMs = Date.UTC(2025, 0, 8, 12, 0, 0);
const nowSeconds = Math.floor(nowMs / 1000);
const node = {
rawSources: {
telemetry: {
snapshots: [
{
rx_time: nowSeconds - 60,
device_metrics: {
battery_level: 80,
voltage: 4.1,
current: 0.75,
},
},
{
rx_time: nowSeconds - 3_600,
device_metrics: {
battery_level: 78,
voltage: 4.05,
current: 0.65,
},
},
],
},
},
};
const { chartModels } = createTelemetryCharts(node, {
nowMs,
chartOptions: {
xAxisTickBuilder: () => [nowMs],
xAxisTickFormatter: () => '08',
},
});
const powerChart = chartModels.find(model => model.id === 'power');
const { options, data } = buildUPlotChartConfig(powerChart);
assert.deepEqual(options.scales.battery.range(), [0, 100]);
assert.deepEqual(options.scales.voltage.range(), [0, 6]);
assert.deepEqual(options.scales.current.range(), [0, 3]);
assert.equal(options.series[1].stroke, '#8856a7');
assert.equal(options.series[2].stroke, '#9ebcda');
assert.equal(options.series[3].stroke, '#3182bd');
assert.deepEqual(options.axes[0].values(null, [nowMs]), ['08']);
assert.equal(options.axes[0].stroke, '#5c6773');
assert.deepEqual(data[0].slice(0, 2), [nowMs - 3_600_000, nowMs - 60_000]);
assert.deepEqual(data[1].slice(0, 2), [78, 80]);
});
test('uPlot chart config maps moving averages and raw points for aggregated telemetry', () => {
const nowMs = Date.UTC(2025, 0, 8, 12, 0, 0);
const nowSeconds = Math.floor(nowMs / 1000);
const snapshots = [
{
rx_time: nowSeconds - 3_600,
device_metrics: { battery_level: 10 },
},
{
rx_time: nowSeconds - 1_800,
device_metrics: { battery_level: 20 },
},
];
const node = { rawSources: { telemetry: { snapshots } } };
const { chartModels } = createTelemetryCharts(node, {
nowMs,
chartOptions: {
lineReducer: points => buildMovingAverageSeries(points, 3_600_000),
},
});
const powerChart = chartModels.find(model => model.id === 'power');
const { options, data } = buildUPlotChartConfig(powerChart);
assert.equal(options.series.length, 3);
assert.equal(options.series[1].stroke.startsWith('rgba('), true);
assert.equal(options.series[2].stroke, '#8856a7');
assert.deepEqual(data[1].slice(0, 2), [10, 15]);
assert.deepEqual(data[2].slice(0, 2), [10, 20]);
});
test('buildUPlotChartConfig applies axis color overrides', () => {
const nowMs = Date.UTC(2025, 0, 8, 12, 0, 0);
const nowSeconds = Math.floor(nowMs / 1000);
const node = {
rawSources: {
telemetry: {
snapshots: [
{
rx_time: nowSeconds - 60,
device_metrics: { battery_level: 80 },
},
],
},
},
};
const { chartModels } = createTelemetryCharts(node, { nowMs });
const powerChart = chartModels.find(model => model.id === 'power');
const { options } = buildUPlotChartConfig(powerChart, {
axisColor: '#ffffff',
gridColor: '#222222',
});
assert.equal(options.axes[0].stroke, '#ffffff');
assert.equal(options.axes[0].grid.stroke, '#222222');
});
test('environment chart renders humidity axis on the right side', () => {
const nowMs = Date.UTC(2025, 0, 8, 12, 0, 0);
const nowSeconds = Math.floor(nowMs / 1000);
const node = {
rawSources: {
telemetry: {
snapshots: [
{
rx_time: nowSeconds - 60,
environment_metrics: {
temperature: 19.5,
relative_humidity: 55,
},
},
],
},
},
};
const { chartModels } = createTelemetryCharts(node, { nowMs });
const envChart = chartModels.find(model => model.id === 'environment');
const { options } = buildUPlotChartConfig(envChart);
const humidityAxis = options.axes.find(axis => axis.scale === 'humidity');
assert.ok(humidityAxis);
assert.equal(humidityAxis.side, 1);
assert.equal(humidityAxis.show, true);
});
test('channel utilization chart includes a right-side utilization axis', () => {
const nowMs = Date.UTC(2025, 0, 8, 12, 0, 0);
const nowSeconds = Math.floor(nowMs / 1000);
const node = {
rawSources: {
telemetry: {
snapshots: [
{
rx_time: nowSeconds - 60,
device_metrics: {
channel_utilization: 40,
air_util_tx: 22,
},
},
],
},
},
};
const { chartModels } = createTelemetryCharts(node, { nowMs });
const channelChart = chartModels.find(model => model.id === 'channel');
const { options } = buildUPlotChartConfig(channelChart);
const rightAxis = options.axes.find(axis => axis.scale === 'channelSecondary');
assert.ok(rightAxis);
assert.equal(rightAxis.side, 1);
assert.equal(rightAxis.show, true);
});
test('createTelemetryCharts returns empty markup when snapshots are missing', () => {
const { chartsHtml, chartModels } = createTelemetryCharts({ rawSources: { telemetry: { snapshots: [] } } });
assert.equal(chartsHtml, '');
assert.equal(chartModels.length, 0);
});
test('mountTelemetryCharts instantiates uPlot for chart containers', () => {
const nowMs = Date.UTC(2025, 0, 8, 12, 0, 0);
const nowSeconds = Math.floor(nowMs / 1000);
const node = {
rawSources: {
telemetry: {
snapshots: [
{
rx_time: nowSeconds - 60,
device_metrics: { battery_level: 80 },
},
],
},
},
};
const { chartModels } = createTelemetryCharts(node, { nowMs });
const [model] = chartModels;
const plotRoot = { innerHTML: 'placeholder' };
const chartContainer = {
querySelector(selector) {
return selector === '[data-telemetry-plot]' ? plotRoot : null;
},
};
const root = {
querySelector(selector) {
return selector === `[data-telemetry-chart-id="${model.id}"]` ? chartContainer : null;
},
};
class UPlotStub {
constructor(options, data, container) {
this.options = options;
this.data = data;
this.container = container;
}
}
const instances = mountTelemetryCharts(chartModels, { root, uPlotImpl: UPlotStub });
assert.equal(plotRoot.innerHTML, '');
assert.equal(instances.length, 1);
assert.equal(instances[0].container, plotRoot);
});
test('mountTelemetryCharts responds to window resize events', async () => {
const nowMs = Date.UTC(2025, 0, 8, 12, 0, 0);
const nowSeconds = Math.floor(nowMs / 1000);
const node = {
rawSources: {
telemetry: {
snapshots: [
{
rx_time: nowSeconds - 60,
device_metrics: { battery_level: 80 },
},
],
},
},
};
const { chartModels } = createTelemetryCharts(node, { nowMs });
const [model] = chartModels;
const plotRoot = {
innerHTML: '',
clientWidth: 320,
clientHeight: 180,
getBoundingClientRect() {
return { width: this.clientWidth, height: this.clientHeight };
},
};
const chartContainer = {
querySelector(selector) {
return selector === '[data-telemetry-plot]' ? plotRoot : null;
},
};
const root = {
querySelector(selector) {
return selector === `[data-telemetry-chart-id="${model.id}"]` ? chartContainer : null;
},
};
const previousResizeObserver = globalThis.ResizeObserver;
const previousAddEventListener = globalThis.addEventListener;
let resizeHandler = null;
globalThis.ResizeObserver = undefined;
globalThis.addEventListener = (event, handler) => {
if (event === 'resize') {
resizeHandler = handler;
}
};
const sizeCalls = [];
class UPlotStub {
constructor(options, data, container) {
this.options = options;
this.data = data;
this.container = container;
this.root = container;
}
setSize(size) {
sizeCalls.push(size);
}
}
mountTelemetryCharts(chartModels, { root, uPlotImpl: UPlotStub });
assert.ok(resizeHandler);
plotRoot.clientWidth = 480;
plotRoot.clientHeight = 240;
resizeHandler();
await new Promise(resolve => setTimeout(resolve, 150));
assert.equal(sizeCalls.length >= 1, true);
assert.deepEqual(sizeCalls[sizeCalls.length - 1], { width: 480, height: 240 });
globalThis.ResizeObserver = previousResizeObserver;
globalThis.addEventListener = previousAddEventListener;
});
test('mountTelemetryChartsWithRetry loads uPlot when missing', async () => {
const nowMs = Date.UTC(2025, 0, 8, 12, 0, 0);
const nowSeconds = Math.floor(nowMs / 1000);
const node = {
rawSources: {
telemetry: {
snapshots: [
{
rx_time: nowSeconds - 60,
device_metrics: { battery_level: 80 },
},
],
},
},
};
const { chartModels } = createTelemetryCharts(node, { nowMs });
const [model] = chartModels;
const plotRoot = { innerHTML: '', clientWidth: 400, clientHeight: 200 };
const chartContainer = {
querySelector(selector) {
return selector === '[data-telemetry-plot]' ? plotRoot : null;
},
};
const root = {
ownerDocument: {
body: {},
querySelector: () => null,
},
querySelector(selector) {
return selector === `[data-telemetry-chart-id="${model.id}"]` ? chartContainer : null;
},
};
const previousUPlot = globalThis.uPlot;
const instances = [];
class UPlotStub {
constructor(options, data, container) {
this.options = options;
this.data = data;
this.container = container;
instances.push(this);
}
}
let loadCalled = false;
const loadUPlot = ({ onLoad }) => {
loadCalled = true;
globalThis.uPlot = UPlotStub;
if (typeof onLoad === 'function') {
onLoad();
}
return true;
};
mountTelemetryChartsWithRetry(chartModels, { root, loadUPlot });
await new Promise(resolve => setTimeout(resolve, 0));
assert.equal(loadCalled, true);
assert.equal(instances.length, 1);
globalThis.uPlot = previousUPlot;
});
+22 -5
View File
@@ -14,7 +14,7 @@
* limitations under the License.
*/
import { renderTelemetryCharts } from './node-page.js';
import { createTelemetryCharts, mountTelemetryChartsWithRetry } from './node-page.js';
const TELEMETRY_BUCKET_SECONDS = 60 * 60;
const HOUR_MS = 60 * 60 * 1000;
@@ -193,6 +193,21 @@ export async function fetchAggregatedTelemetry({
.filter(snapshot => snapshot != null);
}
/**
* Fetch and render aggregated telemetry charts.
*
* @param {{
* document?: Document,
* rootId?: string,
* fetchImpl?: Function,
* bucketSeconds?: number,
* windowMs?: number,
* createCharts?: Function,
* mountCharts?: Function,
* uPlotImpl?: Function,
* }} options Optional overrides for testing.
* @returns {Promise<boolean>} ``true`` when charts were rendered successfully.
*/
export async function initializeChartsPage(options = {}) {
const documentRef = options.document ?? globalThis.document;
if (!documentRef || typeof documentRef.getElementById !== 'function') {
@@ -204,7 +219,8 @@ export async function initializeChartsPage(options = {}) {
return false;
}
const renderCharts = typeof options.renderCharts === 'function' ? options.renderCharts : renderTelemetryCharts;
const createCharts = typeof options.createCharts === 'function' ? options.createCharts : createTelemetryCharts;
const mountCharts = typeof options.mountCharts === 'function' ? options.mountCharts : mountTelemetryChartsWithRetry;
const fetchImpl = options.fetchImpl ?? globalThis.fetch;
const bucketSeconds = options.bucketSeconds ?? TELEMETRY_BUCKET_SECONDS;
const windowMs = options.windowMs ?? CHART_WINDOW_MS;
@@ -218,7 +234,7 @@ export async function initializeChartsPage(options = {}) {
return true;
}
const node = { rawSources: { telemetry: { snapshots } } };
const chartsHtml = renderCharts(node, {
const chartState = createCharts(node, {
nowMs: Date.now(),
chartOptions: {
windowMs,
@@ -228,11 +244,12 @@ export async function initializeChartsPage(options = {}) {
lineReducer: points => buildMovingAverageSeries(points, HOUR_MS),
},
});
if (!chartsHtml) {
if (!chartState.chartsHtml) {
container.innerHTML = renderStatus('Telemetry snapshots are unavailable.');
return true;
}
container.innerHTML = chartsHtml;
container.innerHTML = chartState.chartsHtml;
mountCharts(chartState.chartModels, { root: container, uPlotImpl: options.uPlotImpl });
return true;
} catch (error) {
console.error('Failed to render aggregated telemetry charts', error);
+21 -2
View File
@@ -65,8 +65,7 @@ function resolveSnapshotList(entry) {
* Build a data model describing the content for chat tabs.
*
* Entries outside the recent activity window, encrypted messages, and
* channels above {@link MAX_CHANNEL_INDEX} are filtered out. Channel
* buckets are only created when messages are present for that channel.
* channels above {@link MAX_CHANNEL_INDEX} are filtered out.
*
* @param {{
* nodes?: Array<Object>,
@@ -288,6 +287,26 @@ export function buildChatTabModel({
logEntries.sort((a, b) => a.ts - b.ts);
let hasPrimaryBucket = false;
for (const bucket of channelBuckets.values()) {
if (bucket.index === 0) {
hasPrimaryBucket = true;
break;
}
}
if (!hasPrimaryBucket) {
const bucketKey = '0';
channelBuckets.set(bucketKey, {
key: bucketKey,
id: buildChannelTabId(bucketKey),
index: 0,
label: '0',
entries: [],
labelPriority: CHANNEL_LABEL_PRIORITY.INDEX,
isPrimaryFallback: true
});
}
const channels = Array.from(channelBuckets.values()).sort((a, b) => {
if (a.index !== b.index) {
return a.index - b.index;
-115
View File
@@ -15,7 +15,6 @@
*/
import { readAppConfig } from './config.js';
import { resolveLegendVisibility } from './map-legend-visibility.js';
import { mergeConfig } from './settings.js';
import { roleColors } from './role-helpers.js';
@@ -205,31 +204,6 @@ function hasNumberValue(value) {
return toFiniteNumber(value) != null;
}
/**
* Toggle the legend hidden class on a container element.
*
* @param {HTMLElement|{ classList?: { toggle?: Function }, className?: string }} container Legend container.
* @param {boolean} hidden Whether the legend should be hidden.
* @returns {void}
*/
function toggleLegendHiddenClass(container, hidden) {
if (!container) return;
if (container.classList && typeof container.classList.toggle === 'function') {
container.classList.toggle('legend-hidden', hidden);
return;
}
if (typeof container.className === 'string') {
const classes = container.className.split(/\s+/).filter(Boolean);
const hasHidden = classes.includes('legend-hidden');
if (hidden && !hasHidden) {
classes.push('legend-hidden');
} else if (!hidden && hasHidden) {
classes.splice(classes.indexOf('legend-hidden'), 1);
}
container.className = classes.join(' ');
}
}
const TILE_LAYER_URL = 'https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png';
/**
@@ -249,7 +223,6 @@ export async function initializeFederationPage(options = {}) {
const fetchImpl = options.fetchImpl || fetch;
const leaflet = options.leaflet || (typeof window !== 'undefined' ? window.L : null);
const mapContainer = document.getElementById('map');
const mapPanel = document.getElementById('mapPanel');
const tableEl = document.getElementById('instances');
const tableBody = document.querySelector('#instances tbody');
const statusEl = document.getElementById('status');
@@ -266,13 +239,6 @@ export async function initializeFederationPage(options = {}) {
let map = null;
let markersLayer = null;
let tileLayer = null;
let legendContainer = null;
let legendToggleButton = null;
let legendVisible = true;
const legendCollapsedValue = mapPanel ? mapPanel.getAttribute('data-legend-collapsed') : null;
const legendDefaultCollapsed = legendCollapsedValue == null
? true
: legendCollapsedValue.trim() !== 'false';
const tableSorters = {
name: { getValue: inst => inst.name ?? '', compare: compareString, hasValue: hasStringValue, defaultDirection: 'asc' },
domain: { getValue: inst => inst.domain ?? '', compare: compareString, hasValue: hasStringValue, defaultDirection: 'asc' },
@@ -391,37 +357,6 @@ export async function initializeFederationPage(options = {}) {
syncSortIndicators();
};
/**
* Update the pressed state of the legend visibility toggle button.
*
* @returns {void}
*/
const updateLegendToggleState = () => {
if (!legendToggleButton) return;
const baseLabel = legendVisible ? 'Hide map legend' : 'Show map legend';
const baseText = legendVisible ? 'Hide legend' : 'Show legend';
legendToggleButton.setAttribute('aria-pressed', legendVisible ? 'true' : 'false');
legendToggleButton.setAttribute('aria-label', baseLabel);
legendToggleButton.textContent = baseText;
};
/**
* Show or hide the map legend component.
*
* @param {boolean} visible Whether the legend should be displayed.
* @returns {void}
*/
const setLegendVisibility = visible => {
legendVisible = Boolean(visible);
if (legendContainer) {
toggleLegendHiddenClass(legendContainer, !legendVisible);
if (typeof legendContainer.setAttribute === 'function') {
legendContainer.setAttribute('aria-hidden', legendVisible ? 'false' : 'true');
}
}
updateLegendToggleState();
};
/**
* Wire up click and keyboard handlers for sortable headers.
*
@@ -548,15 +483,6 @@ export async function initializeFederationPage(options = {}) {
const canRenderLegend =
typeof leaflet.control === 'function' && leaflet.DomUtil && typeof leaflet.DomUtil.create === 'function';
if (canRenderLegend) {
const legendMediaQuery = typeof window !== 'undefined' && window.matchMedia
? window.matchMedia('(max-width: 1024px)')
: null;
const initialLegendVisible = resolveLegendVisibility({
defaultCollapsed: legendDefaultCollapsed,
mediaQueryMatches: legendMediaQuery ? legendMediaQuery.matches : false
});
legendVisible = initialLegendVisible;
const legendStops = NODE_COUNT_COLOR_STOPS.map((stop, index) => {
const lower = index === 0 ? 0 : NODE_COUNT_COLOR_STOPS[index - 1].limit;
const upper = stop.limit - 1;
@@ -569,11 +495,7 @@ export async function initializeFederationPage(options = {}) {
const legend = leaflet.control({ position: 'bottomright' });
legend.onAdd = function onAdd() {
const container = leaflet.DomUtil.create('div', 'legend legend--instances');
container.id = 'federationLegend';
container.setAttribute('aria-label', 'Active nodes legend');
container.setAttribute('role', 'region');
container.setAttribute('aria-hidden', initialLegendVisible ? 'false' : 'true');
toggleLegendHiddenClass(container, !initialLegendVisible);
const header = leaflet.DomUtil.create('div', 'legend-header', container);
const title = leaflet.DomUtil.create('span', 'legend-title', header);
title.textContent = 'Active nodes';
@@ -586,46 +508,9 @@ export async function initializeFederationPage(options = {}) {
const label = leaflet.DomUtil.create('span', 'legend-label', item);
label.textContent = stop.label;
});
legendContainer = container;
return container;
};
legend.addTo(map);
const legendToggleControl = leaflet.control({ position: 'bottomright' });
legendToggleControl.onAdd = function onAdd() {
const container = leaflet.DomUtil.create('div', 'leaflet-control legend-toggle');
const button = leaflet.DomUtil.create('button', 'legend-toggle-button', container);
button.type = 'button';
button.setAttribute('aria-controls', 'federationLegend');
button.addEventListener?.('click', event => {
event.preventDefault();
event.stopPropagation();
setLegendVisibility(!legendVisible);
});
legendToggleButton = button;
updateLegendToggleState();
if (leaflet.DomEvent && typeof leaflet.DomEvent.disableClickPropagation === 'function') {
leaflet.DomEvent.disableClickPropagation(container);
}
if (leaflet.DomEvent && typeof leaflet.DomEvent.disableScrollPropagation === 'function') {
leaflet.DomEvent.disableScrollPropagation(container);
}
return container;
};
legendToggleControl.addTo(map);
setLegendVisibility(initialLegendVisible);
if (legendMediaQuery) {
const changeHandler = event => {
if (legendDefaultCollapsed) return;
setLegendVisibility(!event.matches);
};
if (typeof legendMediaQuery.addEventListener === 'function') {
legendMediaQuery.addEventListener('change', changeHandler);
} else if (typeof legendMediaQuery.addListener === 'function') {
legendMediaQuery.addListener(changeHandler);
}
}
}
for (const instance of instances) {
+1 -28
View File
@@ -44,7 +44,6 @@ import {
formatChatPresetTag
} from './chat-format.js';
import { initializeInstanceSelector } from './instance-selector.js';
import { initializeMobileMenu } from './mobile-menu.js';
import { MESSAGE_LIMIT, normaliseMessageLimit } from './message-limit.js';
import { CHAT_LOG_ENTRY_TYPES, buildChatTabModel, MAX_CHANNEL_INDEX } from './chat-log-tabs.js';
import { renderChatTabs } from './chat-tabs.js';
@@ -120,8 +119,6 @@ export function initializeApp(config) {
const isChatView = bodyClassList ? bodyClassList.contains('view-chat') : false;
const isMapView = bodyClassList ? bodyClassList.contains('view-map') : false;
const mapZoomOverride = Number.isFinite(config.mapZoom) ? Number(config.mapZoom) : null;
initializeMobileMenu({ documentObject: document, windowObject: window });
/**
* Column sorter configuration for the node table.
*
@@ -195,7 +192,7 @@ export function initializeApp(config) {
});
const NODE_LIMIT = 1000;
const TRACE_LIMIT = 200;
const TRACE_MAX_AGE_SECONDS = 28 * 24 * 60 * 60;
const TRACE_MAX_AGE_SECONDS = 7 * 24 * 60 * 60;
const SNAPSHOT_LIMIT = SNAPSHOT_WINDOW;
const CHAT_LIMIT = MESSAGE_LIMIT;
const CHAT_RECENT_WINDOW_SECONDS = 7 * 24 * 60 * 60;
@@ -1804,27 +1801,6 @@ export function initializeApp(config) {
potatoMeshNamespace.getRoleColor = getRoleColor;
potatoMeshNamespace.getRoleKey = getRoleKey;
potatoMeshNamespace.normalizeRole = normalizeRole;
potatoMeshNamespace.map = map || null;
potatoMeshNamespace.leaflet = typeof L === 'undefined' ? null : L;
potatoMeshNamespace.mapLayers = {
markersLayer: markersLayer || null,
neighborLinesLayer: neighborLinesLayer || null,
traceLinesLayer: traceLinesLayer || null,
};
/**
* Expose the active map instance and Leaflet context for shared overlays.
*
* @returns {{ map: ?Object, leaflet: ?Object, layers: Object }} Map context.
*/
potatoMeshNamespace.getMapContext = () => ({
map: map || null,
leaflet: typeof L === 'undefined' ? null : L,
layers: {
markersLayer: markersLayer || null,
neighborLinesLayer: neighborLinesLayer || null,
traceLinesLayer: traceLinesLayer || null,
},
});
/**
* Escape a CSS selector fragment with a defensive fallback for
@@ -3894,9 +3870,6 @@ export function initializeApp(config) {
if (!map || !markersLayer || !hasLeaflet) {
return;
}
if (mapPanel && mapPanel.classList && mapPanel.classList.contains('map-panel--embedded')) {
return;
}
if (neighborLinesLayer) {
neighborLinesLayer.clearLayers();
}
-271
View File
@@ -1,271 +0,0 @@
/*
* Copyright © 2025-26 l5yth & contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const MOBILE_MENU_MEDIA_QUERY = '(max-width: 900px)';
const FOCUSABLE_SELECTOR = [
'a[href]',
'button:not([disabled])',
'input:not([disabled])',
'select:not([disabled])',
'textarea:not([disabled])',
'[tabindex]:not([tabindex="-1"])'
].join(', ');
/**
* Collect the elements that can receive focus within a container.
*
* @param {?Element} container DOM node hosting focusable descendants.
* @returns {Array<Element>} Ordered list of focusable elements.
*/
function resolveFocusableElements(container) {
if (!container || typeof container.querySelectorAll !== 'function') {
return [];
}
const candidates = Array.from(container.querySelectorAll(FOCUSABLE_SELECTOR));
return candidates.filter(candidate => {
if (!candidate || typeof candidate.getAttribute !== 'function') {
return false;
}
return candidate.getAttribute('aria-hidden') !== 'true';
});
}
/**
* Build a menu controller for handling toggle state, focus trapping, and
* responsive layout swapping.
*
* @param {{
* documentObject?: Document,
* windowObject?: Window
* }} [options]
* @returns {{
* initialize: () => void,
* openMenu: () => void,
* closeMenu: () => void,
* syncLayout: () => void
* }}
*/
function createMobileMenuController(options = {}) {
const documentObject = options.documentObject || document;
const windowObject = options.windowObject || window;
const menuToggle = documentObject.getElementById('mobileMenuToggle');
const menu = documentObject.getElementById('mobileMenu');
const menuPanel = menu ? menu.querySelector('.mobile-menu__panel') : null;
const closeTriggers = menu ? Array.from(menu.querySelectorAll('[data-mobile-menu-close]')) : [];
const menuLinks = menu ? Array.from(menu.querySelectorAll('a')) : [];
const body = documentObject.body;
const mediaQuery = windowObject.matchMedia
? windowObject.matchMedia(MOBILE_MENU_MEDIA_QUERY)
: null;
let isOpen = false;
let lastActive = null;
/**
* Toggle the ``aria-expanded`` state on the menu trigger.
*
* @param {boolean} expanded Whether the menu is open.
* @returns {void}
*/
function setExpandedState(expanded) {
if (!menuToggle || typeof menuToggle.setAttribute !== 'function') {
return;
}
menuToggle.setAttribute('aria-expanded', expanded ? 'true' : 'false');
}
/**
* Synchronize the meta row placement based on the active media query.
*
* @returns {void}
*/
function syncLayout() {
return;
}
/**
* Open the slide-in menu and trap focus within the panel.
*
* @returns {void}
*/
function openMenu() {
if (!menu || !menuToggle || !menuPanel) {
return;
}
syncLayout();
menu.hidden = false;
menu.classList.add('is-open');
if (body && body.classList) {
body.classList.add('menu-open');
}
setExpandedState(true);
isOpen = true;
lastActive = documentObject.activeElement || null;
const focusables = resolveFocusableElements(menuPanel);
const focusTarget = focusables[0] || menuPanel;
if (focusTarget && typeof focusTarget.focus === 'function') {
focusTarget.focus();
}
}
/**
* Close the menu and restore focus to the trigger.
*
* @returns {void}
*/
function closeMenu() {
if (!menu || !menuToggle) {
return;
}
menu.classList.remove('is-open');
menu.hidden = true;
if (body && body.classList) {
body.classList.remove('menu-open');
}
setExpandedState(false);
isOpen = false;
if (lastActive && typeof lastActive.focus === 'function') {
lastActive.focus();
}
}
/**
* Toggle open or closed based on the trigger interaction.
*
* @param {Event} event Click event originating from the trigger.
* @returns {void}
*/
function handleToggleClick(event) {
if (event && typeof event.preventDefault === 'function') {
event.preventDefault();
}
if (isOpen) {
closeMenu();
} else {
openMenu();
}
}
/**
* Trap tab focus within the menu panel while open.
*
* @param {KeyboardEvent} event Keydown event from the panel.
* @returns {void}
*/
function handleKeydown(event) {
if (!isOpen || !event) {
return;
}
if (event.key === 'Escape') {
event.preventDefault();
closeMenu();
return;
}
if (event.key !== 'Tab') {
return;
}
const focusables = resolveFocusableElements(menuPanel);
if (!focusables.length) {
return;
}
const first = focusables[0];
const last = focusables[focusables.length - 1];
const active = documentObject.activeElement;
if (event.shiftKey && active === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && active === last) {
event.preventDefault();
first.focus();
}
}
/**
* Close the menu when navigation state changes.
*
* @returns {void}
*/
function handleRouteChange() {
if (isOpen) {
closeMenu();
}
}
/**
* Attach event listeners and sync initial layout.
*
* @returns {void}
*/
function initialize() {
if (!menuToggle || !menu) {
return;
}
menuToggle.addEventListener('click', handleToggleClick);
closeTriggers.forEach(trigger => {
trigger.addEventListener('click', closeMenu);
});
menuLinks.forEach(link => {
link.addEventListener('click', closeMenu);
});
if (menuPanel && typeof menuPanel.addEventListener === 'function') {
menuPanel.addEventListener('keydown', handleKeydown);
}
if (mediaQuery) {
if (typeof mediaQuery.addEventListener === 'function') {
mediaQuery.addEventListener('change', syncLayout);
} else if (typeof mediaQuery.addListener === 'function') {
mediaQuery.addListener(syncLayout);
}
}
if (windowObject && typeof windowObject.addEventListener === 'function') {
windowObject.addEventListener('hashchange', handleRouteChange);
windowObject.addEventListener('popstate', handleRouteChange);
}
syncLayout();
setExpandedState(false);
}
return {
initialize,
openMenu,
closeMenu,
syncLayout,
};
}
/**
* Initialize the mobile menu using the live DOM environment.
*
* @param {{
* documentObject?: Document,
* windowObject?: Window
* }} [options]
* @returns {{
* initialize: () => void,
* openMenu: () => void,
* closeMenu: () => void,
* syncLayout: () => void
* }}
*/
export function initializeMobileMenu(options = {}) {
const controller = createMobileMenuController(options);
controller.initialize();
return controller;
}
export const __test__ = {
createMobileMenuController,
resolveFocusableElements,
};
-387
View File
@@ -1,387 +0,0 @@
/*
* Copyright © 2025-26 l5yth & contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const DEFAULT_FETCH_OPTIONS = Object.freeze({ cache: 'no-store' });
const DAY_SECONDS = 86_400;
const MAP_PADDING = [18, 18];
const MAX_FIT_ZOOM = 14;
const DEFAULT_ZOOM = 12;
const MAP_CONTEXT_WAIT_INTERVAL_MS = 50;
const MAP_CONTEXT_WAIT_TIMEOUT_MS = 1500;
const ROLE_BY_DAY = Object.freeze([
'LOST_AND_FOUND',
'ROUTER',
'ROUTER_LATE',
'REPEATER',
'CLIENT_BASE',
'CLIENT',
'CLIENT_MUTE',
'TRACKER',
'SENSOR',
'CLIENT_HIDDEN',
]);
const MAX_DAYS = ROLE_BY_DAY.length;
/**
* Coerce a candidate coordinate into a finite number.
*
* @param {*} value Raw coordinate candidate.
* @returns {?number} Finite number or ``null`` when invalid.
*/
function toFiniteNumber(value) {
if (value == null || value === '') return null;
const numeric = typeof value === 'number' ? value : Number(value);
return Number.isFinite(numeric) ? numeric : null;
}
/**
* Resolve the node identifier from a reference payload.
*
* @param {*} reference Node reference payload.
* @returns {?string} Canonical identifier or ``null`` when unavailable.
*/
function resolveReferenceId(reference) {
if (!reference || typeof reference !== 'object') return null;
const nodeId = reference.nodeId ?? reference.node_id;
const nodeNum = reference.nodeNum ?? reference.node_num ?? reference.num;
const candidate = nodeId ?? nodeNum;
if (candidate == null) return null;
const text = String(candidate).trim();
return text.length ? text : null;
}
/**
* Locate the shared map instance exposed by the dashboard.
*
* @param {Object} options Optional configuration.
* @returns {{ map: ?Object, leaflet: ?Object }} Map context.
*/
function resolveMapContext(options) {
if (typeof options.getMapContext === 'function') {
return options.getMapContext() || { map: null, leaflet: null };
}
const namespace = options.namespace ?? globalThis.PotatoMesh ?? null;
if (namespace && typeof namespace.getMapContext === 'function') {
return namespace.getMapContext() || { map: null, leaflet: null };
}
return {
map: namespace?.map ?? null,
leaflet: namespace?.leaflet ?? globalThis.L ?? null,
layers: namespace?.mapLayers ?? null,
};
}
/**
* Wait briefly for the shared map context to become available.
*
* @param {Object} options Optional configuration.
* @returns {Promise<{ map: ?Object, leaflet: ?Object }>} Map context.
*/
async function waitForMapContext(options) {
const deadline = Date.now() + MAP_CONTEXT_WAIT_TIMEOUT_MS;
while (Date.now() < deadline) {
const context = resolveMapContext(options);
if (context.map && context.leaflet) {
return context;
}
await new Promise(resolve => setTimeout(resolve, MAP_CONTEXT_WAIT_INTERVAL_MS));
}
return resolveMapContext(options);
}
/**
* Resolve the map panel element for reuse.
*
* @param {?Document} doc Host document reference.
* @param {Object} options Optional overrides.
* @returns {?HTMLElement} Map panel element.
*/
function resolveMapPanel(doc, options) {
if (options.mapPanel) return options.mapPanel;
if (!doc || typeof doc.getElementById !== 'function') return null;
return doc.getElementById('mapPanel');
}
/**
* Hide the map section when no map data is available.
*
* @param {?HTMLElement} section Map panel section.
* @param {?HTMLElement} statusEl Status element.
* @returns {void}
*/
function hidePanel(section, statusEl) {
if (statusEl) {
statusEl.textContent = '';
statusEl.hidden = true;
}
if (section) {
section.hidden = true;
}
}
/**
* Interpolate a color channel.
*
* @param {number} start Start value.
* @param {number} end End value.
* @param {number} t Interpolation factor.
* @returns {number} Interpolated channel value.
*/
function colorForDay(dayIndex, getRoleColor) {
if (typeof getRoleColor !== 'function') return null;
const clampedDay = Math.max(0, Math.min(dayIndex, ROLE_BY_DAY.length - 1));
const role = ROLE_BY_DAY[clampedDay];
return getRoleColor(role);
}
/**
* Extract usable position entries from a raw payload.
*
* @param {Array<Object>} positions Position payload entries.
* @param {number} nowSec Reference timestamp in seconds.
* @returns {Array<{ lat: number, lon: number, time: number, day: number }>} Parsed entries.
*/
function extractPositionEntries(positions, nowSec) {
if (!Array.isArray(positions)) return [];
const entries = [];
positions.forEach(entry => {
const lat = toFiniteNumber(entry?.latitude ?? entry?.lat);
const lon = toFiniteNumber(entry?.longitude ?? entry?.lon ?? entry?.lng);
if (lat == null || lon == null) return;
const time = toFiniteNumber(entry?.position_time ?? entry?.positionTime) ??
toFiniteNumber(entry?.rx_time ?? entry?.rxTime);
if (time == null || time <= 0) return;
const ageSec = Math.max(0, nowSec - time);
const dayIndex = Math.floor(ageSec / DAY_SECONDS);
if (dayIndex >= MAX_DAYS) return;
entries.push({ lat, lon, time, day: dayIndex });
});
return entries;
}
/**
* Fetch position history for a node reference.
*
* @param {string} identifier Canonical node identifier.
* @param {Function} fetchFn Fetch implementation.
* @returns {Promise<Array<Object>>} Position payloads.
*/
async function fetchPositions(identifier, fetchFn) {
const url = `/api/positions/${encodeURIComponent(identifier)}`;
const response = await fetchFn(url, DEFAULT_FETCH_OPTIONS);
if (response.status === 404) return [];
if (!response.ok) {
throw new Error(`Failed to load node positions (HTTP ${response.status})`);
}
const payload = await response.json();
return Array.isArray(payload) ? payload : [];
}
/**
* Move the shared map panel into the overlay slot and return a restore handler.
*
* @param {HTMLElement} mapPanel Shared map panel element.
* @param {HTMLElement} slot Target slot element.
* @returns {Function} Cleanup handler restoring the original panel placement.
*/
function moveMapPanel(mapPanel, slot) {
if (!mapPanel || !slot) {
return () => {};
}
if (mapPanel.parentNode === slot) {
return () => {};
}
const parent = mapPanel.parentNode;
const nextSibling = mapPanel.nextSibling;
slot.appendChild(mapPanel);
if (mapPanel.classList) {
mapPanel.classList.add('map-panel--embedded');
}
return () => {
if (mapPanel.classList) {
mapPanel.classList.remove('map-panel--embedded');
}
if (parent && typeof parent.insertBefore === 'function') {
parent.insertBefore(mapPanel, nextSibling);
}
};
}
/**
* Initialize the node detail map panel using the shared map instance.
*
* @param {Element} root Root element containing the map panel.
* @param {Object} reference Node reference payload.
* @param {{
* fetchImpl?: Function,
* leaflet?: Object,
* logger?: Console,
* document?: Document,
* mapPanel?: HTMLElement,
* getMapContext?: Function,
* namespace?: Object,
* }} [options] Optional overrides.
* @returns {Promise<Function|null>} Cleanup handler when the panel is shown.
*/
export async function initializeNodeDetailMapPanel(root, reference, options = {}) {
const section = root?.querySelector?.('[data-node-map-panel]') ?? null;
const slot = root?.querySelector?.('[data-node-map-slot]') ?? null;
if (!section || !slot) return null;
const statusEl = root?.querySelector?.('[data-node-map-status]') ?? null;
const identifier = resolveReferenceId(reference);
if (!identifier) {
hidePanel(section, statusEl);
return null;
}
const fetchFn = typeof options.fetchImpl === 'function' ? options.fetchImpl : globalThis.fetch;
if (typeof fetchFn !== 'function') {
hidePanel(section, statusEl);
return null;
}
const mapPanel = resolveMapPanel(options.document ?? globalThis.document, options);
if (!mapPanel) {
hidePanel(section, statusEl);
return null;
}
const { map, leaflet, layers } = await waitForMapContext(options);
if (!map || !leaflet) {
hidePanel(section, statusEl);
return null;
}
let restorePanel = null;
let restoreFitBounds = null;
try {
const nowSec = Math.floor(Date.now() / 1000);
const positions = await fetchPositions(identifier, fetchFn);
const entries = extractPositionEntries(positions, nowSec);
if (entries.length === 0) {
hidePanel(section, statusEl);
return null;
}
if (statusEl) {
statusEl.hidden = false;
statusEl.textContent = `${entries.length} position${entries.length === 1 ? '' : 's'}`;
}
section.hidden = false;
restorePanel = moveMapPanel(mapPanel, slot);
const fitBoundsEl = options.document?.getElementById?.('fitBounds') ?? null;
if (fitBoundsEl && typeof fitBoundsEl.checked === 'boolean') {
const previous = fitBoundsEl.checked;
fitBoundsEl.checked = false;
restoreFitBounds = () => {
fitBoundsEl.checked = previous;
};
}
const prevCenter = typeof map.getCenter === 'function' ? map.getCenter() : null;
const prevZoom = typeof map.getZoom === 'function' ? map.getZoom() : null;
const getRoleColor =
typeof options.getRoleColor === 'function'
? options.getRoleColor
: options.namespace?.getRoleColor ?? globalThis.PotatoMesh?.getRoleColor;
const latest = entries.reduce((acc, entry) => (entry.time > acc.time ? entry : acc), entries[0]);
const latestColor = colorForDay(latest.day, getRoleColor) ?? '#2b6cb0';
const ordered = entries.slice().sort((a, b) => b.time - a.time);
const pathLatLngs = ordered.map(entry => [entry.lat, entry.lon]);
const layerGroup = leaflet.layerGroup().addTo(map);
if (layers?.markersLayer && typeof layers.markersLayer.clearLayers === 'function') {
layers.markersLayer.clearLayers();
}
if (layers?.neighborLinesLayer && typeof layers.neighborLinesLayer.clearLayers === 'function') {
layers.neighborLinesLayer.clearLayers();
}
if (layers?.traceLinesLayer && typeof layers.traceLinesLayer.clearLayers === 'function') {
layers.traceLinesLayer.clearLayers();
}
const polyline = leaflet.polyline(pathLatLngs, {
color: latestColor,
weight: 2,
opacity: 0.42,
className: 'neighbor-connection-line node-detail-path-line'
});
polyline.addTo(layerGroup);
ordered.forEach(entry => {
const color = colorForDay(entry.day, getRoleColor) ?? '#2b6cb0';
const marker = leaflet.circleMarker([entry.lat, entry.lon], {
radius: 9,
color: '#000',
weight: 1,
fillColor: color,
fillOpacity: 0.7,
opacity: 0.7
});
marker.addTo(layerGroup);
});
if (pathLatLngs.length > 1 && typeof map.fitBounds === 'function') {
map.fitBounds(pathLatLngs, { padding: MAP_PADDING, maxZoom: MAX_FIT_ZOOM });
} else if (typeof map.setView === 'function') {
map.setView(pathLatLngs[pathLatLngs.length - 1], DEFAULT_ZOOM);
}
if (typeof map.invalidateSize === 'function') {
map.invalidateSize(true);
}
return () => {
if (layerGroup && typeof map.removeLayer === 'function') {
map.removeLayer(layerGroup);
} else if (layerGroup && typeof layerGroup.remove === 'function') {
layerGroup.remove();
}
restorePanel();
if (restoreFitBounds) {
restoreFitBounds();
}
if (prevCenter && typeof map.setView === 'function') {
map.setView(prevCenter, prevZoom ?? map.getZoom?.());
}
if (typeof map.invalidateSize === 'function') {
map.invalidateSize(true);
}
};
} catch (error) {
if (restorePanel) {
restorePanel();
}
if (restoreFitBounds) {
restoreFitBounds();
}
if (options.logger && typeof options.logger.error === 'function') {
options.logger.error('Failed to load node positions', error);
}
hidePanel(section, statusEl);
return null;
}
}
export const __testUtils = {
toFiniteNumber,
resolveReferenceId,
extractPositionEntries,
colorForDay,
ROLE_BY_DAY,
};
+13 -18
View File
@@ -14,8 +14,7 @@
* limitations under the License.
*/
import { fetchNodeDetailHtml } from './node-page.js';
import { initializeNodeDetailMapPanel } from './node-detail-map.js';
import { fetchNodeDetailHtml, mountTelemetryChartsWithRetry } from './node-page.js';
/**
* Escape a string for safe HTML injection.
@@ -69,6 +68,9 @@ function hasValidReference(reference) {
* fetchImpl?: Function,
* refreshImpl?: Function,
* renderShortHtml?: Function,
* mountCharts?: Function,
* uPlotImpl?: Function,
* loadUPlot?: Function,
* privateMode?: boolean,
* logger?: Console
* }} [options] Behaviour overrides.
@@ -102,12 +104,14 @@ export function createNodeDetailOverlayManager(options = {}) {
const fetchImpl = options.fetchImpl;
const refreshImpl = options.refreshImpl;
const renderShortHtml = options.renderShortHtml;
const mountCharts = typeof options.mountCharts === 'function' ? options.mountCharts : mountTelemetryChartsWithRetry;
const uPlotImpl = options.uPlotImpl;
const loadUPlot = options.loadUPlot;
let requestToken = 0;
let lastTrigger = null;
let isVisible = false;
let keydownHandler = null;
let mapCleanup = null;
function lockBodyScroll(lock) {
if (!documentRef.body || !documentRef.body.style) {
@@ -156,10 +160,6 @@ export function createNodeDetailOverlayManager(options = {}) {
lockBodyScroll(false);
detachKeydown();
requestToken += 1;
if (typeof mapCleanup === 'function') {
mapCleanup();
mapCleanup = null;
}
const trigger = lastTrigger;
lastTrigger = null;
if (trigger && typeof trigger.focus === 'function') {
@@ -204,26 +204,21 @@ export function createNodeDetailOverlayManager(options = {}) {
}
const currentToken = ++requestToken;
try {
const html = await fetchDetail(reference, {
const result = await fetchDetail(reference, {
fetchImpl,
refreshImpl,
renderShortHtml,
privateMode,
includeMapPanel: true,
returnState: true,
});
if (currentToken !== requestToken) {
return;
}
content.innerHTML = html;
if (typeof mapCleanup === 'function') {
mapCleanup();
mapCleanup = null;
const resolvedHtml = typeof result === 'string' ? result : result?.html;
content.innerHTML = resolvedHtml ?? '';
if (result && typeof result === 'object' && Array.isArray(result.chartModels)) {
mountCharts(result.chartModels, { root: content, uPlotImpl, loadUPlot });
}
mapCleanup = await initializeNodeDetailMapPanel(content, reference, {
fetchImpl,
logger,
document: documentRef,
});
if (typeof closeButton.focus === 'function') {
closeButton.focus();
}
+498 -270
View File
@@ -29,7 +29,6 @@ import {
fmtTemperature,
fmtTx,
} from './short-info-telemetry.js';
import { initializeNodeDetailMapPanel } from './node-detail-map.js';
const DEFAULT_FETCH_OPTIONS = Object.freeze({ cache: 'no-store' });
const MESSAGE_LIMIT = 50;
@@ -125,6 +124,15 @@ const TELEMETRY_CHART_SPECS = Object.freeze([
ticks: 4,
color: '#2ca25f',
},
{
id: 'channelSecondary',
position: 'right',
label: 'Utilization (%)',
min: 0,
max: 100,
ticks: 4,
color: '#2ca25f',
},
],
series: [
{
@@ -138,7 +146,7 @@ const TELEMETRY_CHART_SPECS = Object.freeze([
},
{
id: 'air',
axis: 'channel',
axis: 'channelSecondary',
color: '#99d8c9',
label: 'Air util tx',
legend: 'Air util TX (%)',
@@ -163,13 +171,13 @@ const TELEMETRY_CHART_SPECS = Object.freeze([
},
{
id: 'humidity',
position: 'left',
position: 'right',
label: 'Humidity (%)',
min: 0,
max: 100,
ticks: 4,
color: '#91bfdb',
visible: false,
visible: true,
},
],
series: [
@@ -858,67 +866,6 @@ function createChartDimensions(spec) {
};
}
/**
* Compute the horizontal drawing position for an axis descriptor.
*
* @param {string} position Axis position keyword.
* @param {Object} dims Chart dimensions.
* @returns {number} X coordinate for the axis baseline.
*/
function resolveAxisX(position, dims) {
switch (position) {
case 'leftSecondary':
return dims.margin.left - 32;
case 'right':
return dims.width - dims.margin.right;
case 'rightSecondary':
return dims.width - dims.margin.right + 32;
case 'left':
default:
return dims.margin.left;
}
}
/**
* Compute the X coordinate for a timestamp constrained to the rolling window.
*
* @param {number} timestamp Timestamp in milliseconds.
* @param {number} domainStart Start of the window in milliseconds.
* @param {number} domainEnd End of the window in milliseconds.
* @param {Object} dims Chart dimensions.
* @returns {number} X coordinate inside the SVG viewport.
*/
function scaleTimestamp(timestamp, domainStart, domainEnd, dims) {
const safeStart = Math.min(domainStart, domainEnd);
const safeEnd = Math.max(domainStart, domainEnd);
const span = Math.max(1, safeEnd - safeStart);
const clamped = clamp(timestamp, safeStart, safeEnd);
const ratio = (clamped - safeStart) / span;
return dims.margin.left + ratio * dims.innerWidth;
}
/**
* Convert a value bound to a specific axis into a Y coordinate.
*
* @param {number} value Series value.
* @param {Object} axis Axis descriptor.
* @param {Object} dims Chart dimensions.
* @returns {number} Y coordinate.
*/
function scaleValueToAxis(value, axis, dims) {
if (!axis) return dims.chartBottom;
if (axis.scale === 'log') {
const minLog = Math.log10(axis.min);
const maxLog = Math.log10(axis.max);
const safe = clamp(value, axis.min, axis.max);
const ratio = (Math.log10(safe) - minLog) / (maxLog - minLog);
return dims.chartBottom - ratio * dims.innerHeight;
}
const safe = clamp(value, axis.min, axis.max);
const ratio = (safe - axis.min) / (axis.max - axis.min || 1);
return dims.chartBottom - ratio * dims.innerHeight;
}
/**
* Collect candidate containers that may hold telemetry values for a snapshot.
*
@@ -1035,129 +982,15 @@ function resolveAxisMax(axis, seriesEntries) {
}
/**
* Render a telemetry series as circles plus an optional translucent guide line.
*
* @param {Object} seriesConfig Series metadata.
* @param {Array<{timestamp: number, value: number}>} points Series points.
* @param {Object} axis Axis descriptor.
* @param {Object} dims Chart dimensions.
* @param {number} domainStart Window start timestamp.
* @param {number} domainEnd Window end timestamp.
* @returns {string} SVG markup for the series.
*/
function renderTelemetrySeries(seriesConfig, points, axis, dims, domainStart, domainEnd, { lineReducer } = {}) {
if (!Array.isArray(points) || points.length === 0) {
return '';
}
const convertPoint = point => {
const cx = scaleTimestamp(point.timestamp, domainStart, domainEnd, dims);
const cy = scaleValueToAxis(point.value, axis, dims);
return { cx, cy, value: point.value };
};
const circleEntries = points.map(point => {
const coords = convertPoint(point);
const tooltip = formatSeriesPointValue(seriesConfig, point.value);
const titleMarkup = tooltip ? `<title>${escapeHtml(tooltip)}</title>` : '';
return `<circle class="node-detail__chart-point" cx="${coords.cx.toFixed(2)}" cy="${coords.cy.toFixed(2)}" r="3.2" fill="${seriesConfig.color}" aria-hidden="true">${titleMarkup}</circle>`;
});
const lineSource = typeof lineReducer === 'function' ? lineReducer(points) : points;
const linePoints = Array.isArray(lineSource) && lineSource.length > 0 ? lineSource : points;
const coordinates = linePoints.map(convertPoint);
let line = '';
if (coordinates.length > 1) {
const path = coordinates
.map((coord, idx) => `${idx === 0 ? 'M' : 'L'}${coord.cx.toFixed(2)} ${coord.cy.toFixed(2)}`)
.join(' ');
line = `<path class="node-detail__chart-trend" d="${path}" fill="none" stroke="${hexToRgba(seriesConfig.color, 0.5)}" stroke-width="1.5" aria-hidden="true"></path>`;
}
return `${line}${circleEntries.join('')}`;
}
/**
* Render a vertical axis when visible.
*
* @param {Object} axis Axis descriptor.
* @param {Object} dims Chart dimensions.
* @returns {string} SVG markup for the axis or an empty string.
*/
function renderYAxis(axis, dims) {
if (!axis || axis.visible === false) {
return '';
}
const x = resolveAxisX(axis.position, dims);
const ticks = axis.scale === 'log'
? buildLogTicks(axis.min, axis.max)
: buildLinearTicks(axis.min, axis.max, axis.ticks);
const tickElements = ticks
.map(value => {
const y = scaleValueToAxis(value, axis, dims);
const tickLength = axis.position === 'left' || axis.position === 'leftSecondary' ? -4 : 4;
const textAnchor = axis.position === 'left' || axis.position === 'leftSecondary' ? 'end' : 'start';
const textOffset = axis.position === 'left' || axis.position === 'leftSecondary' ? -6 : 6;
return `
<g class="node-detail__chart-tick" aria-hidden="true">
<line x1="${x}" y1="${y.toFixed(2)}" x2="${(x + tickLength).toFixed(2)}" y2="${y.toFixed(2)}"></line>
<text x="${(x + textOffset).toFixed(2)}" y="${(y + 3).toFixed(2)}" text-anchor="${textAnchor}" dominant-baseline="middle">${escapeHtml(formatAxisTick(value, axis))}</text>
</g>
`;
})
.join('');
const labelPadding = axis.position === 'left' || axis.position === 'leftSecondary' ? -56 : 56;
const labelX = x + labelPadding;
const labelY = (dims.chartTop + dims.chartBottom) / 2;
const labelTransform = `rotate(-90 ${labelX.toFixed(2)} ${labelY.toFixed(2)})`;
return `
<g class="node-detail__chart-axis node-detail__chart-axis--y" aria-hidden="true">
<line x1="${x}" y1="${dims.chartTop}" x2="${x}" y2="${dims.chartBottom}"></line>
${tickElements}
<text class="node-detail__chart-axis-label" x="${labelX.toFixed(2)}" y="${labelY.toFixed(2)}" text-anchor="middle" dominant-baseline="middle" transform="${labelTransform}">${escapeHtml(axis.label)}</text>
</g>
`;
}
/**
* Render the horizontal floating seven-day axis with midnight ticks.
*
* @param {Object} dims Chart dimensions.
* @param {number} domainStart Window start timestamp.
* @param {number} domainEnd Window end timestamp.
* @param {Array<number>} tickTimestamps Midnight tick timestamps.
* @returns {string} SVG markup for the X axis.
*/
function renderXAxis(dims, domainStart, domainEnd, tickTimestamps, { labelFormatter = formatCompactDate } = {}) {
const y = dims.chartBottom;
const ticks = tickTimestamps
.map(ts => {
const x = scaleTimestamp(ts, domainStart, domainEnd, dims);
const labelY = y + 18;
const xStr = x.toFixed(2);
const yStr = labelY.toFixed(2);
const label = labelFormatter(ts);
return `
<g class="node-detail__chart-tick" aria-hidden="true">
<line class="node-detail__chart-grid-line" x1="${xStr}" y1="${dims.chartTop}" x2="${xStr}" y2="${dims.chartBottom}"></line>
<text x="${xStr}" y="${yStr}" text-anchor="end" dominant-baseline="central" transform="rotate(-90 ${xStr} ${yStr})">${escapeHtml(label)}</text>
</g>
`;
})
.join('');
return `
<g class="node-detail__chart-axis node-detail__chart-axis--x" aria-hidden="true">
<line x1="${dims.margin.left}" y1="${y}" x2="${dims.width - dims.margin.right}" y2="${y}"></line>
${ticks}
</g>
`;
}
/**
* Render a single telemetry chart defined by ``spec``.
* Build a telemetry chart model from a specification and series entries.
*
* @param {Object} spec Chart specification.
* @param {Array<{timestamp: number, snapshot: Object}>} entries Telemetry entries.
* @param {number} nowMs Reference timestamp.
* @returns {string} Rendered chart markup or an empty string.
* @param {Object} chartOptions Rendering overrides.
* @returns {Object|null} Chart model or ``null`` when empty.
*/
function renderTelemetryChart(spec, entries, nowMs, chartOptions = {}) {
function buildTelemetryChartModel(spec, entries, nowMs, chartOptions = {}) {
const windowMs = Number.isFinite(chartOptions.windowMs) && chartOptions.windowMs > 0 ? chartOptions.windowMs : TELEMETRY_WINDOW_MS;
const timeRangeLabel = stringOrNull(chartOptions.timeRangeLabel) ?? 'Last 7 days';
const domainEnd = nowMs;
@@ -1171,7 +1004,7 @@ function renderTelemetryChart(spec, entries, nowMs, chartOptions = {}) {
})
.filter(entry => entry != null);
if (seriesEntries.length === 0) {
return '';
return null;
}
const adjustedAxes = spec.axes.map(axis => {
const resolvedMax = resolveAxisMax(axis, seriesEntries);
@@ -1189,22 +1022,33 @@ function renderTelemetryChart(spec, entries, nowMs, chartOptions = {}) {
})
.filter(entry => entry != null);
if (plottedSeries.length === 0) {
return '';
return null;
}
const axesMarkup = adjustedAxes.map(axis => renderYAxis(axis, dims)).join('');
const tickBuilder = typeof chartOptions.xAxisTickBuilder === 'function' ? chartOptions.xAxisTickBuilder : buildMidnightTicks;
const tickFormatter = typeof chartOptions.xAxisTickFormatter === 'function' ? chartOptions.xAxisTickFormatter : formatCompactDate;
const ticks = tickBuilder(nowMs, windowMs);
const xAxisMarkup = renderXAxis(dims, domainStart, domainEnd, ticks, { labelFormatter: tickFormatter });
return {
id: spec.id,
title: spec.title,
timeRangeLabel,
domainStart,
domainEnd,
dims,
axes: adjustedAxes,
seriesEntries: plottedSeries,
ticks: tickBuilder(nowMs, windowMs),
tickFormatter,
lineReducer: typeof chartOptions.lineReducer === 'function' ? chartOptions.lineReducer : null,
};
}
const seriesMarkup = plottedSeries
.map(series =>
renderTelemetrySeries(series.config, series.points, series.axis, dims, domainStart, domainEnd, {
lineReducer: chartOptions.lineReducer,
}),
)
.join('');
const legendItems = plottedSeries
/**
* Render a telemetry chart container for a chart model.
*
* @param {Object} model Chart model.
* @returns {string} Chart markup.
*/
function renderTelemetryChartMarkup(model) {
const legendItems = model.seriesEntries
.map(series => {
const legendLabel = stringOrNull(series.config.legend) ?? series.config.label;
return `
@@ -1218,22 +1062,428 @@ function renderTelemetryChart(spec, entries, nowMs, chartOptions = {}) {
const legendMarkup = legendItems
? `<div class="node-detail__chart-legend" aria-hidden="true">${legendItems}</div>`
: '';
const ariaLabel = `${model.title} over last seven days`;
return `
<figure class="node-detail__chart">
<figure class="node-detail__chart" data-telemetry-chart-id="${escapeHtml(model.id)}">
<figcaption class="node-detail__chart-header">
<h4>${escapeHtml(spec.title)}</h4>
<span>${escapeHtml(timeRangeLabel)}</span>
<h4>${escapeHtml(model.title)}</h4>
<span>${escapeHtml(model.timeRangeLabel)}</span>
</figcaption>
<svg viewBox="0 0 ${dims.width} ${dims.height}" preserveAspectRatio="xMidYMid meet" role="img" aria-label="${escapeHtml(`${spec.title} over last seven days`)}">
${axesMarkup}
${xAxisMarkup}
${seriesMarkup}
</svg>
<div class="node-detail__chart-plot" data-telemetry-plot role="img" aria-label="${escapeHtml(ariaLabel)}"></div>
${legendMarkup}
</figure>
`;
}
/**
* Build a sorted timestamp index shared across series entries.
*
* @param {Array<Object>} seriesEntries Plotted series entries.
* @param {Function|null} lineReducer Optional line reducer.
* @returns {{timestamps: Array<number>, indexByTimestamp: Map<number, number>}} Timestamp index.
*/
function buildChartTimestampIndex(seriesEntries, lineReducer) {
const timestampSet = new Set();
for (const entry of seriesEntries) {
if (!entry || !Array.isArray(entry.points)) continue;
entry.points.forEach(point => {
if (point && Number.isFinite(point.timestamp)) {
timestampSet.add(point.timestamp);
}
});
if (typeof lineReducer === 'function') {
const reduced = lineReducer(entry.points);
if (Array.isArray(reduced)) {
reduced.forEach(point => {
if (point && Number.isFinite(point.timestamp)) {
timestampSet.add(point.timestamp);
}
});
}
}
}
const timestamps = Array.from(timestampSet).sort((a, b) => a - b);
const indexByTimestamp = new Map(timestamps.map((ts, idx) => [ts, idx]));
return { timestamps, indexByTimestamp };
}
/**
* Convert a list of points into an aligned values array.
*
* @param {Array<{timestamp: number, value: number}>} points Series points.
* @param {Map<number, number>} indexByTimestamp Timestamp index.
* @param {number} length Length of the output array.
* @returns {Array<number|null>} Values aligned to timestamps.
*/
function mapSeriesValues(points, indexByTimestamp, length) {
const values = Array.from({ length }, () => null);
if (!Array.isArray(points)) {
return values;
}
for (const point of points) {
if (!point || !Number.isFinite(point.timestamp)) continue;
const idx = indexByTimestamp.get(point.timestamp);
if (idx == null) continue;
values[idx] = Number.isFinite(point.value) ? point.value : null;
}
return values;
}
/**
* Build uPlot series and data arrays for a chart model.
*
* @param {Object} model Chart model.
* @returns {{data: Array<Array<number|null>>, series: Array<Object>}} uPlot data and series config.
*/
function buildTelemetryChartData(model) {
const { timestamps, indexByTimestamp } = buildChartTimestampIndex(model.seriesEntries, model.lineReducer);
const data = [timestamps];
const series = [{ label: 'Time' }];
model.seriesEntries.forEach(entry => {
const baseConfig = {
label: entry.config.label,
scale: entry.axis.id,
};
if (model.lineReducer) {
const reducedPoints = model.lineReducer(entry.points);
const linePoints = Array.isArray(reducedPoints) && reducedPoints.length > 0 ? reducedPoints : entry.points;
const lineValues = mapSeriesValues(linePoints, indexByTimestamp, timestamps.length);
series.push({
...baseConfig,
stroke: hexToRgba(entry.config.color, 0.5),
width: 1.5,
points: { show: false },
});
data.push(lineValues);
const pointValues = mapSeriesValues(entry.points, indexByTimestamp, timestamps.length);
series.push({
...baseConfig,
stroke: entry.config.color,
width: 0,
points: { show: true, size: 6, width: 1 },
});
data.push(pointValues);
} else {
const values = mapSeriesValues(entry.points, indexByTimestamp, timestamps.length);
series.push({
...baseConfig,
stroke: entry.config.color,
width: 1.5,
points: { show: true, size: 6, width: 1 },
});
data.push(values);
}
});
return { data, series };
}
/**
* Build uPlot chart configuration and data for a telemetry chart.
*
* @param {Object} model Chart model.
* @returns {{options: Object, data: Array<Array<number|null>>}} uPlot config and data.
*/
function buildUPlotChartConfig(model, { width, height, axisColor, gridColor } = {}) {
const { data, series } = buildTelemetryChartData(model);
const fallbackWidth = Math.round(model.dims.width * 1.8);
const resolvedWidth = Number.isFinite(width) && width > 0 ? width : fallbackWidth;
const resolvedHeight = Number.isFinite(height) && height > 0 ? height : model.dims.height;
const axisStroke = stringOrNull(axisColor) ?? '#5c6773';
const gridStroke = stringOrNull(gridColor) ?? 'rgba(12, 15, 18, 0.08)';
const axes = [
{
scale: 'x',
side: 2,
stroke: axisStroke,
grid: { show: true, stroke: gridStroke },
splits: () => model.ticks,
values: (u, splits) => splits.map(value => model.tickFormatter(value)),
},
];
const scales = {
x: {
time: true,
range: () => [model.domainStart, model.domainEnd],
},
};
model.axes.forEach(axis => {
const ticks = axis.scale === 'log'
? buildLogTicks(axis.min, axis.max)
: buildLinearTicks(axis.min, axis.max, axis.ticks);
const side = axis.position === 'right' || axis.position === 'rightSecondary' ? 1 : 3;
axes.push({
scale: axis.id,
side,
show: axis.visible !== false,
stroke: axisStroke,
grid: { show: false },
label: axis.label,
splits: () => ticks,
values: (u, splits) => splits.map(value => formatAxisTick(value, axis)),
});
scales[axis.id] = {
distr: axis.scale === 'log' ? 3 : 1,
log: axis.scale === 'log' ? 10 : undefined,
range: () => [axis.min, axis.max],
};
});
return {
options: {
width: resolvedWidth,
height: resolvedHeight,
padding: [
model.dims.margin.top,
model.dims.margin.right,
model.dims.margin.bottom,
model.dims.margin.left,
],
legend: { show: false },
series,
axes,
scales,
},
data,
};
}
/**
* Instantiate uPlot charts for the provided chart models.
*
* @param {Array<Object>} chartModels Chart models to render.
* @param {{root?: ParentNode, uPlotImpl?: Function}} [options] Rendering options.
* @returns {Array<Object>} Instantiated uPlot charts.
*/
export function mountTelemetryCharts(chartModels, { root, uPlotImpl } = {}) {
if (!Array.isArray(chartModels) || chartModels.length === 0) {
return [];
}
const host = root ?? globalThis.document;
if (!host || typeof host.querySelector !== 'function') {
return [];
}
const uPlotCtor = typeof uPlotImpl === 'function' ? uPlotImpl : globalThis.uPlot;
if (typeof uPlotCtor !== 'function') {
console.warn('uPlot is unavailable; telemetry charts will not render.');
return [];
}
const instances = [];
const colorRoot = host?.ownerDocument?.body ?? host?.body ?? globalThis.document?.body ?? null;
const axisColor = colorRoot && typeof globalThis.getComputedStyle === 'function'
? globalThis.getComputedStyle(colorRoot).getPropertyValue('--muted').trim()
: null;
const gridColor = colorRoot && typeof globalThis.getComputedStyle === 'function'
? globalThis.getComputedStyle(colorRoot).getPropertyValue('--line').trim()
: null;
chartModels.forEach(model => {
const container = host.querySelector(`[data-telemetry-chart-id="${model.id}"]`);
if (!container) return;
const plotRoot = container.querySelector('[data-telemetry-plot]');
if (!plotRoot) return;
plotRoot.innerHTML = '';
const plotWidth = plotRoot.clientWidth || plotRoot.getBoundingClientRect?.().width;
const plotHeight = plotRoot.clientHeight || plotRoot.getBoundingClientRect?.().height;
const { options, data } = buildUPlotChartConfig(model, {
width: plotWidth ? Math.round(plotWidth) : undefined,
height: plotHeight ? Math.round(plotHeight) : undefined,
axisColor: axisColor || undefined,
gridColor: gridColor || undefined,
});
const instance = new uPlotCtor(options, data, plotRoot);
instance.__potatoMeshRoot = plotRoot;
instances.push(instance);
});
registerTelemetryChartResize(instances);
return instances;
}
const telemetryResizeRegistry = new Set();
const telemetryResizeObservers = new WeakMap();
let telemetryResizeListenerAttached = false;
let telemetryResizeDebounceId = null;
const TELEMETRY_RESIZE_DEBOUNCE_MS = 120;
function resizeUPlotInstance(instance) {
if (!instance || typeof instance.setSize !== 'function') {
return;
}
const root = instance.__potatoMeshRoot ?? instance.root ?? null;
if (!root) return;
const rect = typeof root.getBoundingClientRect === 'function' ? root.getBoundingClientRect() : null;
const width = Number.isFinite(root.clientWidth) ? root.clientWidth : rect?.width;
const height = Number.isFinite(root.clientHeight) ? root.clientHeight : rect?.height;
if (!width || !height) return;
instance.setSize({ width: Math.round(width), height: Math.round(height) });
}
function registerTelemetryChartResize(instances) {
if (!Array.isArray(instances) || instances.length === 0) {
return;
}
const scheduleResize = () => {
if (telemetryResizeDebounceId != null) {
clearTimeout(telemetryResizeDebounceId);
}
telemetryResizeDebounceId = setTimeout(() => {
telemetryResizeDebounceId = null;
telemetryResizeRegistry.forEach(instance => resizeUPlotInstance(instance));
}, TELEMETRY_RESIZE_DEBOUNCE_MS);
};
instances.forEach(instance => {
telemetryResizeRegistry.add(instance);
resizeUPlotInstance(instance);
if (typeof globalThis.ResizeObserver === 'function') {
if (telemetryResizeObservers.has(instance)) return;
const observer = new globalThis.ResizeObserver(scheduleResize);
telemetryResizeObservers.set(instance, observer);
const root = instance.__potatoMeshRoot ?? instance.root ?? null;
if (root && typeof observer.observe === 'function') {
observer.observe(root);
}
}
});
if (!telemetryResizeListenerAttached && typeof globalThis.addEventListener === 'function') {
globalThis.addEventListener('resize', () => {
scheduleResize();
});
telemetryResizeListenerAttached = true;
}
}
function defaultLoadUPlot({ documentRef, onLoad }) {
if (!documentRef || typeof documentRef.querySelector !== 'function') {
return false;
}
const existing = documentRef.querySelector('script[data-uplot-loader="true"]');
if (existing) {
if (existing.dataset.loaded === 'true' && typeof onLoad === 'function') {
onLoad();
} else if (typeof existing.addEventListener === 'function' && typeof onLoad === 'function') {
existing.addEventListener('load', onLoad, { once: true });
}
return true;
}
if (typeof documentRef.createElement !== 'function') {
return false;
}
const script = documentRef.createElement('script');
script.src = '/assets/vendor/uplot/uPlot.iife.min.js';
script.defer = true;
script.dataset.uplotLoader = 'true';
if (typeof script.addEventListener === 'function') {
script.addEventListener('load', () => {
script.dataset.loaded = 'true';
if (typeof onLoad === 'function') {
onLoad();
}
});
}
const head = documentRef.head ?? documentRef.body;
if (head && typeof head.appendChild === 'function') {
head.appendChild(script);
return true;
}
return false;
}
/**
* Mount telemetry charts, retrying briefly if uPlot has not loaded yet.
*
* @param {Array<Object>} chartModels Chart models to render.
* @param {{root?: ParentNode, uPlotImpl?: Function, loadUPlot?: Function}} [options] Rendering options.
* @returns {Array<Object>} Instantiated uPlot charts.
*/
export function mountTelemetryChartsWithRetry(chartModels, { root, uPlotImpl, loadUPlot } = {}) {
const instances = mountTelemetryCharts(chartModels, { root, uPlotImpl });
if (instances.length > 0 || typeof uPlotImpl === 'function') {
return instances;
}
const host = root ?? globalThis.document;
if (!host || typeof host.querySelector !== 'function') {
return instances;
}
let mounted = false;
let attempts = 0;
const maxAttempts = 10;
const retryDelayMs = 50;
const retry = () => {
if (mounted) return;
attempts += 1;
const next = mountTelemetryCharts(chartModels, { root, uPlotImpl });
if (next.length > 0) {
mounted = true;
return;
}
if (attempts >= maxAttempts) {
return;
}
setTimeout(retry, retryDelayMs);
};
const loadFn = typeof loadUPlot === 'function' ? loadUPlot : defaultLoadUPlot;
loadFn({
documentRef: host.ownerDocument ?? globalThis.document,
onLoad: () => {
const next = mountTelemetryCharts(chartModels, { root, uPlotImpl });
if (next.length > 0) {
mounted = true;
}
},
});
setTimeout(retry, 0);
return instances;
}
/**
* Create chart markup and models for telemetry charts.
*
* @param {Object} node Normalised node payload.
* @param {{ nowMs?: number, chartOptions?: Object }} [options] Rendering options.
* @returns {{chartsHtml: string, chartModels: Array<Object>}} Chart markup and models.
*/
export function createTelemetryCharts(node, { nowMs = Date.now(), chartOptions = {} } = {}) {
const telemetrySource = node?.rawSources?.telemetry;
const snapshotHistory = Array.isArray(node?.rawSources?.telemetrySnapshots) && node.rawSources.telemetrySnapshots.length > 0
? node.rawSources.telemetrySnapshots
: null;
const aggregatedSnapshots = Array.isArray(telemetrySource?.snapshots)
? telemetrySource.snapshots
: null;
const rawSnapshots = snapshotHistory ?? aggregatedSnapshots;
if (!Array.isArray(rawSnapshots) || rawSnapshots.length === 0) {
return { chartsHtml: '', chartModels: [] };
}
const entries = rawSnapshots
.map(snapshot => {
const timestamp = resolveSnapshotTimestamp(snapshot);
if (timestamp == null) return null;
return { timestamp, snapshot };
})
.filter(entry => entry != null && entry.timestamp >= nowMs - TELEMETRY_WINDOW_MS && entry.timestamp <= nowMs)
.sort((a, b) => a.timestamp - b.timestamp);
if (entries.length === 0) {
return { chartsHtml: '', chartModels: [] };
}
const chartModels = TELEMETRY_CHART_SPECS
.map(spec => buildTelemetryChartModel(spec, entries, nowMs, chartOptions))
.filter(model => model != null);
if (chartModels.length === 0) {
return { chartsHtml: '', chartModels: [] };
}
const chartsHtml = `
<section class="node-detail__charts">
<div class="node-detail__charts-grid">
${chartModels.map(model => renderTelemetryChartMarkup(model)).join('')}
</div>
</section>
`;
return { chartsHtml, chartModels };
}
/**
* Render the telemetry charts for the supplied node when telemetry snapshots
* exist.
@@ -1243,41 +1493,7 @@ function renderTelemetryChart(spec, entries, nowMs, chartOptions = {}) {
* @returns {string} Chart grid markup or an empty string.
*/
export function renderTelemetryCharts(node, { nowMs = Date.now(), chartOptions = {} } = {}) {
const telemetrySource = node?.rawSources?.telemetry;
const snapshotHistory = Array.isArray(node?.rawSources?.telemetrySnapshots) && node.rawSources.telemetrySnapshots.length > 0
? node.rawSources.telemetrySnapshots
: null;
const aggregatedSnapshots = Array.isArray(telemetrySource?.snapshots)
? telemetrySource.snapshots
: null;
const rawSnapshots = snapshotHistory ?? aggregatedSnapshots;
if (!Array.isArray(rawSnapshots) || rawSnapshots.length === 0) {
return '';
}
const entries = rawSnapshots
.map(snapshot => {
const timestamp = resolveSnapshotTimestamp(snapshot);
if (timestamp == null) return null;
return { timestamp, snapshot };
})
.filter(entry => entry != null && entry.timestamp >= nowMs - TELEMETRY_WINDOW_MS && entry.timestamp <= nowMs)
.sort((a, b) => a.timestamp - b.timestamp);
if (entries.length === 0) {
return '';
}
const charts = TELEMETRY_CHART_SPECS
.map(spec => renderTelemetryChart(spec, entries, nowMs, chartOptions))
.filter(chart => stringOrNull(chart));
if (charts.length === 0) {
return '';
}
return `
<section class="node-detail__charts">
<div class="node-detail__charts-grid">
${charts.join('')}
</div>
</section>
`;
return createTelemetryCharts(node, { nowMs, chartOptions }).chartsHtml;
}
/**
@@ -2295,11 +2511,11 @@ function renderTraceroutes(traces, renderShortHtml, { roleIndex = null, node = n
*
* @param {Object} node Normalised node payload.
* @param {{
* neighbors?: Array<Object>,
* messages?: Array<Object>,
* neighbors?: Array<Object>,
* messages?: Array<Object>,
* traces?: Array<Object>,
* includeMapPanel?: boolean,
* renderShortHtml: Function,
* renderShortHtml: Function,
* chartsHtml?: string,
* }} options Rendering options.
* @returns {string} HTML fragment representing the detail view.
*/
@@ -2307,9 +2523,9 @@ function renderNodeDetailHtml(node, {
neighbors = [],
messages = [],
traces = [],
includeMapPanel = false,
renderShortHtml,
roleIndex = null,
chartsHtml = null,
chartNowMs = Date.now(),
} = {}) {
const roleAwareBadge = renderRoleAwareBadge(renderShortHtml, {
@@ -2323,21 +2539,10 @@ function renderNodeDetailHtml(node, {
const longName = stringOrNull(node.longName ?? node.long_name);
const identifier = stringOrNull(node.nodeId ?? node.node_id);
const tableHtml = renderSingleNodeTable(node, renderShortHtml);
const chartsHtml = renderTelemetryCharts(node, { nowMs: chartNowMs });
const telemetryChartsHtml = stringOrNull(chartsHtml) ?? renderTelemetryCharts(node, { nowMs: chartNowMs });
const neighborsHtml = renderNeighborGroups(node, neighbors, renderShortHtml, { roleIndex });
const tracesHtml = renderTraceroutes(traces, renderShortHtml, { roleIndex, node });
const messagesHtml = renderMessages(messages, renderShortHtml, node);
const mapPanelHtml = includeMapPanel
? `
<section class="node-detail__section node-detail__map-panel" data-node-map-panel>
<div class="node-detail__map-header">
<h3>Position history</h3>
<span class="node-detail__map-status" data-node-map-status>Loading positions</span>
</div>
<div class="node-detail__map-slot" data-node-map-slot></div>
</section>
`
: '';
const sections = [];
if (neighborsHtml) {
@@ -2360,8 +2565,7 @@ function renderNodeDetailHtml(node, {
<header class="node-detail__header">
<h2 class="node-detail__title">${badgeHtml}${nameHtml}${identifierHtml}</h2>
</header>
${mapPanelHtml}
${chartsHtml ?? ''}
${telemetryChartsHtml ?? ''}
${tableSection}
${contentHtml}
`;
@@ -2475,16 +2679,17 @@ async function fetchTracesForNode(identifier, { fetchImpl } = {}) {
}
/**
* Initialise the node detail page by hydrating the DOM with fetched data.
* Fetch node detail data and render the HTML fragment.
*
* @param {{
* document?: Document,
* fetchImpl?: Function,
* refreshImpl?: Function,
* renderShortHtml?: Function,
* includeMapPanel?: boolean,
* chartNowMs?: number,
* chartOptions?: Object,
* }} options Optional overrides for testing.
* @returns {Promise<boolean>} ``true`` when the node was rendered successfully.
* @returns {Promise<string|{html: string, chartModels: Array<Object>}>} Rendered markup or chart models when requested.
*/
export async function fetchNodeDetailHtml(referenceData, options = {}) {
if (!referenceData || typeof referenceData !== 'object') {
@@ -2514,16 +2719,38 @@ export async function fetchNodeDetailHtml(referenceData, options = {}) {
fetchTracesForNode(messageIdentifier, { fetchImpl: options.fetchImpl }),
]);
const roleIndex = await buildTraceRoleIndex(traces, neighborRoleIndex, { fetchImpl: options.fetchImpl });
return renderNodeDetailHtml(node, {
const chartNowMs = Number.isFinite(options.chartNowMs) ? options.chartNowMs : Date.now();
const chartState = createTelemetryCharts(node, {
nowMs: chartNowMs,
chartOptions: options.chartOptions ?? {},
});
const html = renderNodeDetailHtml(node, {
neighbors: node.neighbors,
messages,
traces,
renderShortHtml,
roleIndex,
includeMapPanel: options.includeMapPanel === true,
chartsHtml: chartState.chartsHtml,
chartNowMs,
});
if (options.returnState === true) {
return { html, chartModels: chartState.chartModels };
}
return html;
}
/**
* Initialise the standalone node detail page and mount telemetry charts.
*
* @param {{
* document?: Document,
* fetchImpl?: Function,
* refreshImpl?: Function,
* renderShortHtml?: Function,
* uPlotImpl?: Function,
* }} options Optional overrides for testing.
* @returns {Promise<boolean>} ``true`` when the node was rendered successfully.
*/
export async function initializeNodeDetailPage(options = {}) {
const documentRef = options.document ?? globalThis.document;
if (!documentRef || typeof documentRef.querySelector !== 'function') {
@@ -2560,18 +2787,15 @@ export async function initializeNodeDetailPage(options = {}) {
const privateMode = (root.dataset?.privateMode ?? '').toLowerCase() === 'true';
try {
const html = await fetchNodeDetailHtml(referenceData, {
const result = await fetchNodeDetailHtml(referenceData, {
fetchImpl: options.fetchImpl,
refreshImpl,
renderShortHtml: options.renderShortHtml,
privateMode,
includeMapPanel: true,
});
root.innerHTML = html;
await initializeNodeDetailMapPanel(root, referenceData, {
fetchImpl: options.fetchImpl,
document: documentRef,
returnState: true,
});
root.innerHTML = result.html;
mountTelemetryChartsWithRetry(result.chartModels, { root, uPlotImpl: options.uPlotImpl });
return true;
} catch (error) {
console.error('Failed to render node detail page', error);
@@ -2608,7 +2832,11 @@ export const __testUtils = {
categoriseNeighbors,
renderNeighborGroups,
renderSingleNodeTable,
createTelemetryCharts,
renderTelemetryCharts,
mountTelemetryCharts,
mountTelemetryChartsWithRetry,
buildUPlotChartConfig,
renderMessages,
renderTraceroutes,
renderTracePath,
+49 -273
View File
@@ -215,214 +215,25 @@ h1 {
.site-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
min-height: 56px;
padding: 4px 0;
margin-bottom: 8px;
}
.site-header__left,
.site-header__right {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
}
.site-header__left {
flex: 1 1 auto;
min-width: 0;
}
.site-header__right {
flex: 0 0 auto;
margin-left: auto;
margin-bottom: 8px;
}
.site-title {
display: inline-flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.site-title-text {
min-width: 0;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.site-title img {
width: 36px;
height: 36px;
width: 52px;
height: 52px;
display: block;
border-radius: 12px;
}
.site-nav {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.site-nav__link {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 12px;
border-radius: 999px;
color: var(--fg);
text-decoration: none;
border: 1px solid transparent;
font-size: 14px;
}
.site-nav__link:hover {
background: var(--card);
}
.site-nav__link.is-active {
border-color: var(--accent);
color: var(--accent);
background: transparent;
font-weight: 600;
}
.site-nav__link:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.menu-toggle {
display: none;
}
.menu-toggle:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.mobile-menu {
position: fixed;
inset: 0;
z-index: 1200;
display: flex;
justify-content: flex-end;
pointer-events: none;
}
.mobile-menu[hidden] {
display: none;
}
.mobile-menu__backdrop {
flex: 1 1 auto;
background: rgba(0, 0, 0, 0.4);
opacity: 0;
transition: opacity 200ms ease;
}
.mobile-menu__panel {
width: min(320px, 86vw);
background: var(--bg2);
color: var(--fg);
padding: 16px;
display: flex;
flex-direction: column;
gap: 16px;
height: 100%;
overflow-y: auto;
transform: translateX(100%);
transition: transform 220ms ease;
box-shadow: -12px 0 32px rgba(0, 0, 0, 0.3);
}
.mobile-menu__header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.mobile-menu__title {
margin: 0;
font-size: 16px;
}
.mobile-menu__close:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.mobile-nav {
display: flex;
flex-direction: column;
gap: 8px;
}
.mobile-nav__link {
display: inline-flex;
align-items: center;
padding: 8px 10px;
border-radius: 10px;
color: var(--fg);
text-decoration: none;
border: 1px solid transparent;
}
.mobile-nav__link.is-active {
border-color: var(--accent);
color: var(--accent);
font-weight: 600;
}
.mobile-nav__link:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.mobile-menu.is-open {
pointer-events: auto;
}
.mobile-menu.is-open .mobile-menu__backdrop {
opacity: 1;
}
.mobile-menu.is-open .mobile-menu__panel {
transform: translateX(0);
}
.menu-open {
overflow: hidden;
}
.section-link {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 10px;
border-radius: 999px;
border: 1px solid var(--line);
color: var(--fg);
text-decoration: none;
font-size: 14px;
}
.section-link:hover {
border-color: var(--accent);
color: var(--accent);
}
.section-link:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
.meta {
color: #555;
margin-bottom: 12px;
@@ -471,29 +282,11 @@ h1 {
@media (max-width: 900px) {
.site-header {
margin-bottom: 4px;
}
.site-header__left {
flex-wrap: nowrap;
}
.site-header__left--federation {
flex-wrap: wrap;
}
.site-nav {
display: none;
}
.menu-toggle {
display: inline-flex;
}
.instance-selector {
flex: 0 1 auto;
flex-direction: column;
align-items: flex-start;
}
.instance-selector,
.instance-select {
width: 100%;
}
@@ -503,7 +296,6 @@ h1 {
}
}
.pill {
display: inline-block;
padding: 2px 8px;
@@ -1199,65 +991,10 @@ body.dark .node-detail-overlay__close:hover {
margin: 12px 0 24px;
}
.node-detail__map-panel {
padding: 0 20px;
margin: 12px 0 24px;
}
.node-detail__map-header {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 8px;
}
.node-detail__map-header h3 {
margin: 0;
font-size: 1.1rem;
}
.node-detail__map-staging {
display: none;
}
.node-detail__map-status {
color: var(--muted);
font-size: 0.95rem;
}
.node-detail__map-slot .map-panel {
height: 220px;
border-radius: 12px;
overflow: hidden;
border: 1px solid var(--line);
}
.map-panel--embedded {
flex: none;
height: 220px;
min-height: 0;
}
.map-panel--embedded #map {
height: 220px;
border-radius: 12px;
border: none;
}
.map-panel--embedded #mapLegend {
display: none;
}
.map-panel--embedded .map-toolbar {
top: 8px;
right: 8px;
}
.node-detail__charts-grid {
display: grid;
gap: 24px;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 640px), 1fr));
grid-template-columns: repeat(auto-fit, minmax(min(100%, 1152px), 1fr));
}
.node-detail__chart {
@@ -1289,10 +1026,45 @@ body.dark .node-detail-overlay__close:hover {
font-size: 1rem;
}
.node-detail__chart svg {
.node-detail__chart-plot {
width: 100%;
height: auto;
height: clamp(240px, 50vw, 360px);
max-height: 420px;
overflow: hidden;
}
.node-detail__chart-plot .uplot {
width: 100%;
height: 100%;
margin: 0;
line-height: 0;
position: relative;
}
.node-detail__chart-plot .uplot .u-wrap,
.node-detail__chart-plot .uplot .u-under,
.node-detail__chart-plot .uplot .u-over {
top: 0;
left: 0;
}
.node-detail__chart-plot .u-axis,
.node-detail__chart-plot .u-axis .u-label,
.node-detail__chart-plot .u-axis .u-value,
.node-detail__chart-plot .u-axis text,
.node-detail__chart-plot .u-axis-label {
color: var(--muted) !important;
fill: var(--muted) !important;
font-size: 0.95rem;
}
.node-detail__chart-plot .u-grid {
stroke: rgba(12, 15, 18, 0.08);
stroke-width: 1;
}
body.dark .node-detail__chart-plot .u-grid {
stroke: rgba(255, 255, 255, 0.15);
}
.node-detail__chart-axis line {
@@ -1957,6 +1729,10 @@ input[type="radio"] {
gap: 12px;
}
.controls--full-screen {
grid-template-columns: minmax(0, 1fr) auto;
}
.controls .filter-input {
width: 100%;
}
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +1 @@
.uplot, .uplot *, .uplot *::before, .uplot *::after {box-sizing: border-box;}.uplot {font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";line-height: 1.5;width: min-content;}.u-title {text-align: center;font-size: 18px;font-weight: bold;}.u-wrap {position: relative;user-select: none;}.u-over, .u-under {position: absolute;}.u-under {overflow: hidden;}.uplot canvas {display: block;position: relative;width: 100%;height: 100%;}.u-axis {position: absolute;}.u-legend {font-size: 14px;margin: auto;text-align: center;}.u-inline {display: block;}.u-inline * {display: inline-block;}.u-inline tr {margin-right: 16px;}.u-legend th {font-weight: 600;}.u-legend th > * {vertical-align: middle;display: inline-block;}.u-legend .u-marker {width: 1em;height: 1em;margin-right: 4px;background-clip: padding-box !important;}.u-inline.u-live th::after {content: ":";vertical-align: middle;}.u-inline:not(.u-live) .u-value {display: none;}.u-series > * {padding: 4px;}.u-series th {cursor: pointer;}.u-legend .u-off > * {opacity: 0.3;}.u-select {background: rgba(0,0,0,0.07);position: absolute;pointer-events: none;}.u-cursor-x, .u-cursor-y {position: absolute;left: 0;top: 0;pointer-events: none;will-change: transform;}.u-hz .u-cursor-x, .u-vt .u-cursor-y {height: 100%;border-right: 1px dashed #607D8B;}.u-hz .u-cursor-y, .u-vt .u-cursor-x {width: 100%;border-bottom: 1px dashed #607D8B;}.u-cursor-pt {position: absolute;top: 0;left: 0;border-radius: 50%;border: 0 solid;pointer-events: none;will-change: transform;/*this has to be !important since we set inline "background" shorthand */background-clip: padding-box !important;}.u-axis.u-off, .u-select.u-off, .u-cursor-x.u-off, .u-cursor-y.u-off, .u-cursor-pt.u-off {display: none;}
+55
View File
@@ -0,0 +1,55 @@
/*
* Copyright © 2025-26 l5yth & contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { mkdir, copyFile, access } from 'node:fs/promises';
import { constants as fsConstants } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
/**
* Resolve an absolute path relative to this script location.
*
* @param {string[]} segments Path segments to append.
* @returns {string} Absolute path resolved from this script.
*/
function resolvePath(...segments) {
const scriptDir = path.dirname(fileURLToPath(import.meta.url));
return path.resolve(scriptDir, ...segments);
}
/**
* Ensure the uPlot assets are available within the public asset tree.
*
* @returns {Promise<void>} Resolves once files have been copied.
*/
async function copyUPlotAssets() {
const sourceDir = resolvePath('..', 'node_modules', 'uplot', 'dist');
const targetDir = resolvePath('..', 'public', 'assets', 'vendor', 'uplot');
const assets = ['uPlot.iife.min.js', 'uPlot.min.css'];
await access(sourceDir, fsConstants.R_OK);
await mkdir(targetDir, { recursive: true });
await Promise.all(
assets.map(async asset => {
const source = path.join(sourceDir, asset);
const target = path.join(targetDir, asset);
await copyFile(source, target);
}),
);
}
await copyUPlotAssets();
+14 -15
View File
@@ -4136,7 +4136,7 @@ RSpec.describe "Potato Mesh Sinatra app" do
end
end
it "excludes nodes whose last activity is older than a week from collection queries" do
it "excludes nodes whose last activity is older than a week" do
clear_database
allow(Time).to receive(:now).and_return(reference_time)
now = reference_time.to_i
@@ -4162,9 +4162,7 @@ RSpec.describe "Potato Mesh Sinatra app" do
expect(ids).not_to include("!stale-node")
get "/api/nodes/!stale-node"
expect(last_response).to be_ok
payload = JSON.parse(last_response.body)
expect(payload["node_id"]).to eq("!stale-node")
expect(last_response.status).to eq(404)
get "/api/nodes/!fresh-node"
expect(last_response).to be_ok
@@ -4534,7 +4532,7 @@ RSpec.describe "Potato Mesh Sinatra app" do
expect(entry["payload_b64"]).to eq("AQI=")
end
it "excludes position entries older than seven days from collection queries" do
it "excludes position entries older than seven days" do
clear_database
allow(Time).to receive(:now).and_return(reference_time)
now = reference_time.to_i
@@ -4563,7 +4561,7 @@ RSpec.describe "Potato Mesh Sinatra app" do
expect(last_response).to be_ok
filtered = JSON.parse(last_response.body)
expect(filtered.map { |row| row["id"] }).to eq([2, 1])
expect(filtered.map { |row| row["id"] }).to eq([2])
end
it "filters positions using the since parameter for both global and node queries" do
@@ -4648,11 +4646,11 @@ RSpec.describe "Potato Mesh Sinatra app" do
end
describe "GET /api/neighbors" do
it "excludes neighbor records older than twenty-eight days from collection queries" do
it "excludes neighbor records older than seven days" do
clear_database
allow(Time).to receive(:now).and_return(reference_time)
now = reference_time.to_i
stale_rx = now - (PotatoMesh::Config.trace_neighbor_window_seconds + 45)
stale_rx = now - (PotatoMesh::Config.week_seconds + 45)
fresh_rx = now - 10
with_db do |db|
@@ -4690,8 +4688,9 @@ RSpec.describe "Potato Mesh Sinatra app" do
expect(last_response).to be_ok
filtered = JSON.parse(last_response.body)
expect(filtered.length).to eq(2)
expect(filtered.map { |row| row["neighbor_id"] }).to eq(["!neighbor-new", "!neighbor-old"])
expect(filtered.length).to eq(1)
expect(filtered.first["neighbor_id"]).to eq("!neighbor-new")
expect(filtered.first["rx_time"]).to eq(fresh_rx)
end
it "honours the since parameter for neighbor queries" do
@@ -4835,7 +4834,7 @@ RSpec.describe "Potato Mesh Sinatra app" do
expect_same_value(second_entry["soil_temperature"], telemetry_metric(second_latest, "soil_temperature"))
end
it "excludes telemetry entries older than seven days from collection queries" do
it "excludes telemetry entries older than seven days" do
clear_database
allow(Time).to receive(:now).and_return(reference_time)
now = reference_time.to_i
@@ -4864,7 +4863,7 @@ RSpec.describe "Potato Mesh Sinatra app" do
expect(last_response).to be_ok
filtered = JSON.parse(last_response.body)
expect(filtered.map { |row| row["id"] }).to eq([2, 1])
expect(filtered.map { |row| row["id"] }).to eq([2])
end
it "filters telemetry rows using the since parameter for both global and node-scoped queries" do
@@ -5237,11 +5236,11 @@ RSpec.describe "Potato Mesh Sinatra app" do
expect(JSON.parse(last_response.body)).to eq([])
end
it "excludes traces older than twenty-eight days" do
it "excludes traces older than one week" do
clear_database
now = Time.now.to_i
recent_rx = now - (PotatoMesh::Config.trace_neighbor_window_seconds / 2)
stale_rx = now - (PotatoMesh::Config.trace_neighbor_window_seconds + 60)
recent_rx = now - (PotatoMesh::Config.week_seconds / 2)
stale_rx = now - (PotatoMesh::Config.week_seconds + 60)
payload = [
{ "id" => 50_001, "src" => 1, "dest" => 2, "rx_time" => recent_rx, "metrics" => {} },
{ "id" => 50_002, "src" => 3, "dest" => 4, "rx_time" => stale_rx, "metrics" => {} },
+3 -1
View File
@@ -13,12 +13,14 @@
See the License for the specific language governing permissions and
limitations under the License.
-->
<link rel="stylesheet" href="/assets/vendor/uplot/uPlot.min.css" />
<script src="/assets/vendor/uplot/uPlot.iife.min.js" defer></script>
<section class="charts-page">
<header class="charts-page__intro">
<h2>Network telemetry trends</h2>
<p>Aggregated telemetry snapshots from every node in the past week.</p>
</header>
<div id="chartsPage" class="charts-page__content">
<div id="chartsPage" class="charts-page__content" data-telemetry-root="true">
<p class="charts-page__status">Loading aggregated telemetry charts…</p>
</div>
</section>
+1 -1
View File
@@ -16,7 +16,7 @@
<section class="federation-page federation-page--full-width">
<div class="federation-page__content">
<div class="federation-page__map-row">
<%= erb :"shared/_map_panel", locals: { full_screen: true, legend_collapsed: true } %>
<%= erb :"shared/_map_panel", locals: { full_screen: true } %>
</div>
<%= erb :"shared/_instances_table" %>
</div>
+16 -64
View File
@@ -75,19 +75,16 @@
main_classes = ["page-main"]
main_classes << "page-main--dashboard" if view_mode == :dashboard
main_classes << "page-main--full-screen" if full_screen_view
show_header = true
show_header = !full_screen_view
show_meta_info = true
show_auto_refresh_controls = view_mode != :federation
show_auto_fit_toggle = %i[dashboard map].include?(view_mode)
map_zoom_override = defined?(map_zoom) ? map_zoom : nil
show_info_button = true
show_info_button = !full_screen_view
show_footer = !full_screen_view
show_filter_input = !%i[node_detail charts federation].include?(view_mode)
show_auto_refresh_toggle = show_auto_refresh_controls
show_refresh_actions = show_auto_refresh_controls || view_mode == :federation
nodes_nav_href = "/nodes"
nodes_nav_active = %i[nodes node_detail].include?(view_mode)
federation_nav_enabled = !private_mode && federation_enabled
controls_classes = ["controls"]
controls_classes << "controls--full-screen" if full_screen_view
refresh_row_classes = ["refresh-row"]
@@ -104,69 +101,24 @@
<div class="<%= shell_classes.join(" ") %>">
<% if show_header %>
<header class="site-header">
<div class="site-header__left<%= federation_nav_enabled ? " site-header__left--federation" : "" %>">
<h1 class="site-title">
<img src="/potatomesh-logo.svg" alt="" aria-hidden="true" />
<span class="site-title-text"><%= site_name %></span>
</h1>
<% if federation_nav_enabled %>
<div class="header-federation">
<div class="instance-selector">
<label class="visually-hidden" for="instanceSelect">Select a region</label>
<select id="instanceSelect" class="instance-select" aria-label="Select instance region">
<option value=""><%= Rack::Utils.escape_html("Select region ...") %></option>
</select>
</div>
<h1 class="site-title">
<img src="/potatomesh-logo.svg" alt="" aria-hidden="true" />
<span class="site-title-text"><%= site_name %></span>
</h1>
<% if !private_mode && federation_enabled %>
<div class="header-federation">
<div class="instance-selector">
<label class="visually-hidden" for="instanceSelect">Select a region</label>
<select id="instanceSelect" class="instance-select" aria-label="Select instance region">
<option value=""><%= Rack::Utils.escape_html("Select region ...") %></option>
</select>
</div>
<% end %>
</div>
<div class="site-header__right">
<nav class="site-nav" aria-label="Primary">
<a href="/" class="site-nav__link<%= view_mode == :dashboard ? " is-active" : "" %>"<%= view_mode == :dashboard ? ' aria-current="page"' : "" %>>Dashboard</a>
<a href="/map" class="site-nav__link<%= view_mode == :map ? " is-active" : "" %>"<%= view_mode == :map ? ' aria-current="page"' : "" %>>Map</a>
<a href="/chat" class="site-nav__link<%= view_mode == :chat ? " is-active" : "" %>"<%= view_mode == :chat ? ' aria-current="page"' : "" %>>Chat</a>
<a href="<%= nodes_nav_href %>" class="site-nav__link<%= nodes_nav_active ? " is-active" : "" %>"<%= nodes_nav_active ? ' aria-current="page"' : "" %>>Nodes</a>
<a href="/charts" class="site-nav__link<%= view_mode == :charts ? " is-active" : "" %>"<%= view_mode == :charts ? ' aria-current="page"' : "" %>>Charts</a>
<% if federation_nav_enabled %>
<a href="/federation" class="site-nav__link<%= view_mode == :federation ? " is-active" : "" %>"<%= view_mode == :federation ? ' aria-current="page"' : "" %>>Federation</a>
<% end %>
</nav>
<button
id="mobileMenuToggle"
class="icon-button menu-toggle"
type="button"
aria-label="Open navigation menu"
aria-expanded="false"
aria-controls="mobileMenu"
>
<span aria-hidden="true">☰</span>
</button>
</div>
</header>
<div id="mobileMenu" class="mobile-menu" hidden>
<div class="mobile-menu__backdrop" data-mobile-menu-close></div>
<div class="mobile-menu__panel" role="dialog" aria-modal="true" aria-labelledby="mobileMenuTitle" tabindex="-1">
<div class="mobile-menu__header">
<h2 id="mobileMenuTitle" class="mobile-menu__title">Menu</h2>
<button class="icon-button mobile-menu__close" type="button" data-mobile-menu-close aria-label="Close navigation menu">
<span aria-hidden="true">×</span>
</button>
</div>
<nav class="mobile-nav" aria-label="Mobile">
<a href="/" class="mobile-nav__link<%= view_mode == :dashboard ? " is-active" : "" %>"<%= view_mode == :dashboard ? ' aria-current="page"' : "" %>>Dashboard</a>
<a href="/map" class="mobile-nav__link<%= view_mode == :map ? " is-active" : "" %>"<%= view_mode == :map ? ' aria-current="page"' : "" %>>Map</a>
<a href="/chat" class="mobile-nav__link<%= view_mode == :chat ? " is-active" : "" %>"<%= view_mode == :chat ? ' aria-current="page"' : "" %>>Chat</a>
<a href="<%= nodes_nav_href %>" class="mobile-nav__link<%= nodes_nav_active ? " is-active" : "" %>"<%= nodes_nav_active ? ' aria-current="page"' : "" %>>Nodes</a>
<a href="/charts" class="mobile-nav__link<%= view_mode == :charts ? " is-active" : "" %>"<%= view_mode == :charts ? ' aria-current="page"' : "" %>>Charts</a>
<% if federation_nav_enabled %>
<a href="/federation" class="mobile-nav__link<%= view_mode == :federation ? " is-active" : "" %>"<%= view_mode == :federation ? ' aria-current="page"' : "" %>>Federation</a>
<% end %>
</nav>
</div>
</div>
<% end %>
</header>
<% end %>
<div id="metaRow" class="row meta">
<div class="row meta">
<% if show_meta_info %>
<div class="meta-info">
<div class="<%= refresh_row_classes.join(" ") %>">
+3 -3
View File
@@ -17,11 +17,14 @@
short_display = node_page_short_name || "Loading"
long_display = node_page_long_name
identifier_display = node_page_identifier || "" %>
<link rel="stylesheet" href="/assets/vendor/uplot/uPlot.min.css" />
<script src="/assets/vendor/uplot/uPlot.iife.min.js" defer></script>
<section
id="nodeDetail"
class="node-detail"
data-node-reference="<%= Rack::Utils.escape_html(reference_json) %>"
data-private-mode="<%= private_mode ? "true" : "false" %>"
data-telemetry-root="true"
>
<header class="node-detail__header">
<h2 class="node-detail__title">
@@ -39,9 +42,6 @@
<p class="node-detail__noscript">This page requires JavaScript to display node information.</p>
</noscript>
</section>
<div class="node-detail__map-staging" aria-hidden="true">
<%= erb :"shared/_map_panel", locals: { full_screen: false, legend_collapsed: true } %>
</div>
<script type="module">
import { initializeNodeDetailPage } from '/assets/js/app/node-page.js';
initializeNodeDetailPage();
+1 -1
View File
@@ -13,7 +13,7 @@
See the License for the specific language governing permissions and
limitations under the License.
-->
<div id="nodes-table" class="nodes-table-wrapper">
<div class="nodes-table-wrapper">
<table id="nodes">
<thead>
<tr>