lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Authored text value and its local appearance requests.

use super::{validate_for, TextAlignment, TextAppearance, TextLayout};

/// Authored display text with optional complete appearance and layout instructions.
///
/// Plain strings carry no local instructions. Content validation happens
/// at the receiving constructor or preflight, without rewriting the source.
/// Clones share immutable source bytes and retain complete local instructions.
///
/// ```
/// use lichtung_plot::{
///     NumericValues,
///     Plot,
///     Text,
///     Theme,
///     coordinates::DataAreaCorner,
///     elements::PlotTextAnnotation,
///     layout::TextPanel,
///     text::{TextAlignment, TextLayout},
/// };
/// let style = Theme::publication().typography().get_composition()
///     .get_text_panel_title().clone().font_size(24.0)?;
/// let title = Text::new("Study\ncontext").style(style).alignment(TextAlignment::End);
/// let note = PlotTextAnnotation::new(DataAreaCorner::TopLeft, title.clone())?;
/// let plot = Plot::scatter(NumericValues::new("x", [0.0, 1.0]),
///     NumericValues::new("y", [1.0, 0.0]))
///     .title(title.clone()).title("Updated heading")
///     .caption(Text::new("Centered caption").alignment(TextAlignment::Center));
/// let panel = TextPanel::new(title, Text::new("Independent body")
///     .layout(TextLayout::default().alignment(TextAlignment::Start)))?;
/// assert_eq!(panel.title(), "Study\ncontext");
/// assert_eq!(note.text(), panel.title());
/// # let _ = plot;
/// # Ok::<(), lichtung_plot::Error>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Text {
    source: Option<std::sync::Arc<String>>,
    style: Option<crate::theme::TextTheme>,
    layout: Option<TextLayout>,
}

impl Text {
    /// Retain one verbatim display source.
    #[must_use]
    pub fn new(source: impl Into<String>) -> Self {
        Self {
            source: Some(std::sync::Arc::new(source.into())),
            style: None,
            layout: None,
        }
    }

    /// Borrow the original source.
    #[must_use]
    pub fn as_str(&self) -> &str {
        self.source.as_ref().map_or("", |source| source.as_str())
    }

    /// Replace the complete exact appearance.
    #[must_use]
    pub fn style(mut self, style: crate::theme::TextTheme) -> Self {
        self.style = Some(style);
        self
    }

    /// Remove local appearance without changing content or layout.
    /// The receiving owner's Theme role supplies appearance when this value is used.
    #[must_use]
    pub fn clear_style(mut self) -> Self {
        self.edit_clear_style();
        self
    }

    /// Inspect local appearance presence.
    #[must_use]
    pub const fn get_style(&self) -> Option<&crate::theme::TextTheme> {
        self.style.as_ref()
    }

    /// Supply a whole layout request, including an explicit default reset.
    #[must_use]
    pub fn layout(mut self, layout: TextLayout) -> Self {
        self.layout = Some(layout);
        self
    }

    /// Remove the local layout request, rather than attach a present default.
    /// Passing this value to an existing slot still follows omission/preserve rules.
    #[must_use]
    pub fn clear_layout(mut self) -> Self {
        self.edit_clear_layout();
        self
    }

    /// Distinguish an omitted layout from a present request.
    #[must_use]
    pub const fn get_layout(&self) -> Option<&TextLayout> {
        self.layout.as_ref()
    }

    /// Edit alignment within this text's one layout request.
    #[must_use]
    pub fn alignment(mut self, alignment: TextAlignment) -> Self {
        self.edit_alignment(alignment);
        self
    }

    pub(crate) const fn edit_alignment(&mut self, alignment: TextAlignment) {
        if self.layout.is_none() {
            // The replaced value is known None. Forget only that empty value so
            // this existing const edit does not require const Arc destruction.
            std::mem::forget(self.layout.replace(TextLayout::EMPTY));
        }
        if let Some(layout) = &mut self.layout {
            layout.alignment = Some(alignment);
        }
    }

