Skip to main content

lichtung_plot/
spec.rs

1//! Shared plot specification and render-result types.
2
3use crate::layout::Layout;
4use crate::significance::SignificancePlan;
5use crate::{NumericFormat, NumericValues};
6
7mod bar;
8mod categorical;
9mod estimate;
10mod facet;
11mod output;
12pub(crate) mod ticks;
13
14pub use bar::{
15    BarInput, BarSamples, Bootstrap, ConfidenceInterval, ErrorBar, PercentileInterval,
16    StandardDeviation, StandardError,
17};
18pub(crate) use bar::{BarSource, ConfidenceIntervalAlgorithm, ErrorBarKind};
19pub use categorical::{CategoricalColorMap, CategoryOrder, ValueSort};
20pub use estimate::{
21    AxisScale, Bounds, CoefficientInput, EstimateStatus, InteractionStyle, LinePathStyle,
22    LinePattern, PointShape, QqLine, RegressionBand, SignificanceMarkStyle, TextWeight,
23};
24pub use facet::{FacetScales, FacetSpec};
25pub(crate) use output::SVG_CSS_DPI;
26pub use output::{PngCompression, PngOptions, PngSizing};
27pub use ticks::{
28    TickContext, TickGeneration, TickPositions, TickRequirement, TickSingleton, TickSpace,
29};
30mod category_labels;
31pub use category_labels::{CategoryLabelSelection, LabelEndpoints};
32
33/// Spacing preset for multiple series within one bar category.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
35pub enum BarSpacing {
36    /// Keep visible space between series bars inside each category.
37    #[default]
38    Comfort,
39    /// Make series bars within each category touch side-by-side.
40    Compact,
41}
42
43/// Histogram bin-selection strategy.
44#[derive(Debug, Clone, Copy, PartialEq, Default)]
45pub enum HistogramBins {
46    /// Select a width with the Freedman-Diaconis rule, falling back to Sturges.
47    /// Automatic selection is capped at 512 bins; constant data uses one
48    /// centered bin.
49    #[default]
50    Auto,
51    /// Render exactly this many centered equal-width bins, including for
52    /// constant data, up to the safety limit of 1,000,000 bins.
53    Count(usize),
54    /// Render bins with this data-space width, provided the resulting count
55    /// does not exceed the 1,000,000-bin safety limit. Constant data uses one
56    /// bin centered on the value and rejects widths that are not representable.
57    Width(f64),
58}
59
60/// Histogram vertical-axis normalization.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
62pub enum HistogramStat {
63    /// Raw observations per bin.
64    #[default]
65    Count,
66    /// Fraction of all observations per bin.
67    Probability,
68    /// Probability density; bin area integrates to one.
69    Density,
70}
71
72/// Density-curve source for an opt-in composite over sample-owned histogram input.
73#[derive(Debug, Clone)]
74pub enum HistogramKde {
75    /// Compute a scale-robust Scott-bandwidth Gaussian KDE from the histogram sample.
76    Internal,
77    /// Draw caller-computed aligned x/y columns in supplied order.
78    ///
79    /// ```
80    /// use lichtung_plot::{HistogramKde, NumericValues};
81    ///
82    /// let kde = HistogramKde::Precomputed {
83    ///     x: NumericValues::new("x", [0.0, 1.0]),
84    ///     y: NumericValues::new("density", [0.1, 0.2]),
85    /// };
86    /// # let _ = kde;
87    /// ```
88    Precomputed {
89        /// Strictly increasing x coordinates within the sample-owned bin support.
90        x: NumericValues,
91        /// Nonnegative densities aligned with x.
92        y: NumericValues,
93    },
94}
95
96impl PartialEq for HistogramKde {
97    fn eq(&self, other: &Self) -> bool {
98        match (self, other) {
99            (Self::Internal, Self::Internal) => true,
100            (
101                Self::Precomputed { x, y },
102                Self::Precomputed {
103                    x: other_x,
104                    y: other_y,
105                },
106            ) => {
107                crate::geometry::numeric_equal(x, other_x)
108                    && crate::geometry::numeric_equal(y, other_y)
109            }
110            _ => false,
111        }
112    }
113}
114
115/// Optional layers composed on a histogram density axis.
116#[derive(Debug, Clone, PartialEq, Default)]
117pub enum HistogramComposite {
118    /// Draw only histogram bars. This is the byte-inert default.
119    #[default]
120    HistogramOnly,
121    /// Draw a thin KDE density curve and one rug mark per source observation.
122    KdeAndRug(HistogramKde),
123}
124
125impl HistogramComposite {
126    pub(crate) const fn is_enabled(&self) -> bool {
127        matches!(self, Self::KdeAndRug(_))
128    }
129}
130
131/// A corner inside one chart's resolved mark panel.
132#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
133pub enum DataAreaCorner {
134    /// Top-left corner.
135    TopLeft,
136    /// Top-right corner.
137    TopRight,
138    /// Bottom-left corner.
139    BottomLeft,
140    /// Bottom-right corner.
141    BottomRight,
142}
143
144/// Caller-owned text block anchored inside a chart panel.
145#[derive(Debug, Clone, PartialEq, Eq)]
146pub struct PlotTextAnnotation {
147    position: crate::TextPosition,
148    text: crate::Text,
149}
150
151impl PlotTextAnnotation {
152    /// Construct one validated panel-corner annotation from plain or styled text.
153    ///
154    /// Local appearance replaces the complete panel-text role. Alignment applies
155    /// within the text block; the selected corner continues to place that block.
156    pub fn new(corner: DataAreaCorner, text: impl Into<crate::Text>) -> Result<Self, crate::Error> {
157        Self::at(crate::TextPosition::corner(corner), text)
158    }
159
160    /// Attach authored text to independent typed data, panel or figure references.
161    pub fn at(
162        position: crate::TextPosition,
163        text: impl Into<crate::Text>,
164    ) -> Result<Self, crate::Error> {
165        let text = text.into();
166        text.required_source("panel text")?;
167        Ok(Self { position, text })
168    }
169
170    /// Semantic reference that owns this annotation's placement.
171    #[must_use]
172    pub const fn position(&self) -> &crate::TextPosition {
173        &self.position
174    }
175
176    /// Verbatim caller-owned annotation text.
177    #[must_use]
178    pub fn text(&self) -> &str {
179        self.text.as_str()
180    }
181
182    pub(crate) const fn content(&self) -> &crate::Text {
183        &self.text
184    }
185}
186
187/// Original-observation overlay for boxplots and violin plots.
188///
189/// Visible modes draw one fixed-style point for every observation in the same
190/// strict sample used by the summary. They do not filter, transform, aggregate,
191/// resample, or create a legend identity.
192#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
193pub enum RawOverlay {
194    /// Draw no raw observations. This is the inert default.
195    #[default]
196    Hidden,
197    /// Draw every observation at its exact category or dodge center.
198    Points,
199    /// Deterministically displace every observation from its center using its
200    /// plot-level source-row identity.
201    Jittered,
202}
203
204impl RawOverlay {
205    /// Whether the overlay draws original observations.
206    #[must_use]
207    pub const fn is_visible(self) -> bool {
208        !matches!(self, Self::Hidden)
209    }
210}
211
212/// Coordinate layout for a categorical heatmap grid.
213#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
214pub enum HeatmapLayout {
215    /// Draw every cell in the Cartesian product of observed x and y levels.
216    #[default]
217    Cartesian,
218    /// Draw the lower triangle of one shared family order.
219    LowerTriangle {
220        /// Whether diagonal coordinates are active cells.
221        diagonal: bool,
222    },
223    /// Draw the upper triangle of one shared family order.
224    UpperTriangle {
225        /// Whether diagonal coordinates are active cells.
226        diagonal: bool,
227    },
228}
229
230/// In-cell value-label policy for heatmaps.
231#[derive(Debug, Clone, PartialEq, Eq, Default)]
232pub enum HeatmapAnnotations {
233    /// Draw no values inside cells.
234    #[default]
235    Hidden,
236    /// Draw finite raw values using one complete panel-local numeric format set.
237    Values(NumericFormat),
238}
239
240/// Caller-owned annotation for one fully-null Cartesian heatmap row.
241#[derive(Debug, Clone, PartialEq, Eq)]
242pub struct HeatmapNullRowAnnotation {
243    row_label: String,
244    text: crate::Text,
245}
246
247impl HeatmapNullRowAnnotation {
248    /// Construct an annotation targeting one normalized heatmap y-category.
249    /// Text can replace the complete selected contrast style and line alignment;
250    /// row identity remains a semantic string and is validated independently.
251    pub fn new(
252        row_label: impl Into<String>,
253        text: impl Into<crate::Text>,
254    ) -> Result<Self, crate::Error> {
255        let annotation = Self {
256            row_label: row_label.into(),
257            text: text.into(),
258        };
259        validate_heatmap_annotation_label(&annotation.row_label, "row label")?;
260        annotation
261            .text
262            .required_source("heatmap fully-null row annotation text")?;
263        Ok(annotation)
264    }
265
266    /// Normalized y-category targeted by this annotation.
267    #[must_use]
268    pub fn row_label(&self) -> &str {
269        &self.row_label
270    }
271
272    /// Verbatim text wrapped inside the merged row.
273    #[must_use]
274    pub fn text(&self) -> &str {
275        self.text.as_str()
276    }
277
278    pub(crate) const fn content(&self) -> &crate::Text {
279        &self.text
280    }
281}
282
283fn validate_heatmap_annotation_label(value: &str, role: &str) -> Result<(), crate::Error> {
284    if value.is_empty() || value.trim() != value || value.chars().any(char::is_control) {
285        return Err(crate::Error::Data(format!(
286            "heatmap fully-null row annotation {role} must be nonempty, trimmed, and contain no control characters"
287        )));
288    }
289    Ok(())
290}
291
292/// Explicit endpoint identities and colors for a dumbbell plot.
293///
294/// Each exact Color replaces the entire endpoint fill and its literal guide
295/// paint. Theme marker geometry and the independent outline still apply.
296/// ```
297/// use lichtung_plot::{Color, DumbbellEndpoints};
298/// let endpoints = DumbbellEndpoints::new(
299///     "Before", Color::rgba(20, 80, 140, 128), "After", Color::rgb(180, 60, 40),
300/// )?;
301/// assert_eq!(endpoints.left_color().get_alpha(), 128);
302/// assert_eq!(endpoints.right_color().get_alpha(), 255);
303/// # Ok::<(), lichtung_plot::Error>(())
304/// ```
305///
306/// ```compile_fail
307/// use lichtung_plot::DumbbellEndpoints;
308/// let _ = DumbbellEndpoints::new("Before", (20, 80, 140), "After", (180, 60, 40));
309/// ```
310#[derive(Debug, Clone, PartialEq, Eq)]
311pub struct DumbbellEndpoints {
312    left_label: String,
313    left_color: crate::Color,
314    right_label: String,
315    right_color: crate::Color,
316}
317
318impl DumbbellEndpoints {
319    /// Construct two explicitly labeled and colored endpoint identities.
320    pub fn new(
321        left_label: impl Into<String>,
322        left_color: crate::Color,
323        right_label: impl Into<String>,
324        right_color: crate::Color,
325    ) -> Result<Self, crate::Error> {
326        let endpoints = Self {
327            left_label: left_label.into(),
328            left_color,
329            right_label: right_label.into(),
330            right_color,
331        };
332        if endpoints.left_label.trim().is_empty() || endpoints.right_label.trim().is_empty() {
333            return Err(crate::Error::Data(
334                "dumbbell endpoint labels must not be empty".into(),
335            ));
336        }
337        if endpoints.left_label.trim() != endpoints.left_label
338            || endpoints.right_label.trim() != endpoints.right_label
339            || endpoints.left_label.chars().any(char::is_control)
340            || endpoints.right_label.chars().any(char::is_control)
341        {
342            return Err(crate::Error::Data(
343                "dumbbell endpoint labels must contain no surrounding whitespace or control characters"
344                    .into(),
345            ));
346        }
347        if endpoints.left_label == endpoints.right_label {
348            return Err(crate::Error::Data(
349                "dumbbell endpoint labels must be distinct".into(),
350            ));
351        }
352        Ok(endpoints)
353    }
354
355    /// Verbatim label for the left-value endpoint.
356    #[must_use]
357    pub fn left_label(&self) -> &str {
358        &self.left_label
359    }
360
361    /// Complete exact RGBA paint for the left-value endpoint and its guide key.
362    #[must_use]
363    pub const fn left_color(&self) -> crate::Color {
364        self.left_color
365    }
366
367    /// Verbatim label for the right-value endpoint.
368    #[must_use]
369    pub fn right_label(&self) -> &str {
370        &self.right_label
371    }
372
373    /// Complete exact RGBA paint for the right-value endpoint and its guide key.
374    #[must_use]
375    pub const fn right_color(&self) -> crate::Color {
376        self.right_color
377    }
378}
379
380/// Caller-owned labels for waterfall base and terminal annotations.
381#[derive(Debug, Clone, PartialEq, Eq)]
382pub struct WaterfallLabels {
383    base: crate::Text,
384    terminal: crate::Text,
385}
386
387impl WaterfallLabels {
388    /// Construct verbatim display labels for the base and terminal values.
389    /// Each Text retains independent complete appearance and line alignment for
390    /// the displayed name plus formatted numeric value. Readers borrow the name.
391    pub fn new(
392        base: impl Into<crate::Text>,
393        terminal: impl Into<crate::Text>,
394    ) -> Result<Self, crate::Error> {
395        let labels = Self {
396            base: base.into(),
397            terminal: terminal.into(),
398        };
399        labels.base.required_source("waterfall base label")?;
400        labels
401            .terminal
402            .required_source("waterfall terminal label")?;
403        Ok(labels)
404    }
405
406    /// Verbatim label for the base or expected output.
407    #[must_use]
408    pub fn base(&self) -> &str {
409        self.base.as_str()
410    }
411
412    /// Verbatim label for the terminal value or final prediction.
413    #[must_use]
414    pub fn terminal(&self) -> &str {
415        self.terminal.as_str()
416    }
417
418    pub(crate) const fn contents(&self) -> [&crate::Text; 2] {
419        [&self.base, &self.terminal]
420    }
421}
422
423/// Legend policy for a heterogeneous composed canvas.
424#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
425pub enum CanvasLegendPolicy {
426    /// Render each panel's own legend.
427    #[default]
428    PerPlot,
429    /// Render one legend after validating that panel legends are compatible.
430    Shared,
431    /// Suppress all panel legends.
432    Hidden,
433}
434
435/// Semantic composition of one discrete legend, independently of its appearance.
436///
437/// Standalone plots and facets use their Plot's selection. Canvas PerPlot uses
438/// each Plot's selection; Shared uses the Canvas selection for every contributor
439/// without changing the stored Plot values. Hidden skips guide-only composition.
440/// Continuous color guides keep their own representation.
441#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
442pub enum LegendComposition {
443    /// Preserve observed identities and complete mark keys in one section.
444    #[default]
445    Combined,
446    /// Explain independent mapped channels in ordered sections within one frame.
447    ///
448    /// Independent group/hue pairs require an explicitly configured group-style
449    /// channel, currently Interaction styles. Unsupported decompositions refuse
450    /// before fonts. Same-field channels remain one complete joint section.
451    Separate,
452}
453
454/// Requested legend placement.
455///
456/// Inside positions are limited to plot edges so layout can reserve data space
457/// without placing the legend in the middle of the main graphic.
458#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
459pub enum LegendPosition {
460    /// Use the plot-type default placement.
461    #[default]
462    Auto,
463    /// Inside the axes at the top-left edge.
464    InsideTopLeft,
465    /// Inside the axes at the top edge.
466    InsideTop,
467    /// Inside the axes at the top-right edge.
468    InsideTopRight,
469    /// Inside the axes at the right-top edge.
470    InsideRightTop,
471    /// Inside the axes at the right edge.
472    InsideRight,
473    /// Inside the axes at the right-bottom edge.
474    InsideRightBottom,
475    /// Inside the axes at the bottom-left edge.
476    InsideBottomLeft,
477    /// Inside the axes at the bottom edge.
478    InsideBottom,
479    /// Inside the axes at the bottom-right edge.
480    InsideBottomRight,
481    /// Inside the axes at the left-top edge.
482    InsideLeftTop,
483    /// Inside the axes at the left edge.
484    InsideLeft,
485    /// Inside the axes at the left-bottom edge.
486    InsideLeftBottom,
487    /// Outside the axes in right-side whitespace, aligned to panel top.
488    OutsideRightTop,
489    /// Outside the axes in right-side whitespace, aligned to panel center.
490    OutsideRight,
491    /// Outside the axes in right-side whitespace, aligned to panel bottom.
492    OutsideRightBottom,
493    /// Outside the axes in top whitespace, aligned to panel left.
494    OutsideTopLeft,
495    /// Outside the axes in top whitespace, aligned to panel center.
496    OutsideTop,
497    /// Outside the axes in top whitespace, aligned to panel right.
498    OutsideTopRight,
499    /// Outside the axes in bottom whitespace, aligned to panel left.
500    OutsideBottomLeft,
501    /// Outside the axes in bottom whitespace, aligned to panel center.
502    OutsideBottom,
503    /// Outside the axes in bottom whitespace, aligned to panel right.
504    OutsideBottomRight,
505    /// Outside the axes in left-side whitespace, aligned to panel top.
506    OutsideLeftTop,
507    /// Outside the axes in left-side whitespace, aligned to panel center.
508    OutsideLeft,
509    /// Outside the axes in left-side whitespace, aligned to panel bottom.
510    OutsideLeftBottom,
511}
512
513/// Visibility and placement policy for a plot legend.
514#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
515pub enum LegendPolicy {
516    /// Use the plot-type default visibility and automatic placement.
517    #[default]
518    Automatic,
519    /// Do not draw a legend.
520    Hidden,
521    /// Draw the legend at the requested placement.
522    Visible(LegendPosition),
523}
524
525impl LegendPolicy {
526    pub(crate) const fn position(self) -> LegendPosition {
527        match self {
528            Self::Visible(position) => position,
529            Self::Automatic | Self::Hidden => LegendPosition::Auto,
530        }
531    }
532}
533
534macro_rules! define_plot_kinds {
535    ($($variant:ident => $documentation:literal),+ $(,)?) => {
536        /// Which plot type a [`crate::Plot`] will produce.
537        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
538        pub enum PlotKind {
539            $(
540                #[doc = $documentation]
541                $variant,
542            )+
543        }
544    };
545}
546
547define_plot_kinds! {
548    Scatter => "Scatter plot.",
549    Histogram => "Single-series numeric histogram with an optional KDE-and-rug density composite.",
550    Density => "Gaussian kernel density estimate.",
551    Qq => "Quantile-quantile plot against a standard normal distribution.",
552    PointInterval => "Point estimates with explicit lower and upper interval bounds.",
553    Line => "Grouped ordered numeric series with optional precomputed ribbons.",
554    Trajectory => "Explicit-group repeated trajectories with neutral connectors.",
555    LinePath => "Explicit-group numeric paths in source-row order.",
556    Interaction => "Precomputed interaction profiles with explicit bounds and optional closed trace styles.",
557    Coefficient => "Named model coefficients with optional drawable bounds.",
558    Forest => "Complete interval estimates with an explicit scientific null.",
559    Dumbbell => "Horizontal paired endpoint estimates with optional replicate identity.",
560    Heatmap => "Categorical grid with a continuous numeric fill.",
561    Bar => "Bar plot with CI error bars.",
562    HorizontalBar => "Horizontal bar plot.",
563    StackedBar => "Stacked vertical bar plot using one categorical series.",
564    StackedHorizontalBar => "Stacked horizontal bar plot using one categorical series.",
565    Boxplot => "Box-and-whisker plot.",
566    Violin => "Mirrored KDE violins with centered inner summaries.",
567    Raincloud => "One-sided KDE clouds with separated summaries and complete observation strips.",
568    Regression => "Regression plot (scatter + fit line).",
569    Marginal => "Marginal plot (marginal histograms + central scatter).",
570    Matrix => "Scatter matrix (small multiples).",
571    Beeswarm => "Categorical rows of collision-separated points with continuous x and color values.",
572    Waterfall => "Cumulative signed deltas between a base and terminal value.",
573}
574
575impl PlotKind {
576    pub(crate) const fn uses_unified_series(self) -> bool {
577        matches!(
578            self,
579            Self::Bar
580                | Self::HorizontalBar
581                | Self::StackedBar
582                | Self::StackedHorizontalBar
583                | Self::Boxplot
584                | Self::Violin
585                | Self::Raincloud
586        )
587    }
588
589    pub(crate) const fn supports_significance_annotations(self) -> bool {
590        matches!(
591            self,
592            Self::Bar
593                | Self::HorizontalBar
594                | Self::StackedBar
595                | Self::StackedHorizontalBar
596                | Self::Boxplot
597                | Self::Violin
598                | Self::Raincloud
599                | Self::Coefficient
600        )
601    }
602
603    pub(crate) const fn legend_default(self, explicit_y_limits: bool) -> LegendDefault {
604        match self {
605            Self::HorizontalBar | Self::StackedHorizontalBar | Self::Dumbbell => {
606                LegendDefault::TopRight(LegendClearance::HorizontalMaximum)
607            }
608            Self::Bar
609            | Self::StackedBar
610            | Self::Line
611            | Self::Trajectory
612            | Self::LinePath
613            | Self::Interaction
614            | Self::Boxplot
615            | Self::Violin
616            | Self::Raincloud
617            | Self::Regression => LegendDefault::TopRight(LegendClearance::VerticalMaximum),
618            Self::Scatter | Self::Marginal if !explicit_y_limits => {
619                LegendDefault::TopRight(LegendClearance::VerticalMaximum)
620            }
621            Self::Matrix => LegendDefault::SelfManaged,
622            _ => LegendDefault::LowestOverlap,
623        }
624    }
625}
626
627#[derive(Debug, Clone, Copy, PartialEq, Eq)]
628pub(crate) enum LegendDefault {
629    LowestOverlap,
630    TopRight(LegendClearance),
631    SelfManaged,
632}
633
634#[derive(Debug, Clone, Copy, PartialEq, Eq)]
635pub(crate) enum LegendClearance {
636    HorizontalMaximum,
637    VerticalMaximum,
638}
639
640use crate::Error;
641
642/// A short borrow of one root-issued allocation and its canonical occurrence.
643/// Geometry, domains and dimensions have exactly one owner: the allocation.
644pub(crate) struct PlotMeasureContext<'v, 'src> {
645    pub(crate) registered: &'v crate::orchestrator::registration::PlotRegistration<'src>,
646    pub(crate) assignment: crate::orchestrator::assignment::RootPlotAssignmentRef<'v>,
647    pub(crate) canvas: Option<&'src crate::Canvas>,
648    pub(crate) text: &'v crate::text::TextService,
649    pub(crate) operation: &'v crate::font::canonical::OperationContext,
650    pub(crate) intrinsic: &'v crate::orchestrator::root::PlotIntrinsics,
651    pub(crate) guides: crate::decorations::legend::discrete::scoped::GuideConsumption<'v>,
652    pub(crate) fit_scope: &'v crate::layout::fit::FitScope,
653}
654
655impl<'v, 'src> PlotMeasureContext<'v, 'src> {
656    pub(crate) const fn fit_scope(&self) -> &'v crate::layout::fit::FitScope {
657        self.fit_scope
658    }
659
660    pub(crate) const fn intrinsic(&self) -> &'v crate::orchestrator::root::PlotIntrinsics {
661        self.intrinsic
662    }
663
664    pub(crate) fn family(&self) -> Result<crate::orchestrator::registration::FamilyRef<'v>, Error> {
665        crate::layout::interior::InteriorRoute::classify(self.registered.family.kind())
666            .validate(self.registered.source)?;
667        self.registered.family()
668    }
669
670    #[expect(
671        clippy::unnecessary_wraps,
672        reason = "the fixed fallible axis-pair interface projects prepared operands without adding validation"
673    )]
674    pub(crate) fn axis_pair(
675        &self,
676        scope: crate::orchestrator::assignment::AxisPairScope,
677    ) -> Result<crate::orchestrator::assignment::AxisPairRef<'v>, Error> {
678        use crate::layout::AxisSide::{Bottom, Left};
679        use crate::orchestrator::assignment::{AssignedAxisRef, AxisDomainAssignments as D};
680        use crate::orchestrator::assignment::{AxisPairRef, AxisPairScope as S};
681        use crate::orchestrator::registration::{AxisSlot as A, MarginalStrip};
682        let axes = &self.registered.axes;
683        let source = self.registered.source;
684        let pair = match (scope, &self.assignment.local.domains) {
685            (S::Pair, D::Pair(domains)) => {
686                [(A::Pair(Bottom), &domains[0]), (A::Pair(Left), &domains[1])]
687            }
688            (S::MarginalCentral, D::Marginal { central, .. }) => [
689                (A::MarginalCentral(Bottom), &central[0]),
690                (A::MarginalCentral(Left), &central[1]),
691            ],
692            (
693                S::MarginalTop,
694                D::Marginal {
695                    central,
696                    strip_density,
697                },
698            ) => [
699                (A::MarginalCentral(Bottom), &central[0]),
700                (
701                    A::MarginalStripDensity(MarginalStrip::Top),
702                    &strip_density[0],
703                ),
704            ],
705            (
706                S::MarginalRight,
707                D::Marginal {
708                    central,
709                    strip_density,
710                },
711            ) => [
712                (
713                    A::MarginalStripDensity(MarginalStrip::Right),
714                    &strip_density[1],
715                ),
716                (A::MarginalCentral(Left), &central[1]),
717            ],
718            (S::MatrixCell { row, column }, D::Matrix { variables, .. }) => [
719                (A::MatrixVariable(column), &variables[column]),
720                (A::MatrixVariable(row), &variables[row]),
721            ],
722            (
723                S::MatrixDiagonalDensity { variable },
724                D::Matrix {
725                    variables,
726                    diagonal_density,
727                },
728            ) => [
729                (A::MatrixVariable(variable), &variables[variable]),
730                (
731                    A::MatrixDiagonalDensity(variable),
732                    &diagonal_density[variable],
733                ),
734            ],
735            _ => unreachable!("axis pair belongs to the selected interior route"),
736        };
737        Ok(AxisPairRef {
738            axes: pair.map(|(slot, domain)| AssignedAxisRef {
739                base: axes.axis_at(source, slot),
740                domain,
741            }),
742        })
743    }
744
745    pub(crate) fn data(&self) -> Result<crate::data::PlotData<'src, 'v>, Error> {
746        self.registered.data(self.operation)
747    }
748
749    pub(crate) fn request(&self) -> crate::text::TextRequestContext<'v, 'src> {
750        crate::text::TextRequestContext::new(&self.registered.appearance, self.text)
751    }
752
753    #[expect(
754        clippy::unnecessary_wraps,
755        reason = "native measurements share the existing fallible range-reader interface"
756    )]
757    pub(crate) fn axis_range(&self, side: crate::layout::AxisSide) -> Result<(f64, f64), Error> {
758        use crate::orchestrator::assignment::AxisDomainAssignments;
759        let index = usize::from(side == crate::layout::AxisSide::Left);
760        let pair = match &self.assignment.local.domains {
761            AxisDomainAssignments::Pair(pair) => pair,
762            AxisDomainAssignments::Marginal { central, .. } => central,
763            AxisDomainAssignments::Matrix { .. } => {
764                unreachable!("Matrix selects an indexed axis pair")
765            }
766        };
767        Ok(pair[index].extent.pair())
768    }
769
770    pub(crate) fn prepared_category_labels(
771        &self,
772        side: usize,
773    ) -> Option<&'v [crate::layout::AxisTick]> {
774        Some(&self.registered.axes.coordinate()?.categories(side)?.ticks)
775    }
776
777    pub(crate) fn semantic_inputs(
778        &self,
779        scope: crate::orchestrator::assignment::AxisPairScope,
780    ) -> Result<[crate::layout::AxisSemanticInputs; 2], Error> {
781        use crate::orchestrator::assignment::AssignedAxisRef;
782
783        let mut inputs = self
784            .axis_pair(scope)?
785            .axes
786            .map(AssignedAxisRef::semantic_inputs);
787        for (side, input) in inputs.iter_mut().enumerate() {
788            input
789                .text_layout
790                .clone_from(&self.registered.appearance.text_layouts.ticks[side]);
791        }
792        Ok(inputs)
793    }
794}
795
796/// Current constrained interior result. FitOutcome/PlanError distinguish measured,
797/// terminal fit and fatal outcomes; provisional misses belong to FeedbackRound.
798/// Point/path families retain selected marks and annotations; other marks remain combined.
799#[derive(Debug)]
800pub(crate) struct PlotRenderResult {
801    pub(crate) layout: Layout,
802    pub(crate) axes: Option<crate::layout::AxisSystemPlan>,
803    pub(crate) grid_axis_gutters: Option<[f64; 4]>,
804    pub(crate) x_domain: AxisDomain,
805    pub(crate) y_domain: AxisDomain,
806    pub(crate) significance: Option<SignificancePlan>,
807    pub(crate) discrete_guide:
808        Option<std::sync::Arc<crate::decorations::legend::discrete::PreparedGuide>>,
809    pub(crate) decoration_mode: DecorationMode,
810    pub(crate) x_tick_keys: Option<Vec<String>>,
811    pub(crate) y_tick_keys: Option<Vec<String>>,
812    pub(crate) deferred_annotation_text: Vec<crate::layout::DeferredAnnotationTextPlan>,
813    pub(crate) producer_text: Vec<crate::render::backend::PlacedText>,
814    pub(crate) panel_text: Vec<crate::decorations::panel_text::PlotTextAnnotationPlan>,
815    pub(crate) self_managed_legend: Option<std::sync::Arc<crate::decorations::legend::Legend>>,
816    pub(crate) matrix_axes: Option<std::sync::Arc<crate::plots::matrix::MatrixAxisPlan>>,
817    pub(crate) marks: Option<std::sync::Arc<crate::layout::interior::SelectedMarkPlan>>,
818    pub(crate) annotations: Option<std::sync::Arc<crate::layout::interior::SelectedAnnotationPlan>>,
819    pub(crate) numeric_presentation:
820        Option<std::sync::Arc<crate::numeric::set::NumericPresentation>>,
821}
822
823/// Semantic kind of one renderer-resolved axis domain.
824#[derive(Debug, Clone, Copy, PartialEq, Eq)]
825pub(crate) enum AxisDomain {
826    Continuous,
827    Categorical,
828}
829
830#[derive(Debug, Clone, Copy, PartialEq, Eq)]
831pub(crate) enum DecorationMode {
832    Standard,
833    SelfManaged,
834}
835
836impl PlotRenderResult {
837    pub(crate) fn draw_body(
838        &self,
839        backend: &mut dyn crate::render::backend::Backend,
840    ) -> Result<DecorationMode, Error> {
841        self.marks
842            .as_ref()
843            .ok_or_else(|| Error::Render("selected mark payload is missing".into()))?
844            .draw(backend)?;
845        self.annotations
846            .as_ref()
847            .ok_or_else(|| Error::Render("selected annotation payload is missing".into()))?
848            .draw(backend)?;
849        Ok(self.decoration_mode)
850    }
851
852    pub(crate) fn new(
853        layout: Layout,
854        discrete_guide: Option<std::sync::Arc<crate::decorations::legend::discrete::PreparedGuide>>,
855    ) -> Self {
856        Self {
857            layout,
858            axes: None,
859            grid_axis_gutters: None,
860            x_domain: AxisDomain::Continuous,
861            y_domain: AxisDomain::Continuous,
862            significance: None,
863            discrete_guide,
864            decoration_mode: DecorationMode::Standard,
865            x_tick_keys: None,
866            y_tick_keys: None,
867            deferred_annotation_text: Vec::new(),
868            producer_text: Vec::new(),
869            panel_text: Vec::new(),
870            self_managed_legend: None,
871            matrix_axes: None,
872            marks: None,
873            annotations: None,
874            numeric_presentation: None,
875        }
876    }
877
878    pub(crate) fn with_self_managed_decorations(mut self) -> Self {
879        self.decoration_mode = DecorationMode::SelfManaged;
880        self
881    }
882
883    pub(crate) fn with_resolved_axis_keys(
884        mut self,
885        x_keys: Vec<String>,
886        y_keys: Vec<String>,
887    ) -> Self {
888        self.x_tick_keys = Some(x_keys);
889        self.y_tick_keys = Some(y_keys);
890        self
891    }
892}