tui_realm_stdlib/components/
container.rsuse tuirealm::command::{Cmd, CmdResult};
use tuirealm::props::{Alignment, AttrValue, Attribute, Borders, Color, Layout, Props};
use tuirealm::ratatui::layout::Rect;
use tuirealm::{Frame, MockComponent, State};
#[derive(Default)]
pub struct Container {
props: Props,
pub children: Vec<Box<dyn MockComponent>>,
}
impl Container {
pub fn foreground(mut self, fg: Color) -> Self {
self.attr(Attribute::Foreground, AttrValue::Color(fg));
self
}
pub fn background(mut self, bg: Color) -> Self {
self.attr(Attribute::Background, AttrValue::Color(bg));
self
}
pub fn borders(mut self, b: Borders) -> Self {
self.attr(Attribute::Borders, AttrValue::Borders(b));
self
}
pub fn title<S: AsRef<str>>(mut self, t: S, a: Alignment) -> Self {
self.attr(
Attribute::Title,
AttrValue::Title((t.as_ref().to_string(), a)),
);
self
}
pub fn layout(mut self, layout: Layout) -> Self {
self.attr(Attribute::Layout, AttrValue::Layout(layout));
self
}
pub fn children(mut self, children: Vec<Box<dyn MockComponent>>) -> Self {
self.children = children;
self
}
}
impl MockComponent for Container {
fn view(&mut self, render: &mut Frame, area: Rect) {
if self.props.get_or(Attribute::Display, AttrValue::Flag(true)) == AttrValue::Flag(true) {
let borders = self
.props
.get_or(Attribute::Borders, AttrValue::Borders(Borders::default()))
.unwrap_borders();
let title = self.props.get(Attribute::Title).map(|x| x.unwrap_title());
let div = crate::utils::get_block(borders, title, true, None);
render.render_widget(div, area);
if let Some(layout) = self.props.get(Attribute::Layout).map(|x| x.unwrap_layout()) {
let chunks = layout.chunks(area);
for (i, chunk) in chunks.into_iter().enumerate() {
if let Some(child) = self.children.get_mut(i) {
child.view(render, chunk);
}
}
}
}
}
fn query(&self, attr: Attribute) -> Option<AttrValue> {
self.props.get(attr)
}
fn attr(&mut self, attr: Attribute, value: AttrValue) {
self.props.set(attr, value.clone());
self.children
.iter_mut()
.for_each(|x| x.attr(attr, value.clone()));
}
fn state(&self) -> State {
State::None
}
fn perform(&mut self, cmd: Cmd) -> CmdResult {
CmdResult::Batch(self.children.iter_mut().map(|x| x.perform(cmd)).collect())
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn test_components_paragraph() {
let component = Container::default()
.background(Color::Blue)
.foreground(Color::Red)
.title("title", Alignment::Center);
assert_eq!(component.state(), State::None);
}
}