Skip to main content

arc_ui/inputs/
checkbox.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/checkbox/checkbox.tsx` & `.module.css`
3//!
4//! P2 Component #12: `checkbox`
5//!
6//! - Behavior & Accessibility: `gpui_kit::base::Checkbox` (`Role::CheckBox`, `Toggled::False |
7//!   True | Mixed`, Space activation, focus handle, disabled semantics).
8//! - Visuals & Motion:
9//!   - `18×18px` visual box inside a `44×44px` (`ControlHeights::MD`) hit target, `5px` radius.
10//!   - Fill scales `0.6 -> 1.0` (`motion.spring.snappy`) with asymmetric fade (`instant` in, `fast` out).
11//!   - Check (`(4.25, 9.25) -> (7.25, 12.25) -> (13.75, 5.75)`) and Indeterminate dash
12//!     (`(4.75, 9) -> (9, 9) -> (13.25, 9)`) share 3 vertices and morph smoothly via
13//!     `motion.spring.morph` while `pathLength` draws via `motion.spring.snappy`!
14//!   - Press dips only the 18×18 box (`scale 0.95`) so the hit area and label never shift.
15
16use std::rc::Rc;
17
18use arc_motion::{
19    PathPoint, PolylinePath, TransformOrigin, arc_spring, arc_transition, is_reduced_motion,
20    scaled_bounds,
21};
22use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography};
23use gpui_kit::{
24    App, BorderStyle, Corners, Edges, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent,
25    KeyUpEvent, MouseButton, ParentElement, RenderOnce, SharedString, Styled, Window,
26    base::{Checkbox as BaseCheckbox, CheckboxState as BaseCheckboxState},
27    bounds, canvas, div, point,
28    prelude::*,
29    px, quad, size,
30};
31
32pub use gpui_kit::base::CheckboxState;
33
34type ChangeHandler = Rc<dyn Fn(&CheckboxState, &mut Window, &mut App)>;
35
36#[derive(Clone, Copy)]
37struct CheckboxInternal {
38    uncontrolled: CheckboxState,
39    hovered: bool,
40    pressed: bool,
41}
42
43/// Arc `Checkbox` with 3-state check/indeterminate 3-vertex morph and spring fill.
44#[derive(IntoElement)]
45pub struct Checkbox {
46    id: ElementId,
47    state: Option<CheckboxState>,
48    default_state: CheckboxState,
49    label: Option<SharedString>,
50    description: Option<SharedString>,
51    accessibility_label: Option<SharedString>,
52    disabled: bool,
53    focus_handle: Option<FocusHandle>,
54    on_checked_change: Option<ChangeHandler>,
55}
56
57impl Checkbox {
58    pub fn new(id: impl Into<ElementId>) -> Self {
59        Self {
60            id: id.into(),
61            state: None,
62            default_state: CheckboxState::Unchecked,
63            label: None,
64            description: None,
65            accessibility_label: None,
66            disabled: false,
67            focus_handle: None,
68            on_checked_change: None,
69        }
70    }
71
72    pub fn state(mut self, state: CheckboxState) -> Self {
73        self.state = Some(state);
74        self
75    }
76
77    pub fn checked(mut self, checked: bool) -> Self {
78        self.state = Some(if checked {
79            CheckboxState::Checked
80        } else {
81            CheckboxState::Unchecked
82        });
83        self
84    }
85
86    pub fn default_state(mut self, state: CheckboxState) -> Self {
87        self.default_state = state;
88        self
89    }
90
91    pub fn default_checked(mut self, checked: bool) -> Self {
92        self.default_state = if checked {
93            CheckboxState::Checked
94        } else {
95            CheckboxState::Unchecked
96        };
97        self
98    }
99
100    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
101        self.label = Some(label.into());
102        self
103    }
104
105    pub fn description(mut self, description: impl Into<SharedString>) -> Self {
106        self.description = Some(description.into());
107        self
108    }
109
110    pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
111        self.accessibility_label = Some(label.into());
112        self
113    }
114
115    pub fn disabled(mut self, disabled: bool) -> Self {
116        self.disabled = disabled;
117        self
118    }
119
120    pub fn track_focus(mut self, handle: &FocusHandle) -> Self {
121        self.focus_handle = Some(handle.clone());
122        self
123    }
124
125    pub fn on_checked_change(
126        mut self,
127        handler: impl Fn(&CheckboxState, &mut Window, &mut App) + 'static,
128    ) -> Self {
129        self.on_checked_change = Some(Rc::new(handler));
130        self
131    }
132}
133
134fn lerp(a: f32, b: f32, t: f32) -> f32 {
135    a + (b - a) * t
136}
137
138impl RenderOnce for Checkbox {
139    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
140        let theme = cx.arc_theme().clone();
141        let colors = theme.colors;
142        let motion = theme.motion;
143        let reduced = is_reduced_motion(cx);
144
145        let is_controlled = self.state.is_some();
146        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-checkbox-state".into());
147        let internal = window.use_keyed_state(state_id, cx, |_, _| CheckboxInternal {
148            uncontrolled: self.default_state,
149            hovered: false,
150            pressed: false,
151        });
152        let snap = *internal.read(cx);
153        let current = self.state.unwrap_or(snap.uncontrolled);
154        let is_on = current != CheckboxState::Unchecked;
155        let is_indet = current == CheckboxState::Indeterminate;
156
157        let fill_scale = if reduced {
158            if is_on { 1.0 } else { 0.6 }
159        } else {
160            arc_spring(
161                (self.id.clone(), "fill-scale"),
162                if is_on { 1.0 } else { 0.6 },
163                motion.spring.snappy,
164                window,
165                cx,
166            )
167        };
168        let fill_opacity = arc_transition(
169            (self.id.clone(), "fill-op"),
170            if is_on { 1.0 } else { 0.0 },
171            if reduced {
172                std::time::Duration::ZERO
173            } else if is_on {
174                motion.duration.instant
175            } else {
176                motion.duration.fast
177            },
178            motion.ease.standard,
179            window,
180            cx,
181        );
182        let path_length = if reduced {
183            if is_on { 1.0 } else { 0.0 }
184        } else {
185            arc_spring(
186                (self.id.clone(), "mark-len"),
187                if is_on { 1.0 } else { 0.0 },
188                motion.spring.snappy,
189                window,
190                cx,
191            )
192            .clamp(0.0, 1.0)
193        };
194        // 0.0 = check, 1.0 = indeterminate dash (3 shared vertices morph smoothly!)
195        let dash_t = if reduced {
196            if is_indet { 1.0 } else { 0.0 }
197        } else {
198            arc_spring(
199                (self.id.clone(), "mark-morph"),
200                if is_indet { 1.0 } else { 0.0 },
201                motion.spring.morph,
202                window,
203                cx,
204            )
205        };
206        let press_scale = if reduced {
207            1.0
208        } else {
209            arc_spring(
210                (self.id.clone(), "press-scale"),
211                if !self.disabled && snap.pressed {
212                    0.95
213                } else {
214                    1.0
215                },
216                motion.spring.snappy,
217                window,
218                cx,
219            )
220        };
221
222        let box_border = if is_on {
223            colors.control_on
224        } else if !self.disabled && snap.hovered {
225            colors.text_muted
226        } else {
227            colors.border_strong
228        };
229        let box_bg = colors.surface;
230        let fill_bg = Hsla {
231            a: colors.control_on.a * fill_opacity,
232            ..colors.control_on
233        };
234        let mark_color = Hsla {
235            a: colors.control_glyph.a * fill_opacity,
236            ..colors.control_glyph
237        };
238
239        let visual_box = canvas(
240            |_, _, _| {},
241            move |rect, _, window, _| {
242                let cx = f32::from(rect.origin.x + rect.size.width * 0.5);
243                let cy = f32::from(rect.origin.y + rect.size.height * 0.5);
244                let base_rect = bounds(point(px(cx - 8.0), px(cy - 8.0)), size(px(16.0), px(16.0)));
245                let box_rect =
246                    scaled_bounds(base_rect, press_scale, press_scale, TransformOrigin::CENTER);
247
248                window.paint_quad(quad(
249                    box_rect,
250                    Corners::all(px(4.0)),
251                    box_bg,
252                    Edges::all(px(1.0)),
253                    box_border,
254                    BorderStyle::Solid,
255                ));
256
257                if fill_opacity > 0.01 {
258                    let fill_rect =
259                        scaled_bounds(box_rect, fill_scale, fill_scale, TransformOrigin::CENTER);
260                    window.paint_quad(quad(
261                        fill_rect,
262                        Corners::all(px(4.0)),
263                        fill_bg,
264                        Edges::default(),
265                        Hsla::transparent_black(),
266                        BorderStyle::Solid,
267                    ));
268                }
269
270                if path_length > 0.01 && mark_color.a > 0.01 {
271                    let ox = box_rect.origin.x;
272                    let oy = box_rect.origin.y;
273                    let sx = f32::from(box_rect.size.width) / 18.0;
274                    let sy = f32::from(box_rect.size.height) / 18.0;
275                    let p0 = (lerp(4.25, 4.75, dash_t) * sx, lerp(9.25, 9.0, dash_t) * sy);
276                    let p1 = (lerp(7.25, 9.0, dash_t) * sx, lerp(12.25, 9.0, dash_t) * sy);
277                    let p2 = (
278                        lerp(13.75, 13.25, dash_t) * sx,
279                        lerp(5.75, 9.0, dash_t) * sy,
280                    );
281                    let poly = PolylinePath::new(vec![
282                        PathPoint::new(p0.0, p0.1),
283                        PathPoint::new(p1.0, p1.1),
284                        PathPoint::new(p2.0, p2.1),
285                    ]);
286                    let sliced = poly.slice(0.0, path_length);
287                    if let Some(b) = sliced.to_stroke_builder(ox, oy, px(1.6))
288                        && let Ok(path) = b.build()
289                    {
290                        window.paint_path(path, mark_color);
291                    }
292                }
293            },
294        )
295        .w(px(28.0))
296        .h(px(28.0))
297        .flex_none();
298
299        let int_change = internal.clone();
300        let int_hover = internal.clone();
301        let int_down = internal.clone();
302        let int_up = internal.clone();
303        let int_out = internal.clone();
304        let int_kd = internal.clone();
305        let int_ku = internal.clone();
306        let on_change = self.on_checked_change;
307        let is_disabled = self.disabled;
308
309        let a11y_label = self
310            .accessibility_label
311            .clone()
312            .or_else(|| self.label.clone())
313            .unwrap_or_else(|| "Checkbox".into());
314
315        let mut base = BaseCheckbox::new(self.id)
316            .state(current as BaseCheckboxState)
317            .disabled(self.disabled)
318            .accessibility_label(a11y_label)
319            .on_change(move |next_state, _, window, cx| {
320                if !is_controlled {
321                    int_change.update(cx, |s, _| s.uncontrolled = next_state);
322                }
323                if let Some(handler) = &on_change {
324                    handler(&next_state, window, cx);
325                }
326                window.refresh();
327            });
328
329        if let Some(handle) = &self.focus_handle {
330            base = base.track_focus(handle);
331        }
332
333        let copy = if self.label.is_some() || self.description.is_some() {
334            Some(
335                div()
336                    .flex()
337                    .flex_col()
338                    .gap(px(2.0))
339                    .pt(px(5.0))
340                    .pr(Spacing::S2)
341                    .when_some(self.label, |this, text| {
342                        this.child(
343                            div()
344                                .text_size(Typography::TEXT_SM)
345                                .text_color(colors.foreground)
346                                .child(text),
347                        )
348                    })
349                    .when_some(self.description, |this, desc| {
350                        this.child(
351                            div()
352                                .text_size(Typography::TEXT_XS)
353                                .text_color(colors.text_muted)
354                                .child(desc),
355                        )
356                    }),
357            )
358        } else {
359            None
360        };
361
362        base.self_start()
363            .flex()
364            .flex_row()
365            .items_start()
366            .rounded(Radii::CONTROL)
367            .when(self.disabled, |this| this.opacity(0.5))
368            .when(!self.disabled, |this| this.cursor_pointer())
369            .on_hover(move |hovered, window, cx| {
370                int_hover.update(cx, |s, _| {
371                    s.hovered = *hovered;
372                    if !*hovered {
373                        s.pressed = false;
374                    }
375                });
376                window.refresh();
377            })
378            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
379                if is_disabled {
380                    return;
381                }
382                int_down.update(cx, |s, _| s.pressed = true);
383                window.refresh();
384            })
385            .on_mouse_up(MouseButton::Left, move |_, window, cx| {
386                int_up.update(cx, |s, _| s.pressed = false);
387                window.refresh();
388            })
389            .on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
390                int_out.update(cx, |s, _| s.pressed = false);
391                window.refresh();
392            })
393            .on_key_down(move |event: &KeyDownEvent, window, cx| {
394                if is_disabled {
395                    return;
396                }
397                if event.keystroke.key == "space" {
398                    int_kd.update(cx, |s, _| s.pressed = true);
399                    window.refresh();
400                }
401            })
402            .on_key_up(move |event: &KeyUpEvent, window, cx| {
403                if event.keystroke.key == "space" {
404                    int_ku.update(cx, |s, _| s.pressed = false);
405                    window.refresh();
406                }
407            })
408            .child(visual_box)
409            .when_some(copy, |this, c| this.child(c))
410    }
411}
412
413#[cfg(test)]
414mod tests {
415    use std::{cell::Cell, rc::Rc};
416
417    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
418    use gpui_kit::{
419        Context, MouseButton, Render, Role, TestAppContext, div,
420        test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
421    };
422
423    use super::*;
424
425    struct CheckboxHost {
426        state: CheckboxState,
427        changes: Rc<Cell<usize>>,
428    }
429
430    impl Render for CheckboxHost {
431        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
432            let changes = self.changes.clone();
433            div().p(Spacing::S4).child(
434                Checkbox::new("terms")
435                    .label("Accept terms")
436                    .state(self.state)
437                    .on_checked_change(cx.listener(move |this, next: &CheckboxState, _, cx| {
438                        this.state = *next;
439                        changes.set(changes.get() + 1);
440                        cx.notify();
441                    })),
442            )
443        }
444    }
445
446    #[gpui_kit::test]
447    fn checkbox_toggles_indeterminate_checked_and_unchecked(cx: &mut TestAppContext) {
448        cx.update(|cx| {
449            gpui_kit::init(cx);
450            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
451        });
452        let changes = Rc::new(Cell::new(0usize));
453        let (view, cx) = cx.add_window_view(|_, _| CheckboxHost {
454            state: CheckboxState::Indeterminate,
455            changes: changes.clone(),
456        });
457
458        cx.update(|window, cx| {
459            window.render_frame(cx);
460            let cb = window.find_by_label("Accept terms");
461            assert_eq!(cb.role(), Some(Role::CheckBox));
462            let pos = cb.bounds().center();
463            window.pointer_down(pos, MouseButton::Left, cx);
464            window.pointer_up(pos, MouseButton::Left, cx);
465            assert_eq!(changes.get(), 1);
466        });
467        assert_eq!(view.read_with(cx, |v, _| v.state), CheckboxState::Checked);
468    }
469}