Skip to main content

lichtung_plot/
layers.rs

1//! Typed supplemental geometry for numeric charts.
2
3use crate::Error;
4
5use crate::LinePattern;
6use crate::{CategoryValues, Color, NumericValues};
7
8/// Closed visual style for a numeric guide line.
9///
10/// The pattern is selected through [`LinePattern`]; arbitrary backend dash
11/// strings are not accepted.
12///
13/// ```
14/// use lichtung_plot::{Color, GuideStyle, LinePattern};
15/// let guide = GuideStyle::new(Color::rgba(20, 80, 140, 128), 1.5, LinePattern::Solid)?
16///     .pattern(LinePattern::Dashed)?;
17/// assert_eq!(guide.get_color().get_alpha(), 128);
18/// # Ok::<(), lichtung_plot::Error>(())
19/// ```
20///
21/// Exact paint is typed; RGB tuples are not style inputs:
22/// ```compile_fail
23/// use lichtung_plot::{GuideStyle, LinePattern};
24/// let _ = GuideStyle::new((20, 80, 140), 1.5, LinePattern::Solid);
25/// ```
26#[derive(Debug, Clone, PartialEq)]
27pub struct GuideStyle {
28    color: Color,
29    width: f32,
30    pattern: LinePattern,
31}
32
33impl GuideStyle {
34    /// Construct a guide style with a complete RGBA paint, positive width, and
35    /// closed line pattern.
36    ///
37    /// # Errors
38    ///
39    /// Returns an error when `width` is not finite and strictly positive.
40    pub fn new(color: Color, width: f32, pattern: LinePattern) -> Result<Self, Error> {
41        if !width.is_finite() || width <= 0.0 {
42            return Err(Error::Data(format!(
43                "guide width must be finite and strictly positive; got {width}"
44            )));
45        }
46        Ok(Self {
47            color,
48            width,
49            pattern,
50        })
51    }
52
53    /// Inspect the complete exact guide paint.
54    pub const fn get_color(&self) -> Color {
55        self.color
56    }
57
58    /// Inspect the positive guide width in CSS pixels.
59    pub const fn get_width(&self) -> f32 {
60        self.width
61    }
62
63    /// Inspect the closed guide pattern.
64    pub const fn get_pattern(&self) -> LinePattern {
65        self.pattern
66    }
67
68    /// Replace the complete exact guide paint.
69    pub fn color(self, color: Color) -> Result<Self, Error> {
70        Self::new(color, self.width, self.pattern)
71    }
72
73    /// Replace the positive guide width in CSS pixels.
74    pub fn width(self, width: f32) -> Result<Self, Error> {
75        Self::new(self.color, width, self.pattern)
76    }
77
78    /// Replace the closed guide pattern.
79    pub fn pattern(self, pattern: LinePattern) -> Result<Self, Error> {
80        Self::new(self.color, self.width, pattern)
81    }
82
83    pub(crate) fn line_style(&self) -> crate::render::backend::LineStyle {
84        crate::render::backend::LineStyle {
85            color: self.color,
86            width: self.width,
87            pattern: self.pattern.stroke_pattern(),
88        }
89    }
90}
91
92/// Supplemental numeric guide geometry.
93///
94/// Horizontal and vertical guides span the resolved panel range. A segment is
95/// finite and may be diagonal. Every coordinate must lie in the corresponding
96/// resolved numeric axis range.
97#[derive(Debug, Clone, PartialEq)]
98pub enum GuideSpec {
99    /// A horizontal guide spanning the numeric x range.
100    Horizontal {
101        /// Numeric y position.
102        y: f64,
103        /// Guide visual style.
104        style: GuideStyle,
105    },
106    /// A vertical guide spanning the numeric y range.
107    Vertical {
108        /// Numeric x position.
109        x: f64,
110        /// Guide visual style.
111        style: GuideStyle,
112    },
113    /// A finite segment between two numeric data-space endpoints.
114    Segment {
115        /// First `(x, y)` endpoint.
116        start: (f64, f64),
117        /// Second `(x, y)` endpoint.
118        end: (f64, f64),
119        /// Guide visual style.
120        style: GuideStyle,
121    },
122}
123
124impl GuideSpec {
125    /// Construct a horizontal guide.
126    #[must_use]
127    pub const fn horizontal(y: f64, style: GuideStyle) -> Self {
128        Self::Horizontal { y, style }
129    }
130
131    /// Construct a vertical guide.
132    #[must_use]
133    pub const fn vertical(x: f64, style: GuideStyle) -> Self {
134        Self::Vertical { x, style }
135    }
136
137    /// Construct a finite segment, including a diagonal guide when both
138    /// coordinates differ between endpoints.
139    #[must_use]
140    pub const fn segment(
141        x_start: f64,
142        y_start: f64,
143        x_end: f64,
144        y_end: f64,
145        style: GuideStyle,
146    ) -> Self {
147        Self::Segment {
148            start: (x_start, y_start),
149            end: (x_end, y_end),
150            style,
151        }
152    }
153}
154
155/// A strict supplemental point layer owned independently from the primary line.
156///
157/// The aligned x/y values are arbitrary caller-selected coordinates. Optional
158/// labels annotate individual points, while an optional legend label identifies
159/// the complete layer once.
160///
161/// ```
162/// use lichtung_plot::{Color, NumericValues, PointLayer, Text, TextAlignment, Theme};
163/// let label = Text::new("Selected coordinates").style(
164///     Theme::publication().typography().get_guides().get_legend_label().clone()
165/// ).alignment(TextAlignment::End);
166/// let layer = PointLayer::new(
167///     NumericValues::new("x", [1.0]), NumericValues::new("y", [2.0]),
168/// ).alpha(128).color(Color::rgb(20, 80, 140)).radius(5)?.legend_label(label);
169/// assert_eq!(layer.get_alpha(), Some(128));
170/// assert_eq!(layer.get_color(), Some(Color::rgb(20, 80, 140)));
171/// # Ok::<(), lichtung_plot::Error>(())
172/// ```
173///
174/// Alpha instructions are exact bytes rather than floating opacity:
175/// ```compile_fail
176/// use lichtung_plot::{NumericValues, PointLayer};
177/// let _ = PointLayer::new(
178///     NumericValues::new("x", [1.0]), NumericValues::new("y", [2.0]),
179/// ).opacity(0.5);
180/// ```
181#[derive(Debug, Clone)]
182pub struct PointLayer {
183    pub(crate) label_layout: Option<crate::TextLayout>,
184    x: NumericValues,
185    y: NumericValues,
186    labels: Option<CategoryValues>,
187    legend_label: crate::Text,
188    color: Option<Color>,
189    radius: Option<u32>,
190    alpha: Option<u8>,
191}
192
193/// A complete strict point layer positioned at prepared ordinary-bar centers.
194///
195/// Category and optional series values resolve against the bar cells. Every row
196/// creates exactly one point and the layer creates no legend.
197///
198/// The constructor's Color owns the complete paint, with no opacity argument:
199/// ```
200/// use lichtung_plot::{BarPointLayer, CategoryValues, Color, NumericValues};
201/// let layer = BarPointLayer::new(
202///     CategoryValues::new("category", ["A"])?, None,
203///     NumericValues::new("value", [2.0]), Color::rgba(20, 80, 140, 0), 4,
204/// )?;
205/// assert_eq!(layer.color().get_alpha(), 0);
206/// # Ok::<(), lichtung_plot::Error>(())
207/// ```
208///
209/// ```compile_fail
210/// use lichtung_plot::{BarPointLayer, CategoryValues, Color, NumericValues};
211/// let _ = BarPointLayer::new(
212///     CategoryValues::new("category", ["A"]).unwrap(), None,
213///     NumericValues::new("value", [2.0]), Color::rgb(20, 80, 140), 4, 0.5,
214/// );
215/// ```
216#[derive(Debug, Clone)]
217pub struct BarPointLayer {
218    category: CategoryValues,
219    series: Option<CategoryValues>,
220    value: NumericValues,
221    color: Color,
222    radius: u32,
223}
224
225impl BarPointLayer {
226    /// Construct an owned bar point layer with optional positioned series.
227    ///
228    /// Pass `None` for a single-series bar and `Some(column)` for a chart whose
229    /// ordinary bars use an explicit positioned series.
230    pub fn new(
231        category: CategoryValues,
232        series: Option<CategoryValues>,
233        value: NumericValues,
234        color: Color,
235        radius: u32,
236    ) -> Result<Self, Error> {
237        validate_point_radius("bar-point-layer", radius)?;
238        Ok(Self {
239            category,
240            series,
241            value,
242            color,
243            radius,
244        })
245    }
246
247    /// Categories resolved against prepared bar categories.
248    #[must_use]
249    pub const fn category_values(&self) -> &CategoryValues {
250        &self.category
251    }
252
253    /// Optional series values resolved against prepared bar series.
254    #[must_use]
255    pub const fn series_values(&self) -> Option<&CategoryValues> {
256        self.series.as_ref()
257    }
258
259    /// Strict finite numeric point values.
260    #[must_use]
261    pub const fn values(&self) -> &NumericValues {
262        &self.value
263    }
264
265    /// Complete exact point paint, including alpha.
266    #[must_use]
267    pub const fn color(&self) -> Color {
268        self.color
269    }
270
271    /// Fixed positive point radius.
272    #[must_use]
273    pub const fn radius(&self) -> u32 {
274        self.radius
275    }
276
277    pub(crate) fn point_style(&self) -> crate::render::backend::PointStyle {
278        crate::render::backend::PointStyle {
279            color: self.color,
280            radius: self.radius,
281            outline: None,
282            shape: crate::PointShape::Circle,
283        }
284    }
285}
286
287impl PointLayer {
288    /// Replace the complete layout default for this layer's column-backed labels.
289    #[must_use]
290    pub fn label_text_layout(mut self, layout: crate::TextLayout) -> Self {
291        self.label_layout = Some(layout);
292        self
293    }
294    /// Construct an owned point layer with owner-theme styling.
295    ///
296    /// The x/y values may describe raw observations or any other supplemental
297    /// coordinates and need not align with the primary line input. They default
298    /// to the next theme-coordinated color and the theme's supplemental radius
299    /// and alpha (built-ins use radius 4 and alpha 204). Nonempty,
300    /// aligned, finite values are validated during chart preflight.
301    #[must_use]
302    pub fn new(x: NumericValues, y: NumericValues) -> Self {
303        Self {
304            x,
305            label_layout: None,
306            y,
307            labels: None,
308            legend_label: crate::Text::UNSET,
309            color: None,
310            radius: None,
311            alpha: None,
312        }
313    }
314
315    /// Replace the automatic mark paint and label paint with complete RGBA.
316    /// An independent explicit alpha instruction takes precedence over this alpha.
317    #[must_use]
318    pub fn color(mut self, color: Color) -> Self {
319        self.color = Some(color);
320        self
321    }
322
323    /// Override the default point radius.
324    ///
325    /// # Errors
326    ///
327    /// Returns an error when `radius` is zero.
328    pub fn radius(mut self, radius: u32) -> Result<Self, Error> {
329        validate_point_radius("point-layer", radius)?;
330        self.radius = Some(radius);
331        Ok(self)
332    }
333
334    /// Replace mark and label alpha, including transparent and opaque endpoints.
335    ///
336    /// This replaces alpha after resolving color, regardless of edit order.
337    /// Without an exact color, label RGB stays owned by its theme text role.
338    #[must_use]
339    pub const fn alpha(mut self, alpha: u8) -> Self {
340        self.alpha = Some(alpha);
341        self
342    }
343
344    /// Inspect the optional caller paint instruction, before theme resolution.
345    pub const fn get_color(&self) -> Option<Color> {
346        self.color
347    }
348
349    /// Inspect the optional caller alpha instruction, before theme resolution.
350    pub const fn get_alpha(&self) -> Option<u8> {
351        self.alpha
352    }
353
354    /// Inspect the optional caller radius instruction, before theme resolution.
355    pub const fn get_radius(&self) -> Option<u32> {
356        self.radius
357    }
358
359    /// Attach one caller-owned annotation label to every point.
360    ///
361    /// Point labels do not create legend entries. They must align one-to-one
362    /// with the layer's x/y coordinates.
363    #[must_use]
364    pub fn labels(mut self, labels: CategoryValues) -> Self {
365        self.labels = Some(labels);
366        self
367    }
368
369    /// Give the complete layer one legend identity.
370    ///
371    /// This creates at most one legend entry and does not label individual
372    /// points. Identity uses the retained source; style and layout remain display
373    /// instructions. Plain replacement retains prior Text instructions. Duplicate
374    /// identities require equal complete displayed Text and mark keys.
375    #[must_use]
376    pub fn legend_label(mut self, label: impl Into<crate::Text>) -> Self {
377        self.legend_label
378            .replace_from(label.into())
379            .expect("public Text always has a source");
380        self
381    }
382
383    /// Remove only the local legend-label appearance, retaining its identity/layout.
384    #[must_use]
385    pub fn clear_legend_label_style(mut self) -> Self {
386        self.legend_label.edit_clear_style();
387        self
388    }
389
390    /// Remove only the local legend-label layout, retaining its identity/appearance.
391    #[must_use]
392    pub fn clear_legend_label_layout(mut self) -> Self {
393        self.legend_label.edit_clear_layout();
394        self
395    }
396
397    pub(crate) const fn x_values(&self) -> &NumericValues {
398        &self.x
399    }
400
401    pub(crate) const fn y_values(&self) -> &NumericValues {
402        &self.y
403    }
404
405    pub(crate) const fn label_values(&self) -> Option<&CategoryValues> {
406        self.labels.as_ref()
407    }
408
409    pub(crate) const fn legend_content(&self) -> Option<&crate::Text> {
410        self.legend_label.provided()
411    }
412
413    pub(crate) fn point_style(
414        &self,
415        automatic_color: (u8, u8, u8),
416        defaults: &crate::theme::mark::SupplementalPointTheme,
417    ) -> crate::render::backend::PointStyle {
418        let color = self.color.unwrap_or_else(|| {
419            crate::theme::color_from_rgb(automatic_color).alpha(defaults.get_fill_alpha())
420        });
421        crate::render::backend::PointStyle {
422            color: self.alpha.map_or(color, |alpha| color.alpha(alpha)),
423            radius: self.radius.unwrap_or(defaults.get_radius()),
424            outline: None,
425            shape: crate::PointShape::Circle,
426        }
427    }
428
429    pub(crate) fn label_appearance(
430        &self,
431        role: &crate::theme::TextTheme,
432    ) -> Result<crate::theme::TextTheme, Error> {
433        let paint = self.color.unwrap_or(role.get_color());
434        role.try_copy()?
435            .color(self.alpha.map_or(paint, |alpha| paint.alpha(alpha)))
436    }
437}
438
439fn validate_point_radius(role: &str, radius: u32) -> Result<(), Error> {
440    if radius == 0 {
441        return Err(Error::Data(format!(
442            "{role} radius must be greater than zero"
443        )));
444    }
445    Ok(())
446}