1use std::time::Duration;
12
13use arc_motion::{arc_spring, arc_transition, is_reduced_motion};
14use arc_tokens::{ActiveArcTheme as _, ControlHeights, Radii, Spacing, Typography};
15use gpui_kit::{
16 App, ElementId, Entity, Focusable as _, Hsla, IntoElement, MouseButton, ParentElement,
17 PathBuilder, Pixels, Point, RenderOnce, SharedString, Styled, Window,
18 base::{Button as BaseButton, StyledExt as _},
19 canvas,
20 component::input::{Input as KitInput, InputState},
21 div, point,
22 prelude::*,
23 px,
24};
25
26use super::field_message::render_field_message;
27
28#[derive(Clone, Default)]
29struct PasswordInternal {
30 visible: bool,
31 toggled: bool,
32 pressed_toggle: bool,
33}
34
35#[derive(IntoElement)]
37pub struct PasswordField {
38 id: ElementId,
39 label: SharedString,
40 state: Entity<InputState>,
41 description: Option<SharedString>,
42 error: Option<SharedString>,
43 show_label: SharedString,
44 hide_label: SharedString,
45 disabled: bool,
46}
47
48impl PasswordField {
49 pub fn new(
50 id: impl Into<ElementId>,
51 label: impl Into<SharedString>,
52 state: &Entity<InputState>,
53 ) -> Self {
54 Self {
55 id: id.into(),
56 label: label.into(),
57 state: state.clone(),
58 description: None,
59 error: None,
60 show_label: "Show password".into(),
61 hide_label: "Hide password".into(),
62 disabled: false,
63 }
64 }
65
66 pub fn description(mut self, description: impl Into<SharedString>) -> Self {
67 self.description = Some(description.into());
68 self
69 }
70
71 pub fn error(mut self, error: impl Into<SharedString>) -> Self {
72 self.error = Some(error.into());
73 self
74 }
75
76 pub fn error_opt(mut self, error: Option<SharedString>) -> Self {
77 self.error = error;
78 self
79 }
80
81 pub fn show_label(mut self, label: impl Into<SharedString>) -> Self {
82 self.show_label = label.into();
83 self
84 }
85
86 pub fn hide_label(mut self, label: impl Into<SharedString>) -> Self {
87 self.hide_label = label.into();
88 self
89 }
90
91 pub fn disabled(mut self, disabled: bool) -> Self {
92 self.disabled = disabled;
93 self
94 }
95}
96
97fn stroke_pts(pts: &[Point<Pixels>], width: Pixels, color: Hsla, window: &mut Window) {
98 if pts.len() < 2 {
99 return;
100 }
101 let mut b = PathBuilder::stroke(width);
102 b.move_to(pts[0]);
103 for p in &pts[1..] {
104 b.line_to(*p);
105 }
106 if let Ok(path) = b.build() {
107 window.paint_path(path, color);
108 }
109}
110
111fn paint_eye_morph(
112 rect: gpui_kit::Bounds<gpui_kit::Pixels>,
113 slash_progress: f32,
114 stroke_color: Hsla,
115 cutout_color: Hsla,
116 scale: f32,
117 window: &mut Window,
118) {
119 let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
120 let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
121 let unit = (f32::from(rect.size.width).min(f32::from(rect.size.height)) / 24.0) * scale;
122 let pt = |x: f32, y: f32| point(px(cx + (x - 12.0) * unit), px(cy + (y - 12.0) * unit));
123
124 let mut upper = Vec::with_capacity(17);
126 let mut lower = Vec::with_capacity(17);
127 for i in 0..=16 {
128 let t = i as f32 / 16.0;
129 let x = 2.0 + t * 20.0;
130 let arch = (t * std::f32::consts::PI).sin() * 6.5;
131 upper.push(pt(x, 12.0 - arch));
132 lower.push(pt(x, 12.0 + arch));
133 }
134 let stroke_w = px((1.75 * unit).max(1.1));
135 stroke_pts(&upper, stroke_w, stroke_color, window);
136 stroke_pts(&lower, stroke_w, stroke_color, window);
137
138 let mut pupil = Vec::with_capacity(21);
140 for i in 0..=20 {
141 let a = (i as f32 / 20.0) * std::f32::consts::TAU;
142 pupil.push(pt(12.0 + a.cos() * 3.0, 12.0 + a.sin() * 3.0));
143 }
144 stroke_pts(&pupil, stroke_w, stroke_color, window);
145
146 if slash_progress > 0.01 {
148 let end = 2.0 + 20.0 * slash_progress.clamp(0.0, 1.0);
149 let slash_pts = [pt(2.0, 2.0), pt(end, end)];
150 stroke_pts(&slash_pts, px((4.4 * unit).max(2.6)), cutout_color, window);
151 let slash_alpha = Hsla {
152 a: stroke_color.a * (slash_progress * 4.0).clamp(0.0, 1.0),
153 ..stroke_color
154 };
155 stroke_pts(&slash_pts, stroke_w, slash_alpha, window);
156 }
157}
158
159impl RenderOnce for PasswordField {
160 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
161 let theme = cx.arc_theme().clone();
162 let colors = theme.colors;
163 let motion = theme.motion;
164 let reduced = is_reduced_motion(cx);
165
166 let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-password-state".into());
167 let internal = window.use_keyed_state(state_id, cx, |_, _| PasswordInternal::default());
168 let snap = internal.read(cx).clone();
169
170 let visible = snap.visible;
171 let is_focused = self.state.read(cx).focus_handle(cx).is_focused(window);
172 let has_error = self.error.as_ref().is_some_and(|e| !e.is_empty());
173
174 let slash_progress = arc_transition(
175 (self.id.clone(), "eye-slash"),
176 if visible { 1.0 } else { 0.0 },
177 if reduced {
178 Duration::ZERO
179 } else {
180 motion.duration.standard
181 },
182 motion.ease.standard,
183 window,
184 cx,
185 );
186 let toggle_scale = if reduced {
187 1.0
188 } else {
189 arc_spring(
190 (self.id.clone(), "toggle-scale"),
191 if snap.pressed_toggle { 0.94 } else { 1.0 },
192 motion.spring.snappy,
193 window,
194 cx,
195 )
196 };
197
198 let border_color = if has_error {
199 colors.danger
200 } else if is_focused {
201 colors.foreground
202 } else {
203 colors.border_strong
204 };
205 let hover_border = colors.foreground;
206 let surface_bg = if self.disabled {
207 colors.surface_muted
208 } else {
209 colors.surface
210 };
211 let icon_color = if visible {
212 colors.foreground
213 } else {
214 colors.text_muted
215 };
216
217 let eye_canvas = canvas(
218 |_, _, _| {},
219 move |rect, _, window, _| {
220 paint_eye_morph(
221 rect,
222 slash_progress,
223 icon_color,
224 surface_bg,
225 toggle_scale,
226 window,
227 );
228 },
229 )
230 .w(px(18.0))
231 .h(px(18.0));
232
233 let toggle_state = self.state.clone();
234 let int_click = internal.clone();
235 let int_down = internal.clone();
236 let int_up = internal.clone();
237 let int_out = internal.clone();
238 let hover_bg = colors.surface_muted;
239 let hover_fg = colors.foreground;
240 let disabled = self.disabled;
241
242 let toggle_btn = BaseButton::new(ElementId::NamedChild(
243 self.id.clone().into(),
244 "toggle-visibility".into(),
245 ))
246 .disabled(disabled)
247 .accessibility_label(if visible {
248 self.hide_label
249 } else {
250 self.show_label
251 })
252 .on_click(move |_, window, cx| {
253 let next_visible = !int_click.read(cx).visible;
254 int_click.update(cx, |s, _| {
255 s.visible = next_visible;
256 s.toggled = true;
257 });
258 toggle_state.update(cx, |s, cx| s.set_masked(!next_visible, window, cx));
259 window.refresh();
260 })
261 .w(px(30.0))
262 .h(px(30.0))
263 .flex_none()
264 .flex()
265 .items_center()
266 .justify_center()
267 .rounded(Radii::CONTROL)
268 .when(!disabled, |this| {
269 this.cursor_pointer()
270 .hover(move |s| s.bg(hover_bg).text_color(hover_fg))
271 })
272 .on_mouse_down(MouseButton::Left, move |_, window, cx| {
273 if !disabled {
274 int_down.update(cx, |s, _| s.pressed_toggle = true);
275 window.refresh();
276 }
277 })
278 .on_mouse_up(MouseButton::Left, move |_, window, cx| {
279 int_up.update(cx, |s, _| s.pressed_toggle = false);
280 window.refresh();
281 })
282 .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
283 int_out.update(cx, |s, _| s.pressed_toggle = false);
284 window.refresh();
285 })
286 .child(eye_canvas);
287
288 let shell = div()
289 .w_full()
290 .min_h(ControlHeights::MD)
291 .pl(Spacing::S3)
292 .pr(px(6.0))
293 .flex()
294 .flex_row()
295 .items_center()
296 .gap(Spacing::S1)
297 .rounded(Radii::CONTROL)
298 .border_1()
299 .border_color(border_color)
300 .bg(surface_bg)
301 .when(self.disabled, |this| this.opacity(0.5))
302 .when(!self.disabled && !has_error && !is_focused, |this| {
303 this.hover(move |s| s.border_color(hover_border))
304 })
305 .child(
306 div()
307 .flex_1()
308 .min_w_0()
309 .text_size(Typography::TEXT_SM)
310 .text_color(colors.foreground)
311 .child(
312 KitInput::new(&self.state)
313 .appearance(false)
314 .disabled(self.disabled)
315 .w_full(),
316 ),
317 )
318 .child(toggle_btn);
319
320 let desc_id = ElementId::NamedChild(self.id.clone().into(), "description".into());
321 let err_id = ElementId::NamedChild(self.id.clone().into(), "error".into());
322
323 let _ = snap.toggled;
324 div()
325 .id(self.id)
326 .w_full()
327 .flex()
328 .flex_col()
329 .child(
330 div()
331 .mb(Spacing::S2)
332 .text_size(Typography::TEXT_SM)
333 .font_medium()
334 .text_color(colors.foreground)
335 .child(self.label),
336 )
337 .child(shell)
338 .child(render_field_message(
339 desc_id,
340 self.description,
341 false,
342 window,
343 cx,
344 ))
345 .child(render_field_message(err_id, self.error, true, window, cx))
346 }
347}
348
349#[cfg(test)]
350mod tests {
351 use arc_tokens::{Accent, ThemeMode, install_arc_theme};
352 use gpui_kit::{
353 Context, Render, Role, TestAppContext, div, px,
354 test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
355 };
356
357 use super::*;
358
359 struct PasswordHost {
360 state: Entity<InputState>,
361 }
362
363 impl Render for PasswordHost {
364 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
365 div().w(px(360.0)).p(Spacing::S4).child(
366 PasswordField::new("pw", "Password", &self.state)
367 .description("Use at least 12 characters."),
368 )
369 }
370 }
371
372 #[gpui_kit::test]
373 fn password_field_toggles_mask_on_eye_click(cx: &mut TestAppContext) {
374 cx.update(|cx| {
375 gpui_kit::init(cx);
376 install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
377 });
378
379 let (view, cx) = cx.add_window_view(|window, cx| {
380 let state = cx.new(|cx| {
381 InputState::new(window, cx)
382 .masked(true)
383 .default_value("arc-secret-42")
384 });
385 PasswordHost { state }
386 });
387
388 cx.update(|window, cx| {
389 window.render_frame(cx);
390 let state = view.read(cx).state.clone();
391 assert_eq!(state.read(cx).value(), "arc-secret-42");
392
393 let btn = window.find_by_label("Show password");
394 assert_eq!(btn.role(), Some(Role::Button));
395 let pos = btn.bounds().center();
396 window.pointer_down(pos, MouseButton::Left, cx);
397 window.pointer_up(pos, MouseButton::Left, cx);
398
399 window.render_frame(cx);
400 let hide = window.find_by_label("Hide password");
401 assert_eq!(hide.role(), Some(Role::Button));
402 let pos2 = hide.bounds().center();
403 window.pointer_down(pos2, MouseButton::Left, cx);
404 window.pointer_up(pos2, MouseButton::Left, cx);
405
406 window.render_frame(cx);
407 let show_again = window.find_by_label("Show password");
408 assert_eq!(show_again.role(), Some(Role::Button));
409 });
410 }
411}