Skip to main content

lichtung_plot/spec/
facet.rs

1//! Closed generic-facet layouts.
2
3use crate::{CategoryValues, Error};
4
5/// Numeric-axis sharing policy for generic facet panels.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
7pub enum FacetScales {
8    /// Share both numeric axes where applicable.
9    #[default]
10    Fixed,
11    /// Resolve the x axis independently per panel.
12    FreeX,
13    /// Resolve the y axis independently per panel.
14    FreeY,
15    /// Resolve both axes independently per panel.
16    Free,
17}
18
19/// One complete generic-facet layout and numeric-axis sharing policy.
20///
21/// A facet is either a row, a column, a row-by-column grid, or one wrapped
22/// categorical dimension. Mixed grid and wrap layouts are not representable,
23/// and numeric axes are fixed unless [`Self::scales`] selects otherwise.
24#[derive(Debug, Clone)]
25pub struct FacetSpec {
26    layout: FacetLayout,
27    scales: FacetScales,
28}
29
30#[derive(Debug, Clone)]
31enum FacetLayout {
32    Row(CategoryValues),
33    Column(CategoryValues),
34    Grid {
35        row: CategoryValues,
36        column: CategoryValues,
37    },
38    Wrap {
39        values: CategoryValues,
40        columns: usize,
41    },
42}
43
44impl FacetSpec {
45    /// Split the plot into rows by one categorical dimension.
46    #[must_use]
47    pub fn row(values: CategoryValues) -> Self {
48        Self {
49            layout: FacetLayout::Row(values),
50            scales: FacetScales::Fixed,
51        }
52    }
53
54    /// Split the plot into columns by one categorical dimension.
55    #[must_use]
56    pub fn column(values: CategoryValues) -> Self {
57        Self {
58            layout: FacetLayout::Column(values),
59            scales: FacetScales::Fixed,
60        }
61    }
62
63    /// Split the plot into a row-by-column grid.
64    pub fn grid(row: CategoryValues, column: CategoryValues) -> Result<Self, Error> {
65        if row.name() == column.name() {
66            return Err(Error::Data(
67                "facet grid row and column must use different columns".into(),
68            ));
69        }
70        Ok(Self {
71            layout: FacetLayout::Grid { row, column },
72            scales: FacetScales::Fixed,
73        })
74    }
75
76    /// Wrap one categorical dimension into a positive number of columns.
77    pub fn wrap(values: CategoryValues, columns: usize) -> Result<Self, Error> {
78        if columns == 0 {
79            return Err(Error::Data(
80                "facet wrap columns must be greater than zero".into(),
81            ));
82        }
83        Ok(Self {
84            layout: FacetLayout::Wrap { values, columns },
85            scales: FacetScales::Fixed,
86        })
87    }
88
89    /// Configure whether facet panels share numeric axes.
90    #[must_use]
91    pub const fn scales(mut self, scales: FacetScales) -> Self {
92        self.scales = scales;
93        self
94    }
95
96    pub(crate) fn matches_original_cell(
97        &self,
98        panel: &crate::layout::FacetCell,
99        authored: &crate::layout::FacetCell,
100    ) -> bool {
101        self.original_cell(panel).as_ref() == Some(authored)
102    }
103
104    /// Convert a prepared renderer occurrence to its complete original keys.
105    pub(crate) fn original_cell(
106        &self,
107        panel: &crate::layout::FacetCell,
108    ) -> Option<crate::layout::FacetCell> {
109        use crate::layout::FacetCell;
110        if let Some((row, column)) = panel.grid_levels() {
111            return Some(FacetCell::grid(
112                self.row_values()?.key_for_level(row)?,
113                self.column_values()?.key_for_level(column)?,
114            ));
115        }
116        let level = panel.single_level()?;
117        let mut fields = self.values();
118        let field = fields.next()?;
119        if fields.next().is_some() {
120            return None;
121        }
122        Some(FacetCell::single(field.key_for_level(level)?))
123    }
124
125    pub(crate) const fn scale_policy(&self) -> FacetScales {
126        self.scales
127    }
128
129    pub(crate) const fn row_values(&self) -> Option<&CategoryValues> {
130        match &self.layout {
131            FacetLayout::Row(values) | FacetLayout::Grid { row: values, .. } => Some(values),
132            FacetLayout::Column(_) | FacetLayout::Wrap { .. } => None,
133        }
134    }
135
136    pub(crate) const fn column_values(&self) -> Option<&CategoryValues> {
137        match &self.layout {
138            FacetLayout::Column(values) | FacetLayout::Grid { column: values, .. } => Some(values),
139            FacetLayout::Row(_) | FacetLayout::Wrap { .. } => None,
140        }
141    }
142
143    pub(crate) const fn wrap_values(&self) -> Option<&CategoryValues> {
144        match &self.layout {
145            FacetLayout::Wrap { values, .. } => Some(values),
146            FacetLayout::Row(_) | FacetLayout::Column(_) | FacetLayout::Grid { .. } => None,
147        }
148    }
149
150    pub(crate) const fn wrap_columns(&self) -> Option<usize> {
151        match &self.layout {
152            FacetLayout::Wrap { columns, .. } => Some(*columns),
153            FacetLayout::Row(_) | FacetLayout::Column(_) | FacetLayout::Grid { .. } => None,
154        }
155    }
156
157    pub(crate) fn values(&self) -> impl Iterator<Item = &CategoryValues> {
158        [self.row_values(), self.column_values(), self.wrap_values()]
159            .into_iter()
160            .flatten()
161    }
162}