termosaic 0.3.0

Semantic, structured output for human, machine-text, and opaque-byte destinations
Documentation
//! Structured styled rendering for cell-grid and widget consumers.
//!
//! [`Doc::render_styled`] and [`PreparedDoc::render_styled`] lay out a semantic
//! document exactly like terminal output does, but produce theme-resolved
//! [`StyledLine`] values instead of ANSI bytes. Cell-grid hosts (for example a
//! `ratatui` surface) paint each [`StyledRun`] with its resolved
//! [`TokenStyle`]; color depth and fallback selection remain the consumer's
//! concern because cell renderers own their terminal capabilities.

use std::convert::Infallible;
use std::fmt;
use std::num::{NonZeroU16, NonZeroU32};

use crate::console_api::map_render_error;
use crate::layout::render_options;
use crate::{
    Doc, HumanLayoutError, HumanLayoutOptions, PreparedDoc, Theme, TokenId, TokenStyle, tokens,
};

/// One semantically styled fragment of a rendered line.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StyledRun {
    text: String,
    token: TokenId,
    style: TokenStyle,
}

impl StyledRun {
    /// Fragment text without line breaks.
    pub fn text(&self) -> &str {
        &self.text
    }

    /// The innermost semantic token covering this fragment.
    pub const fn token(&self) -> &TokenId {
        &self.token
    }

    /// Theme style resolved from the fragment's full token stack.
    pub fn style(&self) -> TokenStyle {
        self.style.clone()
    }
}

/// One rendered line of styled fragments, without a trailing line break.
#[derive(Default)]
pub struct StyledLine {
    runs: Vec<StyledRun>,
    used_runs: usize,
}

impl Clone for StyledLine {
    fn clone(&self) -> Self {
        Self {
            runs: self.runs().to_vec(),
            used_runs: self.used_runs,
        }
    }
}

impl fmt::Debug for StyledLine {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("StyledLine")
            .field("runs", &self.runs())
            .finish()
    }
}

impl PartialEq for StyledLine {
    fn eq(&self, other: &Self) -> bool {
        self.runs() == other.runs()
    }
}

impl Eq for StyledLine {}

impl StyledLine {
    /// Styled fragments in display order.
    pub fn runs(&self) -> &[StyledRun] {
        &self.runs[..self.used_runs]
    }

    /// Concatenated text of the line.
    pub fn text(&self) -> String {
        self.runs().iter().map(StyledRun::text).collect()
    }
}

/// Retained storage for repeated styled rendering.
///
/// The workspace owns both layout scratch storage and styled output buffers.
/// After a document has been rendered once at the required high-water mark,
/// subsequent compatible renders reuse those allocations. The returned lines
/// borrow the workspace and remain valid until its next mutable use.
pub struct StyledRenderWorkspace {
    layout: laidout::RenderWorkspace,
    output: StyledOutputWorkspace,
}

#[derive(Default)]
struct StyledOutputWorkspace {
    lines: Vec<StyledLine>,
    used_lines: usize,
}

impl Default for StyledRenderWorkspace {
    fn default() -> Self {
        Self::new()
    }
}

impl StyledRenderWorkspace {
    /// Creates an empty growable styled-rendering workspace.
    pub fn new() -> Self {
        Self {
            layout: laidout::RenderWorkspace::growable(),
            output: StyledOutputWorkspace::default(),
        }
    }

    /// Releases every retained layout and styled-output allocation.
    pub fn release_capacity(&mut self) {
        self.layout.release_capacity();
        self.output = StyledOutputWorkspace::default();
    }
}

impl StyledOutputWorkspace {
    fn reset(&mut self) {
        self.used_lines = 0;
        self.push_line();
    }

    fn push_line(&mut self) {
        if self.used_lines == self.lines.len() {
            self.lines.push(StyledLine::default());
        }
        self.lines[self.used_lines].used_runs = 0;
        self.used_lines += 1;
    }

    fn push_text(&mut self, value: &str, token: &TokenId, style: TokenStyle) {
        if value.is_empty() {
            return;
        }
        let line = self
            .lines
            .get_mut(self.used_lines - 1)
            .expect("styled output always has a current line");
        if line.used_runs > 0 {
            let last = &mut line.runs[line.used_runs - 1];
            if last.token == *token && last.style == style {
                last.text.push_str(value);
                return;
            }
        }
        if line.used_runs == line.runs.len() {
            line.runs.push(StyledRun {
                text: String::new(),
                token: token.clone(),
                style,
            });
        } else {
            let run = &mut line.runs[line.used_runs];
            run.text.clear();
            run.token.clone_from(token);
            run.style = style;
        }
        let run = &mut line.runs[line.used_runs];
        run.text.push_str(value);
        line.used_runs += 1;
    }

