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,58 +87,24 @@ 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 RequestLayoutState = AnyElement;
type PrepaintState = ();
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 checked = self.checked; let checked = self.checked;
let on_click = self.on_click.clone(); let on_click = self.on_click.clone();
let toggle_state = window.use_keyed_state(self.id.clone(), cx, |_, _| checked);
let (bg, toggle_bg) = match self.checked { let (bg, toggle_bg) = match checked {
true => (cx.theme().primary, cx.theme().background), true => (cx.theme().primary, cx.theme().background),
false => (cx.theme().switch, cx.theme().background), false => (cx.theme().switch, cx.theme().background),
}; };
let (bg, toggle_bg) = match self.disabled { let (bg, toggle_bg) = if self.disabled {
true => { (
if self.checked { if checked { bg.alpha(0.5) } else { bg },
(cx.theme().muted.darken(0.05), toggle_bg.opacity(0.8)) toggle_bg.alpha(0.35),
)
} else { } else {
(cx.theme().muted, toggle_bg.opacity(0.8)) (bg, toggle_bg)
}
}
false => (bg, toggle_bg),
}; };
let (bg_width, bg_height) = match self.size { let (bg_width, bg_height) = match self.size {
@ -156,9 +122,7 @@ impl Element for Switch {
cx.theme().radius cx.theme().radius
}; };
let mut element = div() div().refine_style(&self.style).child(
.refine_style(&self.style)
.child(
h_flex() h_flex()
.id(self.id.clone()) .id(self.id.clone())
.gap_2() .gap_2()
@ -189,28 +153,24 @@ impl Element for Switch {
.shadow_md() .shadow_md()
.size(bar_width) .size(bar_width)
.map(|this| { .map(|this| {
let prev_checked = state.prev_checked.clone(); let prev_checked = toggle_state.read(cx);
if !self.disabled if !self.disabled && *prev_checked != checked {
&& prev_checked let duration = Duration::from_secs_f64(0.15);
.borrow() cx.spawn({
.map_or(false, |prev| prev != checked) let toggle_state = toggle_state.clone();
{ async move |cx| {
let dur = Duration::from_secs_f64(0.15); cx.background_executor().timer(duration).await;
cx.spawn(async move |cx| { _ = toggle_state
cx.background_executor().timer(dur).await; .update(cx, |this, _| *this = checked);
}
*prev_checked.borrow_mut() = Some(checked);
}) })
.detach(); .detach();
this.with_animation( this.with_animation(
ElementId::NamedInteger( ElementId::NamedInteger("move".into(), checked as u64),
"move".into(), Animation::new(duration),
checked as u64,
),
Animation::new(dur),
move |this, delta| { move |this, delta| {
let max_x = let max_x = bg_width - bar_width - inset * 2;
bg_width - bar_width - inset * 2;
let x = if checked { let x = if checked {
max_x * delta max_x * delta
} else { } else {
@ -228,13 +188,13 @@ impl Element for Switch {
}), }),
), ),
) )
.when_some(self.label.take(), |this, label| { .when_some(self.label, |this, label| {
this.child(div().line_height(bg_height).child(label).map(|this| { this.child(div().line_height(bg_height).child(label).map(
match self.size { |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(
on_click on_click
@ -242,43 +202,14 @@ impl Element for Switch {
.map(|c| c.clone()) .map(|c| c.clone())
.filter(|_| !self.disabled), .filter(|_| !self.disabled),
|this, on_click| { |this, on_click| {
let prev_checked = state.prev_checked.clone(); let toggle_state = toggle_state.clone();
this.on_mouse_down(gpui::MouseButton::Left, move |_, window, cx| { this.on_mouse_down(gpui::MouseButton::Left, move |_, window, cx| {
cx.stop_propagation(); cx.stop_propagation();
*prev_checked.borrow_mut() = Some(checked); _ = toggle_state.update(cx, |this, _| *this = checked);
on_click(&!checked, window, cx); 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)
} }
} }