use std::time::Duration;
use arc_motion::{arc_spring, arc_transition, is_reduced_motion};
use arc_tokens::{ActiveArcTheme as _, ControlHeights, Radii, Spacing, Typography};
use gpui_kit::{
App, ElementId, Entity, Focusable as _, Hsla, IntoElement, MouseButton, ParentElement,
PathBuilder, Pixels, Point, RenderOnce, SharedString, Styled, Window,
base::{Button as BaseButton, StyledExt as _},
canvas,
component::input::{Input as KitInput, InputState},
div, point,
prelude::*,
px,
};
use super::field_message::render_field_message;
#[derive(Clone, Default)]
struct PasswordInternal {
visible: bool,
toggled: bool,
pressed_toggle: bool,
}
#[derive(IntoElement)]
pub struct PasswordField {
id: ElementId,
label: SharedString,
state: Entity<InputState>,
description: Option<SharedString>,
error: Option<SharedString>,
show_label: SharedString,
hide_label: SharedString,
disabled: bool,
}
impl PasswordField {
pub fn new(
id: impl Into<ElementId>,
label: impl Into<SharedString>,
state: &Entity<InputState>,
) -> Self {
Self {
id: id.into(),
label: label.into(),
state: state.clone(),
description: None,
error: None,
show_label: "Show password".into(),
hide_label: "Hide password".into(),
disabled: false,
}
}
pub fn description(mut self, description: impl Into<SharedString>) -> Self {
self.description = Some(description.into());
self
}
pub fn error(mut self, error: impl Into<SharedString>) -> Self {
self.error = Some(error.into());
self
}
pub fn error_opt(mut self, error: Option<SharedString>) -> Self {
self.error = error;
self
}
pub fn show_label(mut self, label: impl Into<SharedString>) -> Self {
self.show_label = label.into();
self
}
pub fn hide_label(mut self, label: impl Into<SharedString>) -> Self {
self.hide_label = label.into();
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
}
fn stroke_pts(pts: &[Point<Pixels>], width: Pixels, color: Hsla, window: &mut Window) {
if pts.len() < 2 {
return;
}
let mut b = PathBuilder::stroke(width);
b.move_to(pts[0]);
for p in &pts[1..] {
b.line_to(*p);
}
if let Ok(path) = b.build() {
window.paint_path(path, color);
}
}
fn paint_eye_morph(
rect: gpui_kit::Bounds<gpui_kit::Pixels>,
slash_progress: f32,
stroke_color: Hsla,
cutout_color: Hsla,
scale: f32,
window: &mut Window,
) {
let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
let unit = (f32::from(rect.size.width).min(f32::from(rect.size.height)) / 24.0) * scale;
let pt = |x: f32, y: f32| point(px(cx + (x - 12.0) * unit), px(cy + (y - 12.0) * unit));
let mut upper = Vec::with_capacity(17);
let mut lower = Vec::with_capacity(17);
for i in 0..=16 {
let t = i as f32 / 16.0;
let x = 2.0 + t * 20.0;
let arch = (t * std::f32::consts::PI).sin() * 6.5;
upper.push(pt(x, 12.0 - arch));
lower.push(pt(x, 12.0 + arch));
}
let stroke_w = px((1.75 * unit).max(1.1));
stroke_pts(&upper, stroke_w, stroke_color, window);
stroke_pts(&lower, stroke_w, stroke_color, window);
let mut pupil = Vec::with_capacity(21);
for i in 0..=20 {
let a = (i as f32 / 20.0) * std::f32::consts::TAU;
pupil.push(pt(12.0 + a.cos() * 3.0, 12.0 + a.sin() * 3.0));
}
stroke_pts(&pupil, stroke_w, stroke_color, window);
if slash_progress > 0.01 {
let end = 2.0 + 20.0 * slash_progress.clamp(0.0, 1.0);
let slash_pts = [pt(2.0, 2.0), pt(end, end)];
stroke_pts(&slash_pts, px((4.4 * unit).max(2.6)), cutout_color, window);
let slash_alpha = Hsla {
a: stroke_color.a * (slash_progress * 4.0).clamp(0.0, 1.0),
..stroke_color
};
stroke_pts(&slash_pts, stroke_w, slash_alpha, window);
}
}
impl RenderOnce for PasswordField {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.arc_theme().clone();
let colors = theme.colors;
let motion = theme.motion;
let reduced = is_reduced_motion(cx);
let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-password-state".into());
let internal = window.use_keyed_state(state_id, cx, |_, _| PasswordInternal::default());
let snap = internal.read(cx).clone();
let visible = snap.visible;
let is_focused = self.state.read(cx).focus_handle(cx).is_focused(window);
let has_error = self.error.as_ref().is_some_and(|e| !e.is_empty());
let slash_progress = arc_transition(
(self.id.clone(), "eye-slash"),
if visible { 1.0 } else { 0.0 },
if reduced {
Duration::ZERO
} else {
motion.duration.standard
},
motion.ease.standard,
window,
cx,
);
let toggle_scale = if reduced {
1.0
} else {
arc_spring(
(self.id.clone(), "toggle-scale"),
if snap.pressed_toggle { 0.94 } else { 1.0 },
motion.spring.snappy,
window,
cx,
)
};
let border_color = if has_error {
colors.danger
} else if is_focused {
colors.foreground
} else {
colors.border_strong
};
let hover_border = colors.foreground;
let surface_bg = if self.disabled {
colors.surface_muted
} else {
colors.surface
};
let icon_color = if visible {
colors.foreground
} else {
colors.text_muted
};
let eye_canvas = canvas(
|_, _, _| {},
move |rect, _, window, _| {
paint_eye_morph(
rect,
slash_progress,
icon_color,
surface_bg,
toggle_scale,
window,
);
},
)
.w(px(18.0))
.h(px(18.0));
let toggle_state = self.state.clone();
let int_click = internal.clone();
let int_down = internal.clone();
let int_up = internal.clone();
let int_out = internal.clone();
let hover_bg = colors.surface_muted;
let hover_fg = colors.foreground;
let disabled = self.disabled;
let toggle_btn = BaseButton::new(ElementId::NamedChild(
self.id.clone().into(),
"toggle-visibility".into(),
))
.disabled(disabled)
.accessibility_label(if visible {
self.hide_label
} else {
self.show_label
})
.on_click(move |_, window, cx| {
let next_visible = !int_click.read(cx).visible;
int_click.update(cx, |s, _| {
s.visible = next_visible;
s.toggled = true;
});
toggle_state.update(cx, |s, cx| s.set_masked(!next_visible, window, cx));
window.refresh();
})
.w(px(30.0))
.h(px(30.0))
.flex_none()
.flex()
.items_center()
.justify_center()
.rounded(Radii::CONTROL)
.when(!disabled, |this| {
this.cursor_pointer()
.hover(move |s| s.bg(hover_bg).text_color(hover_fg))
})
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
if !disabled {
int_down.update(cx, |s, _| s.pressed_toggle = true);
window.refresh();
}
})
.on_mouse_up(MouseButton::Left, move |_, window, cx| {
int_up.update(cx, |s, _| s.pressed_toggle = false);
window.refresh();
})
.on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
int_out.update(cx, |s, _| s.pressed_toggle = false);
window.refresh();
})
.child(eye_canvas);
let shell = div()
.w_full()
.min_h(ControlHeights::MD)
.pl(Spacing::S3)
.pr(px(6.0))
.flex()
.flex_row()
.items_center()
.gap(Spacing::S1)
.rounded(Radii::CONTROL)
.border_1()
.border_color(border_color)
.bg(surface_bg)
.when(self.disabled, |this| this.opacity(0.5))
.when(!self.disabled && !has_error && !is_focused, |this| {
this.hover(move |s| s.border_color(hover_border))
})
.child(
div()
.flex_1()
.min_w_0()
.text_size(Typography::TEXT_SM)
.text_color(colors.foreground)
.child(
KitInput::new(&self.state)
.appearance(false)
.disabled(self.disabled)
.w_full(),
),
)
.child(toggle_btn);
let desc_id = ElementId::NamedChild(self.id.clone().into(), "description".into());
let err_id = ElementId::NamedChild(self.id.clone().into(), "error".into());
let _ = snap.toggled;
div()
.id(self.id)
.w_full()
.flex()
.flex_col()
.child(
div()
.mb(Spacing::S2)
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(colors.foreground)
.child(self.label),
)
.child(shell)
.child(render_field_message(
desc_id,
self.description,
false,
window,
cx,
))
.child(render_field_message(err_id, self.error, true, window, cx))
}
}
#[cfg(test)]
mod tests {
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{
Context, Render, Role, TestAppContext, div, px,
test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
};
use super::*;
struct PasswordHost {
state: Entity<InputState>,
}
impl Render for PasswordHost {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div().w(px(360.0)).p(Spacing::S4).child(
PasswordField::new("pw", "Password", &self.state)
.description("Use at least 12 characters."),
)
}
}
#[gpui_kit::test]
fn password_field_toggles_mask_on_eye_click(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let (view, cx) = cx.add_window_view(|window, cx| {
let state = cx.new(|cx| {
InputState::new(window, cx)
.masked(true)
.default_value("arc-secret-42")
});
PasswordHost { state }
});
cx.update(|window, cx| {
window.render_frame(cx);
let state = view.read(cx).state.clone();
assert_eq!(state.read(cx).value(), "arc-secret-42");
let btn = window.find_by_label("Show password");
assert_eq!(btn.role(), Some(Role::Button));
let pos = btn.bounds().center();
window.pointer_down(pos, MouseButton::Left, cx);
window.pointer_up(pos, MouseButton::Left, cx);
window.render_frame(cx);
let hide = window.find_by_label("Hide password");
assert_eq!(hide.role(), Some(Role::Button));
let pos2 = hide.bounds().center();
window.pointer_down(pos2, MouseButton::Left, cx);
window.pointer_up(pos2, MouseButton::Left, cx);
window.render_frame(cx);
let show_again = window.find_by_label("Show password");
assert_eq!(show_again.role(), Some(Role::Button));
});
}
}