Skip to main content

lichtung_plot/theme/
value.rs

1//! Complete construction values, independent of per-operation resolution state.
2
3use crate::font::canonical::FontStack;
4use crate::Result;
5
6use super::{
7    AnnotationTheme, AxisTheme, ColorScales, CompositionTheme, LegendTheme, MarkTheme,
8    ResolvedTheme, SurfaceTheme, TypographyTheme,
9};
10
11/// Complete immutable appearance, independent of fonts discovered during rendering.
12///
13/// Built-in constructors return ordinary complete values. Customize a cloned
14/// value with [`Theme::customize`] and attach the built result to a Plot or Canvas.
15///
16/// ```
17/// use lichtung_plot::{Color, Theme};
18/// let base = Theme::publication();
19/// let title = base.typography().get_root().get_title().clone()
20///     .color(Color::hex("#194A75")?)?;
21/// let root = base.typography().get_root().clone().title(title)?;
22/// let typography = base.typography().clone().root(root)?;
23/// let custom = base.customize().typography(typography).build()?;
24/// assert_ne!(custom.typography(), base.typography());
25/// # Ok::<(), lichtung_plot::Error>(())
26/// ```
27///
28/// Built-ins are complete values, not closed selector variants:
29/// ```compile_fail
30/// let _ = lichtung_plot::Theme::Publication;
31/// ```
32///
33/// Resolution is private:
34/// ```compile_fail
35/// let _ = lichtung_plot::Theme::publication().resolve();
36/// ```
37#[derive(Clone, Debug, PartialEq)]
38pub struct Theme {
39    pub(crate) surfaces: SurfaceTheme,
40    pub(crate) typography: TypographyTheme,
41    pub(crate) axes: AxisTheme,
42    pub(crate) legend: LegendTheme,
43    pub(crate) composition: CompositionTheme,
44    pub(crate) marks: MarkTheme,
45    pub(crate) annotations: AnnotationTheme,
46    pub(crate) color_scales: ColorScales,
47}
48
49/// Construction-only working copy of a complete [`Theme`].
50#[derive(Clone, Debug)]
51pub struct ThemeBuilder {
52    value: Theme,
53}
54
55thread_local! {
56    static CONSTRUCTION_THEME: std::cell::RefCell<Option<std::sync::Arc<Theme>>> =
57        const { std::cell::RefCell::new(None) };
58}
59
60struct ConstructionThemeGuard(Option<std::sync::Arc<Theme>>);
61
62impl Drop for ConstructionThemeGuard {
63    fn drop(&mut self) {
64        let previous = self.0.take();
65        let retired = CONSTRUCTION_THEME.with(|slot| slot.replace(previous));
66        drop(retired);
67    }
68}
69
70macro_rules! components {
71    ($($field:ident: $ty:ty => $get:ident),+ $(,)?) => {
72        impl Theme {
73            $(
74                #[doc = concat!("Borrow the complete `", stringify!($field), "` component.")]
75                pub fn $field(&self) -> &$ty { &self.$field }
76            )+
77        }
78        impl ThemeBuilder {
79            $(
80                #[doc = concat!("Borrow the current complete `", stringify!($field), "` component.")]
81                pub fn $get(&self) -> &$ty { self.value.$field() }
82                #[doc = concat!("Replace the complete `", stringify!($field), "` construction input.")]
83                #[must_use]
84                pub fn $field(mut self, value: $ty) -> Self {
85                    self.value.$field = value;
86                    self
87                }
88            )+
89        }
90    };
91}
92
93components!(surfaces: SurfaceTheme => get_surfaces,
94    typography: TypographyTheme => get_typography, axes: AxisTheme => get_axes,
95    legend: LegendTheme => get_legend, composition: CompositionTheme => get_composition,
96    marks: MarkTheme => get_marks, annotations: AnnotationTheme => get_annotations,
97    color_scales: ColorScales => get_color_scales);
98
99impl Theme {
100    /// Supply a construction default for new plots and canvases in a synchronous
101    /// closure. Existing configurations and render operations remain independent
102    /// of the scope. Nested scopes restore their predecessor, including on unwind.
103    ///
104    /// This is thread-local, not task-local: returning a Future does not extend
105    /// the scope to its later polling.
106    pub fn with_context<R>(&self, f: impl FnOnce() -> R) -> R {
107        let current = std::sync::Arc::new(self.clone());
108        let previous = CONSTRUCTION_THEME.with(|slot| slot.replace(Some(current)));
109        let _guard = ConstructionThemeGuard(previous);
110        f()
111    }
112
113    pub(crate) fn captured_default() -> Option<std::sync::Arc<Self>> {
114        CONSTRUCTION_THEME.with(|slot| slot.borrow().clone())
115    }
116
117    #[expect(
118        clippy::too_many_arguments,
119        reason = "the complete constructor retains eight independently owned components"
120    )]
121    /// Construct all eight complete components without discovering fonts or data domains.
122    pub fn new(
123        surfaces: SurfaceTheme,
124        typography: TypographyTheme,
125        axes: AxisTheme,
126        legend: LegendTheme,
127        composition: CompositionTheme,
128        marks: MarkTheme,
129        annotations: AnnotationTheme,
130        color_scales: ColorScales,
131    ) -> Result<Self> {
132        let value = Self {
133            surfaces,
134            typography,
135            axes,
136            legend,
137            composition,
138            marks,
139            annotations,
140            color_scales,
141        };
142        value.validate()?;
143        Ok(value)
144    }
145
146    pub(crate) fn validate(&self) -> Result<()> {
147        self.typography().validate()?;
148        self.axes().validate()?;
149        self.legend().validate_in()?;
150        self.marks().validate()?;
151        self.annotations().validate()
152    }
153
154    /// Clean high-contrast publication appearance with generous whitespace.
155    pub fn publication() -> Self {
156        super::resolved::publication_theme().expect("validated publication constructor")
157    }
158
159    /// Muted blues and greens with bottom/left coordinate frame sides.
160    pub fn nature() -> Self {
161        super::resolved::nature_theme().expect("validated nature constructor")
162    }
163
164    /// High-saturation scientific palette and emphasized axes.
165    pub fn science() -> Self {
166        super::resolved::science_theme().expect("validated science constructor")
167    }
168
169    /// Accessible pastel appearance for HCI publications.
170    pub fn chi() -> Self {
171        super::resolved::chi_theme().expect("validated CHI constructor")
172    }
173
174    pub(crate) fn resolve(&self) -> Result<ResolvedTheme> {
175        ResolvedTheme::new(self.clone())
176    }
177
178    /// Start a complete construction-only working copy, leaving this value unchanged.
179    pub fn customize(&self) -> ThemeBuilder {
180        ThemeBuilder::new(self.clone())
181    }
182}
183
184impl ThemeBuilder {
185    /// Consume a complete initial theme for construction edits.
186    pub fn new(value: Theme) -> Self {
187        Self { value }
188    }
189
190    /// Replace the stack in all eighteen roles once; later role edits take precedence normally.
191    pub fn font_stack(mut self, stack: FontStack) -> Result<Self> {
192        self.value.typography = self.value.typography.with_font_stack(stack)?;
193        Ok(self)
194    }
195
196    /// Validate and return the complete immutable appearance.
197    pub fn build(self) -> Result<Theme> {
198        self.value.validate()?;
199        Ok(self.value)
200    }
201}