switch: Apply use_keyed_state to store toggle state for animation. (#1091)

Ref https://github.com/zed-industries/zed/pull/34741

Now `Switch` can use impl RenderOnce.
This commit is contained in:
Jason Lee 2025-07-24 19:22:55 +08:00 committed by GitHub
parent 76a64eb072
commit 479ab8f0d6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,15 +1,15 @@
use crate::{ use crate::{
h_flex, text::Text, tooltip::Tooltip, ActiveTheme, Colorize, Disableable, Side, Sizable, Size, h_flex, text::Text, tooltip::Tooltip, ActiveTheme, Disableable, Side, Sizable, Size, StyledExt,
StyledExt,
}; };
use gpui::{ use gpui::{
div, prelude::FluentBuilder as _, px, Animation, AnimationExt as _, AnyElement, App, Element, div, prelude::FluentBuilder as _, px, Animation, AnimationExt as _, App, ElementId,
ElementId, GlobalElementId, InteractiveElement, IntoElement, LayoutId, ParentElement as _, InteractiveElement, IntoElement, ParentElement as _, RenderOnce, SharedString,
SharedString, StatefulInteractiveElement, StyleRefinement, Styled, Window, StatefulInteractiveElement, StyleRefinement, Styled, Window,
}; };
use std::{cell::RefCell, rc::Rc, time::Duration}; use std::{rc::Rc, time::Duration};
/// A Switch element that can be toggled on or off. /// A Switch element that can be toggled on or off.
#[derive(IntoElement)]
pub struct Switch { pub struct Switch {
id: ElementId, id: ElementId,
style: StyleRefinement, style: StyleRefinement,
@ -87,198 +87,129 @@ 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 {
let checked = self.checked;
let on_click = self.on_click.clone();
let toggle_state = window.use_keyed_state(self.id.clone(), cx, |_, _| checked);
fn into_element(self) -> Self::Element { let (bg, toggle_bg) = match checked {
self true => (cx.theme().primary, cx.theme().background),
} false => (cx.theme().switch, cx.theme().background),
} };
#[derive(Default)] let (bg, toggle_bg) = if self.disabled {
pub struct SwitchState { (
prev_checked: Rc<RefCell<Option<bool>>>, if checked { bg.alpha(0.5) } else { bg },
} toggle_bg.alpha(0.35),
)
} else {
(bg, toggle_bg)
};
impl Element for Switch { let (bg_width, bg_height) = match self.size {
type RequestLayoutState = AnyElement; Size::XSmall | Size::Small => (px(28.), px(16.)),
_ => (px(36.), px(20.)),
};
let bar_width = match self.size {
Size::XSmall | Size::Small => px(12.),
_ => px(16.),
};
let inset = px(2.);
let radius = if cx.theme().radius >= px(4.) {
bg_height
} else {
cx.theme().radius
};
type PrepaintState = (); div().refine_style(&self.style).child(
h_flex()
fn id(&self) -> Option<ElementId> { .id(self.id.clone())
Some(self.id.clone()) .gap_2()
} .items_start()
.when(self.label_side.is_left(), |this| this.flex_row_reverse())
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 checked = self.checked;
let on_click = self.on_click.clone();
let (bg, toggle_bg) = match self.checked {
true => (cx.theme().primary, cx.theme().background),
false => (cx.theme().switch, cx.theme().background),
};
let (bg, toggle_bg) = match self.disabled {
true => {
if self.checked {
(cx.theme().muted.darken(0.05), toggle_bg.opacity(0.8))
} else {
(cx.theme().muted, toggle_bg.opacity(0.8))
}
}
false => (bg, toggle_bg),
};
let (bg_width, bg_height) = match self.size {
Size::XSmall | Size::Small => (px(28.), px(16.)),
_ => (px(36.), px(20.)),
};
let bar_width = match self.size {
Size::XSmall | Size::Small => px(12.),
_ => px(16.),
};
let inset = px(2.);
let radius = if cx.theme().radius >= px(4.) {
bg_height
} else {
cx.theme().radius
};
let mut element = div()
.refine_style(&self.style)
.child( .child(
h_flex() // Switch Bar
div()
.id(self.id.clone()) .id(self.id.clone())
.gap_2() .w(bg_width)
.items_start() .h(bg_height)
.when(self.label_side.is_left(), |this| this.flex_row_reverse()) .rounded(radius)
.child( .flex()
// Switch Bar .items_center()
div() .border(inset)
.id(self.id.clone()) .border_color(cx.theme().transparent)
.w(bg_width) .bg(bg)
.h(bg_height) .when_some(self.tooltip.clone(), |this, tooltip| {
.rounded(radius) this.tooltip(move |window, cx| {
.flex() Tooltip::new(tooltip.clone()).build(window, cx)
.items_center() })
.border(inset)
.border_color(cx.theme().transparent)
.bg(bg)
.when_some(self.tooltip.clone(), |this, tooltip| {
this.tooltip(move |window, cx| {
Tooltip::new(tooltip.clone()).build(window, cx)
})
})
.child(
// Switch Toggle
div()
.rounded(radius)
.bg(toggle_bg)
.shadow_md()
.size(bar_width)
.map(|this| {
let prev_checked = state.prev_checked.clone();
if !self.disabled
&& prev_checked
.borrow()
.map_or(false, |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()
}
}),
),
)
.when_some(self.label.take(), |this, label| {
this.child(div().line_height(bg_height).child(label).map(|this| {
match self.size {
Size::XSmall | Size::Small => this.text_sm(),
_ => this.text_base(),
}
}))
}) })
.when_some( .child(
on_click // Switch Toggle
.as_ref() div()
.map(|c| c.clone()) .rounded(radius)
.filter(|_| !self.disabled), .bg(toggle_bg)
|this, on_click| { .shadow_md()
let prev_checked = state.prev_checked.clone(); .size(bar_width)
this.on_mouse_down(gpui::MouseButton::Left, move |_, window, cx| { .map(|this| {
cx.stop_propagation(); let prev_checked = toggle_state.read(cx);
*prev_checked.borrow_mut() = Some(checked); if !self.disabled && *prev_checked != checked {
on_click(&!checked, window, cx); let duration = Duration::from_secs_f64(0.15);
}) cx.spawn({
}, let toggle_state = toggle_state.clone();
async move |cx| {
cx.background_executor().timer(duration).await;
_ = toggle_state
.update(cx, |this, _| *this = checked);
}
})
.detach();
this.with_animation(
ElementId::NamedInteger("move".into(), checked as u64),
Animation::new(duration),
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()
}
}),
), ),
) )
.into_any_element(); .when_some(self.label, |this, label| {
this.child(div().line_height(bg_height).child(label).map(
((element.request_layout(window, cx), element), state) |this| match self.size {
}) Size::XSmall | Size::Small => this.text_sm(),
} _ => this.text_base(),
},
fn prepaint( ))
&mut self, })
_: Option<&gpui::GlobalElementId>, .when_some(
_: Option<&gpui::InspectorElementId>, on_click
_: gpui::Bounds<gpui::Pixels>, .as_ref()
element: &mut Self::RequestLayoutState, .map(|c| c.clone())
window: &mut Window, .filter(|_| !self.disabled),
cx: &mut App, |this, on_click| {
) { let toggle_state = toggle_state.clone();
element.prepaint(window, cx); this.on_mouse_down(gpui::MouseButton::Left, move |_, window, cx| {
} cx.stop_propagation();
_ = toggle_state.update(cx, |this, _| *this = checked);
fn paint( on_click(&!checked, window, cx);
&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)
} }
} }