use std::sync::Arc;
use super::{
button::ButtonSize,
names,
part_style::Length,
recipe::{Case, Interaction, Name, Recipe},
shared::{ChangeHandler, Choice, Chosen, Orientation},
theme::{Themed, current_theme},
toggle::{Toggle, TogglePart},
};
use crate::{
app::theme::{BorderSize, PaletteColor, RadiusSize, Theme},
components::{Column, Row},
core::{Signal, SignalValue},
layout::Alignment,
node::{Element, FocusGroup, NodeUpdate, border::Border},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ToggleGroupPart {
Root,
Item,
Separator,
}
names!(ToggleGroupPart {
Root => "root",
Item => "item",
Separator => "separator",
});
struct Item {
label: Arc<str>,
icon: Option<Name>,
icon_only: bool,
disabled: bool,
on: bool,
pick: Arc<dyn Fn() + Send + Sync>,
id: Option<Arc<str>>,
states: Vec<Name>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ToggleGroupState {
Horizontal,
Vertical,
Disabled,
Invalid,
}
names!(ToggleGroupState {
Horizontal => "horizontal",
Vertical => "vertical",
Disabled => "disabled",
Invalid => "invalid",
});
pub type ToggleGroupSize = ButtonSize;
pub type ToggleGroupOrientation = Orientation;
pub type ToggleGroupRenderer = Arc<dyn Fn(ToggleGroup) -> Element + Send + Sync>;
pub struct ToggleGroup<T = (), V: ?Sized = T> {
choices: Vec<Choice<T>>,
chosen: Chosen<T, V>,
on_change: Vec<ChangeHandler<V>>,
toggles: Toggles,
}
impl<T: Clone + PartialEq + Send + Sync + 'static> ToggleGroup<T, T> {
pub fn new(value: Signal<T>, choices: impl IntoIterator<Item = impl Into<Choice<T>>>) -> Self
where
T: SignalValue,
{
Self::of(Chosen::one(value), choices)
}
pub fn controlled(
value: T,
choices: impl IntoIterator<Item = impl Into<Choice<T>>>,
on_change: impl Fn(&T) + Send + Sync + 'static,
) -> Self {
Self::of(Chosen::held_one(value), choices).on_change(on_change)
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static> ToggleGroup<T, [T]> {
pub fn multiple(values: Signal<Vec<T>>, choices: impl IntoIterator<Item = impl Into<Choice<T>>>) -> Self
where
Vec<T>: SignalValue,
{
Self::of(Chosen::many(values), choices)
}
pub fn controlled_multiple(
values: impl IntoIterator<Item = T>,
choices: impl IntoIterator<Item = impl Into<Choice<T>>>,
on_change: impl Fn(&[T]) + Send + Sync + 'static,
) -> Self {
Self::of(Chosen::held_many(values.into_iter().collect()), choices).on_change(on_change)
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static, V: ?Sized + 'static> ToggleGroup<T, V> {
fn of(chosen: Chosen<T, V>, choices: impl IntoIterator<Item = impl Into<Choice<T>>>) -> Self {
Self {
choices: choices.into_iter().map(Into::into).collect(),
chosen,
on_change: Vec::new(),
toggles: Toggles {
items: Vec::new(),
size: ButtonSize::default().into(),
orientation: Orientation::Horizontal,
label: None,
disabled: false,
invalid: false,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
id: None,
key: None,
},
}
}
pub fn on_change(mut self, handler: impl Fn(&V) + Send + Sync + 'static) -> Self {
self.on_change.push(Arc::new(handler));
self
}
pub fn label(mut self, label: &str) -> Self {
self.toggles.label = Some(Arc::from(label));
self
}
pub fn size(mut self, size: impl Into<Name>) -> Self {
self.toggles.size = size.into();
self
}
pub fn orientation(mut self, orientation: Orientation) -> Self {
self.toggles.orientation = orientation;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.toggles.disabled = disabled;
self
}
pub fn invalid(mut self, invalid: bool) -> Self {
self.toggles.invalid = invalid;
self
}
pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
let state = state.into();
self.toggles.states.retain(|held| *held != state);
if on {
self.toggles.states.push(state);
}
self
}
pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(super::PartStyle) -> super::PartStyle) -> Self {
self.toggles.rules = self.toggles.rules.base(part, style);
self
}
pub fn rules(mut self, rules: &Recipe) -> Self {
self.toggles.rules = self.toggles.rules.extend(rules);
self
}
pub fn force(mut self, interaction: Option<Interaction>) -> Self {
self.toggles.forced = interaction;
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.toggles.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.toggles.key = Some(key.into());
self
}
pub(crate) fn erase(self) -> Toggles {
let handlers: Arc<[ChangeHandler<V>]> = self.on_change.into();
let mut toggles = self.toggles;
toggles.items = self
.choices
.into_iter()
.map(|choice| Item {
on: self.chosen.has(&choice.value),
pick: self.chosen.picker(choice.value, handlers.clone()),
label: choice.label,
icon: choice.icon,
icon_only: choice.icon_only,
disabled: choice.disabled,
id: choice.id,
states: choice.states,
})
.collect();
toggles
}
pub fn build(self, theme: &Theme) -> Element {
self.erase().build(theme)
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static, V: ?Sized + 'static> From<ToggleGroup<T, V>> for Element {
fn from(group: ToggleGroup<T, V>) -> Self {
group.build(¤t_theme())
}
}
pub(crate) struct Toggles {
items: Vec<Item>,
size: Name,
orientation: Orientation,
label: Option<Arc<str>>,
disabled: bool,
invalid: bool,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl Toggles {
pub(crate) fn size(mut self, size: Name) -> Self {
self.size = size;
self
}
pub(crate) fn disabled(mut self, disabled: bool) -> Self {
self.disabled |= disabled;
self
}
pub(crate) fn commands(&self) -> Vec<super::toolbar::ToolbarCommand> {
self
.items
.iter()
.map(|item| super::toolbar::ToolbarCommand {
label: item.label.clone(),
icon: item.icon,
icon_only: item.icon_only,
disabled: self.disabled || item.disabled,
checked: Some(item.on),
run: item.pick.clone(),
id: None,
key: None,
})
.collect()
}
pub(crate) fn build(self, theme: &Theme) -> Element {
let vertical = self.orientation == Orientation::Vertical;
let mut case = Case::new()
.size(self.size)
.breakpoint(super::current_breakpoint())
.state(ToggleGroupState::Horizontal, !vertical)
.state(ToggleGroupState::Vertical, vertical)
.state(ToggleGroupState::Disabled, self.disabled)
.state(ToggleGroupState::Invalid, self.invalid);
for state in &self.states {
case = case.state(state.clone(), true);
}
let recipe = theme
.resolve::<ToggleGroup>(&case, Some(&self.rules))
.owned_by(self.id.as_ref());
let item = recipe.rules_for(ToggleGroupPart::Item, TogglePart::Root);
let separator = recipe.part(ToggleGroupPart::Separator);
let separated = separator.rest().width.is_some() || separator.rest().height.is_some();
let entry = self
.items
.iter()
.position(|item| item.on && !item.disabled)
.or_else(|| self.items.iter().position(|item| !item.disabled));
let mut children = Vec::with_capacity(self.items.len() * 2);
for (index, choice) in self.items.into_iter().enumerate() {
if index > 0 && separated {
children.push(Element::from(Row::new().part(&separator)));
}
let pick = choice.pick;
let mut toggle = Toggle::new(&choice.label)
.size(self.size)
.icon_only(choice.icon_only)
.on(choice.on)
.disabled(self.disabled || choice.disabled)
.rules(&item)
.force(self.forced.filter(|_| Some(index) == entry))
.on_change(move |_| pick());
if let Some(name) = choice.icon {
toggle = toggle.icon(name);
}
if let Some(id) = choice.id {
toggle = toggle.id(id);
}
for state in choice.states {
toggle = toggle.state(state, true);
}
children.push(toggle.build(theme));
}
let root_part = recipe.part(ToggleGroupPart::Root);
let mut root: Element = if vertical {
children
.into_iter()
.fold(
Column::new()
.part(&root_part)
.focus_group(FocusGroup::vertical().one_stop(true))
.align_items(Alignment::Stretch)
.clip(),
Column::child,
)
.into()
} else {
children
.into_iter()
.fold(
Row::new()
.part(&root_part)
.focus_group(FocusGroup::horizontal().one_stop(true))
.align_items(Alignment::Stretch)
.clip(),
Row::child,
)
.into()
};
let node = &mut *root.node;
NodeUpdate::describe(node, Arc::from("a11y_role"), Arc::from("group"));
if let Some(label) = self.label {
NodeUpdate::describe(node, Arc::from("a11y_name"), label);
}
if self.invalid {
NodeUpdate::describe(node, Arc::from("a11y_invalid"), Arc::from("true"));
}
if let Some(id) = self.id {
NodeUpdate::id(node, id);
}
if let Some(key) = self.key {
root = root.key(key);
}
root
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static, V: ?Sized + 'static> crate::ui::Styled for ToggleGroup<T, V> {
type Component = Self;
fn rules(self, rules: &crate::ui::Recipe) -> Self {
Self::rules(self, rules)
}
fn state(self, state: impl Into<crate::ui::Name>, on: bool) -> Self {
Self::state(self, state, on)
}
}
impl<T: Send + Sync + 'static, V: ?Sized + 'static> Themed for ToggleGroup<T, V> {
const NAME: &'static str = "toggle_group";
type Renderer = ToggleGroupRenderer;
fn parts() -> crate::ui::Declared {
ToggleGroupPart::declared()
}
fn states() -> crate::ui::Declared {
ToggleGroupState::declared()
}
fn recipe() -> Recipe {
use PaletteColor::{Background, Input};
use ToggleGroupPart::{Item, Root, Separator};
Recipe::new()
.base(Root, |s| {
s.radius(RadiusSize::Md)
.background(Background)
.border(Border::inside(BorderSize::Sm, Input))
})
.base(Item, |s| s.radius(0.0))
.base(Separator, |s| s.width(1.0).background(Input))
.state(ToggleGroupState::Vertical, Separator, |s| s.width(Length::Auto).height(1.0))
.state(ToggleGroupState::Invalid, Root, |s| {
s.border(Border::inside(BorderSize::Sm, PaletteColor::Destructive))
})
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static, V: ?Sized + 'static> super::FieldControl for ToggleGroup<T, V> {
fn in_field(mut self, field: &super::InField) -> Element {
if self.toggles.label.is_none() && !field.label.is_empty() {
self.toggles.label = Some(field.label.clone());
}
self.toggles.invalid |= field.judgment == Some(super::Judgment::Invalid);
self.toggles.disabled |= field.disabled;
self.into()
}
}