use std::sync::Arc;
use super::{
names,
part_style::{Length, PartTransition},
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe},
shared::{fading, pressable},
theme::{Themed, current_theme},
};
use crate::{
animation::Transition,
app::theme::{BorderSize, MotionDuration, OpacityLevel, PaletteColor, RadiusSize, Theme, TypographyStyle},
components::{self, Row},
core::Signal,
layout::{Alignment, layout_kind::Justify},
node::{CursorIcon, Element, dimension::Dimension},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SwitchPart {
Root,
Track,
Thumb,
Label,
}
names!(SwitchPart {
Root => "root",
Track => "track",
Thumb => "thumb",
Label => "label",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SwitchState {
On,
Invalid,
Disabled,
}
names!(SwitchState {
On => "on",
Invalid => "invalid",
Disabled => "disabled",
});
pub type SwitchRenderer = Arc<dyn Fn(SwitchView) -> Element + Send + Sync>;
pub struct Switch {
label: Arc<str>,
label_hidden: bool,
on: 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 Switch {
pub fn new(label: &str) -> Self {
Self {
label: Arc::from(label),
label_hidden: false,
on: 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 on(mut self, on: bool) -> Self {
self.on = on;
self
}
pub fn bind(self, on: Signal<bool>) -> Self {
let set = on.clone();
let mut bound = self.on(on.get());
bound.on_change.insert(0, Arc::new(move |next| set.set(next)));
bound
}
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(SwitchState::On, self.on)
.state(SwitchState::Invalid, self.invalid)
.state(SwitchState::Disabled, self.disabled);
let view = SwitchView {
label: self.label,
label_hidden: self.label_hidden,
on: self.on,
invalid: self.invalid,
disabled: self.disabled,
recipe: theme
.resolve::<Switch>(&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::<Switch>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl From<Switch> for Element {
fn from(switch: Switch) -> Self {
switch.build(¤t_theme())
}
}
pub struct SwitchView {
pub label: Arc<str>,
pub label_hidden: bool,
pub on: 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 SwitchView {
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.on);
(!handlers.is_empty() && !self.disabled).then(|| {
move || {
for handler in &handlers {
handler(next);
}
}
})
}
pub fn track(&self) -> components::Button {
let mut track = pressable(&self.part(SwitchPart::Track), self.disabled)
.justify(Justify::Start)
.describe("a11y_role", "switch")
.describe("a11y_name", self.label.clone())
.describe("a11y_checked", if self.on { "true" } else { "false" });
if let Some(press) = self.press() {
track = track.on_click(move |_| press());
}
if let Some(id) = &self.id {
track = track.id(id.clone());
}
if let Some(key) = &self.key {
track = track.key(key.clone());
}
track
}
pub fn travel(&self) -> Option<f32> {
let theme = self.theme();
let px = |length: Option<Length>| match length?.resolve(theme)? {
Dimension::Px(px) => Some(px),
_ => None,
};
let (track, thumb) = (self.part(SwitchPart::Track).rest(), self.part(SwitchPart::Thumb).rest());
let padding = track
.padding_x
.map(|padding| padding.resolve(&theme.spacing(), 0.0))
.unwrap_or(0.0);
Some((px(track.width)? - 2.0 * padding - px(thumb.width)?).max(0.0))
}
pub fn thumb(&self) -> Row {
let thumb = Row::new().part(&self.part(SwitchPart::Thumb));
match self.travel() {
Some(travel) => thumb.offset(if self.on { travel } else { 0.0 }, 0.0),
None => thumb,
}
}
pub fn render(self) -> Element {
let mut track = self.track().child(self.thumb());
if self.on && self.travel().is_none() {
track = track.justify(Justify::End);
}
let mut root = Row::new()
.align_items(Alignment::Center)
.part(&self.part(SwitchPart::Root))
.child(track);
if !self.label_hidden {
let part = self.part(SwitchPart::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()
}
}
impl crate::ui::Styled for Switch {
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 Switch {
const NAME: &'static str = "switch";
const ROOT: &'static str = "track";
type Renderer = SwitchRenderer;
fn parts() -> crate::ui::Declared {
SwitchPart::declared()
}
fn states() -> crate::ui::Declared {
SwitchState::declared()
}
fn recipe() -> Recipe {
use PaletteColor::*;
use SwitchPart::{Label, Root, Thumb, Track};
Recipe::new()
.base(Root, |s| s.gap(8.0).foreground(Foreground))
.base(Track, |s| {
fading(
s.width(36.0)
.height(20.0)
.padding_x(2.0)
.radius(RadiusSize::Full)
.background(Input)
.cursor(CursorIcon::Pointer),
)
})
.base(Thumb, |s| {
s.square(16.0)
.radius(RadiusSize::Full)
.background(Background)
.transition(PartTransition::new(Transition::offset_x(), MotionDuration::Fast))
})
.base(Label, |s| {
s.typography(TypographyStyle::Body).cursor(CursorIcon::Pointer)
})
.focus_visible(Track, |s| s.focus_ring())
.state(SwitchState::On, Track, |s| s.background(Primary))
.state(SwitchState::Invalid, Track, |s| {
s.border(crate::node::border::Border::inside(BorderSize::Sm, Destructive))
})
.state(SwitchState::Disabled, Root, |s| s.opacity(OpacityLevel::Disabled))
.state(SwitchState::Disabled, Track, |s| s.cursor(CursorIcon::Default))
.state(SwitchState::Disabled, Label, |s| s.cursor(CursorIcon::Default))
}
}
impl super::FieldControl for Switch {
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()
}
}