    pub(crate) const fn alignment_request(&self) -> Option<TextAlignment> {
        match &self.layout {
            Some(layout) => layout.alignment,
            None => None,
        }
    }

    pub(crate) fn try_copy(&self) -> crate::Result<Self> {
        Ok(Self {
            source: self.source.clone(),
            style: self
                .style
                .as_ref()
                .map(crate::theme::TextTheme::try_copy)
                .transpose()?,
            layout: self.layout.clone(),
        })
    }

    pub(crate) fn try_copy_with_source(&self, source: String) -> crate::Result<Self> {
        Ok(Self {
            source: Some(adopt_text_source_checked(source)?),
            style: self
                .style
                .as_ref()
                .map(crate::theme::TextTheme::try_copy)
                .transpose()?,
            layout: self.layout.clone(),
        })
    }

    pub(crate) fn appearance<'a>(
        &'a self,
        role: impl Into<TextAppearance<'a>>,
    ) -> TextAppearance<'a> {
        let role = role.into();
        TextAppearance {
            theme: self.style.as_ref().unwrap_or(role.theme),
            exact_override: self.style.is_some() || role.exact_override,
            layout: self.layout.as_ref().or(role.layout),
        }
    }

    pub(crate) fn resolved_alignment(&self, default: TextAlignment) -> TextAlignment {
        self.alignment_request().unwrap_or(default)
    }
}

impl Text {
    pub(crate) const UNSET: Self = Self {
        source: None,
        style: None,
        layout: None,
    };

    pub(crate) fn appearance_only(&self) -> Self {
        Self {
            source: None,
            style: self.style.clone(),
            layout: self.layout.clone(),
        }
    }

    pub(crate) fn apply_appearance(&mut self, appearance: Self) {
        self.style = appearance.style;
        self.layout = appearance.layout;
    }

    pub(crate) const fn is_provided(&self) -> bool {
        self.source.is_some()
    }

    pub(crate) const fn provided(&self) -> Option<&Self> {
        if self.is_provided() {
            Some(self)
        } else {
            None
        }
    }

    pub(crate) fn required_source(&self, role: &str) -> crate::Result<&str> {
        let source = self.source.as_ref().ok_or_else(|| {
            crate::Error::Render(format!("{role}: required text source is unset").into())
        })?;
        validate_for(source, role)?;
        Ok(source)
    }

    pub(crate) fn edit_style(&mut self, style: crate::theme::TextTheme) {
        self.style = Some(style);
    }
    pub(crate) fn edit_layout(&mut self, layout: TextLayout) {
        self.layout = Some(layout);
    }
    pub(crate) fn edit_clear_style(&mut self) {
        self.style = None;
    }
    pub(crate) fn edit_clear_layout(&mut self) {
        self.layout = None;
    }
    pub(crate) fn resolve_source(&self, source: String) -> crate::Result<Text> {
        if self.is_provided() {
            self.try_copy()
        } else {
            self.try_copy_with_source(source)
        }
    }
    pub(crate) fn observe_feedback(
        &self,
        round: &mut crate::layout::kernel::FeedbackRound,
    ) -> crate::Result<()> {
        round.observe_count(usize::from(self.is_provided()))?;
        round.observe_authored_text(self)
    }

    pub(crate) fn replace_from(&mut self, incoming: Text) -> crate::Result<()> {
        if !incoming.is_provided() {
            return Err(crate::Error::Render(
                "text replacement: required text source is unset".into(),
            ));
        }
        self.source = incoming.source;
        if incoming.style.is_some() {
            self.style = incoming.style;
        }
        if incoming.layout.is_some() {
            self.layout = incoming.layout;
        }
        Ok(())
    }
}

fn adopt_text_source_checked(source: String) -> crate::Result<std::sync::Arc<String>> {
    crate::data::source::source_arc(source)
}

impl From<String> for Text {
    fn from(source: String) -> Self {
        Self::new(source)
    }
}

impl From<&str> for Text {
    fn from(source: &str) -> Self {
        Self::new(source)
    }
}

impl From<&String> for Text {
    fn from(source: &String) -> Self {
        Self::new(source)
    }
}