use std::rc::Rc;
use arc_motion::{
PathPoint, PolylinePath, TransformOrigin, arc_spring, arc_transition, is_reduced_motion,
scaled_bounds,
};
use arc_tokens::{ActiveArcTheme as _, Radii, Spacing, Typography};
use gpui_kit::{
App, BorderStyle, Corners, Edges, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent,
KeyUpEvent, MouseButton, ParentElement, RenderOnce, SharedString, Styled, Window,
base::{Checkbox as BaseCheckbox, CheckboxState as BaseCheckboxState},
bounds, canvas, div, point,
prelude::*,
px, quad, size,
};
pub use gpui_kit::base::CheckboxState;
type ChangeHandler = Rc<dyn Fn(&CheckboxState, &mut Window, &mut App)>;
#[derive(Clone, Copy)]
struct CheckboxInternal {
uncontrolled: CheckboxState,
hovered: bool,
pressed: bool,
}
#[derive(IntoElement)]
pub struct Checkbox {
id: ElementId,
state: Option<CheckboxState>,
default_state: CheckboxState,
label: Option<SharedString>,
description: Option<SharedString>,
accessibility_label: Option<SharedString>,
disabled: bool,
focus_handle: Option<FocusHandle>,
on_checked_change: Option<ChangeHandler>,
}
impl Checkbox {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
state: None,
default_state: CheckboxState::Unchecked,
label: None,
description: None,
accessibility_label: None,
disabled: false,
focus_handle: None,
on_checked_change: None,
}
}
pub fn state(mut self, state: CheckboxState) -> Self {
self.state = Some(state);
self
}
pub fn checked(mut self, checked: bool) -> Self {
self.state = Some(if checked {
CheckboxState::Checked
} else {
CheckboxState::Unchecked
});
self
}
pub fn default_state(mut self, state: CheckboxState) -> Self {
self.default_state = state;
self
}
pub fn default_checked(mut self, checked: bool) -> Self {
self.default_state = if checked {
CheckboxState::Checked
} else {
CheckboxState::Unchecked
};
self
}
pub fn label(mut self, label: impl Into<SharedString>) -> Self {
self.label = Some(label.into());
self
}
pub fn description(mut self, description: impl Into<SharedString>) -> Self {
self.description = Some(description.into());
self
}
pub fn accessibility_label(mut self, label: impl Into<SharedString>) -> Self {
self.accessibility_label = Some(label.into());
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn track_focus(mut self, handle: &FocusHandle) -> Self {
self.focus_handle = Some(handle.clone());
self
}
pub fn on_checked_change(
mut self,
handler: impl Fn(&CheckboxState, &mut Window, &mut App) + 'static,
) -> Self {
self.on_checked_change = Some(Rc::new(handler));
self
}
}
fn lerp(a: f32, b: f32, t: f32) -> f32 {
a + (b - a) * t
}
impl RenderOnce for Checkbox {
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 is_controlled = self.state.is_some();
let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-checkbox-state".into());
let internal = window.use_keyed_state(state_id, cx, |_, _| CheckboxInternal {
uncontrolled: self.default_state,
hovered: false,
pressed: false,
});
let snap = *internal.read(cx);
let current = self.state.unwrap_or(snap.uncontrolled);
let is_on = current != CheckboxState::Unchecked;
let is_indet = current == CheckboxState::Indeterminate;
let fill_scale = if reduced {
if is_on { 1.0 } else { 0.6 }
} else {
arc_spring(
(self.id.clone(), "fill-scale"),
if is_on { 1.0 } else { 0.6 },
motion.spring.snappy,
window,
cx,
)
};
let fill_opacity = arc_transition(
(self.id.clone(), "fill-op"),
if is_on { 1.0 } else { 0.0 },
if reduced {
std::time::Duration::ZERO
} else if is_on {
motion.duration.instant
} else {
motion.duration.fast
},
motion.ease.standard,
window,
cx,
);
let path_length = if reduced {
if is_on { 1.0 } else { 0.0 }
} else {
arc_spring(
(self.id.clone(), "mark-len"),
if is_on { 1.0 } else { 0.0 },
motion.spring.snappy,
window,
cx,
)
.clamp(0.0, 1.0)
};
let dash_t = if reduced {
if is_indet { 1.0 } else { 0.0 }
} else {
arc_spring(
(self.id.clone(), "mark-morph"),
if is_indet { 1.0 } else { 0.0 },
motion.spring.morph,
window,
cx,
)
};
let press_scale = if reduced {
1.0
} else {
arc_spring(
(self.id.clone(), "press-scale"),
if !self.disabled && snap.pressed {
0.95
} else {
1.0
},
motion.spring.snappy,
window,
cx,
)
};
let box_border = if is_on {
colors.control_on
} else if !self.disabled && snap.hovered {
colors.text_muted
} else {
colors.border_strong
};
let box_bg = colors.surface;
let fill_bg = Hsla {
a: colors.control_on.a * fill_opacity,
..colors.control_on
};
let mark_color = Hsla {
a: colors.control_glyph.a * fill_opacity,
..colors.control_glyph
};
let visual_box = canvas(
|_, _, _| {},
move |rect, _, 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 base_rect = bounds(point(px(cx - 8.0), px(cy - 8.0)), size(px(16.0), px(16.0)));
let box_rect =
scaled_bounds(base_rect, press_scale, press_scale, TransformOrigin::CENTER);
window.paint_quad(quad(
box_rect,
Corners::all(px(4.0)),
box_bg,
Edges::all(px(1.0)),
box_border,
BorderStyle::Solid,
));
if fill_opacity > 0.01 {
let fill_rect =
scaled_bounds(box_rect, fill_scale, fill_scale, TransformOrigin::CENTER);
window.paint_quad(quad(
fill_rect,
Corners::all(px(4.0)),
fill_bg,
Edges::default(),
Hsla::transparent_black(),
BorderStyle::Solid,
));
}
if path_length > 0.01 && mark_color.a > 0.01 {
let ox = box_rect.origin.x;
let oy = box_rect.origin.y;
let sx = f32::from(box_rect.size.width) / 18.0;
let sy = f32::from(box_rect.size.height) / 18.0;
let p0 = (lerp(4.25, 4.75, dash_t) * sx, lerp(9.25, 9.0, dash_t) * sy);
let p1 = (lerp(7.25, 9.0, dash_t) * sx, lerp(12.25, 9.0, dash_t) * sy);
let p2 = (
lerp(13.75, 13.25, dash_t) * sx,
lerp(5.75, 9.0, dash_t) * sy,
);
let poly = PolylinePath::new(vec![
PathPoint::new(p0.0, p0.1),
PathPoint::new(p1.0, p1.1),
PathPoint::new(p2.0, p2.1),
]);
let sliced = poly.slice(0.0, path_length);
if let Some(b) = sliced.to_stroke_builder(ox, oy, px(1.6))
&& let Ok(path) = b.build()
{
window.paint_path(path, mark_color);
}
}
},
)
.w(px(28.0))
.h(px(28.0))
.flex_none();
let int_change = internal.clone();
let int_hover = internal.clone();
let int_down = internal.clone();
let int_up = internal.clone();
let int_out = internal.clone();
let int_kd = internal.clone();
let int_ku = internal.clone();
let on_change = self.on_checked_change;
let is_disabled = self.disabled;
let a11y_label = self
.accessibility_label
.clone()
.or_else(|| self.label.clone())
.unwrap_or_else(|| "Checkbox".into());
let mut base = BaseCheckbox::new(self.id)
.state(current as BaseCheckboxState)
.disabled(self.disabled)
.accessibility_label(a11y_label)
.on_change(move |next_state, _, window, cx| {
if !is_controlled {
int_change.update(cx, |s, _| s.uncontrolled = next_state);
}
if let Some(handler) = &on_change {
handler(&next_state, window, cx);
}
window.refresh();
});
if let Some(handle) = &self.focus_handle {
base = base.track_focus(handle);
}
let copy = if self.label.is_some() || self.description.is_some() {
Some(
div()
.flex()
.flex_col()
.gap(px(2.0))
.pt(px(5.0))
.pr(Spacing::S2)
.when_some(self.label, |this, text| {
this.child(
div()
.text_size(Typography::TEXT_SM)
.text_color(colors.foreground)
.child(text),
)
})
.when_some(self.description, |this, desc| {
this.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(desc),
)
}),
)
} else {
None
};
base.self_start()
.flex()
.flex_row()
.items_start()
.rounded(Radii::CONTROL)
.when(self.disabled, |this| this.opacity(0.5))
.when(!self.disabled, |this| this.cursor_pointer())
.on_hover(move |hovered, window, cx| {
int_hover.update(cx, |s, _| {
s.hovered = *hovered;
if !*hovered {
s.pressed = false;
}
});
window.refresh();
})
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
if is_disabled {
return;
}
int_down.update(cx, |s, _| s.pressed = true);
window.refresh();
})
.on_mouse_up(MouseButton::Left, move |_, window, cx| {
int_up.update(cx, |s, _| s.pressed = false);
window.refresh();
})
.on_mouse_up_out(MouseButton::Left, move |_, window, cx| {
int_out.update(cx, |s, _| s.pressed = false);
window.refresh();
})
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if is_disabled {
return;
}
if event.keystroke.key == "space" {
int_kd.update(cx, |s, _| s.pressed = true);
window.refresh();
}
})
.on_key_up(move |event: &KeyUpEvent, window, cx| {
if event.keystroke.key == "space" {
int_ku.update(cx, |s, _| s.pressed = false);
window.refresh();
}
})
.child(visual_box)
.when_some(copy, |this, c| this.child(c))
}
}
#[cfg(test)]
mod tests {
use std::{cell::Cell, rc::Rc};
use arc_tokens::{Accent, ThemeMode, install_arc_theme};
use gpui_kit::{
Context, MouseButton, Render, Role, TestAppContext, div,
test::{TestEventExt as _, TestQueryExt as _, TestWindowExt as _},
};
use super::*;
struct CheckboxHost {
state: CheckboxState,
changes: Rc<Cell<usize>>,
}
impl Render for CheckboxHost {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let changes = self.changes.clone();
div().p(Spacing::S4).child(
Checkbox::new("terms")
.label("Accept terms")
.state(self.state)
.on_checked_change(cx.listener(move |this, next: &CheckboxState, _, cx| {
this.state = *next;
changes.set(changes.get() + 1);
cx.notify();
})),
)
}
}
#[gpui_kit::test]
fn checkbox_toggles_indeterminate_checked_and_unchecked(cx: &mut TestAppContext) {
cx.update(|cx| {
gpui_kit::init(cx);
install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
});
let changes = Rc::new(Cell::new(0usize));
let (view, cx) = cx.add_window_view(|_, _| CheckboxHost {
state: CheckboxState::Indeterminate,
changes: changes.clone(),
});
cx.update(|window, cx| {
window.render_frame(cx);
let cb = window.find_by_label("Accept terms");
assert_eq!(cb.role(), Some(Role::CheckBox));
let pos = cb.bounds().center();
window.pointer_down(pos, MouseButton::Left, cx);
window.pointer_up(pos, MouseButton::Left, cx);
assert_eq!(changes.get(), 1);
});
assert_eq!(view.read_with(cx, |v, _| v.state), CheckboxState::Checked);
}
}