arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: `Arc源码/arc-library/registry/components/password-field/password-field.tsx` & `.module.css`
//!
//! P2 Component #17: `password-field`
//!
//! - Masked single-line `InputState` wrapped with `.appearance(false)`.
//! - `EyeMorph` vector canvas: one eye outline + iris circle with an animated diagonal slash
//!   (`pathLength: 0 <-> 1` over `motion.duration.standard` + surface cutout stroke beneath).
//! - Shared `FieldMessage` animated description/error rows.

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,
}

/// Arc `PasswordField` — masked password input with animated `EyeMorph` reveal slash.
#[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));

    // Almond eye outline sampled smoothly across upper and lower arcs.
    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);

    // Iris circle (cx=12, cy=12, r=3).
    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);

    // Animated diagonal slash (2,2) -> (22,22) with surface cutout stroke underneath.
    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));
        });
    }
}