Skip to main content

promkit_widgets/jsonstream/
jsonstream.rs

1use super::jsonz::{self, Row, RowOperation};
2
3/// Represents a stream of JSON data, allowing for efficient navigation and manipulation.
4#[derive(Clone)]
5pub struct JsonStream {
6    rows: Vec<Row>,
7    position: usize,
8}
9
10impl JsonStream {
11    pub fn new<'a, I: IntoIterator<Item = &'a serde_json::Value>>(iter: I) -> Self {
12        Self {
13            rows: jsonz::create_rows(iter),
14            position: 0,
15        }
16    }
17}
18
19impl JsonStream {
20    /// Returns a reference to the underlying vector of rows.
21    pub fn rows(&self) -> &[Row] {
22        &self.rows
23    }
24
25    /// Extracts a specified number of rows from the current position in JSON stream.
26    pub fn extract_rows_from_current(&self, n: usize) -> Vec<Row> {
27        self.rows.extract(self.position, n)
28    }
29
30    /// Toggles the visibility of a node at the cursor's current position.
31    pub fn toggle(&mut self) {
32        let index = self.rows.toggle(self.position);
33        self.position = index;
34    }
35
36    /// Sets the visibility of all rows in JSON stream.
37    pub fn set_nodes_visibility(&mut self, collapsed: bool) {
38        self.rows.set_rows_visibility(collapsed);
39        self.position = 0;
40    }
41
42    /// Moves the cursor backward through JSON stream.
43    pub fn up(&mut self) -> bool {
44        let index = self.rows.up(self.position);
45        let ret = index != self.position;
46        self.position = index;
47        ret
48    }
49
50    /// Moves the cursor to the head position in JSON stream.
51    pub fn head(&mut self) -> bool {
52        self.position = self.rows.head();
53        true
54    }
55
56    /// Moves the cursor forward through JSON stream.
57    pub fn down(&mut self) -> bool {
58        let index = self.rows.down(self.position);
59        let ret = index != self.position;
60        self.position = index;
61        ret
62    }
63
64    /// Moves the cursor to the last position in JSON stream.
65    pub fn tail(&mut self) -> bool {
66        self.position = self.rows.tail();
67        true
68    }
69}