termosaic 0.3.0

Semantic, structured output for human, machine-text, and opaque-byte destinations
Documentation
//! Open style attributes.
//!
//! [`TokenStyle`](crate::TokenStyle) models the four attributes every terminal
//! backend understands. Backends need more than that — a cell-grid host has fill
//! characters, a hyperlink-aware writer has URLs, a Ratatui host has modifiers
//! Termosaic has no opinion about — and Termosaic cannot enumerate them.
//!
//! Attributes are the seam. The vocabulary is open, exactly like
//! [`TokenId`](crate::TokenId): any backend mints its own names and reads them
//! back after theme resolution. The value domain is closed, so styles remain
//! comparable and cheap to clone.
//!
//! Termosaic's own writers ignore every attribute. An attribute means whatever
//! the backend that minted it decides, and no other backend is affected by it.

use std::fmt;
use std::sync::Arc;

use crate::theme::Color;
use crate::token::{valid_static_token, validate_token};

/// A validated style attribute name.
///
/// Attribute names use the same grammar as [`TokenId`](crate::TokenId):
/// dot-separated lowercase segments, so `ratatui.modifier` and `grid.fill` sit
/// in distinct namespaces without collision.
///
/// Names are `&'static str` rather than [`Cow`](std::borrow::Cow) because a
/// backend's attribute vocabulary is a compile-time property of that backend.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct StyleAttr(&'static str);

impl StyleAttr {
    /// Construct an attribute name, failing at compile time when the literal
    /// violates the name grammar.
    pub const fn from_static(value: &'static str) -> Self {
        if !valid_static_token(value) {
            panic!("invalid style attribute name");
        }
        Self(value)
    }

    /// Validate a name without constructing in const context.
    ///
    /// Useful when a backend derives its vocabulary from a table rather than
    /// from literals; the name itself must still be `'static`.
    pub fn checked(value: &'static str) -> Result<Self, StyleAttrError> {
        validate_token(value).map_err(StyleAttrError)?;
        Ok(Self(value))
    }

    pub const fn as_str(&self) -> &'static str {
        self.0
    }
}

impl fmt::Display for StyleAttr {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.0)
    }
}

/// A style attribute name that violates the name grammar.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StyleAttrError(crate::TokenIdError);

impl fmt::Display for StyleAttrError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "invalid style attribute name: {}", self.0)
    }
}

impl std::error::Error for StyleAttrError {}

/// The closed value domain an attribute may carry.
///
/// Closed so that styles remain comparable. A backend needing a richer value
/// indexes its own table with [`AttrValue::Index`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AttrValue {
    Color(Color),
    Flag(bool),
    Number(i32),
    /// An index into a table the minting backend owns.
    Index(u32),
}

impl AttrValue {
    pub const fn as_color(self) -> Option<Color> {
        match self {
            Self::Color(color) => Some(color),
            _ => None,
        }
    }

    pub const fn as_flag(self) -> Option<bool> {
        match self {
            Self::Flag(value) => Some(value),
            _ => None,
        }
    }

    pub const fn as_number(self) -> Option<i32> {
        match self {
            Self::Number(value) => Some(value),
            _ => None,
        }
    }

    pub const fn as_index(self) -> Option<u32> {
        match self {
            Self::Index(value) => Some(value),
            _ => None,
        }
    }
}

/// An immutable, shared set of style attributes keyed by name.
///
/// Clones share their backing storage. Adding or removing an attribute creates
/// new storage; reading, cloning, theme resolution without attribute patches,
/// and styled rendering of resolved values allocate nothing.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct AttrSet {
    entries: Option<Arc<Vec<(StyleAttr, AttrValue)>>>,
}

impl AttrSet {
    pub const fn new() -> Self {
        Self { entries: None }
    }

    /// Set `attr`, replacing any existing value for the same name.
    #[must_use]
    pub fn set(self, attr: StyleAttr, value: AttrValue) -> Self {
        let mut entries = self.as_slice().to_vec();
        if let Some((_, slot)) = entries.iter_mut().find(|(name, _)| *name == attr) {
            if *slot == value {
                return self;
            }
            *slot = value;
        } else {
            entries.push((attr, value));
        }
        Self::from_entries(entries)
    }

