use std::sync::Arc;
use super::{
icons, names,
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
shared::{ChangeHandler, Choice, Chosen, fading, glyph, pressable},
theme::{Themed, current_theme},
};
use crate::{
app::theme::{BorderSize, IconSize, OpacityLevel, PaletteColor, RadiusSize, Theme, TypographyStyle},
components::{self, Row},
core::{Signal, SignalValue},
layout::Alignment,
node::{CursorIcon, Element, FocusGroup, border::Border as Line},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ChipPart {
Root,
Icon,
Label,
}
names!(ChipPart {
Root => "root",
Icon => "icon",
Label => "label",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ChipState {
Selected,
Icon,
Disabled,
}
names!(ChipState {
Selected => "selected",
Icon => "icon",
Disabled => "disabled",
});
pub type ChipRenderer = Arc<dyn Fn(ChipView) -> Element + Send + Sync>;
pub struct Chip {
label: Arc<str>,
icon: Option<Name>,
selected: 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 Chip {
pub fn new(label: &str) -> Self {
Self {
label: Arc::from(label),
icon: None,
selected: false,
disabled: false,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
on_change: Vec::new(),
id: None,
key: None,
}
}
pub fn icon(mut self, name: impl Into<Name>) -> Self {
self.icon = Some(name.into());
self
}
pub fn selected(mut self, selected: bool) -> Self {
self.selected = selected;
self
}
pub fn bind(self, selected: Signal<bool>) -> Self {
let set = selected.clone();
self.selected(selected.get()).on_change(move |next| set.set(next))
}
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(ChipState::Selected, self.selected)
.state(ChipState::Icon, self.selected || self.icon.is_some())
.state(ChipState::Disabled, self.disabled);
let view = ChipView {
label: self.label,
icon: self.icon,
selected: self.selected,
disabled: self.disabled,
recipe: theme
.resolve::<Chip>(&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::<Chip>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl From<Chip> for Element {
fn from(chip: Chip) -> Self {
chip.build(¤t_theme())
}
}
pub struct ChipView {
pub label: Arc<str>,
pub icon: Option<Name>,
pub selected: 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 ChipView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part).forced(self.forced)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn root(&self) -> components::Button {
let mut root = pressable(&self.part(ChipPart::Root), self.disabled)
.describe("a11y_role", "button")
.describe("a11y_name", self.label.clone())
.describe("a11y_pressed", if self.selected { "true" } else { "false" });
let (handlers, next) = (self.on_change.clone(), !self.selected);
if !handlers.is_empty() && !self.disabled {
root = root.on_click(move |_| {
for handler in &handlers {
handler(next);
}
});
}
if let Some(id) = &self.id {
root = root.id(id.clone());
}
if let Some(key) = &self.key {
root = root.key(key.clone());
}
root
}
pub fn shown_icon(&self) -> Option<Name> {
if self.selected {
Some(Name::from(icons::CHECK))
} else {
self.icon
}
}
pub fn render(self) -> Element {
let mut root = self.root();
if let Some(name) = self.shown_icon() {
root = root.child(glyph(&self.part(ChipPart::Icon), name, false));
}
let label = self.part(ChipPart::Label);
root.child(label.text(&self.label).nowrap().part(&label)).into()
}
}
impl crate::ui::Styled for Chip {
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 Chip {
const NAME: &'static str = "chip";
type Renderer = ChipRenderer;
fn parts() -> crate::ui::Declared {
ChipPart::declared()
}
fn states() -> crate::ui::Declared {
ChipState::declared()
}
fn recipe() -> Recipe {
use ChipPart::{Icon, Label, Root};
use PaletteColor::*;
let line = |color: PaletteColor| Line::inside(BorderSize::Sm, color);
Recipe::new()
.base(Root, |s| {
fading(
s.height(28.0)
.padding_x(12.0)
.gap(6.0)
.radius(RadiusSize::Full)
.background(Background)
.border(line(Input))
.foreground(Foreground)
.cursor(CursorIcon::Pointer),
)
})
.base(Label, |s| s.typography(TypographyStyle::Label))
.base(Icon, |s| s.square(IconSize::Sm))
.hovered(Root, |s| s.background(Highlight).foreground(HighlightForeground))
.pressed(Root, |s| s.veil(StatePressed))
.focus_visible(Root, |s| s.focus_ring())
.state(ChipState::Icon, Root, |s| s.padding_start(8.0))
.state(ChipState::Selected, Root, |s| {
s.background(Primary).border(line(Primary)).foreground(PrimaryForeground)
})
.when(Selector::new().state(ChipState::Selected).hovered(), Root, |s| {
s.background(PrimaryHover)
.border(line(PrimaryHover))
.foreground(PrimaryForeground)
})
.state(ChipState::Disabled, Root, |s| {
s.opacity(OpacityLevel::Disabled).cursor(CursorIcon::Default)
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ChipGroupPart {
Root,
Item,
}
names!(ChipGroupPart {
Root => "root",
Item => "item",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ChipGroupState {
Disabled,
Invalid,
}
names!(ChipGroupState {
Disabled => "disabled",
Invalid => "invalid",
});
pub type ChipGroupRenderer = Arc<dyn Fn(ChipGroup) -> Element + Send + Sync>;
struct Item {
label: Arc<str>,
icon: Option<Name>,
disabled: bool,
selected: bool,
pick: Arc<dyn Fn() + Send + Sync>,
id: Option<Arc<str>>,
states: Vec<Name>,
}
pub struct ChipGroup<T = (), V: ?Sized = T> {
choices: Vec<Choice<T>>,
chosen: Chosen<T, V>,
on_change: Vec<ChangeHandler<V>>,
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<T: Clone + PartialEq + Send + Sync + 'static, V: ?Sized + 'static> ChipGroup<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(),
label: None,
disabled: false,
invalid: false,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
id: None,
key: None,
}
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static> ChipGroup<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> ChipGroup<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> ChipGroup<T, V> {
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.label = Some(Arc::from(label));
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn invalid(mut self, invalid: bool) -> Self {
self.invalid = invalid;
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 mut case = Case::new()
.breakpoint(super::current_breakpoint())
.state(ChipGroupState::Disabled, self.disabled)
.state(ChipGroupState::Invalid, self.invalid);
for state in &self.states {
case = case.state(state.clone(), true);
}
let recipe = theme
.resolve::<ChipGroup>(&case, Some(&self.rules))
.owned_by(self.id.as_ref());
let item = recipe.rules_for(ChipGroupPart::Item, ChipPart::Root);
let mut root = Row::new()
.wrap()
.align_items(Alignment::Center)
.overflow_visible()
.part(&recipe.part(ChipGroupPart::Root))
.focus_group(FocusGroup::horizontal().one_stop(true))
.describe("a11y_role", "group");
if let Some(label) = &self.label {
root = root.describe("a11y_name", label.clone());
}
if self.invalid {
root = root.describe("a11y_invalid", "true");
}
let handlers: Arc<[ChangeHandler<V>]> = self.on_change.into();
let items: Vec<Item> = self
.choices
.into_iter()
.map(|choice| Item {
selected: self.chosen.has(&choice.value),
pick: self.chosen.picker(choice.value, handlers.clone()),
label: choice.label,
icon: choice.icon,
disabled: choice.disabled,
id: choice.id,
states: choice.states,
})
.collect();
let entry = items
.iter()
.position(|item| item.selected && !item.disabled)
.or_else(|| items.iter().position(|item| !item.disabled));
for (index, choice) in items.into_iter().enumerate() {
let pick = choice.pick;
let mut chip = Chip::new(&choice.label)
.selected(choice.selected)
.disabled(self.disabled || choice.disabled)
.rules(&item)
.force(self.forced.filter(|_| Some(index) == entry))
.on_change(move |_| pick());
if let Some(name) = choice.icon {
chip = chip.icon(name);
}
if let Some(id) = choice.id {
chip = chip.id(id);
}
for state in choice.states {
chip = chip.state(state, true);
}
root = root.child(chip.build(theme));
}
if let Some(id) = self.id {
root = root.id(id);
}
if let Some(key) = self.key {
root = root.key(key);
}
root.into()
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static, V: ?Sized + 'static> From<ChipGroup<T, V>> for Element {
fn from(group: ChipGroup<T, V>) -> Self {
group.build(¤t_theme())
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static, V: ?Sized + 'static> crate::ui::Styled for ChipGroup<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 ChipGroup<T, V> {
const NAME: &'static str = "chip_group";
type Renderer = ChipGroupRenderer;
fn parts() -> crate::ui::Declared {
ChipGroupPart::declared()
}
fn states() -> crate::ui::Declared {
ChipGroupState::declared()
}
fn recipe() -> Recipe {
Recipe::new()
.base(ChipGroupPart::Root, |s| s.gap(6.0))
.state(ChipGroupState::Invalid, ChipGroupPart::Item, |s| {
s.border(Line::inside(BorderSize::Sm, PaletteColor::Destructive))
})
}
}
impl<T: Clone + PartialEq + Send + Sync + 'static, V: ?Sized + 'static> super::FieldControl for ChipGroup<T, V> {
fn in_field(mut self, field: &super::InField) -> Element {
if self.label.is_none() && !field.label.is_empty() {
self.label = Some(field.label.clone());
}
self.invalid |= field.judgment == Some(super::Judgment::Invalid);
self.disabled |= field.disabled;
self.into()
}
}