use std::str::FromStr; use mlua::{FromLua, IntoLua}; use ratatui::style::{Color, Styled, Stylize}; #[derive(Clone, Copy, Debug, Default)] pub struct Style { pub fg: Option, pub bg: Option, pub italic: bool, pub bold: bool, pub underlined: bool } impl Style { pub const fn new() -> Self { Self { fg: None, bg: None, italic: false, bold: false, underlined: false, } } pub const fn fg(mut self, color: Color) -> Self { self.fg = Some(color); self } pub const fn bg(mut self, color: Color) -> Self { self.bg = Some(color); self } pub fn apply(&self, s: S) -> ::Item where S: Styled, I: Styled, { s.set_style(self.style()) } pub fn style(&self) -> ratatui::style::Style { let mut style = ratatui::style::Style::default(); if let Some(fg) = self.fg { style = style.fg(fg) } if let Some(bg) = self.bg { style = style.bg(bg) } if self.italic { style = style.italic() } if self.bold { style = style.bold() } if self.underlined { style = style.underlined() } style } } impl<'lua> FromLua<'lua> for Style { fn from_lua( value: mlua::prelude::LuaValue<'lua>, _lua: &'lua mlua::prelude::Lua, ) -> mlua::prelude::LuaResult { if value.is_table() { let table = value.as_table().unwrap(); let mut style = Style::new(); if let Ok(fg) = table.get::<_, String>("fg").or_else(|_| table.get(1)) { match Color::from_str(&fg) { Ok(fg) => style.fg = Some(fg), Err(_) => return Err(mlua::Error::runtime("could not parse fg")) } } if let Ok(bg) = table.get::<_, String>("bg").or_else(|_| table.get(2)) { match Color::from_str(&bg) { Ok(bg) => style.bg = Some(bg), Err(_) => return Err(mlua::Error::runtime("could not parse bg")) } } if let Ok(italic) = table.get::<_, bool>("italic") { style.italic = italic } if let Ok(bold) = table.get::<_, bool>("bold") { style.bold = bold } if let Ok(underlined) = table.get::<_, bool>("underlined") { style.underlined = underlined } return Ok(style) } Err(mlua::Error::runtime("could not parse style")) } } impl<'lua> IntoLua<'lua> for Style { fn into_lua( self, lua: &'lua mlua::prelude::Lua, ) -> mlua::prelude::LuaResult> { let table = lua.create_table()?; table.set("fg", self.fg.map(|s| s.to_string()).into_lua(lua)?)?; table.set("bg", self.bg.map(|s| s.to_string()).into_lua(lua)?)?; table.into_lua(lua) } }