use std::{panic::Location, sync::Arc};
use super::{
combobox::{Choices, One, OneOf},
icon::Icon,
icons, names,
part_style::{FontFamily, Length, Opacity, PartStyle},
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
text_box::{self, TextBoxSize},
theme::{Themed, current_theme},
};
use crate::{
app::theme::{
BorderSize, ControlSize, IconSize, OpacityLevel, PaletteColor, RadiusSize, ShadowStyle, Theme, TypographyStyle,
},
components::SelectOption,
core::{Signal, SignalValue},
layout::text_style::{FontWeight, TextStyle},
node::{
CursorIcon, Element, NodeUpdate, Outline, SelectCheckmarkPosition, SelectIcon, SelectPartStyle, SelectStyle,
SpacingValue, TextColor,
border::{Border, Borders},
dimension::Dimension,
padding::Padding,
},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SelectPart {
Trigger,
Value,
Placeholder,
Chevron,
Panel,
Item,
Check,
Detail,
Hint,
Group,
Separator,
}
names!(SelectPart {
Trigger => "trigger",
Value => "value",
Placeholder => "placeholder",
Chevron => "chevron",
Panel => "panel",
Item => "item",
Check => "check",
Detail => "detail",
Hint => "hint",
Group => "group",
Separator => "separator",
});
pub type SelectSize = TextBoxSize;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SelectState {
Open,
Invalid,
Warning,
Valid,
ReadOnly,
Disabled,
FullWidth,
Selected,
Fluid,
}
names!(SelectState {
Open => "open",
Invalid => "invalid",
Warning => "warning",
Valid => "valid",
ReadOnly => "read_only",
Disabled => "disabled",
FullWidth => "full_width",
Selected => "selected",
Fluid => "fluid",
});
pub type SelectRenderer = Arc<dyn Fn(SelectView) -> Element + Send + Sync>;
pub struct Select<V = ()> {
choices: Box<dyn OneOf<V>>,
placeholder: Option<Arc<str>>,
label: Option<Arc<str>>,
size: Name,
invalid: bool,
warning: bool,
valid: bool,
read_only: bool,
disabled: bool,
full_width: bool,
fit_options: bool,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
name: Option<Arc<str>>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl<T> Select<T>
where
T: Clone + PartialEq + Send + Sync + SignalValue + 'static,
Vec<T>: SignalValue,
{
pub fn new(value: Signal<T>, options: impl IntoIterator<Item = impl Into<SelectOption<T>>>) -> Self {
Self::of(Box::new(One::bound(
value,
options.into_iter().map(Into::into).collect(),
)))
}
#[track_caller]
pub fn controlled(
value: T,
options: impl IntoIterator<Item = impl Into<SelectOption<T>>>,
on_change: impl Fn(&T) + Send + Sync + 'static,
) -> Self {
let options = options.into_iter().map(Into::into).collect();
Self::of(Box::new(One::controlled(value, options, Location::caller()))).on_change(on_change)
}
}
impl<T> Select<Option<T>>
where
T: Clone + PartialEq + Send + Sync + SignalValue + 'static,
Option<T>: SignalValue,
Vec<Option<T>>: SignalValue,
{
pub fn optional(value: Signal<Option<T>>, options: impl IntoIterator<Item = impl Into<SelectOption<T>>>) -> Self {
let options = options.into_iter().map(|option| option.into().map(Some)).collect();
Self::of(Box::new(One::bound(value, options).with_empty(None)))
}
}
impl<V: 'static> Select<V> {
fn of(choices: Box<dyn OneOf<V>>) -> Self {
Self {
choices,
placeholder: None,
label: None,
size: SelectSize::default().into(),
invalid: false,
warning: false,
valid: false,
read_only: false,
disabled: false,
full_width: false,
fit_options: false,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
name: None,
id: None,
key: None,
}
}
pub fn on_change(mut self, handler: impl Fn(&V) + Send + Sync + 'static) -> Self {
self.choices.on_change(Arc::new(handler));
self
}
pub fn placeholder(mut self, placeholder: &str) -> Self {
self.placeholder = Some(Arc::from(placeholder));
self
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
pub fn size(mut self, size: impl Into<Name>) -> Self {
self.size = size.into();
self
}
pub fn invalid(mut self, invalid: bool) -> Self {
self.invalid = invalid;
self
}
pub fn warning(mut self, warning: bool) -> Self {
self.warning = warning;
self
}
pub fn valid(mut self, valid: bool) -> Self {
self.valid = valid;
self
}
pub fn read_only(mut self, read_only: bool) -> Self {
self.read_only = read_only;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn full_width(mut self, full_width: bool) -> Self {
self.full_width = full_width;
self
}
pub fn fit_options(mut self, fit_options: bool) -> Self {
self.fit_options = fit_options;
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
}
#[cfg(feature = "form")]
pub fn name(mut self, name: impl Into<Arc<str>>) -> Self {
self.name = Some(name.into());
self
}
pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> 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 invalid = self.invalid;
let warning = self.warning && !invalid;
let valid = self.valid && !invalid && !warning;
let case = Case {
variant: None,
size: Some(self.size),
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(SelectState::Invalid, invalid)
.state(SelectState::Warning, warning)
.state(SelectState::Valid, valid)
.state(SelectState::ReadOnly, self.read_only)
.state(SelectState::Disabled, self.disabled)
.state(SelectState::FullWidth, self.full_width);
let mut choices = self.choices;
choices.name(self.id.as_deref().or(self.key.as_deref()));
let choices: Box<dyn Choices> = choices;
let view = SelectView {
placeholder: self.placeholder,
label: self.label,
invalid,
read_only: self.read_only,
disabled: self.disabled,
recipe: theme
.resolve::<Select>(&case, Some(&self.rules))
.owned_by(self.id.as_ref()),
case,
rules: self.rules,
forced: self.forced,
fit_options: self.fit_options,
choices: Arc::from(choices),
name: self.name,
id: self.id,
key: self.key,
};
match theme.renderer::<Select>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl<V: 'static> From<Select<V>> for Element {
fn from(select: Select<V>) -> Self {
select.build(¤t_theme())
}
}
pub struct AnySelect(Box<dyn Held>);
#[derive(Default)]
pub(crate) struct Dress<'a> {
pub size: Option<Name>,
pub label: Option<&'a str>,
pub rules: Option<&'a Recipe>,
pub disabled: bool,
}
trait Held: Send + Sync {
fn build_dressed(self: Box<Self>, theme: &Theme, dress: Dress<'_>) -> Element;
}
impl<V: 'static> Held for Select<V> {
fn build_dressed(self: Box<Self>, theme: &Theme, dress: Dress<'_>) -> Element {
let mut select = *self;
if let Some(size) = dress.size {
select = select.size(size);
}
if let Some(label) = dress.label {
select = select.label(label);
}
if let Some(rules) = dress.rules {
select = select.rules(rules);
}
if dress.disabled {
select = select.disabled(true);
}
select.build(theme)
}
}
impl<V: 'static> From<Select<V>> for AnySelect {
fn from(select: Select<V>) -> Self {
Self(Box::new(select))
}
}
impl AnySelect {
pub(crate) fn build(self, theme: &Theme, dress: Dress<'_>) -> Element {
self.0.build_dressed(theme, dress)
}
}
pub struct SelectView {
pub placeholder: Option<Arc<str>>,
pub label: Option<Arc<str>>,
pub invalid: bool,
pub read_only: bool,
pub disabled: bool,
pub recipe: ResolvedRecipe,
case: Case,
rules: Recipe,
forced: Option<Interaction>,
fit_options: bool,
choices: Arc<dyn Choices>,
#[cfg_attr(not(feature = "form"), allow(dead_code))]
name: Option<Arc<str>>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl SelectView {
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 in_state(&self, state: impl Into<Name>) -> ResolvedRecipe {
let case = self.case.clone().state(state, true);
self.theme().resolve::<Select>(&case, Some(&self.rules))
}
pub fn select_style(&self) -> SelectStyle {
engine_style(&self.recipe, self.forced, &|state| self.in_state(state)).menu_fits_options(self.fit_options)
}
pub fn select(self, style: SelectStyle) -> Element {
let theme = self.theme().clone();
let trigger = self.part(SelectPart::Trigger).rest();
let mut node = self
.choices
.clone()
.build_plain(style, self.placeholder.clone(), self.read_only)
.into_node();
if let Some(width) = trigger.width.and_then(|width| width.resolve(&theme)) {
NodeUpdate::width(&mut node, width);
}
if let Some(width) = trigger.max_width.and_then(|width| width.resolve(&theme)) {
NodeUpdate::max_width(&mut node, width);
}
if let Some(height) = trigger.height.and_then(|height| height.resolve(&theme)) {
NodeUpdate::height(&mut node, height);
}
if let Some(opacity) = opacity(trigger.opacity, &theme) {
NodeUpdate::opacity(&mut node, opacity);
}
if let Some(cursor) = trigger.cursor {
NodeUpdate::cursor(&mut node, cursor);
}
NodeUpdate::tab_index(&mut node, 0);
NodeUpdate::disabled(&mut node, self.disabled);
if let Some(label) = &self.label {
NodeUpdate::describe(&mut node, Arc::from("a11y_name"), label.clone());
}
if self.read_only {
NodeUpdate::describe(&mut node, Arc::from("a11y_readonly"), Arc::from("true"));
}
#[cfg(feature = "form")]
if let Some(name) = &self.name {
NodeUpdate::name(&mut node, name.clone());
}
let mut select = Element::from_node(node);
if let Some(id) = &self.id {
select = select.id(id.clone());
}
if let Some(key) = &self.key {
select = select.key(key.clone());
}
select
}
pub fn render(self) -> Element {
let style = self.select_style();
self.select(style)
}
}
fn ink(theme: &Theme, style: &PartStyle) -> TextStyle {
let mut text = style.text.resolve(theme);
match &style.foreground {
Some(TextColor::Color(color)) => text.color = *color,
Some(TextColor::Palette(role)) => text.color = theme.palette_color(role.clone()),
None => {}
}
text
}
pub(crate) fn engine_style(
recipe: &ResolvedRecipe,
forced: Option<Interaction>,
in_state: &dyn Fn(Name) -> ResolvedRecipe,
) -> SelectStyle {
use SelectPart::{Check, Chevron, Detail, Group, Hint, Item, Panel, Placeholder, Separator, Trigger, Value};
let theme = recipe.theme();
let trigger = recipe.part(Trigger).forced(forced);
let rest = trigger.rest();
let value = rest.clone().merged(&recipe.part(Value).forced(forced).rest());
let placeholder = value.clone().merged(&recipe.part(Placeholder).forced(forced).rest());
let mut text = engine_part(&rest, theme).text(ink(theme, &value));
if let Some(color) = &value.foreground {
text = text.text_color(color.clone());
}
let mut style = SelectStyle::unstyled();
style.trigger = text;
style.placeholder_text = Some(ink(theme, &placeholder));
if let Some(gap) = rest.gap {
style.trigger_gap = gap;
}
let states = trigger.styles();
if !states.hovered.is_empty() {
style.trigger_hovered = Some(engine_part(&states.hovered, theme));
}
if !states.focus_visible.is_empty() {
style.trigger_focused = Some(engine_part(&states.focus_visible, theme));
}
style.trigger_open = Some(engine_part(
&in_state(SelectState::Open.into()).part(Trigger).rest(),
theme,
));
let chevron = recipe.part(Chevron).forced(forced).rest();
style.chevron = icon(icons::CHEVRON_DOWN, &chevron, theme);
if let Some(color) = &chevron.foreground {
style.chevron_color = Some(color.clone().into());
}
let menu = recipe.part(Panel).rest();
style.menu = engine_part(
&PartStyle {
height: None,
..menu.clone()
},
theme,
);
style.menu_gap = spacing(menu.gap, theme).unwrap_or(4.0);
if let Some(height) = px(menu.height, theme) {
style.max_menu_height = height;
}
if let Some(width) = px(menu.min_width, theme) {
style.min_menu_width = width;
}
let item = recipe.part(Item);
let chosen = in_state(SelectState::Selected.into()).part(Item);
style.option = engine_part(&item.rest(), theme);
style.option_selected = Some(engine_part(&chosen.rest(), theme));
style.option_disabled = Some(engine_part(
&in_state(SelectState::Disabled.into()).part(Item).rest(),
theme,
));
style.option_detail = engine_part(&recipe.part(Detail).rest(), theme);
style.option_hint = engine_part(&recipe.part(Hint).rest(), theme);
style.group_label = engine_part(&recipe.part(Group).rest(), theme);
style.separator = engine_part(&recipe.part(Separator).rest(), theme);
if !item.styles().hovered.is_empty() {
style.option_hovered = Some(engine_part(&item.styles().hovered, theme));
}
if !chosen.styles().hovered.is_empty() {
style.option_selected_hovered = Some(engine_part(&chosen.styles().hovered, theme));
}
if let Some(gap) = item.rest().gap {
style.checkmark_gap = gap.into();
style.option_adornment_gap = gap.into();
}
let check = in_state(SelectState::Selected.into()).part(Check).rest();
style.checkmark = icon(icons::CHECK, &check, theme);
style.checkmark_position = SelectCheckmarkPosition::Trailing;
style.single_checkmark = true;
if let Some(side) = px(check.width, theme) {
style.checkmark_size = Some(side.max(0.0));
}
if let Some(color) = &check.foreground {
style.checkmark_color = Some(color.clone().into());
}
style
}
pub(crate) fn px(length: Option<Length>, theme: &Theme) -> Option<f32> {
match length?.resolve(theme)? {
Dimension::Px(px) => Some(px),
_ => None,
}
}
pub(crate) fn spacing(value: Option<SpacingValue>, theme: &Theme) -> Option<f32> {
value.map(|value| value.resolve(&theme.spacing(), 0.0))
}
pub(crate) fn opacity(opacity: Option<Opacity>, theme: &Theme) -> Option<f32> {
match opacity? {
Opacity::Value(value) => Some(value),
Opacity::Level(level) => theme.opacities().try_get(level),
}
}
pub(crate) fn icon(name: &'static str, style: &PartStyle, theme: &Theme) -> SelectIcon {
let (side, theme) = (style.width.unwrap_or(Length::Icon(IconSize::Md)), theme.clone());
SelectIcon::element(move |color| {
let mut icon = Icon::new(name).size(side);
if let Some(color) = color {
icon = icon.color(color);
}
icon.build(&theme)
})
}
pub(crate) fn engine_part(style: &PartStyle, theme: &Theme) -> SelectPartStyle {
let mut part = SelectPartStyle::new();
if let Some(color) = &style.background {
part = part.background(color.clone());
}
match (&style.border, &style.underline) {
(Some(border), None) => part = part.border_custom(Borders::all(border.clone())),
(border, Some(line)) => {
let mut borders = border.clone().map(Borders::all).unwrap_or_default();
borders.bottom = Some(line.clone());
part = part.border_custom(borders);
}
(None, None) => {}
}
if let Some(radius) = style.radius {
part.border_radius = Some(radius);
}
if let Some(shadow) = &style.shadow {
part = part.box_shadow(shadow.clone());
}
let ring = match (&style.outline, style.focus_ring) {
(Some(outline), _) => Some(outline.clone()),
(None, Some(true)) => Some(theme.focus_ring().outline()),
_ => None,
};
if let Some(ring) = ring {
part = part.outline(ring);
}
if let Some(opacity) = opacity(style.opacity, theme) {
part = part.opacity(opacity);
}
let [top, end, bottom, start] = style.paddings();
if top.is_some() || end.is_some() || bottom.is_some() || start.is_some() {
let none = SpacingValue::from(0.0);
part = part.padding(
Padding::new()
.top(top.unwrap_or(none))
.right(end.unwrap_or(none))
.bottom(bottom.unwrap_or(none))
.left(start.unwrap_or(none)),
);
}
if let Some(height) = px(style.height, theme).or_else(|| px(style.min_height, theme)) {
part = part.min_height(height);
}
if style.sets_text() {
part = part.text(style.text.resolve(theme));
}
if let Some(color) = &style.foreground {
part = part.text_color(color.clone());
}
part
}
impl<V: 'static> crate::ui::Styled for Select<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<V: 'static> Themed for Select<V> {
const NAME: &'static str = "select";
const ROOT: &'static str = "trigger";
type Renderer = SelectRenderer;
fn parts() -> crate::ui::Declared {
SelectPart::declared()
}
fn states() -> crate::ui::Declared {
SelectState::declared()
}
fn recipe() -> Recipe {
use PaletteColor::{
Background, Destructive, Foreground, Highlight, Muted, MutedForeground, Popover, Ring, Success,
};
use SelectPart::{Check, Chevron, Detail, Group, Hint, Item, Panel, Placeholder, Separator, Trigger};
let edge = |color: PaletteColor| Border::inside(BorderSize::Sm, color);
let ring = |color: PaletteColor| Outline::new(2.0, color).offset(-2.0);
let recipe = Recipe::new()
.base(Trigger, |s| {
s.width(260.0)
.max_width(Length::Fill)
.height(ControlSize::Md)
.padding_x(12.0)
.gap(8.0)
.radius(RadiusSize::Md)
.background(Background)
.border(edge(PaletteColor::Input))
.foreground(Foreground)
.typography(TypographyStyle::Body)
.cursor(CursorIcon::Pointer)
})
.base(Placeholder, |s| s.foreground(MutedForeground))
.base(Chevron, |s| s.square(IconSize::Md).foreground(MutedForeground))
.base(Panel, |s| {
s.gap(4.0)
.padding_x(4.0)
.padding_y(4.0)
.radius(RadiusSize::Lg)
.background(Popover)
.border(edge(PaletteColor::Border))
.shadow(ShadowStyle::Md)
})
.base(Item, |s| {
s.height(32.0)
.padding_x(8.0)
.gap(8.0)
.radius(RadiusSize::Sm)
.foreground(Foreground)
.typography(TypographyStyle::Body)
})
.row_density(Selector::new(), Item, 32.0)
.base(Check, |s| s.square(IconSize::Md).foreground(Foreground))
.base(Detail, |s| {
s.typography(TypographyStyle::Caption).foreground(MutedForeground)
})
.base(Hint, |s| {
s.font_family(FontFamily::Mono)
.font_size(11.0)
.foreground(MutedForeground)
})
.base(Group, |s| {
s.padding_x(8.0)
.padding_top(6.0)
.padding_bottom(4.0)
.typography(TypographyStyle::Caption)
.font_size(11.0)
.weight(FontWeight::SemiBold)
.foreground(MutedForeground)
})
.base(Separator, |s| {
s.height(1.0)
.padding_y(4.0)
.background(PaletteColor::Border)
})
.hovered(Trigger, |s| s.border(edge(Ring)))
.focus_visible(Trigger, |s| s.outline(ring(Ring)))
.state(SelectState::Open, Trigger, |s| s.outline(ring(Ring)))
.hovered(Item, |s| s.background(Highlight))
.state(SelectState::Disabled, Item, |s| s.opacity(0.45))
.size(SelectSize::Sm, Trigger, |s| s.height(ControlSize::Sm).font_size(13.0))
.size(SelectSize::Lg, Trigger, |s| s.height(ControlSize::Lg).font_size(15.0))
.state(SelectState::FullWidth, Trigger, |s| s.width(Length::Fill))
.state(SelectState::ReadOnly, Trigger, |s| {
s.background(Muted)
.border(edge(PaletteColor::Border))
.cursor(CursorIcon::Default)
})
.state(SelectState::Disabled, Trigger, |s| {
s.background(Muted)
.opacity(OpacityLevel::Disabled)
.cursor(CursorIcon::Default)
});
let recipe = [
(SelectState::Invalid, Destructive),
(SelectState::Warning, PaletteColor::Warning),
(SelectState::Valid, Success),
]
.into_iter()
.fold(recipe, |recipe, (state, color)| {
recipe
.state(state, Trigger, |s| s.border(edge(color.clone())))
.when(Selector::new().state(state).hovered(), Trigger, |s| {
s.border(edge(color.clone()))
})
.when(Selector::new().state(state).focus_visible(), Trigger, |s| {
s.outline(ring(color.clone()))
})
.when(Selector::new().state(state).state(SelectState::Open), Trigger, |s| {
s.outline(ring(color))
})
});
let fluid = || Selector::new().state(SelectState::Fluid);
let recipe = recipe
.state(SelectState::Fluid, Trigger, |s| {
text_box::fluid_box(s)
.width(Length::Fill)
.height(text_box::FLUID_HEIGHT)
})
.when(fluid().hovered(), Trigger, |s| text_box::fluid_line(s, Ring))
.when(fluid().state(SelectState::ReadOnly), Trigger, |s| {
text_box::fluid_line(s, PaletteColor::Border)
})
.when(fluid().state(SelectState::ReadOnly).hovered(), Trigger, |s| {
text_box::fluid_line(s, PaletteColor::Border)
});
[
(SelectState::Invalid, Destructive),
(SelectState::Warning, PaletteColor::Warning),
(SelectState::Valid, Success),
]
.into_iter()
.fold(recipe, |recipe, (state, color)| {
recipe
.when(fluid().state(state), Trigger, |s| {
text_box::fluid_line(s, color.clone())
})
.when(fluid().state(state).hovered(), Trigger, |s| {
text_box::fluid_line(s, color)
})
})
}
}
impl<V: 'static> super::FieldControl for Select<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());
}
if !(self.invalid || self.warning || self.valid) {
self.invalid = field.judgment == Some(super::Judgment::Invalid);
self.warning = field.judgment == Some(super::Judgment::Warning);
self.valid = field.judgment == Some(super::Judgment::Valid);
}
self.disabled |= field.disabled;
if field.fluid {
self = self.state(SelectState::Fluid, true);
}
self.into()
}
fn has_fluid_form(&self) -> bool {
true
}
}