Explorar el Código

map: simplify and refactor

lunar-mining hace 4 años
padre
commit
7637c8e872
Se han modificado 8 ficheros con 182 adiciones y 91 borrados
  1. 13 0
      Cargo.lock
  2. 2 0
      bin/map/Cargo.toml
  3. 16 40
      bin/map/src/app.rs
  4. 22 8
      bin/map/src/main.rs
  5. 72 0
      bin/map/src/node.rs
  6. 13 8
      bin/map/src/notes/list.rs
  7. 2 2
      bin/map/src/types.rs
  8. 42 33
      bin/map/src/ui.rs

+ 13 - 0
Cargo.lock

@@ -2811,6 +2811,19 @@ dependencies = [
 ]
 
 [[package]]
+<<<<<<< HEAD
+=======
+name = "map"
+version = "0.3.0"
+dependencies = [
+ "rand 0.6.5",
+ "smol",
+ "termion",
+ "tui",
+]
+
+[[package]]
+>>>>>>> 4ca0ed7 (map: simplify and refactor)
 name = "matches"
 version = "0.1.9"
 source = "registry+https://github.com/rust-lang/crates.io-index"

+ 2 - 0
bin/map/Cargo.toml

@@ -11,3 +11,5 @@ edition = "2021"
 # Misc
 termion = "1.5.6"
 tui = "0.16.0"
+smol = "1.2.4"
+rand = "0.6.5"

+ 16 - 40
bin/map/src/app.rs

@@ -1,9 +1,10 @@
 use crate::{
-    info::InfoScreen,
+    node::{NodeId, NodeInfo},
     list::StatefulList,
-    types::{NodeId, NodeInfo},
 };
-use std::collections::HashMap;
+use rand::Rng;
+use smol::Timer;
+use std::{collections::HashMap, time::Duration};
 
 // the information here should be continually updating
 // nodes are added from the result of rpc requests
@@ -11,49 +12,24 @@ use std::collections::HashMap;
 #[derive(Clone)]
 pub struct App {
     pub node_list: StatefulList,
+    pub node_info: NodeInfo,
 }
 
 impl App {
     pub fn new() -> App {
-        let mut hashmap: HashMap<NodeId, NodeInfo> = HashMap::new();
-
-        let node_id = Self::get_node_id();
-        let node_info = Self::get_node_info();
-
-        // TODO: fix this
-        for id in node_id.iter() {
-            for info in node_info.iter() {
-                hashmap.insert(id.to_string(), info.to_string());
-            }
-        }
-
-        let node_info = InfoScreen::new();
-        App { node_list: StatefulList::new(hashmap, node_info) }
-    }
-
-    fn get_node_id() -> Vec<String> {
-        let mut node_list = Vec::new();
-        for num in 1..100 {
-            let new_nodes = format!("\nNode {}\n", num);
-            node_list.push(new_nodes);
-        }
-        node_list
+        let node_info = NodeInfo::new();
+        let node_id = NodeId::new();
+        let node_list = StatefulList::new(node_id);
+        App { node_list, node_info }
     }
 
-    fn get_node_info() -> Vec<String> {
-        let mut node_info = Vec::new();
-        for _num in 1..100 {
-            //let new_info = format!("\nConnections: {}\n", num);
-            let new_info = "";
-            node_info.push(new_info.to_string());
-        }
-        node_info
-    }
-
-    // every 5 seconds
     // TODO: implement this
-    //fn update(&mut self) {
-    //    let node = self.node.remove(0);
-    //    self.nodes.push(node);
+    //async fn sleep(self, dur: Duration) {
+    //    Timer::after(dur).await;
+    //}
+
+    //pub async fn update(mut self) {
+    //    self.node_list.nodes.insert("New node joined".to_string(), "".to_string());
+    //    //self.sleep(Duration::from_secs(2)).await;
     //}
 }

+ 22 - 8
bin/map/src/main.rs

