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
80pub(crate) fn 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 replace_visual(
209        &mut self,
210        color: Option<Color>,
211        width: Option<f32>,
212        pattern: Option<LinePattern>,
213    ) {
214        self.color = color;
215        self.width = width;
216        self.pattern = pattern;
217    }
218
219    pub(crate) fn line_style(&self, theme: &crate::Theme) -> crate::render::backend::LineStyle {
220        let defaults = theme
221            .marks
222            .get_strokes()
223            .get_references()
224            .get_estimate_reference();
225        crate::render::backend::LineStyle {
226            color: self.color.unwrap_or(defaults.get_color()),
227            width: self.width.unwrap_or(defaults.get_width()),
228            pattern: self.pattern.unwrap_or(defaults.get_pattern()),
229        }
230    }
231}
232
233/// A strict supplemental point layer owned independently from the primary line.
234///
235/// The aligned x/y values are arbitrary caller-selected coordinates. Optional
236/// labels annotate individual points, while an optional legend label identifies
237/// the complete layer once.
238///
239/// ```
240/// use lichtung_plot::{Color, NumericValues, Text, Theme, elements::PointLayer, text::TextAlignment};
241/// let label = Text::new("Selected coordinates").style(
242///     Theme::publication().typography().get_guides().get_legend_label().clone()
243/// ).alignment(TextAlignment::End);
244/// let layer = PointLayer::new(
245///     NumericValues::new("x", [1.0]), NumericValues::new("y", [2.0]),
246/// ).alpha(0.5)?.color(Color::rgb(20, 80, 140)).radius(5)?.legend_label(label);
247/// assert_eq!(layer.get_alpha(), Some(0.5));
248/// assert_eq!(layer.get_color(), Some(Color::rgb(20, 80, 140)));
249/// # Ok::<(), lichtung_plot::Error>(())
250/// ```
251///
252/// There is one explicit alpha setter; no second opacity alias:
253/// ```compile_fail
254/// use lichtung_plot::{NumericValues, elements::PointLayer};
255/// let _ = PointLayer::new(
256///     NumericValues::new("x", [1.0]), NumericValues::new("y", [2.0]),
257/// ).opacity(0.5);
258/// ```
259#[derive(Debug, Clone)]
260pub struct PointLayer {
261    pub(crate) identity: crate::data::InstanceId,
262    pub(crate) label_layout: Option<crate::text::TextLayout>,
263    x: NumericValues,
264    y: NumericValues,
265    labels: Option<CategoryValues>,
266    legend_label: crate::Text,
267    color: Option<Color>,
268    radius: Option<u32>,
269    alpha: Option<f64>,
270}
271
272/// A complete strict point layer positioned at prepared ordinary-bar centers.
273///
274/// Category and optional series values resolve against the bar cells. Every row
275/// creates exactly one point and the layer creates no legend.
276///
277/// Each explicit Color owns its complete paint, including zero opacity:
278/// ```
279/// use lichtung_plot::{CategoryValues, Color, NumericValues, elements::BarPointLayer};
280/// let layer = BarPointLayer::new(
281///     CategoryValues::new("category", ["A"])?,
282///     NumericValues::new("value", [2.0]),
283/// ).color(Color::rgba(20, 80, 140, 0.0)?).radius(4)?;
284/// assert_eq!(layer.get_color().unwrap().get_alpha(), 0.0);
285/// # Ok::<(), lichtung_plot::Error>(())
286/// ```
287#[derive(Debug, Clone)]
288pub struct BarPointLayer {
289    pub(crate) identity: crate::data::InstanceId,
290    category: CategoryValues,
291    series: Option<CategoryValues>,
292    value: NumericValues,
293    color: Option<Color>,
294    radius: Option<u32>,
295}
296
297impl BarPointLayer {
298    /// Construct independent observations at their native category slots.
299    /// Omitted paint and radius are resolved from the effective plot theme.
300    #[must_use]
301    pub fn new(category: CategoryValues, value: NumericValues) -> Self {
302        Self {
303            identity: crate::data::InstanceId::new(),
304            category,
305            series: None,
306            value,
307            color: None,
308            radius: None,
309        }
310    }
311
312    /// Bind positioned series independently of the main plot's source.
313    #[must_use]
314    pub fn series(mut self, series: CategoryValues) -> Self {
315        self.series = Some(series);
316        self
317    }
318
319    /// Supply a complete fixed point paint, with its original opacity.
320    #[must_use]
321    pub fn color(mut self, color: Color) -> Self {
322        self.color = Some(color);
323        self
324    }
325
326    /// Supply a fixed positive CSS point radius.
327    pub fn radius(mut self, radius: u32) -> Result<Self, Error> {
328        validate_point_radius("bar-point-layer", radius)?;
329        self.radius = Some(radius);
330        Ok(self)
331    }
332
333    /// Categories resolved against prepared bar categories.
334    #[must_use]
335    pub const fn category_values(&self) -> &CategoryValues {
336        &self.category
337    }
338
339    /// Optional series values resolved against prepared bar series.
340    #[must_use]
341    pub const fn series_values(&self) -> Option<&CategoryValues> {
342        self.series.as_ref()
343    }
344
345    /// Strict finite numeric point values.
346    #[must_use]
347    pub const fn values(&self) -> &NumericValues {
348        &self.value
349    }
350
351    /// The explicit complete paint, or None for theme paint.
352    #[must_use]
353    pub const fn get_color(&self) -> Option<Color> {
354        self.color
355    }
356
357    /// The explicit radius, or None for the theme radius.
358    #[must_use]
359    pub const fn get_radius(&self) -> Option<u32> {
360        self.radius
361    }
362
363    pub(crate) fn replace_visual(&mut self, color: Option<Color>, radius: Option<u32>) {
364        self.color = color;
365        self.radius = radius;
366    }
367
368    pub(crate) fn point_style(&self, theme: &crate::Theme) -> crate::render::backend::PointStyle {
369        let defaults = theme.marks.get_points().get_supplemental();
370        let color = self.color.unwrap_or_else(|| {
371            crate::theme::color_from_rgb(theme.marks.get_neutral_paints().get_path().as_rgb())
372                .with_alpha(defaults.get_fill_alpha())
373        });
374        crate::render::backend::PointStyle {
375            color,
376            radius: self.radius.unwrap_or(defaults.get_radius()),
377            outline: None,
378            shape: crate::style::PointShape::Circle,
379        }
380    }
381}
382
383impl PointLayer {
384    /// Replace the complete layout default for this layer's column-backed labels.
385    #[must_use]
386    pub fn label_text_layout(mut self, layout: crate::text::TextLayout) -> Self {
387        self.label_layout = Some(layout);
388        self
389    }
390    /// Construct an owned point layer with owner-theme styling.
391    ///
392    /// The x/y values may describe raw observations or any other supplemental
393    /// coordinates and need not align with the primary line input. They default
394    /// to the next theme-coordinated color and the theme's supplemental radius
395    /// and alpha (built-ins use radius 4 and alpha 0.8). Nonempty,
396    /// aligned, finite values are validated during chart preflight.
397    #[must_use]
398    pub fn new(x: NumericValues, y: NumericValues) -> Self {
399        Self {
400            identity: crate::data::InstanceId::new(),
401            x,
402            label_layout: None,
403            y,
404            labels: None,
405            legend_label: crate::Text::UNSET,
406            color: None,
407            radius: None,
408            alpha: None,
409        }
410    }
411
412    /// Replace the automatic mark paint and label paint with complete RGBA.
413    /// An independent explicit alpha instruction takes precedence over this alpha.
414    #[must_use]
415    pub fn color(mut self, color: Color) -> Self {
416        self.color = Some(color);
417        self
418    }
419
420    /// Override the default point radius.
421    ///
422    /// # Errors
423    ///
424    /// Returns an error when `radius` is zero.
425    pub fn radius(mut self, radius: u32) -> Result<Self, Error> {
426        validate_point_radius("point-layer", radius)?;
427        self.radius = Some(radius);
428        Ok(self)
429    }
430
431    /// Replace mark and label alpha, including transparent and opaque endpoints.
432    ///
433    /// This replaces alpha after resolving color, regardless of edit order.
434    /// Without an exact color, label RGB stays owned by its theme text role.
435    pub fn alpha(mut self, alpha: f64) -> Result<Self, Error> {
436        self.alpha = Some(crate::alpha::validated_alpha(alpha)?);
437        Ok(self)
438    }
439
440    /// Inspect the optional caller paint instruction, before theme resolution.
441    pub const fn get_color(&self) -> Option<Color> {
442        self.color
443    }
444
445    /// Inspect the optional caller alpha instruction, before theme resolution.
446    pub const fn get_alpha(&self) -> Option<f64> {
447        self.alpha
448    }
449
450    /// Inspect the optional caller radius instruction, before theme resolution.
451    pub const fn get_radius(&self) -> Option<u32> {
452        self.radius
453    }
454
455    /// Attach one caller-owned annotation label to every point.
456    ///
457    /// Point labels do not create legend entries. They must align one-to-one
458    /// with the layer's x/y coordinates.
459    #[must_use]
460    pub fn labels(mut self, labels: CategoryValues) -> Self {
461        self.labels = Some(labels);
462        self
463    }
464
465    /// Give the complete layer one legend identity.
466    ///
467    /// This creates at most one legend entry and does not label individual
468    /// points. Identity uses the retained source; style and layout remain display
469    /// instructions. Plain replacement retains prior Text instructions. Duplicate
470    /// identities require equal complete displayed Text and mark keys.
471    #[must_use]
472    pub fn legend_label(mut self, label: impl Into<crate::Text>) -> Self {
473        self.legend_label
474            .replace_from(label.into())
475            .expect("public Text always has a source");
476        self
477    }
478
479    /// Remove only the local legend-label appearance, retaining its identity/layout.
480    #[must_use]
481    pub fn clear_legend_label_style(mut self) -> Self {
482        self.legend_label.edit_clear_style();
483        self
484    }
485
486    /// Remove only the local legend-label layout, retaining its identity/appearance.
487    #[must_use]
488    pub fn clear_legend_label_layout(mut self) -> Self {
489        self.legend_label.edit_clear_layout();
490        self
491    }
492
493    pub(crate) const fn x_values(&self) -> &NumericValues {
494        &self.x
495    }
496
497    pub(crate) const fn y_values(&self) -> &NumericValues {
498        &self.y
499    }
500
501    pub(crate) const fn label_values(&self) -> Option<&CategoryValues> {
502        self.labels.as_ref()
503    }
504
505    pub(crate) const fn legend_content(&self) -> Option<&crate::Text> {
506        self.legend_label.provided()
507    }
508
509    pub(crate) fn replace_visual(
510        &mut self,
511        color: Option<Color>,
512        radius: Option<u32>,
513        alpha: Option<f64>,
514        legend: crate::Text,
515        layout: Option<crate::text::TextLayout>,
516    ) {
517        self.color = color;
518        self.radius = radius;
519        self.alpha = alpha;
520        self.legend_label.apply_appearance(legend);
521        self.label_layout = layout;
522    }
523
524    pub(crate) fn point_style(
525        &self,
526        automatic_color: (u8, u8, u8),
527        defaults: &crate::theme::mark::SupplementalPointTheme,
528    ) -> crate::render::backend::PointStyle {
529        let color = self.color.unwrap_or_else(|| {
530            crate::theme::color_from_rgb(automatic_color).with_alpha(defaults.get_fill_alpha())
531        });
532        crate::render::backend::PointStyle {
533            color: self.alpha.map_or(color, |alpha| color.with_alpha(alpha)),
534            radius: self.radius.unwrap_or(defaults.get_radius()),
535            outline: None,
536            shape: crate::style::PointShape::Circle,
537        }
538    }
539
540    pub(crate) fn label_appearance(
541        &self,
542        role: &crate::theme::TextTheme,
543    ) -> Result<crate::theme::TextTheme, Error> {
544        let paint = self.color.unwrap_or(role.get_color());
545        role.try_copy()?
546            .color(self.alpha.map_or(paint, |alpha| paint.with_alpha(alpha)))
547    }
548}
549
550pub(crate) fn validate_point_radius(role: &str, radius: u32) -> Result<(), Error> {
551    if radius == 0 {
552        return Err(Error::Data(
553            format!("{role} radius must be greater than zero").into(),
554        ));
555    }
556    Ok(())
557}