prismatica/integration/ratatui.rs
1//! Ratatui integration.
2//!
3//! Provides conversion between [`Color`](crate::Color) and [`ratatui::style::Color`].
4//!
5//! Forward conversion always produces [`Color::Rgb`](ratatui::style::Color::Rgb).
6//! Reverse conversion uses [`TryFrom`] since only the `Rgb` variant can be converted.
7//!
8//! # Examples
9//!
10//! ```ignore
11//! use prismatica::crameri::BATLOW;
12//!
13//! let color = BATLOW.eval(0.5);
14//! let rat_color: ratatui::style::Color = color.into();
15//!
16//! // Reverse: only Rgb variant converts
17//! let back = prismatica::Color::try_from(rat_color).unwrap();
18//! assert_eq!(color, back);
19//! ```
20
21use crate::impl_into_framework_color;
22use crate::{Color, ConversionError};
23
24/// Convert a prismatica [`Color`] to a [`ratatui::style::Color::Rgb`].
25///
26/// # Examples
27///
28/// ```ignore
29/// let color = prismatica::Color::new(128, 64, 32);
30/// let rat: ratatui::style::Color = color.into();
31/// ```
32impl From<Color> for ::ratatui::style::Color {
33 fn from(c: Color) -> Self {
34 ::ratatui::style::Color::Rgb(c.r, c.g, c.b)
35 }
36}
37
38/// Try to convert a [`ratatui::style::Color`] to a prismatica [`Color`].
39///
40/// Only the `Rgb` variant can be converted. Named colors (e.g., `Red`, `Blue`)
41/// and other variants return an error.
42///
43/// # Errors
44///
45/// Returns [`ConversionError`](crate::ConversionError) if the color is not
46/// a `Color::Rgb` variant.
47///
48/// # Examples
49///
50/// ```ignore
51/// use prismatica::Color;
52///
53/// let rgb = ratatui::style::Color::Rgb(128, 64, 32);
54/// assert!(Color::try_from(rgb).is_ok());
55///
56/// let named = ratatui::style::Color::Red;
57/// assert!(Color::try_from(named).is_err());
58/// ```
59impl TryFrom<::ratatui::style::Color> for Color {
60 type Error = ConversionError;
61
62 fn try_from(c: ::ratatui::style::Color) -> Result<Self, Self::Error> {
63 match c {
64 ::ratatui::style::Color::Rgb(r, g, b) => Ok(Color::new(r, g, b)),
65 _ => Err(ConversionError {
66 message: "only ratatui::style::Color::Rgb can be converted to prismatica::Color",
67 }),
68 }
69 }
70}
71
72impl_into_framework_color!(::ratatui::style::Color);