@@ -1,3 +1,10 @@
+// next/ prev:
+//      select_node(i)
+//      NodeInfo
+//          set-content(node_info)
+//              clear current text
+//              let text = ...
+
 use std::{
     io,
     io::Read,
@@ -10,7 +17,7 @@ use tui::{
 };
 
 pub mod app;
-pub mod info;
+pub mod node;
 pub mod list;
 pub mod types;
 pub mod ui;
@@ -47,10 +54,10 @@ fn run_app<B: Backend>(
 
     terminal.clear()?;
 
-    let mut last_tick = Instant::now();
-
     app.node_list.state.select(Some(0));
 
+    let mut last_tick = Instant::now();
+
     loop {
         terminal.draw(|f| ui::ui(f, &mut app))?;
 
@@ -60,14 +67,21 @@ fn run_app<B: Backend>(
                     terminal.clear()?;
                     return Ok(())
                 }
-                Key::Char('j') => app.node_list.next(),
-                Key::Char('k') => app.node_list.previous(),
+                Key::Char('j') => {
+                    app.node_list.next();
+                    app.node_info.next();
+                }
+                Key::Char('k') => {
+                    app.node_list.previous();
+                    app.node_info.previous();
+                }
                 _ => (),
             }
         }
 
-        if last_tick.elapsed() >= tick_rate {
-            last_tick = Instant::now();
-        }
+        //if last_tick.elapsed() >= tick_rate {
+        //    app.clone().update();
+        //    last_tick = Instant::now();
+        //}
     }
 }

+ 72 - 0
bin/map/src/node.rs

@@ -0,0 +1,72 @@
+use rand::Rng;
+
+#[derive(Clone)]
+pub struct NodeInfo {
+    pub info: Vec<String>,
+    pub index: usize,
+}
+
+impl NodeInfo {
+    pub fn new() -> NodeInfo {
+        let info = Self::make_info();
+        let index = 0;
+        NodeInfo { info, index }
+    }
+
+    // set content
+    fn make_info() -> Vec<String> {
+        let mut node_info = Vec::new();
+        for num in 1..3 {
+            let new_info = format!(
+                "Connections: {}
+                                   ",
+                num
+            );
+            node_info.push(new_info.to_string());
+        }
+        node_info
+    }
+
+    pub fn next(&mut self) {
+        self.index = (self.index + 1) % self.info.len();
+    }
+
+    pub fn previous(&mut self) {
+        if self.index > 0 {
+            self.index -= 1;
+        } else {
+            self.index = self.info.len() - 1;
+        }
+    }
+}
+
+#[derive(Clone)]
+pub struct NodeId {
+    pub id: Vec<String>,
+}
+
+impl NodeId {
+    pub fn new() -> NodeId {
+        let id = Self::get_node_id();
+        NodeId { id }
+    }
+    fn get_node_id() -> Vec<String> {
+        let mut node_list = Vec::new();
+        for num in 1..10 {
+            let mut rng = rand::thread_rng();
+            let new_nodes = format!("Node: {}", rng.gen::<u32>());
+            node_list.push(new_nodes);
+        }
+        node_list
+    }
+}
+
+// fn get_node_info() -> Vec<String> {
+//     let mut node_info = Vec::new();
+//     for _num in 1..100 {
+//         //let new_info = format!("\nConnections: {}\n", num);
+//         let new_info = "";
+//         node_info.push(new_info.to_string());
+//     }
+//     node_info
+// }

+ 13 - 8
bin/map/src/list.rs → bin/map/src/notes/list.rs

@@ -1,26 +1,31 @@
 use crate::{
-    info::InfoScreen,
-    types::{NodeId, NodeInfo},
+    info::{NodeId, NodeInfo},
+    ui::render_selected,
 };
 use std::collections::HashMap;
 use tui::widgets::ListState;
 
