use std::collections::BTreeSet;
use super::Query;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum LinkMode {
#[default]
Highlight,
Filter,
Isolate,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct LinkSelection {
pub rows: BTreeSet<usize>,
pub source: Option<String>,
pub predicate: Option<String>,
}
impl LinkSelection {
pub fn is_empty(&self) -> bool {
self.rows.is_empty() && self.predicate.is_none()
}
pub fn contains(&self, row: usize) -> bool {
self.rows.contains(&row)
}
}
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct LinkHub {
pub key: String,
pub selection: LinkSelection,
pub mode: LinkMode,
revision: u64,
}
impl LinkHub {
pub fn new(key: impl Into<String>) -> Self {
Self {
key: key.into(),
selection: LinkSelection::default(),
mode: LinkMode::Highlight,
revision: 0,
}
}
pub fn set_rows(&mut self, rows: impl IntoIterator<Item = usize>, source: impl Into<String>) {
self.selection = LinkSelection {
rows: rows.into_iter().collect(),
source: Some(source.into()),
predicate: None,
};
self.revision += 1;
}
pub fn set_predicate(
&mut self,
predicate: impl Into<String>,
rows: impl IntoIterator<Item = usize>,
source: impl Into<String>,
) {
self.selection = LinkSelection {
rows: rows.into_iter().collect(),
source: Some(source.into()),
predicate: Some(predicate.into()),
};
self.revision += 1;
}
pub fn clear(&mut self) {
if !self.selection.is_empty() {
self.selection = LinkSelection::default();
self.revision += 1;
}
}
pub fn selection(&self) -> &LinkSelection {
&self.selection
}
pub fn mode(&self) -> LinkMode {
self.mode
}
pub fn set_mode(&mut self, mode: LinkMode) {
if mode != self.mode {
self.mode = mode;
self.revision += 1;
}
}
pub fn revision(&self) -> u64 {
self.revision
}
pub fn rows_for(&self, data: &super::Dataset, predicate: &str) -> Option<Vec<usize>> {
Query::parse(predicate).ok().map(|query| query.matching_rows(data))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn selections_and_modes_bump_the_revision() {
let mut hub = LinkHub::new("trace.csv");
assert!(hub.selection().is_empty());
hub.set_rows([1, 3], "plot");
assert!(hub.selection().contains(3));
assert_eq!(hub.selection().source.as_deref(), Some("plot"));
assert!(hub.revision() > 0);
hub.set_mode(LinkMode::Filter);
assert_eq!(hub.mode(), LinkMode::Filter);
hub.clear();
assert!(hub.selection().is_empty());
}
}