Deduplicate Switch animations (#287)

This commit is contained in:
xda 2024-09-29 21:21:56 +09:00 committed by GitHub
parent baa45173d1
commit e43cc48465
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,13 +1,13 @@
use std::time::Duration; use std::{cell::RefCell, rc::Rc, time::Duration};
use crate::{h_flex, theme::ActiveTheme, Disableable, Sizable, Size}; use crate::{h_flex, theme::ActiveTheme, Disableable, Sizable, Size};
use gpui::{ use gpui::{
div, prelude::FluentBuilder as _, px, Animation, AnimationExt as _, Div, ElementId, div, prelude::FluentBuilder as _, px, Animation, AnimationExt as _, AnyElement, Element,
InteractiveElement, IntoElement, ParentElement as _, RenderOnce, SharedString, Stateful, ElementId, GlobalElementId, InteractiveElement, IntoElement, LayoutId, ParentElement as _,
Styled as _, WindowContext, SharedString, Styled as _, WindowContext,
}; };
type OnClick = Box<dyn Fn(&bool, &mut WindowContext) + 'static>; type OnClick = Rc<dyn Fn(&bool, &mut WindowContext)>;
pub enum LabelSide { pub enum LabelSide {
Left, Left,
@ -20,10 +20,8 @@ impl LabelSide {
} }
} }
#[derive(IntoElement)]
pub struct Switch { pub struct Switch {
id: ElementId, id: ElementId,
base: Stateful<Div>,
checked: bool, checked: bool,
disabled: bool, disabled: bool,
label: Option<SharedString>, label: Option<SharedString>,
@ -37,7 +35,6 @@ impl Switch {
let id: ElementId = id.into(); let id: ElementId = id.into();
Self { Self {
id: id.clone(), id: id.clone(),
base: div().id(id),
checked: false, checked: false,
disabled: false, disabled: false,
label: None, label: None,
@ -57,8 +54,11 @@ impl Switch {
self self
} }
pub fn on_click(mut self, handler: impl Fn(&bool, &mut WindowContext) + 'static) -> Self { pub fn on_click<F>(mut self, handler: F) -> Self
self.on_click = Some(Box::new(handler)); where
F: Fn(&bool, &mut WindowContext) + 'static,
{
self.on_click = Some(Rc::new(handler));
self self
} }
@ -82,10 +82,39 @@ impl Disableable for Switch {
} }
} }
impl RenderOnce for Switch { impl IntoElement for Switch {
fn render(self, cx: &mut gpui::WindowContext) -> impl IntoElement { type Element = Self;
fn into_element(self) -> Self::Element {
self
}
}
#[derive(Default)]
pub struct SwitchState {
prev_checked: Rc<RefCell<Option<bool>>>,
}
impl Element for Switch {
type RequestLayoutState = AnyElement;
type PrepaintState = ();
fn id(&self) -> Option<ElementId> {
Some(self.id.clone())
}
fn request_layout(
&mut self,
global_id: Option<&GlobalElementId>,
cx: &mut WindowContext,
) -> (LayoutId, Self::RequestLayoutState) {
cx.with_element_state::<SwitchState, _>(global_id.unwrap(), move |state, cx| {
let state = state.unwrap_or_default();
let theme = cx.theme(); let theme = cx.theme();
let checked = self.checked; let checked = self.checked;
let on_click = self.on_click.clone();
let (bg, toggle_bg) = match self.checked { let (bg, toggle_bg) = match self.checked {
true => (theme.primary, theme.background), true => (theme.primary, theme.background),
@ -107,14 +136,15 @@ impl RenderOnce for Switch {
}; };
let inset = px(2.); let inset = px(2.);
h_flex() let mut element = h_flex()
.id(self.id) .id(self.id.clone())
.items_center() .items_center()
.gap_2() .gap_2()
.when(self.label_side.left(), |this| this.flex_row_reverse()) .when(self.label_side.left(), |this| this.flex_row_reverse())
.child( .child(
// Switch Bar // Switch Bar
self.base div()
.id(self.id.clone())
.w(bg_width) .w(bg_width)
.h(bg_height) .h(bg_height)
.rounded(bg_height / 2.) .rounded(bg_height / 2.)
@ -130,9 +160,26 @@ impl RenderOnce for Switch {
.rounded_full() .rounded_full()
.bg(toggle_bg) .bg(toggle_bg)
.size(bar_width) .size(bar_width)
.with_animation( .map(|this| {
ElementId::NamedInteger("move".into(), checked as usize), let prev_checked = state.prev_checked.clone();
Animation::new(Duration::from_secs_f64(0.15)), if !self.disabled
&& prev_checked
.borrow()
.map_or(false, |prev| prev != checked)
{
let dur = Duration::from_secs_f64(0.15);
cx.spawn(|cx| async move {
cx.background_executor().timer(dur).await;
*prev_checked.borrow_mut() = Some(checked);
})
.detach();
this.with_animation(
ElementId::NamedInteger(
"move".into(),
checked as usize,
),
Animation::new(dur),
move |this, delta| { move |this, delta| {
let max_x = bg_width - bar_width - inset * 2; let max_x = bg_width - bar_width - inset * 2;
let x = if checked { let x = if checked {
@ -142,23 +189,60 @@ impl RenderOnce for Switch {
}; };
this.left(x) 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()
}
}),
), ),
) )
.when_some(self.label, |this, label| { .when_some(self.label.clone(), |this, label| {
this.child(div().child(label).map(|this| match self.size { this.child(div().child(label).map(|this| match self.size {
Size::XSmall | Size::Small => this.text_sm(), Size::XSmall | Size::Small => this.text_sm(),
_ => this.text_base(), _ => this.text_base(),
})) }))
}) })
.when_some( .when_some(
self.on_click.filter(|_| !self.disabled), on_click
.as_ref()
.map(|c| c.clone())
.filter(|_| !self.disabled),
|this, on_click| { |this, on_click| {
let prev_checked = state.prev_checked.clone();
this.on_mouse_down(gpui::MouseButton::Left, move |_, cx| { this.on_mouse_down(gpui::MouseButton::Left, move |_, cx| {
cx.stop_propagation(); cx.stop_propagation();
on_click(&!self.checked, cx); *prev_checked.borrow_mut() = Some(checked);
on_click(&!checked, cx);
}) })
}, },
) )
.into_any_element();
((element.request_layout(cx), element), state)
})
}
fn prepaint(
&mut self,
_: Option<&gpui::GlobalElementId>,
_: gpui::Bounds<gpui::Pixels>,
element: &mut Self::RequestLayoutState,
cx: &mut WindowContext,
) {
element.prepaint(cx);
}
fn paint(
&mut self,
_: Option<&gpui::GlobalElementId>,
_: gpui::Bounds<gpui::Pixels>,
element: &mut Self::RequestLayoutState,
_: &mut Self::PrepaintState,
cx: &mut WindowContext,
) {
element.paint(cx)
} }
} }