    fn as_slice(&self) -> &[(StyleAttr, AttrValue)] {
        self.entries.as_deref().map(Vec::as_slice).unwrap_or(&[])
    }

    pub fn get(&self, attr: StyleAttr) -> Option<AttrValue> {
        self.as_slice()
            .iter()
            .find(|(name, _)| *name == attr)
            .map(|(_, value)| *value)
    }

    pub fn contains(&self, attr: StyleAttr) -> bool {
        self.get(attr).is_some()
    }

    /// Remove `attr`, preserving the order of the remaining entries.
    pub fn remove(&mut self, attr: StyleAttr) -> Option<AttrValue> {
        let position = self.as_slice().iter().position(|(name, _)| *name == attr)?;
        let mut entries = self.as_slice().to_vec();
        let (_, value) = entries.remove(position);
        *self = Self::from_entries(entries);
        Some(value)
    }

    pub fn len(&self) -> usize {
        self.as_slice().len()
    }

    pub fn is_empty(&self) -> bool {
        self.entries.is_none()
    }

    pub fn iter(&self) -> impl Iterator<Item = (StyleAttr, AttrValue)> + '_ {
        self.as_slice().iter().copied()
    }

    /// Overlay `patch` onto `self`; entries in `patch` win.
    #[must_use]
    pub fn merged(mut self, patch: &Self) -> Self {
        for (attr, value) in patch.iter() {
            self = self.set(attr, value);
        }
        self
    }

    fn from_entries(entries: Vec<(StyleAttr, AttrValue)>) -> Self {
        if entries.is_empty() {
            Self::new()
        } else {
            Self {
                entries: Some(Arc::new(entries)),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const GRID_FILL: StyleAttr = StyleAttr::from_static("grid.fill");
    const BLINK: StyleAttr = StyleAttr::from_static("blink");

    #[test]
    fn attributes_round_trip_by_name() {
        let set = AttrSet::new()
            .set(GRID_FILL, AttrValue::Number(0x2591))
            .set(BLINK, AttrValue::Flag(true));

        assert_eq!(set.get(GRID_FILL), Some(AttrValue::Number(0x2591)));
        assert_eq!(set.get(BLINK), Some(AttrValue::Flag(true)));
        assert_eq!(set.len(), 2);
    }

    #[test]
    fn setting_the_same_name_replaces_rather_than_appends() {
        let set = AttrSet::new()
            .set(BLINK, AttrValue::Flag(true))
            .set(BLINK, AttrValue::Flag(false));

        assert_eq!(set.get(BLINK), Some(AttrValue::Flag(false)));
        assert_eq!(set.len(), 1);
    }

    #[test]
    fn attribute_count_is_not_artificially_capped() {
        let mut set = AttrSet::new();
        for name in [
            "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11",
        ] {
            set = set.set(
                StyleAttr::checked(name).expect("valid"),
                AttrValue::Flag(true),
            );
        }
        assert_eq!(set.len(), 12);
    }

    #[test]
    fn removing_preserves_the_order_of_remaining_entries() {
        let first = StyleAttr::from_static("first");
        let second = StyleAttr::from_static("second");
        let third = StyleAttr::from_static("third");
        let mut set = AttrSet::new()
            .set(first, AttrValue::Number(1))
            .set(second, AttrValue::Number(2))
            .set(third, AttrValue::Number(3));

        assert_eq!(set.remove(second), Some(AttrValue::Number(2)));
        assert_eq!(
            set.iter().collect::<Vec<_>>(),
            vec![(first, AttrValue::Number(1)), (third, AttrValue::Number(3)),]
        );
    }

    #[test]
    fn merging_lets_the_patch_win() {
        let flag = StyleAttr::from_static("flag");
        let base = AttrSet::new().set(flag, AttrValue::Flag(false));
        let patch = AttrSet::new().set(flag, AttrValue::Flag(true));

        assert_eq!(base.merged(&patch).get(flag), Some(AttrValue::Flag(true)));
    }

    #[test]
    fn invalid_names_are_rejected() {
        assert!(StyleAttr::checked("Not Valid").is_err());
    }
}