Switch
An on/off toggle.
Web replica of the native GPUI output
use gpui::{prelude::*, Context, Window};
use crate::ui::switch::Switch;
pub struct Preferences {
airplane_mode: bool,
}
impl Render for Preferences {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
Switch::new("airplane", self.airplane_mode)
.label("Airplane mode")
.on_toggle(cx.listener(|this, on: &bool, _, cx| {
this.airplane_mode = *on;
cx.notify();
}))
}
}Installation
Add the component
$ cargo hyuskui add switchOr copy it by hand: paste the source below into
src/ui/switch.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::switch::*;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>;
#[derive(IntoElement)]
pub struct Switch {
id: ElementId,
on: bool,
label: Option<SharedString>,
disabled: bool,
on_toggle: Option<ToggleHandler>,
}
impl Switch {
pub fn new(id: impl Into<ElementId>, on: bool) -> Self {
Self {
id: id.into(),
on,
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
}
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 Switch {
fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
let theme = cx.theme();
let on = self.on;
let disabled = self.disabled;
let track = div()
.w(px(32.0))
.h(px(18.0))
.flex()
.items_center()
.px(px(2.0))
.rounded_full()
.bg(if on { theme.primary } else { theme.input })
.when(on, |this| this.justify_end())
.child(
div()
.size(px(14.0))
.rounded_full()
.bg(if on { theme.primary_foreground } else { theme.background })
.shadow_sm(),
);
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(track)
.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(&!on, window, cx))
})
}
}