use std::sync::Arc;
use super::{
button::{Button, ButtonPart},
field::{FieldControl, InField},
icon::Icon,
input::{Input, InputPart, InputView},
names,
part_style::{Length, PartStyle},
recipe::{Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe},
select::{AnySelect, Dress, Select, SelectPart},
text_box::{self, Judgment, TextBoxState},
theme::{Themed, current_theme},
};
use crate::{
app::{
events::TextInputEvent,
theme::{IconSize, OpacityLevel, PaletteColor, RadiusSize, Theme},
},
components::Row,
layout::Alignment,
node::{Element, RadiusValue, border::Border, color::Color, dimension::Dimension},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum InputGroupPart {
Root,
Field,
Control,
Addon,
AddonIcon,
Separator,
Button,
Select,
}
names!(InputGroupPart {
Root => "root",
Field => "field",
Control => "control",
Addon => "addon",
AddonIcon => "addon_icon",
Separator => "separator",
Button => "button",
Select => "select",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum InputGroupState {
Disabled,
FullWidth,
}
names!(InputGroupState {
Disabled => "disabled",
FullWidth => "full_width",
});
pub type InputGroupSize = super::TextBoxSize;
pub type InputGroupRenderer = Arc<dyn Fn(InputGroupView) -> Element + Send + Sync>;
pub enum InputAddon {
Text(Arc<str>),
Icon(Name),
Button(Button),
Select(AnySelect),
}
impl InputAddon {
pub fn text(text: &str) -> Self {
Self::Text(Arc::from(text))
}
pub fn icon(name: impl Into<Name>) -> Self {
Self::Icon(name.into())
}
}
impl From<&str> for InputAddon {
fn from(text: &str) -> Self {
Self::text(text)
}
}
impl From<String> for InputAddon {
fn from(text: String) -> Self {
Self::Text(Arc::from(text))
}
}
impl From<Button> for InputAddon {
fn from(button: Button) -> Self {
Self::Button(button)
}
}
impl<V: 'static> From<Select<V>> for InputAddon {
fn from(select: Select<V>) -> Self {
Self::Select(select.into())
}
}
pub struct InputGroup {
input: Input,
leading: Vec<InputAddon>,
trailing: Vec<InputAddon>,
full_width: bool,
states: Vec<Name>,
rules: Recipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl InputGroup {
pub fn new(input: Input) -> Self {
Self {
input,
leading: Vec::new(),
trailing: Vec::new(),
full_width: false,
states: Vec::new(),
rules: Recipe::new(),
id: None,
key: None,
}
}
pub fn leading(mut self, addon: impl Into<InputAddon>) -> Self {
self.leading.push(addon.into());
self
}
pub fn trailing(mut self, addon: impl Into<InputAddon>) -> Self {
self.trailing.push(addon.into());
self
}
pub fn size(mut self, size: impl Into<Name>) -> Self {
self.input = self.input.size(size);
self
}
pub fn invalid(mut self, invalid: bool) -> Self {
self.input = self.input.invalid(invalid);
self
}
pub fn warning(mut self, warning: bool) -> Self {
self.input = self.input.warning(warning);
self
}
pub fn valid(mut self, valid: bool) -> Self {
self.input = self.input.valid(valid);
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.input = self.input.disabled(disabled);
self
}
pub fn read_only(mut self, read_only: bool) -> Self {
self.input = self.input.read_only(read_only);
self
}
pub fn label(mut self, label: &str) -> Self {
self.input = self.input.label(label);
self
}
#[cfg(feature = "form")]
pub fn name(mut self, name: impl Into<Arc<str>>) -> Self {
self.input = self.input.name(name);
self
}
pub fn force(mut self, interaction: Option<Interaction>) -> Self {
self.input = self.input.force(interaction);
self
}
pub fn full_width(mut self, full_width: bool) -> Self {
self.full_width = full_width;
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(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 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 on_input(mut self, handler: impl Fn(&TextInputEvent) + Send + Sync + 'static) -> Self {
self.input = self.input.on_input(handler);
self
}
pub fn on_submit(mut self, handler: impl Fn(&str) + Send + Sync + 'static) -> Self {
self.input = self.input.on_submit(handler);
self
}
pub fn build(self, theme: &Theme) -> Element {
let boxed = self.input.boxed.clone();
let case = boxed
.case(self.states.clone())
.state(InputGroupState::Disabled, boxed.disabled)
.state(InputGroupState::FullWidth, self.full_width);
let recipe = theme
.resolve::<InputGroup>(&case, Some(&self.rules))
.owned_by(self.id.as_ref());
let (mut leading, mut trailing) = (self.leading, self.trailing);
let mut input = self.input;
if matches!(leading.last(), Some(InputAddon::Icon(_)))
&& let Some(InputAddon::Icon(name)) = leading.pop()
{
input = input.icon(name);
}
let end_icon = match trailing.first() {
Some(InputAddon::Icon(_)) => match trailing.remove(0) {
InputAddon::Icon(name) => Some(name),
_ => None,
},
_ => None,
};
let count = leading.len() + 1 + trailing.len();
let at_input = leading.len();
let corners = |index: usize| (index == 0, index + 1 == count);
let of_input = recipe
.rules_for(InputGroupPart::Field, InputPart::Root)
.extend(&recipe.rules_for(InputGroupPart::Control, InputPart::Control))
.extend(&corner_rules(&recipe, InputPart::Control, corners(at_input)));
let view = InputGroupView {
size: boxed.size,
disabled: boxed.disabled,
leading,
trailing,
at_input,
count,
end_icon,
input: input.rules(&of_input).view(theme),
recipe,
id: self.id,
key: self.key,
};
match theme.renderer::<InputGroup>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
fn corner_rules(recipe: &ResolvedRecipe, part: impl Into<Name>, (first, last): (bool, bool)) -> Recipe {
let radius = recipe
.part(InputGroupPart::Root)
.rest()
.radius
.map(|radius| radius.top_left);
let Some(round) = radius else {
return Recipe::new();
};
let at = |end: bool| if end { round } else { RadiusValue::Px(0.0) };
Recipe::new().base(part, |s| s.corners(at(first), at(last), at(last), at(first)))
}
impl FieldControl for InputGroup {
fn in_field(mut self, field: &InField) -> Element {
self.input.boxed.in_field(field);
self.into()
}
}
impl From<InputGroup> for Element {
fn from(group: InputGroup) -> Self {
group.build(¤t_theme())
}
}
pub struct InputGroupView {
pub input: InputView,
pub leading: Vec<InputAddon>,
pub trailing: Vec<InputAddon>,
pub end_icon: Option<Name>,
pub size: Name,
pub disabled: bool,
pub recipe: ResolvedRecipe,
at_input: usize,
count: usize,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl InputGroupView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn separator(&self) -> Row {
Row::new().part(&self.part(InputGroupPart::Separator))
}
fn cell(&self, child: Element) -> Row {
Row::new()
.align_items(Alignment::Center)
.part(&self.part(InputGroupPart::Addon))
.child(child)
}
fn glyph(&self, name: Name) -> Element {
let part = self.part(InputGroupPart::AddonIcon);
let side = part.rest().width.unwrap_or(Length::Icon(IconSize::Md));
Row::new()
.part(&part)
.child(Icon::new(name).size(side).build(self.theme()))
.into()
}
pub fn addon(&self, addon: InputAddon, index: usize) -> Element {
let ends = (index == 0, index + 1 == self.count);
match addon {
InputAddon::Text(text) => {
let part = self.part(InputGroupPart::Addon);
self.cell(part.text(&text).nowrap().into()).into()
}
InputAddon::Icon(name) => self.cell(self.glyph(name)).into(),
InputAddon::Button(button) => {
let rules = self
.recipe
.rules_for(InputGroupPart::Button, ButtonPart::Root)
.extend(&corner_rules(&self.recipe, ButtonPart::Root, ends));
let button = button.size(self.size).rules(&rules);
let button = if self.disabled { button.disabled(true) } else { button };
button.build(self.theme())
}
InputAddon::Select(select) => {
let rules = self
.recipe
.rules_for(InputGroupPart::Select, SelectPart::Trigger)
.extend(&corner_rules(&self.recipe, SelectPart::Trigger, ends));
select.build(
self.theme(),
Dress {
size: Some(self.size),
rules: Some(&rules),
disabled: self.disabled,
..Dress::default()
},
)
}
}
}
pub fn field(&self) -> Element {
let mut control = self.input.control();
let mut end = None;
if let Some(name) = self.end_icon {
let side = match self
.part(InputGroupPart::AddonIcon)
.rest()
.width
.and_then(|width| width.resolve(self.theme()))
{
Some(Dimension::Px(px)) => px,
_ => 0.0,
};
control = control.padding_right(self.input.end_room(side));
end = Some(Row::new().pointer_events_none().child(self.glyph(name)));
}
Row::new()
.flex(1.0)
.align_items(Alignment::Stretch)
.child(self.input.render_with_end(control, end))
.into()
}
pub fn render(mut self) -> Element {
let leading = std::mem::take(&mut self.leading);
let trailing = std::mem::take(&mut self.trailing);
let mut root = Row::new()
.align_items(Alignment::Stretch)
.part(&self.part(InputGroupPart::Root))
.clip();
let mut index = 0;
for addon in leading {
if index > 0 {
root = root.child(self.separator());
}
root = root.child(self.addon(addon, index));
index += 1;
}
if index > 0 {
root = root.child(self.separator());
}
root = root.child(self.field());
index += 1;
debug_assert_eq!(index, self.at_input + 1);
for addon in trailing {
root = root.child(self.separator()).child(self.addon(addon, index));
index += 1;
}
if let Some(id) = self.id {
root = root.id(id);
}
if let Some(key) = self.key {
root = root.key(key);
}
root.into()
}
}
impl crate::ui::Styled for InputGroup {
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 InputGroup {
const NAME: &'static str = "input_group";
type Renderer = InputGroupRenderer;
fn parts() -> crate::ui::Declared {
InputGroupPart::declared()
}
fn states() -> crate::ui::Declared {
InputGroupState::declared()
}
fn recipe() -> Recipe {
use InputGroupPart::{Addon, AddonIcon, Button, Control, Field, Root, Select, Separator};
use PaletteColor::{Background, Muted, MutedForeground, Ring};
let clear = Color::new(0, 0, 0, 0);
let unedged = move |s: PartStyle| s.background(clear).border(Border::inside(1.0, clear));
let recipe = Recipe::new()
.base(Root, |s| {
s.width(280.0)
.max_width(Length::Fill)
.radius(RadiusSize::Md)
.background(Background)
.border(text_box::edge(PaletteColor::Input))
})
.hovered(Root, |s| s.border(text_box::edge(Ring)))
.state(InputGroupState::FullWidth, Root, |s| s.width(Length::Fill))
.state(InputGroupState::Disabled, Root, |s| {
s.background(Muted).opacity(OpacityLevel::Disabled)
})
.base(Field, |s| s.width(Length::Fill))
.state(InputGroupState::Disabled, Field, |s| s.opacity(1.0))
.base(Control, move |s| unedged(s).padding_x(10.0))
.hovered(Control, move |s| s.border(Border::inside(1.0, clear)))
.base(Addon, |s| {
s.padding_x(10.0)
.background(Muted)
.foreground(MutedForeground)
.font_size(13.0)
})
.size(text_box::TextBoxSize::Sm, Addon, |s| s.font_size(12.0))
.size(text_box::TextBoxSize::Lg, Addon, |s| s.font_size(14.0))
.base(AddonIcon, |s| s.square(IconSize::Md).foreground(MutedForeground))
.base(Separator, |s| s.width(1.0).background(PaletteColor::Input))
.state(InputGroupState::Disabled, Button, |s| s.opacity(1.0))
.base(Select, move |s| unedged(s).width(Length::Auto))
.hovered(Select, move |s| s.border(Border::inside(1.0, clear)))
.state(InputGroupState::Disabled, Select, |s| s.opacity(1.0));
[Judgment::Invalid, Judgment::Warning, Judgment::Valid]
.into_iter()
.fold(recipe, |recipe, judgment| {
let (state, color) = (TextBoxState::from(judgment), judgment.color());
recipe
.state(state, Root, |s| s.border(text_box::edge(color.clone())))
.when(super::recipe::Selector::new().state(state).hovered(), Root, |s| {
s.border(text_box::edge(color))
})
})
}
}