tui_realm_stdlib/components/
radio.rsuse tuirealm::command::{Cmd, CmdResult, Direction};
use tuirealm::props::{
Alignment, AttrValue, Attribute, Borders, Color, PropPayload, PropValue, Props, Style,
TextModifiers,
};
use tuirealm::ratatui::text::Line as Spans;
use tuirealm::ratatui::{layout::Rect, widgets::Tabs};
use tuirealm::{Frame, MockComponent, State, StateValue};
#[derive(Default)]
pub struct RadioStates {
pub choice: usize, pub choices: Vec<String>, }
impl RadioStates {
pub fn next_choice(&mut self, rewind: bool) {
if rewind && self.choice + 1 >= self.choices.len() {
self.choice = 0;
} else if self.choice + 1 < self.choices.len() {
self.choice += 1;
}
}
pub fn prev_choice(&mut self, rewind: bool) {
if rewind && self.choice == 0 && !self.choices.is_empty() {
self.choice = self.choices.len() - 1;
} else if self.choice > 0 {
self.choice -= 1;
}
}
pub fn set_choices(&mut self, spans: &[String]) {
self.choices = spans.to_vec();
if self.choice >= self.choices.len() {
self.choice = match self.choices.len() {
0 => 0,
l => l - 1,
};
}
}
pub fn select(&mut self, i: usize) {
if i < self.choices.len() {
self.choice = i;
}
}
}
#[derive(Default)]
pub struct Radio {
props: Props,
pub states: RadioStates,
}
impl Radio {
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 inactive(mut self, s: Style) -> Self {
self.attr(Attribute::FocusStyle, AttrValue::Style(s));
self
}
pub fn rewind(mut self, r: bool) -> Self {
self.attr(Attribute::Rewind, AttrValue::Flag(r));
self
}
pub fn choices<S: AsRef<str>>(mut self, choices: &[S]) -> Self {
self.attr(
Attribute::Content,
AttrValue::Payload(PropPayload::Vec(
choices
.iter()
.map(|x| PropValue::Str(x.as_ref().to_string()))
.collect(),
)),
);
self
}
pub fn value(mut self, i: usize) -> Self {
self.attr(
Attribute::Value,
AttrValue::Payload(PropPayload::One(PropValue::Usize(i))),
);
self
}
fn is_rewind(&self) -> bool {
self.props
.get_or(Attribute::Rewind, AttrValue::Flag(false))
.unwrap_flag()
}
}
impl MockComponent for Radio {
fn view(&mut self, render: &mut Frame, area: Rect) {
if self.props.get_or(Attribute::Display, AttrValue::Flag(true)) == AttrValue::Flag(true) {
let choices: Vec<Spans> = self
.states
.choices
.iter()
.map(|x| Spans::from(x.clone()))
.collect();
let foreground = self
.props
.get_or(Attribute::Foreground, AttrValue::Color(Color::Reset))
.unwrap_color();
let background = self
.props
.get_or(Attribute::Background, AttrValue::Color(Color::Reset))
.unwrap_color();
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 focus = self
.props
.get_or(Attribute::Focus, AttrValue::Flag(false))
.unwrap_flag();
let inactive_style = self
.props
.get(Attribute::FocusStyle)
.map(|x| x.unwrap_style());
let div = crate::utils::get_block(borders, title, focus, inactive_style);
let (fg, block_color): (Color, Color) = match focus {
true => (foreground, foreground),
false => (foreground, Color::Reset),
};
let modifiers = match focus {
true => TextModifiers::REVERSED,
false => TextModifiers::empty(),
};
let radio: Tabs = Tabs::new(choices)
.block(div)
.select(self.states.choice)
.style(Style::default().fg(block_color).bg(background))
.highlight_style(Style::default().fg(fg).add_modifier(modifiers));
render.render_widget(radio, area);
}
}
fn query(&self, attr: Attribute) -> Option<AttrValue> {
self.props.get(attr)
}
fn attr(&mut self, attr: Attribute, value: AttrValue) {
match attr {
Attribute::Content => {
let choices: Vec<String> = value
.unwrap_payload()
.unwrap_vec()
.iter()
.map(|x| x.clone().unwrap_str())
.collect();
self.states.set_choices(&choices);
}
Attribute::Value => {
self.states
.select(value.unwrap_payload().unwrap_one().unwrap_usize());
}
attr => {
self.props.set(attr, value);
}
}
}
fn state(&self) -> State {
State::One(StateValue::Usize(self.states.choice))
}
fn perform(&mut self, cmd: Cmd) -> CmdResult {
match cmd {
Cmd::Move(Direction::Right) => {
self.states.next_choice(self.is_rewind());
CmdResult::Changed(self.state())
}
Cmd::Move(Direction::Left) => {
self.states.prev_choice(self.is_rewind());
CmdResult::Changed(self.state())
}
Cmd::Submit => {
CmdResult::Submit(self.state())
}
_ => CmdResult::None,
}
}
}
#[cfg(test)]
mod test {
use super::*;
use pretty_assertions::assert_eq;
use tuirealm::props::{PropPayload, PropValue};
#[test]
fn test_components_radio_states() {
let mut states: RadioStates = RadioStates::default();
assert_eq!(states.choice, 0);
assert_eq!(states.choices.len(), 0);
let choices: &[String] = &[
"lemon".to_string(),
"strawberry".to_string(),
"vanilla".to_string(),
"chocolate".to_string(),
];
states.set_choices(choices);
assert_eq!(states.choice, 0);
assert_eq!(states.choices.len(), 4);
states.prev_choice(false);
assert_eq!(states.choice, 0);
states.next_choice(false);
assert_eq!(states.choice, 1);
states.next_choice(false);
assert_eq!(states.choice, 2);
states.next_choice(false);
states.next_choice(false);
assert_eq!(states.choice, 3);
states.prev_choice(false);
assert_eq!(states.choice, 2);
let choices: &[String] = &["lemon".to_string(), "strawberry".to_string()];
states.set_choices(choices);
assert_eq!(states.choice, 1); assert_eq!(states.choices.len(), 2);
let choices: &[String] = &[];
states.set_choices(choices);
assert_eq!(states.choice, 0); assert_eq!(states.choices.len(), 0);
let choices: &[String] = &[
"lemon".to_string(),
"strawberry".to_string(),
"vanilla".to_string(),
"chocolate".to_string(),
];
states.set_choices(choices);
assert_eq!(states.choice, 0);
states.prev_choice(true);
assert_eq!(states.choice, 3);
states.next_choice(true);
assert_eq!(states.choice, 0);
states.next_choice(true);
assert_eq!(states.choice, 1);
states.prev_choice(true);
assert_eq!(states.choice, 0);
}
#[test]
fn test_components_radio() {
let mut component = Radio::default()
.background(Color::Blue)
.foreground(Color::Red)
.borders(Borders::default())
.title("C'est oui ou bien c'est non?", Alignment::Center)
.choices(&["Oui!", "Non", "Peut-ĂȘtre"])
.value(1)
.rewind(false);
assert_eq!(component.states.choice, 1);
assert_eq!(component.states.choices.len(), 3);
component.attr(
Attribute::Value,
AttrValue::Payload(PropPayload::One(PropValue::Usize(2))),
);
assert_eq!(component.state(), State::One(StateValue::Usize(2)));
component.states.choice = 1;
assert_eq!(component.state(), State::One(StateValue::Usize(1)));
assert_eq!(
component.perform(Cmd::Move(Direction::Left)),
CmdResult::Changed(State::One(StateValue::Usize(0))),
);
assert_eq!(component.state(), State::One(StateValue::Usize(0)));
assert_eq!(
component.perform(Cmd::Move(Direction::Left)),
CmdResult::Changed(State::One(StateValue::Usize(0))),
);
assert_eq!(component.state(), State::One(StateValue::Usize(0)));
assert_eq!(
component.perform(Cmd::Move(Direction::Right)),
CmdResult::Changed(State::One(StateValue::Usize(1))),
);
assert_eq!(component.state(), State::One(StateValue::Usize(1)));
assert_eq!(
component.perform(Cmd::Move(Direction::Right)),
CmdResult::Changed(State::One(StateValue::Usize(2))),
);
assert_eq!(component.state(), State::One(StateValue::Usize(2)));
assert_eq!(
component.perform(Cmd::Move(Direction::Right)),
CmdResult::Changed(State::One(StateValue::Usize(2))),
);
assert_eq!(component.state(), State::One(StateValue::Usize(2)));
assert_eq!(
component.perform(Cmd::Submit),
CmdResult::Submit(State::One(StateValue::Usize(2))),
);
}
}