use std::hash::Hash;
use super::super::{
sanitize,
theme::{painter::PaintHook, ControlPaint, PaintMode, Painter, RadioStyle},
SemanticStatus, Ui,
};
use super::options::{Config, RadioLayout, RadioOption, RadioSize};
use crate::{Id, Response};
pub struct RadioGroup<'a, T> {
pub(super) selected: &'a mut T,
pub(super) options: Vec<RadioOption<T>>,
pub(super) cfg: Config,
pub(super) painter: Option<PaintHook<'a>>,
}
impl<'a, T: PartialEq + Hash> RadioGroup<'a, T> {
pub fn new<O: Into<RadioOption<T>>>(
selected: &'a mut T,
options: impl IntoIterator<Item = O>,
) -> Self {
Self {
selected,
options: options.into_iter().map(Into::into).collect(),
cfg: Config::default(),
painter: None,
}
}
pub fn id_source(mut self, source: impl Hash) -> Self {
self.cfg.id = Some(Id::new(source));
self
}
pub fn enabled(mut self, enabled: bool) -> Self {
self.cfg.enabled = enabled;
self
}
pub fn status(mut self, status: SemanticStatus) -> Self {
self.cfg.status = status;
self
}
pub fn layout(mut self, layout: RadioLayout) -> Self {
self.cfg.layout = layout;
self
}
pub fn horizontal(self) -> Self {
self.layout(RadioLayout::Horizontal)
}
#[track_caller]
pub fn columns(self, columns: usize) -> Self {
if columns == 0 {
crate::context::invalid_value("RadioGroup::columns", "expected >= 1; ignored".into());
return self;
}
self.layout(RadioLayout::Grid(columns))
}
pub fn size(mut self, size: RadioSize) -> Self {
self.cfg.size = size;
self
}
pub fn focus_follows_selection(mut self, follow: bool) -> Self {
self.cfg.follow_focus = follow;
self
}
#[track_caller]
pub fn row_gap(mut self, gap: f32) -> Self {
self.cfg.row_gap = sanitize::non_negative("RadioGroup::row_gap", gap).or(self.cfg.row_gap);
self
}
#[track_caller]
pub fn column_gap(mut self, gap: f32) -> Self {
self.cfg.column_gap =
sanitize::non_negative("RadioGroup::column_gap", gap).or(self.cfg.column_gap);
self
}
#[track_caller]
pub fn label_gap(mut self, gap: f32) -> Self {
self.cfg.label_gap =
sanitize::non_negative("RadioGroup::label_gap", gap).or(self.cfg.label_gap);
self
}
#[track_caller]
pub fn min_row_height(mut self, height: f32) -> Self {
self.cfg.min_row_height = sanitize::non_negative("RadioGroup::min_row_height", height)
.or(self.cfg.min_row_height);
self
}
pub fn style(mut self, style: RadioStyle) -> Self {
self.cfg.style = style;
self
}
pub fn painter(
mut self,
mode: PaintMode,
paint: impl Fn(&mut Painter<'_>, ControlPaint) + 'a,
) -> Self {
self.painter = Some(PaintHook {
mode,
callback: Box::new(paint),
});
self
}
}
impl Ui<'_> {
pub fn radio_group<T, O>(
&mut self,
selected: &mut T,
options: impl IntoIterator<Item = O>,
) -> Response
where
T: PartialEq + Hash,
O: Into<RadioOption<T>>,
{
self.add(RadioGroup::new(selected, options))
}
pub fn radio_value<T: PartialEq + Hash>(
&mut self,
selected: &mut T,
value: T,
label: impl Into<String>,
) -> Response {
self.add(RadioGroup::new(selected, [(value, label.into())]))
}
}