1use 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
52pub trait StyleConverter {
58 fn color(&self, color: Color) -> ratatui_core::style::Color;
60
61 fn attrs(&self, _attrs: AttrSet, style: Style) -> Style {
69 style
70 }
71
72 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#[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#[must_use]
113pub fn to_style(style: TokenStyle) -> Style {
114 to_style_with(style, &NativeStyleConverter)
115}
116
117#[must_use]
119pub fn to_style_with(style: TokenStyle, converter: &impl StyleConverter) -> Style {
120 converter.style(style)
121}
122
123#[must_use]
129pub fn to_color(color: Color) -> ratatui_core::style::Color {
130 NativeStyleConverter.color(color)
131}
132
133#[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#[must_use]
178pub fn to_line(line: &StyledLine) -> Line<'_> {
179 to_line_with(line, &NativeStyleConverter)
180}
181
182#[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#[must_use]
198pub fn to_text(lines: &[StyledLine]) -> Text<'_> {
199 to_text_with(lines, &NativeStyleConverter)
200}
201
202#[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
216pub 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 pub fn new() -> Self {
235 Self::with_converter(NativeStyleConverter)
236 }
237}
238
239impl<C: StyleConverter> RatatuiRenderer<C> {
240 pub fn with_converter(converter: C) -> Self {
242 Self {
243 styled: StyledRenderWorkspace::new(),
244 converter,
245 }
246 }
247
248 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 pub fn release_capacity(&mut self) {
268 self.styled.release_capacity();
269 }
270}
271
272pub 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
287pub 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}