    fn push_indent(&mut self, indent: u32, token: &TokenId, style: TokenStyle) {
        if indent == 0 {
            return;
        }
        let line = self
            .lines
            .get_mut(self.used_lines - 1)
            .expect("styled output always has a current line");
        if line.used_runs == line.runs.len() {
            line.runs.push(StyledRun {
                text: String::new(),
                token: token.clone(),
                style,
            });
        } else {
            let run = &mut line.runs[line.used_runs];
            run.text.clear();
            run.token.clone_from(token);
            run.style = style;
        }
        let run = &mut line.runs[line.used_runs];
        for _ in 0..indent {
            run.text.push(' ');
        }
        line.used_runs += 1;
    }

    fn output(&self) -> &[StyledLine] {
        &self.lines[..self.used_lines]
    }
}

impl Doc {
    /// Prepares and renders this document as styled lines at `width` columns.
    ///
    /// Equivalent to [`Doc::prepare`] followed by
    /// [`PreparedDoc::render_styled`]. Repeated rendering uses the prepared
    /// form.
    pub fn render_styled(
        &self,
        width: NonZeroU16,
        theme: &Theme,
        options: HumanLayoutOptions,
    ) -> Result<Vec<StyledLine>, HumanLayoutError> {
        self.prepare()?.render_styled(width, theme, options)
    }

    /// Prepares and renders this document through reusable styled storage.
    ///
    /// Repeated rendering prepares the document once and calls
    /// [`PreparedDoc::render_styled_into`].
    pub fn render_styled_into<'workspace>(
        &self,
        width: NonZeroU16,
        theme: &Theme,
        options: HumanLayoutOptions,
        workspace: &'workspace mut StyledRenderWorkspace,
    ) -> Result<&'workspace [StyledLine], HumanLayoutError> {
        self.prepare()?
            .render_styled_into(width, theme, options, workspace)
    }
}

impl PreparedDoc {
    /// Renders this document as styled lines at `width` columns.
    ///
    /// Layout semantics match terminal document output for the same options
    /// and width. Every fragment carries the style resolved from its full
    /// semantic token stack, outermost token first, so nested tokens override
    /// outer rules exactly as they do in terminal rendering.
    ///
    /// A document with `n` line breaks renders as `n + 1` lines; an empty
    /// document renders as one empty line, and blank lines carry no runs.
    pub fn render_styled(
        &self,
        width: NonZeroU16,
        theme: &Theme,
        options: HumanLayoutOptions,
    ) -> Result<Vec<StyledLine>, HumanLayoutError> {
        let mut workspace = StyledRenderWorkspace::new();
        Ok(self
            .render_styled_into(width, theme, options, &mut workspace)?
            .to_vec())
    }

    /// Renders through retained layout and styled-output storage.
    ///
    /// Layout and styling semantics match [`PreparedDoc::render_styled`].
    /// The returned slice borrows `workspace` and remains valid until its next
    /// mutable use.
    pub fn render_styled_into<'workspace>(
        &self,
        width: NonZeroU16,
        theme: &Theme,
        options: HumanLayoutOptions,
        workspace: &'workspace mut StyledRenderWorkspace,
    ) -> Result<&'workspace [StyledLine], HumanLayoutError> {
        workspace.output.reset();
        let layout = laidout::solve_into(
            self.inner(),
            render_options(NonZeroU32::from(width), options),
            &mut workspace.layout,
        )
        .map_err(map_render_error)?;
        let mut visitor = StyledVisitor {
            theme,
            output: &mut workspace.output,
        };
        layout.visit(&mut visitor).map_err(|error| match error {
            laidout::VisitError::Workspace(error) => map_render_error(error),
            laidout::VisitError::Visitor(error) => match error {},
        })?;
        Ok(workspace.output.output())
    }
}

struct StyledVisitor<'a> {
    theme: &'a Theme,
    output: &'a mut StyledOutputWorkspace,
}

impl laidout::LayoutVisitor<TokenId> for StyledVisitor<'_> {
    type Error = Infallible;

    fn text(
        &mut self,
        text: &str,
        annotations: laidout::ActiveAnnotations<'_, TokenId>,
    ) -> Result<(), Self::Error> {
        let style = self
            .theme
            .resolve_stack(annotations.iter().map(|(_, token)| token));
        if let Some((_, token)) = annotations.innermost() {
            self.output.push_text(text, token, style);
        } else {
            self.output.push_text(text, &tokens::TEXT, style);
        }
        Ok(())
    }

    fn newline(
        &mut self,
        indent: u32,
        annotations: laidout::ActiveAnnotations<'_, TokenId>,
    ) -> Result<(), Self::Error> {
        let style = self
            .theme
            .resolve_stack(annotations.iter().map(|(_, token)| token));
        self.output.push_line();
        if let Some((_, token)) = annotations.innermost() {
            self.output.push_indent(indent, token, style);
        } else {
            self.output.push_indent(indent, &tokens::TEXT, style);
        }
        Ok(())
    }
}