Skip to main content

lichtung_plot/
layers.rs

1//! Typed supplemental geometry for numeric charts.
2
3use crate::Error;
4
5use crate::style::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, elements::GuideStyle, style::LinePattern};
15/// let guide = GuideStyle::new(Color::rgba(20, 80, 140, 128.0 / 255.0)?, 1.5, LinePattern::Solid)?
16///     .pattern(LinePattern::Dashed)?;
17/// assert_eq!(guide.get_color().get_alpha(), 128.0 / 255.0);
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::{elements::GuideStyle, style::LinePattern};
24/// let _ = GuideStyle::new((20, 80, 140), 1.5, LinePattern::Solid);
25/// ```
26#[derive(Debug, Clone, Copy, 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        validate_guide_width(width)?;
42        Ok(Self {
43            color,
44            width,
45            pattern,
46        })
47    }
48
49    /// Inspect the complete exact guide paint.
50    pub const fn get_color(&self) -> Color {
51        self.color
52    }
53
54    /// Inspect the positive guide width in CSS pixels.
55    pub const fn get_width(&self) -> f32 {
56        self.width
57    }
58
59    /// Inspect the closed guide pattern.
60    pub const fn get_pattern(&self) -> LinePattern {
61        self.pattern
62    }
63
64    /// Replace the complete exact guide paint.
65    pub fn color(self, color: Color) -> Result<Self, Error> {
66        Self::new(color, self.width, self.pattern)
67    }
68
69    /// Replace the positive guide width in CSS pixels.
70    pub fn width(self, width: f32) -> Result<Self, Error> {
71        Self::new(self.color, width, self.pattern)
72    }
73
74    /// Replace the closed guide pattern.
75    pub fn pattern(self, pattern: LinePattern) -> Result<Self, Error> {
76        Self::new(self.color, self.width, pattern)
77    }
78}
79
80fn validate_guide_width(width: f32) -> Result<(), Error> {
81    if !width.is_finite() || width <= 0.0 {
82        return Err(Error::Data(
83            format!("guide width must be finite and strictly positive; got {width}").into(),
84        ));
85    }
86    Ok(())
87}
88
89/// The scientific geometry of a supplemental reference line.
90#[derive(Debug, Clone, Copy, PartialEq)]
91#[non_exhaustive]
92pub enum GuideGeometry {
93    /// A horizontal line across the resolved panel range.
94    Horizontal {
95        /// Authored numeric y coordinate.
96        y: f64,
97    },
98    /// A vertical line across the resolved panel range.
99    Vertical {
100        /// Authored numeric x coordinate.
101        x: f64,
102    },
103    /// A finite segment in scientific coordinates.
104    Segment {
105        /// First endpoint.
106        start: (f64, f64),
107        /// Second endpoint.
108        end: (f64, f64),
109    },
110}
111
112/// An authored numeric guide, independent of its owner's effective theme.
113///
114/// Geometry never expands the scientific window. Finite off-window portions
115/// are clipped; omitted visual fields resolve at preparation against the
116/// effective theme's estimate-reference stroke.
117#[derive(Debug, Clone, PartialEq)]
118pub struct GuideSpec {
119    geometry: GuideGeometry,
120    color: Option<Color>,
121    width: Option<f32>,
122    pattern: Option<LinePattern>,
123}
124
125impl GuideSpec {
126    const fn new(geometry: GuideGeometry) -> Self {
127        Self {
128            geometry,
129            color: None,
130            width: None,
131            pattern: None,
132        }
133    }
134
135    /// Construct a horizontal guide with theme styling.
136    #[must_use]
137    pub const fn horizontal(y: f64) -> Self {
138        Self::new(GuideGeometry::Horizontal { y })
139    }
140
141    /// Construct a vertical guide with theme styling.
142    #[must_use]
143    pub const fn vertical(x: f64) -> Self {
144        Self::new(GuideGeometry::Vertical { x })
145    }
146
147    /// Construct a finite scientific segment with theme styling.
148    #[must_use]
149    pub const fn segment(x_start: f64, y_start: f64, x_end: f64, y_end: f64) -> Self {
150        Self::new(GuideGeometry::Segment {
151            start: (x_start, y_start),
152            end: (x_end, y_end),
153        })
154    }
155
156    /// Borrow the original scientific geometry.
157    pub const fn geometry(&self) -> &GuideGeometry {
158        &self.geometry
159    }
160
161    /// Supply all three exact visual overrides.
162    #[must_use]
163    pub fn style(self, style: GuideStyle) -> Self {
164        Self {
165            geometry: self.geometry,
166            color: Some(style.color),
167            width: Some(style.width),
168            pattern: Some(style.pattern),
169        }
170    }
171
172    /// Override only the complete reference paint.
173    #[must_use]
174    pub fn color(mut self, color: Color) -> Self {
175        self.color = Some(color);
176        self
177    }
178
179    /// Override only the positive finite CSS stroke width.
180    pub fn width(mut self, width: f32) -> Result<Self, Error> {
181        validate_guide_width(width)?;
182        self.width = Some(width);
183        Ok(self)
184    }
185
186    /// Override only the line pattern.
187    #[must_use]
188    pub fn pattern(mut self, pattern: LinePattern) -> Self {
189        self.pattern = Some(pattern);
190        self
191    }
192
193    /// The explicitly supplied paint, if any.
194    pub const fn get_color(&self) -> Option<Color> {
195        self.color
196    }
197
198    /// The explicitly supplied width, if any.
199    pub const fn get_width(&self) -> Option<f32> {
200        self.width
201    }
202
203    /// The explicitly supplied pattern, if any.
204    pub const fn get_pattern(&self) -> Option<LinePattern> {
205        self.pattern
206    }
207
208    pub(crate) fn line_style(&self, theme: &crate::Theme) -> crate::render::backend::LineStyle {
209        let defaults = theme
210            .marks
211            .get_strokes()
212            .get_references()
213            .get_estimate_reference();
214        crate::render::backend::LineStyle {
215            color: self.color.unwrap_or(defaults.get_color()),
216            width: self.width.unwrap_or(defaults.get_width()),
217            pattern: self.pattern.unwrap_or(defaults.get_pattern()),
218        }
219    }
220}
221
222/// A strict supplemental point layer owned independently from the primary line.
223///
224/// The aligned x/y values are arbitrary caller-selected coordinates. Optional
225/// labels annotate individual points, while an optional legend label identifies
226/// the complete layer once.
227///
228/// ```
229/// use lichtung_plot::{Color, NumericValues, Text, Theme, elements::PointLayer, text::TextAlignment};
230/// let label = Text::new("Selected coordinates").style(
231///     Theme::publication().typography().get_guides().get_legend_label().clone()
232/// ).alignment(TextAlignment::End);
233/// let layer = PointLayer::new(
234///     NumericValues::new("x", [1.0]), NumericValues::new("y", [2.0]),
235/// ).alpha(0.5)?.color(Color::rgb(20, 80, 140)).radius(5)?.legend_label(label);
236/// assert_eq!(layer.get_alpha(), Some(0.5));
237/// assert_eq!(layer.get_color(), Some(Color::rgb(20, 80, 140)));
238/// # Ok::<(), lichtung_plot::Error>(())
239/// ```
240///
241/// There is one explicit alpha setter; no second opacity alias:
242/// ```compile_fail
243/// use lichtung_plot::{NumericValues, elements::PointLayer};
244/// let _ = PointLayer::new(
245///     NumericValues::new("x", [1.0]), NumericValues::new("y", [2.0]),
246/// ).opacity(0.5);
247/// ```
248#[derive(Debug, Clone)]
249pub struct PointLayer {
250    pub(crate) identity: crate::data::InstanceId,
251    pub(crate) label_layout: Option<crate::text::TextLayout>,
252    x: NumericValues,
253    y: NumericValues,
254    labels: Option<CategoryValues>,
255    legend_label: crate::Text,
256    color: Option<Color>,
257    radius: Option<u32>,
258    alpha: Option<f64>,
259}
260
261/// A complete strict point layer positioned at prepared ordinary-bar centers.
262///
263/// Category and optional series values resolve against the bar cells. Every row
264/// creates exactly one point and the layer creates no legend.
265///
266/// Each explicit Color owns its complete paint, including zero opacity:
267/// ```
268/// use lichtung_plot::{CategoryValues, Color, NumericValues, elements::BarPointLayer};
269/// let layer = BarPointLayer::new(
270///     CategoryValues::new("category", ["A"])?,
271///     NumericValues::new("value", [2.0]),
272/// ).color(Color::rgba(20, 80, 140, 0.0)?).radius(4)?;
273/// assert_eq!(layer.get_color().unwrap().get_alpha(), 0.0);
274/// # Ok::<(), lichtung_plot::Error>(())
275/// ```
276#[derive(Debug, Clone)]
277pub struct BarPointLayer {
278    pub(crate) identity: crate::data::InstanceId,
279    category: CategoryValues,
280    series: Option<CategoryValues>,
281    value: NumericValues,
282    color: Option<Color>,
283    radius: Option<u32>,
284}
285
286impl BarPointLayer {
287    /// Construct independent observations at their native category slots.
288    /// Omitted paint and radius are resolved from the effective plot theme.
289    #[must_use]
290    pub fn new(category: CategoryValues, value: NumericValues) -> Self {
291        Self {
292            identity: crate::data::InstanceId::new(),
293            category,
294            series: None,
295            value,
296            color: None,
297            radius: None,
298        }
299    }
300
301    /// Bind positioned series independently of the main plot's source.
302    #[must_use]
303    pub fn series(mut self, series: CategoryValues) -> Self {
304        self.series = Some(series);
305        self
306    }
307
308    /// Supply a complete fixed point paint, with its original opacity.
309    #[must_use]
310    pub fn color(mut self, color: Color) -> Self {
311        self.color = Some(color);
312        self
313    }
314
315    /// Supply a fixed positive CSS point radius.
316    pub fn radius(mut self, radius: u32) -> Result<Self, Error> {
317        validate_point_radius("bar-point-layer", radius)?;
318        self.radius = Some(radius);
319        Ok(self)
320    }
321
322    /// Categories resolved against prepared bar categories.
323    #[must_use]
324    pub const fn category_values(&self) -> &CategoryValues {
325        &self.category
326    }
327
328    /// Optional series values resolved against prepared bar series.
329    #[must_use]
330    pub const fn series_values(&self) -> Option<&CategoryValues> {
331        self.series.as_ref()
332    }
333
334    /// Strict finite numeric point values.
335    #[must_use]
336    pub const fn values(&self) -> &NumericValues {
337        &self.value
338    }
339
340    /// The explicit complete paint, or None for theme paint.
341    #[must_use]
342    pub const fn get_color(&self) -> Option<Color> {
343        self.color
344    }
345
346    /// The explicit radius, or None for the theme radius.
347    #[must_use]
348    pub const fn get_radius(&self) -> Option<u32> {
349        self.radius
350    }
351
352    pub(crate) fn point_style(&self, theme: &crate::Theme) -> crate::render::backend::PointStyle {
353        let defaults = theme.marks.get_points().get_supplemental();
354        let color = self.color.unwrap_or_else(|| {
355            crate::theme::color_from_rgb(theme.marks.get_neutral_paints().get_path().as_rgb())
356                .with_alpha(defaults.get_fill_alpha())
357        });
358        crate::render::backend::PointStyle {
359            color,
360            radius: self.radius.unwrap_or(defaults.get_radius()),
361            outline: None,
362            shape: crate::style::PointShape::Circle,
363        }
364    }
365}
366
367impl PointLayer {
368    /// Replace the complete layout default for this layer's column-backed labels.
369    #[must_use]
370    pub fn label_text_layout(mut self, layout: crate::text::TextLayout) -> Self {
371        self.label_layout = Some(layout);
372        self
373    }
374    /// Construct an owned point layer with owner-theme styling.
375    ///
376    /// The x/y values may describe raw observations or any other supplemental
377    /// coordinates and need not align with the primary line input. They default
378    /// to the next theme-coordinated color and the theme's supplemental radius
379    /// and alpha (built-ins use radius 4 and alpha 0.8). Nonempty,
380    /// aligned, finite values are validated during chart preflight.
381    #[must_use]
382    pub fn new(x: NumericValues, y: NumericValues) -> Self {
383        Self {
384            identity: crate::data::InstanceId::new(),
385            x,
386            label_layout: None,
387            y,
388            labels: None,
389            legend_label: crate::Text::UNSET,
390            color: None,
391            radius: None,
392            alpha: None,
393        }
394    }
395
396    /// Replace the automatic mark paint and label paint with complete RGBA.
397    /// An independent explicit alpha instruction takes precedence over this alpha.
398    #[must_use]
399    pub fn color(mut self, color: Color) -> Self {
400        self.color = Some(color);
401        self
402    }
403
404    /// Override the default point radius.
405    ///
406    /// # Errors
407    ///
408    /// Returns an error when `radius` is zero.
409    pub fn radius(mut self, radius: u32) -> Result<Self, Error> {
410        validate_point_radius("point-layer", radius)?;
411        self.radius = Some(radius);
412        Ok(self)
413    }
414
415    /// Replace mark and label alpha, including transparent and opaque endpoints.
416    ///
417    /// This replaces alpha after resolving color, regardless of edit order.
418    /// Without an exact color, label RGB stays owned by its theme text role.
419    pub fn alpha(mut self, alpha: f64) -> Result<Self, Error> {
420        self.alpha = Some(crate::alpha::validated_alpha(alpha)?);
421        Ok(self)
422    }
423
424    /// Inspect the optional caller paint instruction, before theme resolution.
425    pub const fn get_color(&self) -> Option<Color> {
426        self.color
427    }
428
429    /// Inspect the optional caller alpha instruction, before theme resolution.
430    pub const fn get_alpha(&self) -> Option<f64> {
431        self.alpha
432    }
433
434    /// Inspect the optional caller radius instruction, before theme resolution.
435    pub const fn get_radius(&self) -> Option<u32> {
436        self.radius
437    }
438
439    /// Attach one caller-owned annotation label to every point.
440    ///
441    /// Point labels do not create legend entries. They must align one-to-one
442    /// with the layer's x/y coordinates.
443    #[must_use]
444    pub fn labels(mut self, labels: CategoryValues) -> Self {
445        self.labels = Some(labels);
446        self
447    }
448
449    /// Give the complete layer one legend identity.
450    ///
451    /// This creates at most one legend entry and does not label individual
452    /// points. Identity uses the retained source; style and layout remain display
453    /// instructions. Plain replacement retains prior Text instructions. Duplicate
454    /// identities require equal complete displayed Text and mark keys.
455    #[must_use]
456    pub fn legend_label(mut self, label: impl Into<crate::Text>) -> Self {
457        self.legend_label
458            .replace_from(label.into())
459            .expect("public Text always has a source");
460        self
461    }
462
463    /// Remove only the local legend-label appearance, retaining its identity/layout.
464    #[must_use]
465    pub fn clear_legend_label_style(mut self) -> Self {
466        self.legend_label.edit_clear_style();
467        self
468    }
469
470    /// Remove only the local legend-label layout, retaining its identity/appearance.
471    #[must_use]
472    pub fn clear_legend_label_layout(mut self) -> Self {
473        self.legend_label.edit_clear_layout();
474        self
475    }
476
477    pub(crate) const fn x_values(&self) -> &NumericValues {
478        &self.x
479    }
480
481    pub(crate) const fn y_values(&self) -> &NumericValues {
482        &self.y
483    }
484
485    pub(crate) const fn label_values(&self) -> Option<&CategoryValues> {
486        self.labels.as_ref()
487    }
488
489    pub(crate) const fn legend_content(&self) -> Option<&crate::Text> {
490        self.legend_label.provided()
491    }
492
493    pub(crate) fn point_style(
494        &self,
495        automatic_color: (u8, u8, u8),
496        defaults: &crate::theme::mark::SupplementalPointTheme,
497    ) -> crate::render::backend::PointStyle {
498        let color = self.color.unwrap_or_else(|| {
499            crate::theme::color_from_rgb(automatic_color).with_alpha(defaults.get_fill_alpha())
500        });
501        crate::render::backend::PointStyle {
502            color: self.alpha.map_or(color, |alpha| color.with_alpha(alpha)),
503            radius: self.radius.unwrap_or(defaults.get_radius()),
504            outline: None,
505            shape: crate::style::PointShape::Circle,
506        }
507    }
508
509    pub(crate) fn label_appearance(
510        &self,
511        role: &crate::theme::TextTheme,
512    ) -> Result<crate::theme::TextTheme, Error> {
513        let paint = self.color.unwrap_or(role.get_color());
514        role.try_copy()?
515            .color(self.alpha.map_or(paint, |alpha| paint.with_alpha(alpha)))
516    }
517}
518
519fn validate_point_radius(role: &str, radius: u32) -> Result<(), Error> {
520    if radius == 0 {
521        return Err(Error::Data(
522            format!("{role} radius must be greater than zero").into(),
523        ));
524    }
525    Ok(())
526}