termosaic 0.2.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::num::{NonZeroU16, NonZeroU32};
use std::ops::Range;

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 const fn style(&self) -> TokenStyle {
        self.style
    }
}

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

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

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

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

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 = laidout::RenderWorkspace::growable();
        let rendered = laidout::render_into(
            self.inner(),
            render_options(NonZeroU32::from(width), options),
            &mut workspace,
        )
        .map_err(map_render_error)?;
        let resolved: Vec<(Range<usize>, &TokenId)> = rendered
            .resolved_spans()
            .map(|(span, token)| (span.range.clone(), token))
            .collect();
        Ok(build_lines(rendered.text(), &resolved, theme))
    }
}

fn build_lines(text: &str, spans: &[(Range<usize>, &TokenId)], theme: &Theme) -> Vec<StyledLine> {
    let mut lines = vec![StyledLine::default()];
    if text.is_empty() {
        return lines;
    }

    let mut boundaries = Vec::with_capacity(spans.len().saturating_mul(2).saturating_add(2));
    boundaries.push(0);
    boundaries.push(text.len());
    for (range, _) in spans {
        boundaries.push(range.start);
        boundaries.push(range.end);
    }
    boundaries.sort_unstable();
    boundaries.dedup();

    for pair in boundaries.windows(2) {
        let segment = pair[0]..pair[1];
        if segment.is_empty() {
            continue;
        }
        // Covering spans sorted outermost first: properly nested spans order
        // by (start ascending, end descending); identical ranges keep the
        // recorded order, which lists outer annotations before inner ones.
        let mut covering: Vec<(usize, &Range<usize>, &TokenId)> = spans
            .iter()
            .enumerate()
            .filter(|(_, (range, _))| range.start <= segment.start && segment.end <= range.end)
            .map(|(index, (range, token))| (index, range, *token))
            .collect();
        covering.sort_by(|left, right| {
            left.1
                .start
                .cmp(&right.1.start)
                .then(right.1.end.cmp(&left.1.end))
                .then(left.0.cmp(&right.0))
        });
        let style = theme.resolve_stack(covering.iter().map(|(_, _, token)| *token));
        let token = covering
            .last()
            .map_or(tokens::TEXT, |(_, _, token)| (*token).clone());

        let mut remainder = &text[segment];
        loop {
            match remainder.split_once('\n') {
                Some((piece, rest)) => {
                    push_run(
                        lines.last_mut().expect("line list is never empty"),
                        piece,
                        &token,
                        style,
                    );
                    lines.push(StyledLine::default());
                    remainder = rest;
                }
                None => {
                    push_run(
                        lines.last_mut().expect("line list is never empty"),
                        remainder,
                        &token,
                        style,
                    );
                    break;
                }
            }
        }
    }
    lines
}

fn push_run(line: &mut StyledLine, text: &str, token: &TokenId, style: TokenStyle) {
    if text.is_empty() {
        return;
    }
    if let Some(last) = line.runs.last_mut()
        && last.token == *token
        && last.style == style
    {
        last.text.push_str(text);
        return;
    }
    line.runs.push(StyledRun {
        text: text.to_owned(),
        token: token.clone(),
        style,
    });
}