lichtung-plot 0.2.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Complete construction values, independent of per-operation resolution state.

use crate::font::canonical::FontStack;
use crate::Result;

use super::{
    AnnotationTheme, AxisTheme, ColorScales, CompositionTheme, LegendTheme, MarkTheme,
    ResolvedTheme, SurfaceTheme, TypographyTheme,
};

/// Complete immutable appearance, independent of fonts discovered during rendering.
///
/// Built-in constructors return ordinary complete values. Customize a cloned
/// value with [`Theme::customize`] and attach the built result to a Plot or Canvas.
///
/// ```
/// use lichtung_plot::{Color, Theme};
/// let base = Theme::publication();
/// let title = base.typography().get_root().get_title().clone()
///     .color(Color::hex("#194A75")?)?;
/// let root = base.typography().get_root().clone().title(title)?;
/// let typography = base.typography().clone().root(root)?;
/// let custom = base.customize().typography(typography).build()?;
/// assert_ne!(custom.typography(), base.typography());
/// # Ok::<(), lichtung_plot::Error>(())
/// ```
///
/// Built-ins are complete values, not closed selector variants:
/// ```compile_fail
/// let _ = lichtung_plot::Theme::Publication;
/// ```
///
/// Resolution is private:
/// ```compile_fail
/// let _ = lichtung_plot::Theme::publication().resolve();
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct Theme {
    pub(crate) surfaces: SurfaceTheme,
    pub(crate) typography: TypographyTheme,
    pub(crate) axes: AxisTheme,
    pub(crate) legend: LegendTheme,
    pub(crate) composition: CompositionTheme,
    pub(crate) marks: MarkTheme,
    pub(crate) annotations: AnnotationTheme,
    pub(crate) color_scales: ColorScales,
}

/// Construction-only working copy of a complete [`Theme`].
#[derive(Clone, Debug)]
pub struct ThemeBuilder {
    value: Theme,
}

thread_local! {
    static CONSTRUCTION_THEME: std::cell::RefCell<Option<std::sync::Arc<Theme>>> =
        const { std::cell::RefCell::new(None) };
}

struct ConstructionThemeGuard(Option<std::sync::Arc<Theme>>);

impl Drop for ConstructionThemeGuard {
    fn drop(&mut self) {
        let previous = self.0.take();
        let retired = CONSTRUCTION_THEME.with(|slot| slot.replace(previous));
        drop(retired);
    }
}

macro_rules! components {
    ($($field:ident: $ty:ty => $get:ident),+ $(,)?) => {
        impl Theme {
            $(
                #[doc = concat!("Borrow the complete `", stringify!($field), "` component.")]
                pub fn $field(&self) -> &$ty { &self.$field }
            )+
        }
        impl ThemeBuilder {
            $(
                #[doc = concat!("Borrow the current complete `", stringify!($field), "` component.")]
                pub fn $get(&self) -> &$ty { self.value.$field() }
                #[doc = concat!("Replace the complete `", stringify!($field), "` construction input.")]
                #[must_use]
                pub fn $field(mut self, value: $ty) -> Self {
                    self.value.$field = value;
                    self
                }
            )+
        }
    };
}

components!(surfaces: SurfaceTheme => get_surfaces,
    typography: TypographyTheme => get_typography, axes: AxisTheme => get_axes,
    legend: LegendTheme => get_legend, composition: CompositionTheme => get_composition,
    marks: MarkTheme => get_marks, annotations: AnnotationTheme => get_annotations,
    color_scales: ColorScales => get_color_scales);

impl Theme {
    /// Supply a construction default for new plots and canvases in a synchronous
    /// closure. Existing configurations and render operations remain independent
    /// of the scope. Nested scopes restore their predecessor, including on unwind.
    ///
    /// This is thread-local, not task-local: returning a Future does not extend
    /// the scope to its later polling.
    pub fn with_context<R>(&self, f: impl FnOnce() -> R) -> R {
        let current = std::sync::Arc::new(self.clone());
        let previous = CONSTRUCTION_THEME.with(|slot| slot.replace(Some(current)));
        let _guard = ConstructionThemeGuard(previous);
        f()
    }

    pub(crate) fn captured_default() -> Option<std::sync::Arc<Self>> {
        CONSTRUCTION_THEME.with(|slot| slot.borrow().clone())
    }

    #[expect(
        clippy::too_many_arguments,
        reason = "the complete constructor retains eight independently owned components"
    )]
    /// Construct all eight complete components without discovering fonts or data domains.
    pub fn new(
        surfaces: SurfaceTheme,
        typography: TypographyTheme,
        axes: AxisTheme,
        legend: LegendTheme,
        composition: CompositionTheme,
        marks: MarkTheme,
        annotations: AnnotationTheme,
        color_scales: ColorScales,
    ) -> Result<Self> {
        let value = Self {
            surfaces,
            typography,
            axes,
            legend,
            composition,
            marks,
            annotations,
            color_scales,
        };
        value.validate()?;
        Ok(value)
    }

    pub(crate) fn validate(&self) -> Result<()> {
        self.typography().validate()?;
        self.axes().validate()?;
        self.legend().validate_in()?;
        self.marks().validate()?;
        self.annotations().validate()
    }

    /// Clean high-contrast publication appearance with generous whitespace.
    pub fn publication() -> Self {
        super::resolved::publication_theme().expect("validated publication constructor")
    }

    /// Muted blues and greens with bottom/left coordinate frame sides.
    pub fn nature() -> Self {
        super::resolved::nature_theme().expect("validated nature constructor")
    }

    /// High-saturation scientific palette and emphasized axes.
    pub fn science() -> Self {
        super::resolved::science_theme().expect("validated science constructor")
    }

    /// Accessible pastel appearance for HCI publications.
    pub fn chi() -> Self {
        super::resolved::chi_theme().expect("validated CHI constructor")
    }

    pub(crate) fn resolve(&self) -> Result<ResolvedTheme> {
        ResolvedTheme::new(self.clone())
    }

    /// Start a complete construction-only working copy, leaving this value unchanged.
    pub fn customize(&self) -> ThemeBuilder {
        ThemeBuilder::new(self.clone())
    }
}

impl ThemeBuilder {
    /// Consume a complete initial theme for construction edits.
    pub fn new(value: Theme) -> Self {
        Self { value }
    }

    /// Replace the stack in all eighteen roles once; later role edits take precedence normally.
    pub fn font_stack(mut self, stack: FontStack) -> Result<Self> {
        self.value.typography = self.value.typography.with_font_stack(stack)?;
        Ok(self)
    }

    /// Validate and return the complete immutable appearance.
    pub fn build(self) -> Result<Theme> {
        self.value.validate()?;
        Ok(self.value)
    }
}