migrate switch onto gpui-base

This commit is contained in:
2026-09-17 16:53:43 +07:00
parent df23067c01
commit 3949644597
+44 -143
View File
@@ -1,19 +1,19 @@
use std::cell::RefCell;
use std::rc::Rc; use std::rc::Rc;
use instant::Duration; use std::time::Duration;
use gpui::prelude::FluentBuilder as _; use gpui::prelude::FluentBuilder as _;
use gpui::{ use gpui::{
Animation, AnimationExt as _, AnyElement, App, Element, ElementId, GlobalElementId, App, ElementId, IntoElement, ParentElement as _, RenderOnce, SharedString, Styled as _, Window,
InteractiveElement, IntoElement, LayoutId, ParentElement as _, SharedString, Styled as _, div, px, white,
Window, div, px, white,
}; };
use gpui_base::{Spring, Switch as BaseSwitch, SwitchThumb, SwitchTrack, spring};
use theme::{ActiveTheme, Side}; use theme::{ActiveTheme, Side};
use crate::{Disableable, Sizable, Size}; use crate::{Disableable, Sizable, Size};
type OnClick = Option<Rc<dyn Fn(&bool, &mut Window, &mut App)>>; type OnClick = Option<Rc<dyn Fn(&bool, &mut Window, &mut App)>>;
#[derive(IntoElement)]
pub struct Switch { pub struct Switch {
id: ElementId, id: ElementId,
checked: bool, checked: bool,
@@ -84,48 +84,14 @@ impl Disableable for Switch {
} }
} }
impl IntoElement for Switch { impl RenderOnce for Switch {
type Element = Self; fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
fn into_element(self) -> Self::Element {
self
}
}
#[derive(Default)]
pub struct SwitchState {
prev_checked: Rc<RefCell<Option<bool>>>,
}
impl Element for Switch {
type PrepaintState = ();
type RequestLayoutState = AnyElement;
fn id(&self) -> Option<ElementId> {
Some(self.id.clone())
}
fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
None
}
fn request_layout(
&mut self,
global_id: Option<&GlobalElementId>,
_: Option<&gpui::InspectorElementId>,
window: &mut Window,
cx: &mut App,
) -> (LayoutId, Self::RequestLayoutState) {
window.with_element_state::<SwitchState, _>(global_id.unwrap(), move |state, window| {
let state = state.unwrap_or_default();
let theme = cx.theme();
let checked = self.checked; let checked = self.checked;
let on_click = self.on_click.clone(); let on_click = self.on_click.clone();
let (bg, toggle_bg) = match self.checked { let (bg, toggle_bg) = match checked {
true => (theme.element_background, white()), true => (cx.theme().element_background, white()),
false => (theme.elevated_surface_background, white()), false => (cx.theme().elevated_surface_background, white()),
}; };
let (bg, toggle_bg) = match self.disabled { let (bg, toggle_bg) = match self.disabled {
@@ -145,10 +111,31 @@ impl Element for Switch {
let inset = px(2.); let inset = px(2.);
let mut element = div() let thumb_left = spring(
.child( (self.id.clone(), "thumb"),
div() if checked {
.id(self.id.clone()) bg_width - bar_width - inset * 2.
} else {
px(0.)
},
Spring::new(Duration::from_secs_f64(0.15)),
window,
cx,
);
let accessibility_label = self.label.clone();
let label = self.label;
div().child(
BaseSwitch::new(self.id.clone())
.checked(checked)
.disabled(self.disabled)
.when_some(accessibility_label, |this, label| {
this.accessibility_label(label)
})
.when_some(on_click, |this, on_click| {
this.on_change(move |next, _event, window, cx| on_click(&next, window, cx))
})
.when(self.label_side.is_left(), |this| this.flex_row_reverse()) .when(self.label_side.is_left(), |this| this.flex_row_reverse())
.child( .child(
div() div()
@@ -157,16 +144,15 @@ impl Element for Switch {
.justify_between() .justify_between()
.items_center() .items_center()
.gap_4() .gap_4()
.when_some(self.label.clone(), |this, label| { .when_some(label, |this, label| {
// Label // Label
this.child( this.child(div().text_sm().text_color(cx.theme().text).child(label))
div().text_sm().text_color(cx.theme().text).child(label),
)
}) })
.child( .child(
// Switch Bar // Switch Bar
div() SwitchTrack::new((self.id.clone(), "track"))
.id(self.id.clone()) .checked(checked)
.disabled(self.disabled)
.flex_shrink_0() .flex_shrink_0()
.w(bg_width) .w(bg_width)
.h(bg_height) .h(bg_height)
@@ -174,59 +160,17 @@ impl Element for Switch {
.flex() .flex()
.items_center() .items_center()
.border(inset) .border(inset)
.border_color(theme.border_transparent) .border_color(cx.theme().border_transparent)
.bg(bg) .bg(bg)
.when(!self.disabled, |this| this.cursor_pointer()) .when(!self.disabled, |this| this.cursor_pointer())
.child( .child(
// Switch Toggle // Switch Toggle
div() SwitchThumb::new(checked)
.rounded_full() .rounded_full()
.when(cx.theme().shadow, |this| this.shadow_sm()) .when(cx.theme().shadow, |this| this.shadow_sm())
.bg(toggle_bg) .bg(toggle_bg)
.size(bar_width) .size(bar_width)
.map(|this| { .left(thumb_left),
let prev_checked = state.prev_checked.clone();
if !self.disabled
&& prev_checked
.borrow()
.is_some_and(|prev| prev != checked)
{
let dur = Duration::from_secs_f64(0.15);
cx.spawn(async move |cx| {
cx.background_executor()
.timer(dur)
.await;
*prev_checked.borrow_mut() =
Some(checked);
})
.detach();
this.with_animation(
ElementId::NamedInteger(
"move".into(),
checked as u64,
),
Animation::new(dur),
move |this, delta| {
let max_x = bg_width
- bar_width
- inset * 2;
let x = if checked {
max_x * delta
} else {
max_x - max_x * delta
};
this.left(x)
},
)
.into_any_element()
} else {
let max_x =
bg_width - bar_width - inset * 2;
let x =
if checked { max_x } else { px(0.) };
this.left(x).into_any_element()
}
}),
), ),
), ),
) )
@@ -238,50 +182,7 @@ impl Element for Switch {
.text_color(cx.theme().text_muted) .text_color(cx.theme().text_muted)
.child(description), .child(description),
) )
}) }),
.when_some(
on_click
.as_ref()
.map(|c| c.clone())
.filter(|_| !self.disabled),
|this, on_click| {
let prev_checked = state.prev_checked.clone();
this.on_mouse_down(gpui::MouseButton::Left, move |_, window, cx| {
cx.stop_propagation();
*prev_checked.borrow_mut() = Some(checked);
on_click(&!checked, window, cx);
})
},
),
) )
.into_any_element();
((element.request_layout(window, cx), element), state)
})
}
fn prepaint(
&mut self,
_: Option<&gpui::GlobalElementId>,
_: Option<&gpui::InspectorElementId>,
_: gpui::Bounds<gpui::Pixels>,
element: &mut Self::RequestLayoutState,
window: &mut Window,
cx: &mut App,
) {
element.prepaint(window, cx);
}
fn paint(
&mut self,
_: Option<&gpui::GlobalElementId>,
_: Option<&gpui::InspectorElementId>,
_: gpui::Bounds<gpui::Pixels>,
element: &mut Self::RequestLayoutState,
_: &mut Self::PrepaintState,
window: &mut Window,
cx: &mut App,
) {
element.paint(window, cx)
} }
} }