view.rs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. use crate::model::NodeInfo;
  2. use std::collections::{HashMap, HashSet};
  3. use tui::widgets::ListState;
  4. #[derive(Clone)]
  5. pub struct View {
  6. pub id_list: IdListView,
  7. pub info_list: InfoListView,
  8. }
  9. impl View {
  10. pub fn new(id_list: IdListView, info_list: InfoListView) -> View {
  11. View { id_list, info_list }
  12. }
  13. pub fn update(&mut self, infos: HashMap<String, NodeInfo>) {
  14. for (id, info) in infos.clone() {
  15. self.id_list.node_id.insert(id.clone());
  16. self.info_list.infos.insert(id, info);
  17. }
  18. }
  19. }
  20. #[derive(Clone)]
  21. pub struct IdListView {
  22. pub state: ListState,
  23. pub node_id: HashSet<String>,
  24. }
  25. impl IdListView {
  26. pub fn new(node_id: HashSet<String>) -> IdListView {
  27. IdListView { state: ListState::default(), node_id }
  28. }
  29. pub fn next(&mut self) {
  30. let i = match self.state.selected() {
  31. Some(i) => {
  32. if i >= self.node_id.len() - 1 {
  33. 0
  34. } else {
  35. i + 1
  36. }
  37. }
  38. None => 0,
  39. };
  40. self.state.select(Some(i));
  41. }
  42. pub fn previous(&mut self) {
  43. let i = match self.state.selected() {
  44. Some(i) => {
  45. if i == 0 {
  46. self.node_id.len() - 1
  47. } else {
  48. i - 1
  49. }
  50. }
  51. None => 0,
  52. };
  53. self.state.select(Some(i));
  54. }
  55. pub fn unselect(&mut self) {
  56. self.state.select(None);
  57. }
  58. }
  59. #[derive(Clone)]
  60. pub struct InfoListView {
  61. pub index: usize,
  62. pub infos: HashMap<String, NodeInfo>,
  63. }
  64. impl InfoListView {
  65. pub fn new(infos: HashMap<String, NodeInfo>) -> InfoListView {
  66. let index = 0;
  67. InfoListView { index, infos }
  68. }
  69. pub async fn next(&mut self) {
  70. self.index = (self.index + 1) % self.infos.len();
  71. }
  72. pub async fn previous(&mut self) {
  73. if self.index > 0 {
  74. self.index -= 1;
  75. } else {
  76. self.index = self.infos.len() - 1;
  77. }
  78. }
  79. }