use std::sync::Arc;
use super::{
icons, names,
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
shared::{Choice, Orientation, fading, glyph, pressable},
theme::{Themed, current_theme},
};
use crate::{
app::theme::{BorderSize, IconSize, OpacityLevel, PaletteColor, RadiusSize, Theme, TypographyStyle},
components::{self, Column, Row},
core::{Signal, SignalValue},
layout::Alignment,
node::{CursorIcon, Element, border::Border},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CheckboxPart {
Root,
Box,
Indicator,
Label,
}
names!(CheckboxPart {
Root => "root",
Box => "box",
Indicator => "indicator",
Label => "label",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CheckboxState {
Checked,
Indeterminate,
Invalid,
Disabled,
}
names!(CheckboxState {
Checked => "checked",
Indeterminate => "indeterminate",
Invalid => "invalid",
Disabled => "disabled",
});
pub type CheckboxRenderer = Arc<dyn Fn(CheckboxView) -> Element + Send + Sync>;
pub struct Checkbox {
label: Arc<str>,
label_hidden: bool,
checked: bool,
indeterminate: bool,
invalid: bool,
disabled: bool,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
on_change: Vec<Arc<dyn Fn(bool) + Send + Sync>>,
on_leave: Vec<Arc<dyn Fn() + Send + Sync>>,
#[cfg_attr(not(feature = "form"), allow(dead_code))]
name: Option<Arc<str>>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl Checkbox {
pub fn new(label: &str) -> Self {
Self {
label: Arc::from(label),
label_hidden: false,
checked: false,
indeterminate: false,
invalid: false,
disabled: false,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
on_change: Vec::new(),
on_leave: Vec::new(),
name: None,
id: None,
key: None,
}
}
pub fn label_hidden(mut self, hidden: bool) -> Self {
self.label_hidden = hidden;
self
}
pub fn checked(mut self, checked: bool) -> Self {
self.checked = checked;
self
}
pub fn bind(self, checked: Signal<bool>) -> Self {
let set = checked.clone();
let mut bound = self.checked(checked.get());
bound.on_change.insert(0, Arc::new(move |next| set.set(next)));
bound
}
pub fn indeterminate(mut self, indeterminate: bool) -> Self {
self.indeterminate = indeterminate;
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
}
#[cfg(feature = "form")]
pub fn name(mut self, name: impl Into<Arc<str>>) -> Self {
self.name = Some(name.into());
self
}
#[cfg_attr(not(feature = "form"), allow(dead_code))]
pub(crate) fn on_leave(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.on_leave.push(Arc::new(handler));
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(CheckboxState::Checked, self.checked && !self.indeterminate)
.state(CheckboxState::Indeterminate, self.indeterminate)
.state(CheckboxState::Invalid, self.invalid)
.state(CheckboxState::Disabled, self.disabled);
let view = CheckboxView {
label: self.label,
label_hidden: self.label_hidden,
checked: self.checked,
indeterminate: self.indeterminate,
invalid: self.invalid,
disabled: self.disabled,
recipe: theme
.resolve::<Checkbox>(&case, Some(&self.rules))
.owned_by(self.id.as_ref()),
forced: self.forced,
on_change: self.on_change,
on_leave: self.on_leave,
name: self.name,
id: self.id,
key: self.key,
};
match theme.renderer::<Checkbox>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl From<Checkbox> for Element {
fn from(checkbox: Checkbox) -> Self {
checkbox.build(¤t_theme())
}
}
pub struct CheckboxView {
pub label: Arc<str>,
pub label_hidden: bool,
pub checked: bool,
pub indeterminate: bool,
pub invalid: bool,
pub disabled: bool,
pub recipe: ResolvedRecipe,
forced: Option<Interaction>,
on_change: Vec<Arc<dyn Fn(bool) + Send + Sync>>,
on_leave: Vec<Arc<dyn Fn() + Send + Sync>>,
#[cfg_attr(not(feature = "form"), allow(dead_code))]
name: Option<Arc<str>>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl CheckboxView {
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, next) = (self.on_change.clone(), self.indeterminate || !self.checked);
(!handlers.is_empty() && !self.disabled).then(|| {
move || {
for handler in &handlers {
handler(next);
}
}
})
}
pub fn control(&self) -> components::Button {
let checked = match (self.indeterminate, self.checked) {
(true, _) => "mixed",
(false, true) => "true",
(false, false) => "false",
};
let mut control = pressable(&self.part(CheckboxPart::Box), self.disabled)
.describe("a11y_role", "checkbox")
.describe("a11y_name", self.label.clone())
.describe("a11y_checked", checked);
if let Some(press) = self.press() {
control = control.on_click(move |_| press());
}
#[cfg(feature = "form")]
if let Some(name) = &self.name {
control = control
.name(name.clone())
.form_value(self.checked.then(|| Arc::from("on")));
}
if !self.on_leave.is_empty() {
let leave = self.on_leave.clone();
control = control.on_blur(move || {
for handler in &leave {
handler();
}
});
}
if let Some(id) = &self.id {
control = control.id(id.clone());
}
if let Some(key) = &self.key {
control = control.key(key.clone());
}
control
}
pub fn indicator(&self) -> Option<Element> {
let name = match (self.indeterminate, self.checked) {
(true, _) => icons::MINUS,
(false, true) => icons::CHECK,
(false, false) => return None,
};
Some(glyph(&self.part(CheckboxPart::Indicator), Name::new(name), false))
}
pub fn render(self) -> Element {
let mut control = self.control();
if let Some(indicator) = self.indicator() {
control = control.child(indicator);
}
let mut root = Row::new()
.align_items(Alignment::Center)
.part(&self.part(CheckboxPart::Root))
.child(control);
if !self.label_hidden {
let part = self.part(CheckboxPart::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);
}
root.into()
}
}
fn edge(color: PaletteColor) -> Border {
Border::inside(BorderSize::Sm, color)
}
impl crate::ui::Styled for Checkbox {
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 Checkbox {
const NAME: &'static str = "checkbox";
type Renderer = CheckboxRenderer;
fn parts() -> crate::ui::Declared {
CheckboxPart::declared()
}
fn states() -> crate::ui::Declared {
CheckboxState::declared()
}
fn recipe() -> Recipe {
use CheckboxState::{Checked, Disabled, Indeterminate, Invalid};
use PaletteColor::*;
let (root, square, indicator, label) = (
CheckboxPart::Root,
CheckboxPart::Box,
CheckboxPart::Indicator,
CheckboxPart::Label,
);
let marked = |s: super::PartStyle| s.background(Primary).border(edge(Primary));
Recipe::new()
.base(root, |s| s.gap(8.0).foreground(Foreground))
.base(square, |s| {
fading(
s.square(16.0)
.radius(RadiusSize::Sm)
.background(Background)
.border(edge(Input))
.cursor(CursorIcon::Pointer),
)
})
.base(indicator, |s| s.square(IconSize::Xs).foreground(PrimaryForeground))
.base(label, |s| {
s.typography(TypographyStyle::Body).cursor(CursorIcon::Pointer)
})
.focus_visible(square, |s| s.focus_ring())
.state(Checked, square, marked)
.state(Indeterminate, square, marked)
.state(Invalid, square, |s| s.border(edge(Destructive)))
.state(Disabled, root, |s| s.opacity(OpacityLevel::Disabled))
.state(Disabled, square, |s| s.background(Muted).cursor(CursorIcon::Default))
.state(Disabled, label, |s| s.cursor(CursorIcon::Default))
.when(Selector::new().state(Checked).state(Disabled), square, |s| {
s.background(Primary)
})
.when(Selector::new().state(Indeterminate).state(Disabled), square, |s| {
s.background(Primary)
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CheckboxGroupPart {
Root,
Item,
}
names!(CheckboxGroupPart {
Root => "root",
Item => "item",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CheckboxGroupState {
Horizontal,
Vertical,
}
names!(CheckboxGroupState {
Horizontal => "horizontal",
Vertical => "vertical",
});
pub(crate) fn toggled<T: PartialEq>(mut checked: Vec<T>, value: T) -> Vec<T> {
match checked.iter().position(|held| *held == value) {
Some(index) => {
checked.remove(index);
}
None => checked.push(value),
}
checked
}
pub(crate) type Turn<T> = Arc<dyn Fn(T) -> Vec<T> + Send + Sync>;
pub(crate) fn turning<T: Clone + PartialEq + Send + Sync + 'static>(signal: Signal<Vec<T>>) -> Turn<T>
where
Vec<T>: SignalValue,
{
Arc::new(move |value| {
signal.update(|held| *held = toggled(std::mem::take(held), value));
signal.get_untracked()
})
}
pub(crate) fn toggling<T: Clone + PartialEq + Send + Sync + 'static>(
value: T,
checked: &[T],
bound: Option<Turn<T>>,
handlers: Vec<Arc<dyn Fn(&[T]) + Send + Sync>>,
) -> impl Fn() + Send + Sync + 'static {
let checked = checked.to_vec();
move || {
let next = match &bound {
Some(turn) => turn(value.clone()),
None => toggled(checked.clone(), value.clone()),
};
for handler in &handlers {
handler(&next);
}
}
}
pub type CheckboxGroupRenderer = Arc<dyn Fn(CheckboxGroupView) -> Element + Send + Sync>;
pub struct CheckboxGroup<T = ()> {
choices: Vec<Choice<T>>,
checked: Vec<T>,
bound: Option<Turn<T>>,
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> CheckboxGroup<T> {
fn of(checked: Vec<T>, bound: Option<Turn<T>>, choices: impl IntoIterator<Item = impl Into<Choice<T>>>) -> Self {
Self {
choices: choices.into_iter().map(Into::into).collect(),
checked,
bound,
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(checked: Signal<Vec<T>>, choices: impl IntoIterator<Item = impl Into<Choice<T>>>) -> Self
where
Vec<T>: SignalValue,
{
Self::of(checked.get(), Some(turning(checked)), choices)
}
pub fn controlled(
checked: impl IntoIterator<Item = T>,
choices: impl IntoIterator<Item = impl Into<Choice<T>>>,
on_change: impl Fn(&[T]) + Send + Sync + 'static,
) -> Self {
Self::of(checked.into_iter().collect(), 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(CheckboxGroupState::Horizontal, !self.orientation.is_vertical())
.state(CheckboxGroupState::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(CheckboxGroupPart::Item, CheckboxPart::Root);
let entry = self
.choices
.iter()
.position(|choice| !self.disabled && !choice.disabled);
let checkboxes = self
.choices
.iter()
.enumerate()
.map(|(index, choice)| {
let press = toggling(
choice.value.clone(),
&self.checked,
self.bound.clone(),
self.on_change.clone(),
);
let mut checkbox = Checkbox::new(&choice.label)
.checked(self.checked.contains(&choice.value))
.invalid(self.invalid)
.disabled(self.disabled || choice.disabled)
.rules(&item)
.on_change(move |_| press());
if Some(index) == entry {
checkbox = checkbox.force(self.forced);
}
checkbox.build(theme)
})
.collect();
let view = CheckboxGroupView {
label: self.label,
orientation: self.orientation,
invalid: self.invalid,
disabled: self.disabled,
recipe,
checkboxes,
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<CheckboxGroup<T>> for Element {
fn from(group: CheckboxGroup<T>) -> Self {
group.build(¤t_theme())
}
}
pub struct CheckboxGroupView {
pub label: Option<Arc<str>>,
pub orientation: Orientation,
pub invalid: bool,
pub disabled: bool,
pub recipe: ResolvedRecipe,
pub checkboxes: Vec<Element>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl CheckboxGroupView {
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 root = self.part(CheckboxGroupPart::Root);
let (id, key, label, checkboxes) = (self.id, self.key, self.label, self.checkboxes);
macro_rules! group {
($holder:expr) => {{
let mut holder = $holder.part(&root).describe("a11y_role", "group");
if let Some(label) = label {
holder = holder.describe("a11y_name", label);
}
for checkbox in checkboxes {
holder = holder.child(checkbox);
}
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 CheckboxGroup<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 CheckboxGroup<T> {
const NAME: &'static str = "checkbox_group";
type Renderer = CheckboxGroupRenderer;
fn parts() -> crate::ui::Declared {
CheckboxGroupPart::declared()
}
fn states() -> crate::ui::Declared {
CheckboxGroupState::declared()
}
fn recipe() -> Recipe {
Recipe::new().base(CheckboxGroupPart::Root, |s| s.gap(12.0)).state(
CheckboxGroupState::Horizontal,
CheckboxGroupPart::Root,
|s| s.gap(24.0),
)
}
}
impl super::FieldControl for Checkbox {
fn in_field(mut self, field: &super::InField) -> Element {
if self.label_hidden && !field.label.is_empty() {
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 CheckboxGroup<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()
}
}