use tuirealm::command::{Cmd, CmdResult, Direction};
use tuirealm::component::Component;
use tuirealm::props::{
AttrValue, Attribute, Borders, Color, PropPayload, PropValue, Props, QueryResult, Style,
TextModifiers, Title,
};
use tuirealm::ratatui::Frame;
use tuirealm::ratatui::layout::Rect;
use tuirealm::ratatui::text::Line;
use tuirealm::ratatui::widgets::Tabs;
use tuirealm::state::{State, StateValue};
use crate::prop_ext::{CommonHighlight, CommonProps};
#[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, choices: impl Into<Vec<String>>) {
self.choices = choices.into();
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)]
#[must_use]
pub struct Radio {
common: CommonProps,
common_hg: CommonHighlight,
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 modifiers(mut self, m: TextModifiers) -> Self {
self.attr(Attribute::TextProps, AttrValue::TextModifiers(m));
self
}
pub fn style(mut self, style: Style) -> Self {
self.attr(Attribute::Style, AttrValue::Style(style));
self
}
pub fn inactive(mut self, s: Style) -> Self {
self.attr(Attribute::UnfocusedBorderStyle, AttrValue::Style(s));
self
}
pub fn borders(mut self, b: Borders) -> Self {
self.attr(Attribute::Borders, AttrValue::Borders(b));
self
}
pub fn title<T: Into<Title>>(mut self, title: T) -> Self {
self.attr(Attribute::Title, AttrValue::Title(title.into()));
self
}
pub fn highlight_style(mut self, s: Style) -> Self {
self.attr(Attribute::HighlightStyle, AttrValue::Style(s));
self
}
pub fn highlight_style_inactive(mut self, s: Style) -> Self {
self.attr(Attribute::HighlightStyleUnfocused, AttrValue::Style(s));
self
}
pub fn rewind(mut self, r: bool) -> Self {
self.attr(Attribute::Rewind, AttrValue::Flag(r));
self
}
pub fn choices<S: Into<String>>(mut self, choices: impl IntoIterator<Item = S>) -> Self {
self.attr(
Attribute::Content,
AttrValue::Payload(PropPayload::Vec(
choices
.into_iter()
.map(|v| PropValue::Str(v.into()))
.collect(),
)),
);
self
}
pub fn value(mut self, i: usize) -> Self {
self.attr(
Attribute::Value,
AttrValue::Payload(PropPayload::Single(PropValue::Usize(i))),
);
self
}
pub fn always_active(mut self) -> Self {
self.attr(Attribute::AlwaysActive, AttrValue::Flag(true));
self
}
fn is_rewind(&self) -> bool {
self.props
.get(Attribute::Rewind)
.and_then(AttrValue::as_flag)
.unwrap_or_default()
}
}
impl Component for Radio {
fn view(&mut self, render: &mut Frame, area: Rect) {
if !self.common.display {
return;
}
let choices: Vec<Line> = self
.states
.choices
.iter()
.map(|x| Line::from(x.as_str()))
.collect();
let mut widget = Tabs::new(choices)
.select(self.states.choice)
.style(self.common.style)
.highlight_style(
self.common_hg
.get_style_focus(self.common.style, self.common.is_active()),
);
if let Some(block) = self.common.get_block() {
widget = widget.block(block);
}
render.render_widget(widget, area);
}
fn query<'a>(&'a self, attr: Attribute) -> Option<QueryResult<'a>> {
if let Some(value) = self
.common
.get_for_query(attr)
.or_else(|| self.common_hg.get_for_query(attr))
{
return Some(value);
}
self.props.get_for_query(attr)
}
fn attr(&mut self, attr: Attribute, value: AttrValue) {
if let Some(value) = self
.common
.set(attr, value)
.and_then(|value| self.common_hg.set(attr, value))
{
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_single().unwrap_usize());
}
attr => {
self.props.set(attr, value);
}
}
}
}
fn state(&self) -> State {
State::Single(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::Invalid(cmd),
}
}
}
#[cfg(test)]
mod test {
use pretty_assertions::assert_eq;
use tuirealm::props::{HorizontalAlignment, PropPayload, PropValue};
use super::*;
#[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(
Title::from("C'est oui ou bien c'est non?").alignment(HorizontalAlignment::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::Single(PropValue::Usize(2))),
);
assert_eq!(component.state(), State::Single(StateValue::Usize(2)));
component.states.choice = 1;
assert_eq!(component.state(), State::Single(StateValue::Usize(1)));
assert_eq!(
component.perform(Cmd::Move(Direction::Left)),
CmdResult::Changed(State::Single(StateValue::Usize(0))),
);
assert_eq!(component.state(), State::Single(StateValue::Usize(0)));
assert_eq!(
component.perform(Cmd::Move(Direction::Left)),
CmdResult::Changed(State::Single(StateValue::Usize(0))),
);
assert_eq!(component.state(), State::Single(StateValue::Usize(0)));
assert_eq!(
component.perform(Cmd::Move(Direction::Right)),
CmdResult::Changed(State::Single(StateValue::Usize(1))),
);
assert_eq!(component.state(), State::Single(StateValue::Usize(1)));
assert_eq!(
component.perform(Cmd::Move(Direction::Right)),
CmdResult::Changed(State::Single(StateValue::Usize(2))),
);
assert_eq!(component.state(), State::Single(StateValue::Usize(2)));
assert_eq!(
component.perform(Cmd::Move(Direction::Right)),
CmdResult::Changed(State::Single(StateValue::Usize(2))),
);
assert_eq!(component.state(), State::Single(StateValue::Usize(2)));
assert_eq!(
component.perform(Cmd::Submit),
CmdResult::Submit(State::Single(StateValue::Usize(2))),
);
}
#[test]
fn various_set_choice_types() {
RadioStates::default().set_choices(&["hello".to_string()]);
RadioStates::default().set_choices(vec!["hello".to_string()]);
RadioStates::default().set_choices(vec!["hello".to_string()].into_boxed_slice());
}
#[test]
fn various_choice_types() {
let _ = Radio::default().choices(["hello"]);
let _ = Radio::default().choices(["hello".to_string()]);
let _ = Radio::default().choices(vec!["hello"]);
let _ = Radio::default().choices(vec!["hello".to_string()]);
let _ = Radio::default().choices(vec!["hello"].into_boxed_slice());
let _ = Radio::default().choices(vec!["hello".to_string()].into_boxed_slice());
}
}