+// TODO: make this just a list
+// hashmaps are owned by App
 #[derive(Clone)]
 pub struct StatefulList {
     pub state: ListState,
-    pub nodes: HashMap<NodeId, NodeInfo>,
-    pub node_info: InfoScreen,
+    pub nodes: NodeId,
+    //pub nodes: HashMap<NodeId, NodeInfo>,
+    //pub node_info: NodeInfo,
+    //pub index: HashMap<usize, NodeInfo>,
+    //pub node_info: InfoScreen,
 }
 
 impl StatefulList {
-    pub fn new(nodes: HashMap<NodeId, NodeInfo>, node_info: InfoScreen) -> StatefulList {
-        StatefulList { state: ListState::default(), nodes, node_info }
+    pub fn new(nodes: NodeId) -> StatefulList {
+        StatefulList { state: ListState::default(), nodes }
     }
 
     pub fn next(&mut self) {
         let i = match self.state.selected() {
             Some(i) => {
-                if i >= self.nodes.len() - 1 {
+                if i >= self.nodes.id.len() - 1 {
                     0
                 } else {
                     i + 1
@@ -35,7 +40,7 @@ impl StatefulList {
         let i = match self.state.selected() {
             Some(i) => {
                 if i == 0 {
-                    self.nodes.len() - 1
+                    self.nodes.id.len() - 1
                 } else {
                     i - 1
                 }

+ 2 - 2
bin/map/src/types.rs

@@ -1,2 +1,2 @@
-pub type NodeId = String;
-pub type NodeInfo = String;
+//pub type NodeId = String;
+//pub type NodeInfo = String;

+ 42 - 33
bin/map/src/ui.rs

@@ -1,63 +1,72 @@
-// first one selected
-
-// list on left
-// info page on right
-// when selected takes up full page
-// identifier is random string
-//
-// event handler for the list
-// when the list is selected
-// updates a hashmap that keep track of selected??
-
-use crate::app::App;
+use crate::{
+    app::App,
+    node::{NodeId, NodeInfo},
+};
 use tui::{
     backend::Backend,
     layout::{Constraint, Direction, Layout},
     style::{Color, Modifier, Style},
     text::Spans,
-    widgets::{Block, List, ListItem},
+    widgets::{Block, Borders, List, ListItem, Paragraph},
     Frame,
 };
 
+// pass node info
 pub fn ui<B: Backend>(f: &mut Frame<B>, app: &mut App) {
     let slice = Layout::default()
         .direction(Direction::Horizontal)
-        .margin(1)
+        .margin(2)
         .constraints([Constraint::Percentage(50), Constraint::Percentage(50)].as_ref())
         .split(f.size());
 
     let nodes: Vec<ListItem> = app
         .node_list
         .nodes
+        .id
         .iter()
-        .map(|(id, info)| {
+        .map(|(id)| {
             let line1 = Spans::from(id.to_string());
-            let line2 = Spans::from(info.to_string());
-
-            ListItem::new(vec![line1, line2]).style(Style::default())
+            ListItem::new(vec![line1]).style(Style::default())
         })
         .collect();
 
     let nodes = List::new(nodes)
-        .block(Block::default())
+        .block(Block::default().borders(Borders::ALL))
         .highlight_style(Style::default().fg(Color::LightCyan).add_modifier(Modifier::BOLD));
 
     f.render_stateful_widget(nodes, slice[0], &mut app.node_list.state);
 
-    let node_info: Vec<ListItem> = app
-        .node_list
-        .node_info
-        .info
-        .iter()
-        .map(|i| {
-            let line1 = Spans::from(i.to_string());
-            ListItem::new(vec![line1]).style(Style::default())
-        })
-        .collect();
+    // TODO render node info as box
+    //let node_info: Vec<ListItem> = app
+    //    .node_list
+    //    .node_info
+    //    .info
+    //    .iter()
+    //    .map(|i| {
+    //        let line1 = Spans::from(i.to_string());
+    //        ListItem::new(vec![line1]).style(Style::default())
+    //    })
+    //    .collect();
 
-    let node_info = List::new(node_info)
-        .block(Block::default())
-        .highlight_style(Style::default().fg(Color::LightCyan).add_modifier(Modifier::BOLD));
+    //let node_info = List::new(node_info)
+    //    .block(Block::default().borders(Borders::ALL))
+    //    .highlight_style(Style::default().fg(Color::LightCyan).add_modifier(Modifier::BOLD));
+
+    //f.render_stateful_widget(node_info, slice[1], &mut app.node_list.state);
+}
+
+// TODO: rename to frame2
+pub fn render_selected(n: &NodeInfo) {
+    //let slice = Layout::default()
+    //    .direction(Direction::Horizontal)
+    //    .margin(2)
+    //    .constraints([Constraint::Percentage(50), Constraint::Percentage(50)].as_ref())
+    //    .split(f.size());
+
+    let text: Vec<Spans> = n.info.iter().map(|i| Spans::from(i.to_string())).collect();
+    let graph = Paragraph::new(text)
+        .block(Block::default().borders(Borders::ALL))
+        .style(Style::default().fg(Color::LightCyan).add_modifier(Modifier::BOLD));
 
-    f.render_stateful_widget(node_info, slice[1], &mut app.node_list.state);
+    //f.render_widget(graph, slice[1]);
 }