Checkbox
A controlled checkbox with an optional label.
Web replica of the native GPUI output
use gpui::{prelude::*, Context, Window};
use crate::ui::checkbox::Checkbox;
pub struct Settings {
accept_terms: bool,
}
impl Render for Settings {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
Checkbox::new("terms", self.accept_terms)
.label("Accept terms and conditions")
.on_toggle(cx.listener(|this, checked: &bool, _, cx| {
this.accept_terms = *checked;
cx.notify();
}))
}
}Installation
Add the component
$ cargo hyuskui add checkboxOr copy it by hand: paste the source below into
src/ui/checkbox.rsand register it insrc/ui/mod.rs.Make sure the theme is installed
Every component reads colors from
crate::theme. If you have not runcargo hyuskui init, follow the installation guide first.
Usage
use crate::ui::checkbox::*;Source
This file is yours after install. Change the styles, add variants, or delete what you do not need.
use gpui::{div, prelude::*, px, App, ElementId, SharedString, Window};
use crate::theme::ActiveTheme;
type ToggleHandler = Box<dyn Fn(&bool, &mut Window, &mut App) + 'static>;
/// A controlled checkbox: the parent view owns `checked` and updates it in `on_toggle`.
#[derive(IntoElement)]
pub struct Checkbox {
id: ElementId,
checked: bool,
label: Option<SharedString>,
disabled: bool,
on_toggle: Option<ToggleHandler>,
}
impl Checkbox {
pub fn new(id: impl Into<ElementId>, checked: bool) -> Self {
Self {
id: id.into(),
checked,
label: None,
disabled: false,
on_toggle: None,
}
}
pub fn label(mut self, label: impl Into<SharedString>) -> Self {
self.label = Some(label.into());
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
/// Receives the *next* checked value.
pub fn on_toggle(mut self, handler: impl Fn(&bool, &mut Window, &mut App) + 'static) -> Self {
self.on_toggle = Some(Box::new(handler));
self
}
}
impl RenderOnce for Checkbox {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let checked = self.checked;
let disabled = self.disabled;
let box_el = div()
.size(px(16.0))
.flex()
.items_center()
.justify_center()
.rounded(px(4.0))
.border_1()
.border_color(if checked { theme.primary } else { theme.input })
.when(checked, |this| {
this.bg(theme.primary)
.text_color(theme.primary_foreground)
.text_xs()
.child("✓")
});
div()
.id(self.id)
.flex()
.items_center()
.gap_2()
.text_sm()
.text_color(theme.foreground)
.when(disabled, |this| this.opacity(0.5).cursor_not_allowed())
.when(!disabled, |this| this.cursor_pointer())
.child(box_el)
.when_some(self.label, |this, label| this.child(label))
.when_some(self.on_toggle.filter(|_| !disabled), |this, handler| {
this.on_click(move |_, window, cx| handler(&!checked, window, cx))
})
}
}