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) fn appearance_only(&self) -> Self {
177        Self {
178            source: None,
179            style: self.style.clone(),
180            layout: self.layout.clone(),
181        }
182    }
183
184    pub(crate) fn apply_appearance(&mut self, appearance: Self) {
185        self.style = appearance.style;
186        self.layout = appearance.layout;
187    }
188
189    pub(crate) const fn is_provided(&self) -> bool {
190        self.source.is_some()
191    }
192
193    pub(crate) const fn provided(&self) -> Option<&Self> {
194        if self.is_provided() {
195            Some(self)
196        } else {
197            None
198        }
199    }
200
201    pub(crate) fn required_source(&self, role: &str) -> crate::Result<&str> {
202        let source = self.source.as_ref().ok_or_else(|| {
203            crate::Error::Render(format!("{role}: required text source is unset").into())
204        })?;
205        validate_for(source, role)?;
206        Ok(source)
207    }
208
209    pub(crate) fn edit_style(&mut self, style: crate::theme::TextTheme) {
210        self.style = Some(style);
211    }
212    pub(crate) fn edit_layout(&mut self, layout: TextLayout) {
213        self.layout = Some(layout);
214    }
215    pub(crate) fn edit_clear_style(&mut self) {
216        self.style = None;
217    }
218    pub(crate) fn edit_clear_layout(&mut self) {
219        self.layout = None;
220    }
221    pub(crate) fn resolve_source(&self, source: String) -> crate::Result<Text> {
222        if self.is_provided() {
223            self.try_copy()
224        } else {
225            self.try_copy_with_source(source)
226        }
227    }
228    pub(crate) fn observe_feedback(
229        &self,
230        round: &mut crate::layout::kernel::FeedbackRound,
231    ) -> crate::Result<()> {
232        round.observe_count(usize::from(self.is_provided()))?;
233        round.observe_authored_text(self)
234    }
235
236    pub(crate) fn replace_from(&mut self, incoming: Text) -> crate::Result<()> {
237        if !incoming.is_provided() {
238            return Err(crate::Error::Render(
239                "text replacement: required text source is unset".into(),
240            ));
241        }
242        self.source = incoming.source;
243        if incoming.style.is_some() {
244            self.style = incoming.style;
245        }
246        if incoming.layout.is_some() {
247            self.layout = incoming.layout;
248        }
249        Ok(())
250    }
251}
252
253fn adopt_text_source_checked(source: String) -> crate::Result<std::sync::Arc<String>> {
254    crate::data::source::source_arc(source)
255}
256
257impl From<String> for Text {
258    fn from(source: String) -> Self {
259        Self::new(source)
260    }
261}
262
263impl From<&str> for Text {
264    fn from(source: &str) -> Self {
265        Self::new(source)
266    }
267}
268
269impl From<&String> for Text {
270    fn from(source: &String) -> Self {
271        Self::new(source)
272    }
273}