use std::sync::Arc;
use super::{
names,
part_style::PartTransition,
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe},
shared::{Choice, Orientation, fading, pressable},
theme::{Themed, current_theme},
};
use crate::{
animation::Transition,
app::theme::{BorderSize, MotionDuration, OpacityLevel, PaletteColor, RadiusSize, Theme, TypographyStyle},
components::{self, Column, Row},
core::{ElementRef, Signal, SignalValue},
layout::Alignment,
node::{CursorIcon, Element, FocusGroup, border::Border},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RadioPart {
Root,
Mark,
Dot,
Label,
Count,
}
names!(RadioPart {
Root => "root",
Mark => "mark",
Dot => "dot",
Label => "label",
Count => "count",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RadioState {
Selected,
Invalid,
Disabled,
}
names!(RadioState {
Selected => "selected",
Invalid => "invalid",
Disabled => "disabled",
});
pub type RadioRenderer = Arc<dyn Fn(RadioView) -> Element + Send + Sync>;
pub struct Radio {
label: Arc<str>,
label_hidden: bool,
count: Option<Arc<str>>,
element: Option<ElementRef>,
selected: bool,
invalid: bool,
disabled: bool,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
on_change: Vec<Arc<dyn Fn(bool) + Send + Sync>>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl Radio {
pub fn new(label: &str) -> Self {
Self {
label: Arc::from(label),
label_hidden: false,
count: None,
element: None,
selected: false,
invalid: false,
disabled: false,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
on_change: Vec::new(),
id: None,
key: None,
}
}
pub fn label_hidden(mut self, hidden: bool) -> Self {
self.label_hidden = hidden;
self
}
pub fn count(mut self, count: impl std::fmt::Display) -> Self {
self.count = Some(Arc::from(count.to_string()));
self
}
pub fn element_ref(mut self, element: ElementRef) -> Self {
self.element = Some(element);
self
}
pub fn selected(mut self, selected: bool) -> Self {
self.selected = selected;
self
}
pub fn invalid(mut self, invalid: bool) -> Self {
self.invalid = invalid;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
let state = state.into();
self.states.retain(|held| *held != state);
if on {
self.states.push(state);
}
self
}
pub fn on_change(mut self, handler: impl Fn(bool) + Send + Sync + 'static) -> Self {
self.on_change.push(Arc::new(handler));
self
}
pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(super::PartStyle) -> super::PartStyle) -> Self {
self.rules = self.rules.base(part, style);
self
}
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
pub fn force(mut self, interaction: Option<Interaction>) -> Self {
self.forced = interaction;
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
pub fn build(self, theme: &Theme) -> Element {
let case = Case {
variant: None,
size: None,
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(RadioState::Selected, self.selected)
.state(RadioState::Invalid, self.invalid)
.state(RadioState::Disabled, self.disabled);
let view = RadioView {
label: self.label,
label_hidden: self.label_hidden,
count: self.count,
element: self.element,
selected: self.selected,
invalid: self.invalid,
disabled: self.disabled,
recipe: theme
.resolve::<Radio>(&case, Some(&self.rules))
.owned_by(self.id.as_ref()),
forced: self.forced,
on_change: self.on_change,
id: self.id,
key: self.key,
};
match theme.renderer::<Radio>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl From<Radio> for Element {
fn from(radio: Radio) -> Self {
radio.build(¤t_theme())
}
}
pub struct RadioView {
pub label: Arc<str>,
pub label_hidden: bool,
pub count: Option<Arc<str>>,
element: Option<ElementRef>,
pub selected: bool,
pub invalid: bool,
pub disabled: bool,
pub recipe: ResolvedRecipe,
forced: Option<Interaction>,
on_change: Vec<Arc<dyn Fn(bool) + Send + Sync>>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl RadioView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part).forced(self.forced)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
fn press(&self) -> Option<impl Fn() + Send + Sync + Clone + 'static> {
let handlers = self.on_change.clone();
(!handlers.is_empty() && !self.disabled && !self.selected).then(|| {
move || {
for handler in &handlers {
handler(true);
}
}
})
}
pub fn mark(&self) -> components::Button {
let mut mark = pressable(&self.part(RadioPart::Mark), self.disabled)
.align_items(Alignment::Center)
.describe("a11y_role", "radio")
.describe("a11y_name", self.label.clone())
.describe("a11y_checked", if self.selected { "true" } else { "false" })
.focus_entry(self.selected);
if let Some(press) = self.press() {
mark = mark.on_click(move |_| press());
}
if let Some(id) = &self.id {
mark = mark.id(id.clone());
}
if let Some(key) = &self.key {
mark = mark.key(key.clone());
}
if let Some(element) = &self.element {
mark = mark.ref_element(element.clone());
}
mark
}
pub fn dot(&self) -> Row {
Row::new().part(&self.part(RadioPart::Dot))
}
pub fn render(self) -> Element {
let mut mark = self.mark();
if self.selected {
mark = mark.child(self.dot());
}
let mut root = Row::new()
.align_items(Alignment::Center)
.part(&self.part(RadioPart::Root))
.child(mark);
if !self.label_hidden {
let part = self.part(RadioPart::Label);
let mut label = Row::new().part(&part).child(part.text(&self.label).nowrap());
if let Some(press) = self.press() {
label = label.on_click(move |_| press());
}
root = root.child(label);
}
if let Some(count) = &self.count {
let part = self.part(RadioPart::Count);
root = root.child(Row::new().part(&part).child(part.text(count).nowrap()));
}
root.into()
}
}
impl crate::ui::Styled for Radio {
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 Themed for Radio {
const NAME: &'static str = "radio";
type Renderer = RadioRenderer;
fn parts() -> crate::ui::Declared {
RadioPart::declared()
}
fn states() -> crate::ui::Declared {
RadioState::declared()
}
fn recipe() -> Recipe {
use PaletteColor::{Background, Destructive, Foreground, Input, MutedForeground, Primary};
use RadioPart::{Count, Dot, Label, Mark, Root};
Recipe::new()
.base(Root, |s| s.gap(8.0).foreground(Foreground))
.base(Mark, |s| {
fading(
s.square(16.0)
.radius(RadiusSize::Full)
.background(Background)
.border(Border::inside(BorderSize::Sm, Input))
.cursor(CursorIcon::Pointer),
)
.transition(PartTransition::new(Transition::border_color(), MotionDuration::Fast))
})
.base(Dot, |s| s.square(8.0).radius(RadiusSize::Full).background(Primary))
.base(Label, |s| {
s.typography(TypographyStyle::Body).cursor(CursorIcon::Pointer)
})
.base(Count, |s| s.typography(TypographyStyle::Caption).foreground(MutedForeground))
.focus_visible(Mark, |s| s.focus_ring())
.state(RadioState::Selected, Mark, |s| {
s.border(Border::inside(BorderSize::Sm, Primary))
})
.state(RadioState::Invalid, Mark, |s| {
s.border(Border::inside(BorderSize::Sm, Destructive))
})
.state(RadioState::Disabled, Root, |s| s.opacity(OpacityLevel::Disabled))
.state(RadioState::Disabled, Mark, |s| s.cursor(CursorIcon::Default))
.state(RadioState::Disabled, Label, |s| s.cursor(CursorIcon::Default))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RadioGroupPart {
Root,
Item,
}
names!(RadioGroupPart {
Root => "root",
Item => "item",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RadioGroupState {
Horizontal,
Vertical,
}
names!(RadioGroupState {
Horizontal => "horizontal",
Vertical => "vertical",
});
pub struct RadioSelection<T> {
pub(crate) selected: Option<T>,
pub(crate) set: Arc<dyn Fn(T) + Send + Sync>,
}
impl<T: Clone + Send + Sync + SignalValue + 'static> From<Signal<T>> for RadioSelection<T> {
fn from(signal: Signal<T>) -> Self {
Self {
selected: Some(signal.get()),
set: Arc::new(move |value| signal.set(value)),
}
}
}
impl<T: Clone + Send + Sync + 'static> From<Signal<Option<T>>> for RadioSelection<T>
where
Option<T>: SignalValue,
{
fn from(signal: Signal<Option<T>>) -> Self {
Self {
selected: signal.get(),
set: Arc::new(move |value| signal.set(Some(value))),
}
}
}
pub(crate) fn selecting<T: Clone + Send + Sync + 'static>(
value: T,
set: Option<Arc<dyn Fn(T) + Send + Sync>>,
handlers: Vec<Arc<dyn Fn(&T) + Send + Sync>>,
) -> impl Fn() + Send + Sync + 'static {
move || {
if let Some(set) = &set {
set(value.clone());
}
for handler in &handlers {
handler(&value);
}
}
}
pub type RadioGroupRenderer = Arc<dyn Fn(RadioGroupView) -> Element + Send + Sync>;
pub struct RadioGroup<T = ()> {
choices: Vec<Choice<T>>,
selected: Option<T>,
set: Option<Arc<dyn Fn(T) + Send + Sync>>,
on_change: Vec<Arc<dyn Fn(&T) + Send + Sync>>,
label: Option<Arc<str>>,
orientation: Orientation,
invalid: bool,
disabled: bool,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl<T: Clone + PartialEq + Send + Sync + 'static> RadioGroup<T> {
fn of(
selected: Option<T>,
set: Option<Arc<dyn Fn(T) + Send + Sync>>,
choices: impl IntoIterator<Item = impl Into<Choice<T>>>,
) -> Self {
Self {
choices: choices.into_iter().map(Into::into).collect(),
selected,
set,
on_change: Vec::new(),
label: None,
orientation: Orientation::Vertical,
invalid: false,
disabled: false,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
id: None,
key: None,
}
}
pub fn new(selected: impl Into<RadioSelection<T>>, choices: impl IntoIterator<Item = impl Into<Choice<T>>>) -> Self {
let selected = selected.into();
Self::of(selected.selected, Some(selected.set), choices)
}
pub fn controlled(
selected: Option<T>,
choices: impl IntoIterator<Item = impl Into<Choice<T>>>,
on_change: impl Fn(&T) + Send + Sync + 'static,
) -> Self {
Self::of(selected, None, choices).on_change(on_change)
}
pub fn on_change(mut self, handler: impl Fn(&T) + Send + Sync + 'static) -> Self {
self.on_change.push(Arc::new(handler));
self
}
pub fn orientation(mut self, orientation: Orientation) -> Self {
self.orientation = orientation;
self
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
pub fn invalid(mut self, invalid: bool) -> Self {
self.invalid = invalid;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
let state = state.into();
self.states.retain(|held| *held != state);
if on {
self.states.push(state);
}
self
}
pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(super::PartStyle) -> super::PartStyle) -> Self {
self.rules = self.rules.base(part, style);
self
}
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
pub fn force(mut self, interaction: Option<Interaction>) -> Self {
self.forced = interaction;
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
pub fn build(self, theme: &Theme) -> Element {
let case = Case {
variant: None,
size: None,
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(RadioGroupState::Horizontal, !self.orientation.is_vertical())
.state(RadioGroupState::Vertical, self.orientation.is_vertical());
let recipe = theme
.resolve::<Self>(&case, Some(&self.rules))
.owned_by(self.id.as_ref());
let item = recipe.rules_for(RadioGroupPart::Item, RadioPart::Root);
let takes = |choice: &Choice<T>| !self.disabled && !choice.disabled;
let entry = self
.choices
.iter()
.position(|choice| self.selected.as_ref() == Some(&choice.value) && takes(choice))
.or_else(|| self.choices.iter().position(takes));
let radios = self
.choices
.iter()
.enumerate()
.map(|(index, choice)| {
let selected = self.selected.as_ref() == Some(&choice.value);
let mut radio = Radio::new(&choice.label)
.selected(selected)
.invalid(self.invalid)
.disabled(self.disabled || choice.disabled)
.rules(&item);
if let Some(id) = &choice.id {
radio = radio.id(id.clone());
}
if let Some(count) = &choice.count {
radio = radio.count(count);
}
if let Some(element) = &choice.element {
radio = radio.element_ref(element.clone());
}
for state in &choice.states {
radio = radio.state(*state, true);
}
if Some(index) == entry {
radio = radio.force(self.forced);
}
if !selected {
let press = selecting(choice.value.clone(), self.set.clone(), self.on_change.clone());
radio = radio.on_change(move |_| press());
}
radio.build(theme)
})
.collect();
let view = RadioGroupView {
label: self.label,
orientation: self.orientation,
invalid: self.invalid,
disabled: self.disabled,
recipe,
radios,
id: self.id,
key: self.key,
};
match theme.renderer::<Self>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static> From<RadioGroup<T>> for Element {
fn from(group: RadioGroup<T>) -> Self {
group.build(¤t_theme())
}
}
pub struct RadioGroupView {
pub label: Option<Arc<str>>,
pub orientation: Orientation,
pub invalid: bool,
pub disabled: bool,
pub recipe: ResolvedRecipe,
pub radios: Vec<Element>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl RadioGroupView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn render(self) -> Element {
let keys = FocusGroup::both().activate(true).one_stop(true);
let root = self.part(RadioGroupPart::Root);
let (id, key, label, radios) = (self.id, self.key, self.label, self.radios);
macro_rules! group {
($holder:expr) => {{
let mut holder = $holder
.part(&root)
.focus_group(keys)
.describe("a11y_role", "radiogroup");
if let Some(label) = label {
holder = holder.describe("a11y_name", label);
}
for radio in radios {
holder = holder.child(radio);
}
if let Some(id) = id {
holder = holder.id(id);
}
if let Some(key) = key {
holder = holder.key(key);
}
holder.into()
}};
}
if self.orientation.is_vertical() {
group!(Column::new())
} else {
group!(Row::new().wrap().align_items(Alignment::Center))
}
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static> crate::ui::Styled for RadioGroup<T> {
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> Themed for RadioGroup<T> {
const NAME: &'static str = "radio_group";
type Renderer = RadioGroupRenderer;
fn parts() -> crate::ui::Declared {
RadioGroupPart::declared()
}
fn states() -> crate::ui::Declared {
RadioGroupState::declared()
}
fn recipe() -> Recipe {
Recipe::new()
.base(RadioGroupPart::Root, |s| s.gap(12.0))
.state(RadioGroupState::Horizontal, RadioGroupPart::Root, |s| s.gap(24.0))
}
}
impl super::FieldControl for Radio {
fn in_field(mut self, field: &super::InField) -> Element {
if self.label_hidden {
self.label = field.label.clone();
}
self.invalid |= field.judgment == Some(super::Judgment::Invalid);
self.disabled |= field.disabled;
self.into()
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static> super::FieldControl for RadioGroup<T> {
fn in_field(mut self, field: &super::InField) -> Element {
if self.label.is_none() {
self.label = Some(field.label.clone());
}
self.invalid |= field.judgment == Some(super::Judgment::Invalid);
self.disabled |= field.disabled;
self.into()
}
}