use std::hash::Hash;
use super::super::{sanitize, SemanticStatus, Ui};
use super::options::{
Config, SegmentOption, SegmentWidth, SegmentedOrientation, SegmentedSize, SegmentedVariant,
};
use crate::{components::theme::SegmentedStyle, CornerRadius, Id, Response};
pub struct SegmentedControl<'a, T> {
pub(super) selected: &'a mut T,
pub(super) options: Vec<SegmentOption<T>>,
pub(super) cfg: Config,
}
impl<'a, T: PartialEq + Hash + Clone> SegmentedControl<'a, T> {
pub fn new<O: Into<SegmentOption<T>>>(
selected: &'a mut T,
options: impl IntoIterator<Item = O>,
) -> Self {
Self {
selected,
options: options.into_iter().map(Into::into).collect(),
cfg: Config::default(),
}
}
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 orientation(mut self, orientation: SegmentedOrientation) -> Self {
self.cfg.orientation = orientation;
self
}
pub fn vertical(self) -> Self {
self.orientation(SegmentedOrientation::Vertical)
}
pub fn variant(mut self, variant: SegmentedVariant) -> Self {
self.cfg.variant = variant;
self
}
pub fn size(mut self, size: SegmentedSize) -> Self {
self.cfg.size = size;
self
}
#[track_caller]
pub fn width(mut self, width: SegmentWidth) -> Self {
match width {
SegmentWidth::Fixed(w) => {
if let Some(w) = sanitize::positive("SegmentedControl::width", w) {
self.cfg.width = SegmentWidth::Fixed(w);
}
}
other => self.cfg.width = other,
}
self
}
#[track_caller]
pub fn min_segment_width(mut self, width: f32) -> Self {
self.cfg.min_width = sanitize::non_negative("SegmentedControl::min_segment_width", width)
.or(self.cfg.min_width);
self
}
pub fn icon_only(mut self, icon_only: bool) -> Self {
self.cfg.icon_only = icon_only;
self
}
pub fn focus_follows_selection(mut self, follow: bool) -> Self {
self.cfg.follow_focus = follow;
self
}
pub fn style(mut self, style: SegmentedStyle) -> Self {
self.cfg.style = style;
self
}
pub fn corner_radius(mut self, radius: impl Into<CornerRadius>) -> Self {
self.cfg.rounding = Some(radius.into());
self
}
}
impl Ui<'_> {
pub fn segmented<T, O>(
&mut self,
selected: &mut T,
options: impl IntoIterator<Item = O>,
) -> Response
where
T: PartialEq + Hash + Clone,
O: Into<SegmentOption<T>>,
{
self.add(SegmentedControl::new(selected, options))
}
}