Skip to main content

termosaic_ratatui/
lib.rs

1//! Ratatui rendering for Termosaic styled documents.
2//!
3//! Termosaic lays out semantic documents; this crate converts the resulting
4//! [`StyledLine`] values into `ratatui-core` text. A raw [`Buffer`], a
5//! `Paragraph`, or another compatible host paints them without ANSI escapes.
6//!
7//! ```
8//! use ratatui_core::buffer::Buffer;
9//! use ratatui_core::layout::Rect;
10//! use termosaic::{AnsiColor, Color, Doc, HumanLayoutOptions, Theme, TokenStyle, tokens};
11//!
12//! let theme = Theme::builder("demo")
13//!     .rule(
14//!         tokens::STATUS_SUCCESS,
15//!         TokenStyle::bold(Color::Ansi(AnsiColor::Green)),
16//!     )?
17//!     .build()?;
18//! let doc = Doc::token_text(tokens::STATUS_SUCCESS, "ready");
19//!
20//! let area = Rect::new(0, 0, 20, 1);
21//! let mut buffer = Buffer::empty(area);
22//! termosaic_ratatui::render_doc(
23//!     &doc,
24//!     &theme,
25//!     HumanLayoutOptions::fast(),
26//!     area,
27//!     &mut buffer,
28//! )?;
29//! assert_eq!(buffer.cell((0, 0)).expect("cell in area").symbol(), "r");
30//! # Ok::<(), Box<dyn std::error::Error>>(())
31//! ```
32//!
33//! Layout runs at a chosen column width in Termosaic; conversion here is
34//! width-independent. Re-render the document when the target area's width
35//! changes. [`render_doc`] handles that common path directly; prepare the
36//! document once and retain a [`RatatuiRenderer`] when painting it repeatedly.
37
38use std::num::NonZeroU16;
39
40use ratatui_core::buffer::Buffer;
41use ratatui_core::layout::Rect;
42use ratatui_core::style::{Modifier, Style};
43use ratatui_core::text::{Line, Span, Text};
44use ratatui_core::widgets::Widget;
45use termosaic::{
46    AnsiColor, AttrSet, Color, ColorDepth, Doc, HumanLayoutError, HumanLayoutOptions, PreparedDoc,
47    ResolvedColor, StyledLine, StyledRenderWorkspace, Theme, TokenStyle,
48};
49
50pub use ratatui_core;
51
52/// Converts Termosaic color and style policy for a Ratatui host.
53///
54/// Implement this trait when a host needs color quantization, palette
55/// substitution, or another backend-owned policy. [`NativeStyleConverter`]
56/// preserves Termosaic RGB values and maps ANSI colors by escape-code meaning.
57pub trait StyleConverter {
58    /// Converts one Termosaic color.
59    fn color(&self, color: Color) -> ratatui_core::style::Color;
60
61    /// Applies backend-owned attributes to a style under construction.
62    ///
63    /// Termosaic carries [`AttrSet`] without interpreting
64    /// it. Override this to give a host's own attribute vocabulary — extra
65    /// modifiers, reversed video, anything ratatui expresses that Termosaic's
66    /// four core fields do not — an effect on the converted style. The default
67    /// ignores every attribute, matching Termosaic's own writers.
68    fn attrs(&self, _attrs: AttrSet, style: Style) -> Style {
69        style
70    }
71
72    /// Converts one resolved token style.
73    fn style(&self, style: TokenStyle) -> Style {
74        let mut converted = Style::new();
75        if let Some(foreground) = style.foreground {
76            converted = converted.fg(self.color(foreground));
77        }
78        if let Some(background) = style.background {
79            converted = converted.bg(self.color(background));
80        }
81        converted = self.attrs(style.attrs, converted);
82        if style.bold {
83            converted = converted.add_modifier(Modifier::BOLD);
84        }
85        if style.dim {
86            converted = converted.add_modifier(Modifier::DIM);
87        }
88        if style.underline {
89            converted = converted.add_modifier(Modifier::UNDERLINED);
90        }
91        converted
92    }
93}
94
95/// Default one-to-one Termosaic-to-Ratatui style conversion.
96#[derive(Clone, Copy, Debug, Default)]
97pub struct NativeStyleConverter;
98
99impl StyleConverter for NativeStyleConverter {
100    fn color(&self, color: Color) -> ratatui_core::style::Color {
101        native_color(color)
102    }
103}
104
105/// Converts a resolved Termosaic token style into a ratatui style.
106///
107/// RGB colors convert to [`ratatui_core::style::Color::Rgb`]; the ANSI
108/// fallback carried by [`termosaic::Color::Rgb`] is not consulted because
109/// color-depth policy belongs to the ratatui backend. Backend-owned attributes
110/// are ignored; use [`to_style_with`] with a converter that implements
111/// [`StyleConverter::attrs`] to act on them.
112#[must_use]
113pub fn to_style(style: TokenStyle) -> Style {
114    to_style_with(style, &NativeStyleConverter)
115}
116
117/// Converts a resolved token style through a host-supplied policy.
118#[must_use]
119pub fn to_style_with(style: TokenStyle, converter: &impl StyleConverter) -> Style {
120    converter.style(style)
121}
122
123/// Converts a Termosaic terminal color into a ratatui color.
124///
125/// The 16 ANSI values map onto ratatui's names for the same escape codes:
126/// normal white (SGR 37) is ratatui `Gray`, bright black is `DarkGray`, and
127/// bright white is ratatui `White`.
128#[must_use]
129pub fn to_color(color: Color) -> ratatui_core::style::Color {
130    NativeStyleConverter.color(color)
131}
132
133/// Converts a Termosaic color for a specific terminal color depth.
134///
135/// Truecolor preserves RGB values, 256-color terminals receive the nearest
136/// xterm palette index, and 16-color terminals receive the portable fallback
137/// carried by [`Color::Rgb`]. Direct ANSI colors retain their escape-code
138/// meaning at every depth.
139#[must_use]
140pub fn to_color_at_depth(color: Color, depth: ColorDepth) -> ratatui_core::style::Color {
141    use ratatui_core::style::Color as Ratatui;
142    match color.resolve(depth) {
143        ResolvedColor::Ansi(color) => native_color(Color::Ansi(color)),
144        ResolvedColor::Indexed(index) => Ratatui::Indexed(index),
145        ResolvedColor::Rgb { red, green, blue } => Ratatui::Rgb(red, green, blue),
146    }
147}
148
149fn native_color(color: Color) -> ratatui_core::style::Color {
150    use ratatui_core::style::Color as Ratatui;
151    match color {
152        Color::Ansi(color) => match color {
153            AnsiColor::Black => Ratatui::Black,
154            AnsiColor::Red => Ratatui::Red,
155            AnsiColor::Green => Ratatui::Green,
156            AnsiColor::Yellow => Ratatui::Yellow,
157            AnsiColor::Blue => Ratatui::Blue,
158            AnsiColor::Magenta => Ratatui::Magenta,
159            AnsiColor::Cyan => Ratatui::Cyan,
160            AnsiColor::White => Ratatui::Gray,
161            AnsiColor::BrightBlack => Ratatui::DarkGray,
162            AnsiColor::BrightRed => Ratatui::LightRed,
163            AnsiColor::BrightGreen => Ratatui::LightGreen,
164            AnsiColor::BrightYellow => Ratatui::LightYellow,
165            AnsiColor::BrightBlue => Ratatui::LightBlue,
166            AnsiColor::BrightMagenta => Ratatui::LightMagenta,
167            AnsiColor::BrightCyan => Ratatui::LightCyan,
168            AnsiColor::BrightWhite => Ratatui::White,
169        },
170        Color::Rgb {
171            red, green, blue, ..
172        } => Ratatui::Rgb(red, green, blue),
173    }
174}
175
176/// Converts one styled line into a ratatui line, borrowing its text.
177#[must_use]
178pub fn to_line(line: &StyledLine) -> Line<'_> {
179    to_line_with(line, &NativeStyleConverter)
180}
181
182/// Converts one styled line through a host-supplied style policy.
183#[must_use]
184pub fn to_line_with<'line>(
185    line: &'line StyledLine,
186    converter: &impl StyleConverter,
187) -> Line<'line> {
188    Line::from(
189        line.runs()
190            .iter()
191            .map(|run| Span::styled(run.text(), converter.style(run.style())))
192            .collect::<Vec<_>>(),
193    )
194}
195
196/// Converts styled lines into ratatui text, borrowing their text.
197#[must_use]
198pub fn to_text(lines: &[StyledLine]) -> Text<'_> {
199    to_text_with(lines, &NativeStyleConverter)
200}
201
202/// Converts styled lines through a host-supplied style policy.
203#[must_use]
204pub fn to_text_with<'lines>(
205    lines: &'lines [StyledLine],
206    converter: &impl StyleConverter,
207) -> Text<'lines> {
208    Text::from(
209        lines
210            .iter()
211            .map(|line| to_line_with(line, converter))
212            .collect::<Vec<_>>(),
213    )
214}
215
216/// Retained Termosaic-to-Ratatui renderer for frame-driven hosts.
217///
218/// This renderer reuses Termosaic layout and styled-output storage and paints
219/// spans directly into the buffer without constructing intermediate Ratatui
220/// `Line` or `Text` vectors.
221pub struct RatatuiRenderer<C = NativeStyleConverter> {
222    styled: StyledRenderWorkspace,
223    converter: C,
224}
225
226impl Default for RatatuiRenderer<NativeStyleConverter> {
227    fn default() -> Self {
228        Self::new()
229    }
230}
231
232impl RatatuiRenderer<NativeStyleConverter> {
233    /// Creates a renderer with native color conversion.
234    pub fn new() -> Self {
235        Self::with_converter(NativeStyleConverter)
236    }
237}
238
239impl<C: StyleConverter> RatatuiRenderer<C> {
240    /// Creates a renderer with host-supplied color and style policy.
241    pub fn with_converter(converter: C) -> Self {
242        Self {
243            styled: StyledRenderWorkspace::new(),
244            converter,
245        }
246    }
247
248    /// Lays out and paints a prepared document at the target area's width.
249    pub fn render_prepared_doc(
250        &mut self,
251        doc: &PreparedDoc,
252        theme: &Theme,
253        options: HumanLayoutOptions,
254        area: Rect,
255        buffer: &mut Buffer,
256    ) -> Result<(), HumanLayoutError> {
257        if area.is_empty() {
258            return Ok(());
259        }
260        let width = NonZeroU16::new(area.width).expect("non-empty area width is non-zero");
261        let lines = doc.render_styled_into(width, theme, options, &mut self.styled)?;
262        paint_lines(lines, &self.converter, area, buffer);
263        Ok(())
264    }
265
266    /// Releases all retained Termosaic rendering capacity.
267    pub fn release_capacity(&mut self) {
268        self.styled.release_capacity();
269    }
270}
271
272/// Lays out and paints a document using the target area's current width.
273///
274/// Empty areas are a no-op. For documents rendered on multiple frames, call
275/// [`Doc::prepare`] once and retain a [`RatatuiRenderer`] instead.
276pub fn render_doc(
277    doc: &Doc,
278    theme: &Theme,
279    options: HumanLayoutOptions,
280    area: Rect,
281    buffer: &mut Buffer,
282) -> Result<(), HumanLayoutError> {
283    let prepared = doc.prepare()?;
284    render_prepared_doc(&prepared, theme, options, area, buffer)
285}
286
287/// Paints a prepared document using the target area's current width.
288///
289/// Creates a one-shot renderer. Resizable and frame-driven widgets retain a
290/// [`RatatuiRenderer`] and call its
291/// [`RatatuiRenderer::render_prepared_doc`] method instead. Empty areas are a
292/// no-op.
293pub fn render_prepared_doc(
294    doc: &PreparedDoc,
295    theme: &Theme,
296    options: HumanLayoutOptions,
297    area: Rect,
298    buffer: &mut Buffer,
299) -> Result<(), HumanLayoutError> {
300    RatatuiRenderer::new().render_prepared_doc(doc, theme, options, area, buffer)
301}
302
303fn paint_lines(
304    lines: &[StyledLine],
305    converter: &impl StyleConverter,
306    area: Rect,
307    buffer: &mut Buffer,
308) {
309    for (row, line) in lines.iter().take(usize::from(area.height)).enumerate() {
310        let y = area
311            .y
312            .saturating_add(u16::try_from(row).unwrap_or(u16::MAX));
313        let mut x = area.x;
314        for run in line.runs() {
315            if x >= area.right() {
316                break;
317            }
318            let span = Span::styled(run.text(), converter.style(run.style()));
319            let span_width = u16::try_from(span.width()).unwrap_or(u16::MAX);
320            span.render(Rect::new(x, y, area.right().saturating_sub(x), 1), buffer);
321            x = x.saturating_add(span_width);
322        }
323    }
324}