Skip to main content

lichtung_plot/text/
value.rs

1//! Authored text value and its local appearance requests.
2
3use super::{validate_for, TextAlignment, TextAppearance, TextLayout};
4
5/// Authored display text with optional complete appearance and layout instructions.
6///
7/// Plain strings carry no local instructions. Content validation happens
8/// at the receiving constructor or preflight, without rewriting the source.
9/// Clones share immutable source bytes and retain complete local instructions.
10///
11/// ```
12/// use lichtung_plot::{
13///     NumericValues,
14///     Plot,
15///     Text,
16///     Theme,
17///     coordinates::DataAreaCorner,
18///     elements::PlotTextAnnotation,
19///     layout::TextPanel,
20///     text::{TextAlignment, TextLayout},
21/// };
22/// let style = Theme::publication().typography().get_composition()
23///     .get_text_panel_title().clone().font_size(24.0)?;
24/// let title = Text::new("Study\ncontext").style(style).alignment(TextAlignment::End);
25/// let note = PlotTextAnnotation::new(DataAreaCorner::TopLeft, title.clone())?;
26/// let plot = Plot::scatter(NumericValues::new("x", [0.0, 1.0]),
27///     NumericValues::new("y", [1.0, 0.0]))
28///     .title(title.clone()).title("Updated heading")
29///     .caption(Text::new("Centered caption").alignment(TextAlignment::Center));
30/// let panel = TextPanel::new(title, Text::new("Independent body")
31///     .layout(TextLayout::default().alignment(TextAlignment::Start)))?;
32/// assert_eq!(panel.title(), "Study\ncontext");
33/// assert_eq!(note.text(), panel.title());
34/// # let _ = plot;
35/// # Ok::<(), lichtung_plot::Error>(())
36/// ```
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct Text {
39    source: Option<std::sync::Arc<String>>,
40    style: Option<crate::theme::TextTheme>,
41    layout: Option<TextLayout>,
42}
43
44impl Text {
45    /// Retain one verbatim display source.
46    #[must_use]
47    pub fn new(source: impl Into<String>) -> Self {
48        Self {
49            source: Some(std::sync::Arc::new(source.into())),
50            style: None,
51            layout: None,
52        }
53    }
54
55    /// Borrow the original source.
56    #[must_use]
57    pub fn as_str(&self) -> &str {
58        self.source.as_ref().map_or("", |source| source.as_str())
59    }
60
61    /// Replace the complete exact appearance.
62    #[must_use]
63    pub fn style(mut self, style: crate::theme::TextTheme) -> Self {
64        self.style = Some(style);
65        self
66    }
67
68    /// Remove local appearance without changing content or layout.
69    /// The receiving owner's Theme role supplies appearance when this value is used.
70    #[must_use]
71    pub fn clear_style(mut self) -> Self {
72        self.edit_clear_style();
73        self
74    }
75
76    /// Inspect local appearance presence.
77    #[must_use]
78    pub const fn get_style(&self) -> Option<&crate::theme::TextTheme> {
79        self.style.as_ref()
80    }
81
82    /// Supply a whole layout request, including an explicit default reset.
83    #[must_use]
84    pub fn layout(mut self, layout: TextLayout) -> Self {
85        self.layout = Some(layout);
86        self
87    }
88
89    /// Remove the local layout request, rather than attach a present default.
90    /// Passing this value to an existing slot still follows omission/preserve rules.
91    #[must_use]
92    pub fn clear_layout(mut self) -> Self {
93        self.edit_clear_layout();
94        self
95    }
96
97    /// Distinguish an omitted layout from a present request.
98    #[must_use]
99    pub const fn get_layout(&self) -> Option<&TextLayout> {
100        self.layout.as_ref()
101    }
102
103    /// Edit alignment within this text's one layout request.
104    #[must_use]
105    pub fn alignment(mut self, alignment: TextAlignment) -> Self {
106        self.edit_alignment(alignment);
107        self
108    }
109
110    pub(crate) const fn edit_alignment(&mut self, alignment: TextAlignment) {
111        if self.layout.is_none() {
112            // The replaced value is known None. Forget only that empty value so
113            // this existing const edit does not require const Arc destruction.
114            std::mem::forget(self.layout.replace(TextLayout::EMPTY));
115        }
116        if let Some(layout) = &mut self.layout {
117            layout.alignment = Some(alignment);
118        }
119    }
120
121    pub(crate) const fn alignment_request(&self) -> Option<TextAlignment> {
122        match &self.layout {
123            Some(layout) => layout.alignment,
124            None => None,
125        }
126    }
127
128    pub(crate) fn try_copy(&self) -> crate::Result<Self> {
129        Ok(Self {
130            source: self.source.clone(),
131            style: self
132                .style
133                .as_ref()
134                .map(crate::theme::TextTheme::try_copy)
135                .transpose()?,
136            layout: self.layout.clone(),
137        })
138    }
139
140    pub(crate) fn try_copy_with_source(&self, source: String) -> crate::Result<Self> {
141        Ok(Self {
142            source: Some(adopt_text_source_checked(source)?),
143            style: self
144                .style
145                .as_ref()
146                .map(crate::theme::TextTheme::try_copy)
147                .transpose()?,
148            layout: self.layout.clone(),
149        })
150    }
151
152    pub(crate) fn appearance<'a>(
153        &'a self,
154        role: impl Into<TextAppearance<'a>>,
155    ) -> TextAppearance<'a> {
156        let role = role.into();
157        TextAppearance {
158            theme: self.style.as_ref().unwrap_or(role.theme),
159            exact_override: self.style.is_some() || role.exact_override,
160            layout: self.layout.as_ref().or(role.layout),
161        }
162    }
163
164    pub(crate) fn resolved_alignment(&self, default: TextAlignment) -> TextAlignment {
165        self.alignment_request().unwrap_or(default)
166    }
167}
168
169impl Text {
170    pub(crate) const UNSET: Self = Self {
171        source: None,
172        style: None,
173        layout: None,
174    };
175
176    pub(crate) const fn is_provided(&self) -> bool {
177        self.source.is_some()
178    }
179
180    pub(crate) const fn provided(&self) -> Option<&Self> {
181        if self.is_provided() {
182            Some(self)
183        } else {
184            None
185        }
186    }
187
188    pub(crate) fn required_source(&self, role: &str) -> crate::Result<&str> {
189        let source = self.source.as_ref().ok_or_else(|| {
190            crate::Error::Render(format!("{role}: required text source is unset").into())
191        })?;
192        validate_for(source, role)?;
193        Ok(source)
194    }
195
196    pub(crate) fn edit_style(&mut self, style: crate::theme::TextTheme) {
197        self.style = Some(style);
198    }
199    pub(crate) fn edit_layout(&mut self, layout: TextLayout) {
200        self.layout = Some(layout);
201    }
202    pub(crate) fn edit_clear_style(&mut self) {
203        self.style = None;
204    }
205    pub(crate) fn edit_clear_layout(&mut self) {
206        self.layout = None;
207    }
208    pub(crate) fn resolve_source(&self, source: String) -> crate::Result<Text> {
209        if self.is_provided() {
210            self.try_copy()
211        } else {
212            self.try_copy_with_source(source)
213        }
214    }
215    pub(crate) fn observe_feedback(
216        &self,
217        round: &mut crate::layout::kernel::FeedbackRound,
218    ) -> crate::Result<()> {
219        round.observe_count(usize::from(self.is_provided()))?;
220        round.observe_authored_text(self)
221    }
222
223    pub(crate) fn replace_from(&mut self, incoming: Text) -> crate::Result<()> {
224        if !incoming.is_provided() {
225            return Err(crate::Error::Render(
226                "text replacement: required text source is unset".into(),
227            ));
228        }
229        self.source = incoming.source;
230        if incoming.style.is_some() {
231            self.style = incoming.style;
232        }
233        if incoming.layout.is_some() {
234            self.layout = incoming.layout;
235        }
236        Ok(())
237    }
238}
239
240fn adopt_text_source_checked(source: String) -> crate::Result<std::sync::Arc<String>> {
241    crate::data::source::source_arc(source)
242}
243
244impl From<String> for Text {
245    fn from(source: String) -> Self {
246        Self::new(source)
247    }
248}
249
250impl From<&str> for Text {
251    fn from(source: &str) -> Self {
252        Self::new(source)
253    }
254}
255
256impl From<&String> for Text {
257    fn from(source: &String) -> Self {
258        Self::new(source)
259    }
260}