use std::sync::Arc;
use super::{
field::{FieldControl, InField},
icon::Icon,
icons,
input::{Input, InputPart, InputView},
names,
part_style::{Length, PartStyle},
recipe::{Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe},
shared::{fading, pressable},
theme::{Themed, current_theme},
};
use crate::{
app::{
component::Component,
ctx::Ctx,
events::TextInputEvent,
theme::{IconSize, PaletteColor, RadiusSize, Theme, TypographyStyle},
},
components::{self, Column, Row},
core::Signal,
layout::Alignment,
node::{CursorIcon, Element, dimension::Dimension, node_kind::ContentKind},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PasswordInputPart {
Root,
Mask,
Toggle,
Strength,
Bar,
Fill,
Description,
}
names!(PasswordInputPart {
Root => "root",
Mask => "mask",
Toggle => "toggle",
Strength => "strength",
Bar => "bar",
Fill => "fill",
Description => "description",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PasswordInputState {
Revealed,
Disabled,
FullWidth,
Fluid,
}
names!(PasswordInputState {
Revealed => "revealed",
Disabled => "disabled",
FullWidth => "full_width",
Fluid => "fluid",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PasswordStrength {
Weak,
Fair,
Good,
Strong,
}
names!(PasswordStrength {
Weak => "weak",
Fair => "fair",
Good => "good",
Strong => "strong",
});
impl PasswordStrength {
pub fn bars(self) -> usize {
match self {
Self::Weak => 1,
Self::Fair => 2,
Self::Good => 3,
Self::Strong => 4,
}
}
pub fn text(self) -> Arc<str> {
let locale = super::current_locale();
let words = &locale.fields;
match self {
Self::Weak => words.weak_password.clone(),
Self::Fair => words.fair_password.clone(),
Self::Good => words.good_password.clone(),
Self::Strong => words.strong_password.clone(),
}
}
}
pub type PasswordInputSize = super::TextBoxSize;
pub type PasswordInputRenderer = Arc<dyn Fn(PasswordInputView) -> Element + Send + Sync>;
type RevealHandler = Arc<dyn Fn(bool) + Send + Sync>;
#[derive(Clone)]
pub struct PasswordInput {
input: Input,
revealed: bool,
on_reveal: Vec<RevealHandler>,
reveal_button: bool,
show_label: Arc<str>,
hide_label: Arc<str>,
strength: Option<PasswordStrength>,
strength_text: Option<Arc<str>>,
new_password: bool,
full_width: bool,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
}
impl PasswordInput {
pub fn new(value: Signal<String>) -> Self {
Self {
input: Input::new(value),
revealed: false,
on_reveal: Vec::new(),
reveal_button: true,
show_label: super::current_locale().fields.show_password.clone(),
hide_label: super::current_locale().fields.hide_password.clone(),
strength: None,
strength_text: None,
new_password: false,
full_width: false,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
id: None,
}
}
pub fn placeholder(mut self, placeholder: &str) -> Self {
self.input = self.input.placeholder(placeholder);
self
}
pub fn icon(mut self, name: impl Into<Name>) -> Self {
self.input = self.input.icon(name);
self
}
pub fn size(mut self, size: impl Into<Name>) -> Self {
self.input = self.input.size(size);
self
}
pub fn reveal(mut self, revealed: bool) -> Self {
self.revealed = revealed;
self
}
pub fn bind_reveal(self, revealed: Signal<bool>) -> Self {
let set = revealed.clone();
self.reveal(revealed.get()).on_reveal(move |next| set.set(next))
}
pub fn on_reveal(mut self, handler: impl Fn(bool) + Send + Sync + 'static) -> Self {
self.on_reveal.push(Arc::new(handler));
self
}
pub fn reveal_button(mut self, reveal_button: bool) -> Self {
self.reveal_button = reveal_button;
self
}
pub fn show_label(mut self, label: &str) -> Self {
self.show_label = Arc::from(label);
self
}
pub fn hide_label(mut self, label: &str) -> Self {
self.hide_label = Arc::from(label);
self
}
pub fn strength(mut self, strength: Option<PasswordStrength>) -> Self {
self.strength = strength;
self
}
pub fn strength_text(mut self, text: &str) -> Self {
self.strength_text = Some(Arc::from(text));
self
}
pub fn new_password(mut self, new_password: bool) -> Self {
self.new_password = new_password;
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 read_only(mut self, read_only: bool) -> Self {
self.input = self.input.read_only(read_only);
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.input = self.input.disabled(disabled);
self
}
pub fn label(mut self, label: &str) -> Self {
self.input = self.input.label(label);
self
}
pub fn full_width(mut self, full_width: bool) -> Self {
self.full_width = full_width;
self.input = self.input.full_width(full_width);
self
}
pub fn on_input(mut self, handler: impl Fn(&TextInputEvent) + Send + Sync + 'static) -> Self {
self.input = self.input.on_input(handler);
self
}
#[cfg(feature = "form")]
pub fn name(mut self, name: impl Into<Arc<str>>) -> Self {
self.input = self.input.name(name);
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 input_rules(mut self, rules: &Recipe) -> Self {
self.input = self.input.rules(rules);
self
}
pub fn force(mut self, interaction: Option<Interaction>) -> Self {
self.forced = interaction;
self.input = self.input.force(interaction);
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
let id = id.into();
self.id = Some(id.clone());
self.input = self.input.id(id);
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.input = self.input.key(key);
self
}
pub fn build(self, theme: &Theme) -> Element {
let disabled = self.input.boxed.disabled;
let mut case = self
.input
.boxed
.case(self.states.clone())
.state(PasswordInputState::Revealed, self.revealed)
.state(PasswordInputState::Disabled, disabled)
.state(PasswordInputState::FullWidth, self.full_width);
if let Some(strength) = self.strength {
case = case.state(strength, true);
}
let view = PasswordInputView {
revealed: self.revealed,
disabled,
toggle_label: if self.revealed {
self.hide_label
} else {
self.show_label
},
reveal_button: self.reveal_button,
strength: self.strength,
strength_text: self.strength_text.or_else(|| self.strength.map(PasswordStrength::text)),
new_password: self.new_password,
recipe: theme
.resolve::<PasswordInput>(&case, Some(&self.rules))
.owned_by(self.id.as_ref()),
forced: self.forced,
on_reveal: self.on_reveal,
input: self.input.view(theme),
};
match theme.renderer::<PasswordInput>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl PasswordInput {
pub fn mount(self, ctx: &mut Ctx) -> Element {
let key = self.input.key.clone();
let props = PasswordProps { input: Arc::new(self) };
match key {
Some(key) => ctx.mount_keyed::<PasswordHost>(&key, props),
None => ctx.mount::<PasswordHost>(props),
}
}
}
#[derive(Clone)]
struct PasswordProps {
input: Arc<PasswordInput>,
}
impl PartialEq for PasswordProps {
fn eq(&self, _: &Self) -> bool {
false
}
}
impl crate::app::component::DevtoolsInspectable for PasswordProps {}
struct PasswordHost {
revealed: Signal<bool>,
}
impl Component for PasswordHost {
type Props = PasswordProps;
fn create(_ctx: &mut Ctx) -> Self {
Self {
revealed: Signal::new(false),
}
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let input = (*ctx.props::<PasswordProps>().input).clone();
let input = if input.on_reveal.is_empty() {
input.bind_reveal(self.revealed.clone())
} else {
input
};
input.build(¤t_theme())
}
}
impl FieldControl for PasswordInput {
fn in_field(mut self, field: &InField) -> Element {
self.input.boxed.in_field(field);
self.into()
}
fn mount_in_field(mut self, field: &InField, ctx: &mut Ctx) -> Element {
self.input.boxed.in_field(field);
self.mount(ctx)
}
fn has_fluid_form(&self) -> bool {
true
}
}
impl From<PasswordInput> for Element {
fn from(input: PasswordInput) -> Self {
input.build(¤t_theme())
}
}
pub struct PasswordInputView {
pub input: InputView,
pub revealed: bool,
pub disabled: bool,
pub toggle_label: Arc<str>,
pub reveal_button: bool,
pub strength: Option<PasswordStrength>,
pub strength_text: Option<Arc<str>>,
pub new_password: bool,
pub recipe: ResolvedRecipe,
forced: Option<Interaction>,
on_reveal: Vec<RevealHandler>,
}
impl PasswordInputView {
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 toggle_side(&self) -> f32 {
match self
.part(PasswordInputPart::Toggle)
.rest()
.width
.and_then(|width| width.resolve(self.theme()))
{
Some(Dimension::Px(px)) => px,
_ => 0.0,
}
}
pub fn has_toggle(&self) -> bool {
self.reveal_button
}
pub fn control(&self) -> components::TextInput {
let content = if self.new_password {
ContentKind::NewPassword
} else {
ContentKind::Password
};
let mut control = self.input.control().content(content);
control = if self.revealed {
control.unmask()
} else {
let spacing = self.part(PasswordInputPart::Mask).rest().text.letter_spacing;
let control = control.mask();
match spacing {
Some(spacing) => control
.letter_spacing(spacing)
.placeholder_style(self.input.placeholder_style()),
None => control,
}
};
if self.has_toggle() {
control = control.padding_right(self.input.end_room(self.toggle_side()));
}
control
}
pub fn toggle(&self) -> Option<components::Button> {
if !self.has_toggle() {
return None;
}
let part = self.part(PasswordInputPart::Toggle);
let side = part.rest().width.unwrap_or(Length::Icon(IconSize::Md));
let mut toggle = pressable(&part, self.disabled)
.describe("a11y_role", "button")
.describe("a11y_name", self.toggle_label.clone())
.describe("a11y_pressed", if self.revealed { "true" } else { "false" })
.child(
Icon::new(if self.revealed { icons::EYE_OFF } else { icons::EYE })
.size(side)
.build(self.theme()),
);
if !self.disabled {
let (handlers, next) = (self.on_reveal.clone(), !self.revealed);
toggle = toggle.on_click(move |_| {
for handler in &handlers {
handler(next);
}
});
}
Some(toggle)
}
pub fn strength_meter(&self) -> Option<Row> {
let filled = self.strength?.bars();
let (bar, full) = (self.part(PasswordInputPart::Bar), self.part(PasswordInputPart::Fill));
let mut meter = Row::new().part(&self.part(PasswordInputPart::Strength));
for index in 0..4 {
meter = meter.child(Row::new().flex(1.0).part(if index < filled { &full } else { &bar }));
}
Some(meter)
}
pub fn description(&self) -> Option<Row> {
let text = self.strength_text.as_ref()?;
let part = self.part(PasswordInputPart::Description);
Some(Row::new().part(&part).child(part.text(text)))
}
pub fn render(self) -> Element {
let end = self.toggle().map(|toggle| Row::new().child(toggle));
let input = self.input.render_with_end(self.control(), end);
let (meter, message) = (self.strength_meter(), self.description());
if meter.is_none() && message.is_none() {
return input.into();
}
let mut root = Column::new()
.align_items(Alignment::Stretch)
.part(&self.part(PasswordInputPart::Root));
if let Some(width) = self
.input
.part(InputPart::Root)
.rest()
.width
.and_then(|width| width.resolve(self.theme()))
{
root = root.width(width).max_width(Dimension::Pct(100.0));
}
let mut root = root.child(input);
if let Some(meter) = meter {
root = root.child(meter);
}
if let Some(message) = message {
root = root.child(message);
}
root.into()
}
}
impl crate::ui::Styled for PasswordInput {
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 PasswordInput {
const NAME: &'static str = "password_input";
type Renderer = PasswordInputRenderer;
fn parts() -> crate::ui::Declared {
PasswordInputPart::declared()
}
fn states() -> crate::ui::Declared {
PasswordInputState::declared()
}
fn recipe() -> Recipe {
use PaletteColor::{Destructive, Foreground, Input, MutedForeground, Success, Warning};
use PasswordInputPart::{Bar, Description, Fill, Mask, Root, Strength, Toggle};
let recipe = Recipe::new()
.base(Root, |s| s.gap(8.0))
.state(PasswordInputState::FullWidth, Root, |s| s.width(Length::Fill))
.state(PasswordInputState::Fluid, Root, |s| s.width(Length::Fill))
.base(Mask, |s| s.letter_spacing(1.0))
.base(Toggle, |s| {
fading(
s.square(IconSize::Md)
.radius(RadiusSize::Sm)
.foreground(MutedForeground)
.cursor(CursorIcon::Pointer),
)
})
.hovered(Toggle, |s| s.foreground(Foreground))
.focus_visible(Toggle, |s| s.focus_ring())
.state(PasswordInputState::Revealed, Toggle, |s| s.foreground(Foreground))
.state(PasswordInputState::Disabled, Toggle, |s| s.cursor(CursorIcon::Default))
.base(Strength, |s| s.gap(4.0))
.base(Bar, |s| s.height(4.0).radius(RadiusSize::Full).background(Input))
.base(Fill, |s| s.height(4.0).radius(RadiusSize::Full).background(Success))
.base(Description, |s| {
s.typography(TypographyStyle::Caption).foreground(Success)
});
[(PasswordStrength::Weak, Destructive), (PasswordStrength::Fair, Warning)]
.into_iter()
.fold(recipe, |recipe, (strength, color)| {
recipe
.state(strength, Fill, |s| s.background(color.clone()))
.state(strength, Description, |s| s.foreground(color))
})
}
}