Skip to main content

crisol_core/data/
link.rs

1//! A selection bus shared by a table, one or more plots, and a grid.
2//!
3//! Each [`LinkHub`] belongs to one dataset. Views publish row sets or a predicate and
4//! read the current selection; the mode says whether other views highlight, filter, or
5//! isolate the selected rows.
6
7use std::collections::BTreeSet;
8
9use super::Query;
10
11/// How linked views react to a selection.
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
13#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
14#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
15#[non_exhaustive]
16/// # Example
17///
18/// ```
19/// use crisol_core::data::LinkMode;
20/// ```
21pub enum LinkMode {
22    /// Draw selected rows with emphasis, keep the rest visible.
23    #[default]
24    Highlight,
25    /// Hide rows that are not selected.
26    Filter,
27    /// Show only the selected rows.
28    Isolate,
29}
30
31/// One selection in a dataset.
32#[derive(Clone, Debug, Default, PartialEq, Eq)]
33#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
34#[non_exhaustive]
35/// # Example
36///
37/// ```
38/// use crisol_core::data::LinkSelection;
39/// ```
40pub struct LinkSelection {
41    /// Selected row indices.
42    pub rows: BTreeSet<usize>,
43    /// The view that published the selection.
44    pub source: Option<String>,
45    /// A predicate used by a plot brush, preserved for a table filter.
46    pub predicate: Option<String>,
47}
48
49impl LinkSelection {
50    /// Whether no rows are selected.
51    pub fn is_empty(&self) -> bool {
52        self.rows.is_empty() && self.predicate.is_none()
53    }
54
55    /// Whether a row is selected.
56    pub fn contains(&self, row: usize) -> bool {
57        self.rows.contains(&row)
58    }
59}
60
61/// The selection bus for one dataset.
62#[derive(Clone, Debug)]
63#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
64#[non_exhaustive]
65/// # Example
66///
67/// ```
68/// use crisol_core::data::LinkHub;
69/// ```
70pub struct LinkHub {
71    /// Dataset key, such as a path or a document id.
72    pub key: String,
73    /// Current selection.
74    pub selection: LinkSelection,
75    /// How views react.
76    pub mode: LinkMode,
77    revision: u64,
78}
79
80impl LinkHub {
81    /// A hub with an empty selection.
82    pub fn new(key: impl Into<String>) -> Self {
83        Self {
84            key: key.into(),
85            selection: LinkSelection::default(),
86            mode: LinkMode::Highlight,
87            revision: 0,
88        }
89    }
90
91    /// Replace the selection with rows.
92    pub fn set_rows(&mut self, rows: impl IntoIterator<Item = usize>, source: impl Into<String>) {
93        self.selection = LinkSelection {
94            rows: rows.into_iter().collect(),
95            source: Some(source.into()),
96            predicate: None,
97        };
98        self.revision += 1;
99    }
100
101    /// Replace the selection with a predicate and the rows it matches.
102    pub fn set_predicate(
103        &mut self,
104        predicate: impl Into<String>,
105        rows: impl IntoIterator<Item = usize>,
106        source: impl Into<String>,
107    ) {
108        self.selection = LinkSelection {
109            rows: rows.into_iter().collect(),
110            source: Some(source.into()),
111            predicate: Some(predicate.into()),
112        };
113        self.revision += 1;
114    }
115
116    /// Clear the selection.
117    pub fn clear(&mut self) {
118        if !self.selection.is_empty() {
119            self.selection = LinkSelection::default();
120            self.revision += 1;
121        }
122    }
123
124    /// The current selection.
125    pub fn selection(&self) -> &LinkSelection {
126        &self.selection
127    }
128
129    /// The mode.
130    pub fn mode(&self) -> LinkMode {
131        self.mode
132    }
133
134    /// Change the mode.
135    pub fn set_mode(&mut self, mode: LinkMode) {
136        if mode != self.mode {
137            self.mode = mode;
138            self.revision += 1;
139        }
140    }
141
142    /// A revision that changes with the selection or the mode.
143    pub fn revision(&self) -> u64 {
144        self.revision
145    }
146
147    /// Rows matching `predicate` in `data`, for a table or plot brush.
148    pub fn rows_for(&self, data: &super::Dataset, predicate: &str) -> Option<Vec<usize>> {
149        Query::parse(predicate).ok().map(|query| query.matching_rows(data))
150    }
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156
157    #[test]
158    fn selections_and_modes_bump_the_revision() {
159        let mut hub = LinkHub::new("trace.csv");
160        assert!(hub.selection().is_empty());
161        hub.set_rows([1, 3], "plot");
162        assert!(hub.selection().contains(3));
163        assert_eq!(hub.selection().source.as_deref(), Some("plot"));
164        assert!(hub.revision() > 0);
165        hub.set_mode(LinkMode::Filter);
166        assert_eq!(hub.mode(), LinkMode::Filter);
167        hub.clear();
168        assert!(hub.selection().is_empty());
169    }
170}