Skip to main content

fc_ui/capabilities/effects/
shimmer.rs

1use gpui::*;
2use std::sync::atomic::{AtomicU32, Ordering};
3use std::time::Duration;
4
5static SHIMMER_ID: AtomicU32 = AtomicU32::new(0);
6
7/// Shimmer 扫过效果。扫光在 -200px..600px 区间内循环移动,
8/// 适用于宽度不超过约 600px 的容器。
9#[derive(IntoElement)]
10pub struct Shimmer {
11    id: ElementId,
12    base: Div,
13    duration: Duration,
14}
15
16impl Shimmer {
17    pub fn new() -> Self {
18        let auto_id = SHIMMER_ID.fetch_add(1, Ordering::Relaxed);
19        Self {
20            id: ElementId::Name(format!("shimmer-{auto_id}").into()),
21            base: div(),
22            duration: Duration::from_millis(1500),
23        }
24    }
25
26    pub fn duration(mut self, duration: Duration) -> Self {
27        self.duration = duration;
28        self
29    }
30}
31
32impl Default for Shimmer {
33    fn default() -> Self {
34        Self::new()
35    }
36}
37
38impl RenderOnce for Shimmer {
39    fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
40        let duration = self.duration;
41
42        self.base.relative().overflow_hidden().child(
43            div()
44                .absolute()
45                .top_0()
46                .bottom_0()
47                .w(px(200.0))
48                .bg(gpui::linear_gradient(
49                    90.0,
50                    gpui::linear_color_stop(gpui::transparent_black(), 0.0),
51                    gpui::linear_color_stop(hsla(0.0, 0.0, 1.0, 0.15), 1.0),
52                ))
53                .with_animation(
54                    ElementId::Name(format!("{}-sweep", self.id).into()),
55                    Animation::new(duration).repeat().with_easing(gpui::linear),
56                    move |this, delta| {
57                        let start = px(-200.0);
58                        let end = px(600.0);
59                        let current = start + (end - start) * delta;
60                        this.left(current)
61                    },
62                ),
63        )
64    }
65}
66
67impl Styled for Shimmer {
68    fn style(&mut self) -> &mut StyleRefinement {
69        self.base.style()
70    }
71}
72
73impl InteractiveElement for Shimmer {
74    fn interactivity(&mut self) -> &mut Interactivity {
75        self.base.interactivity()
76    }
77}
78
79impl StatefulInteractiveElement for Shimmer {}
80
81impl ParentElement for Shimmer {
82    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
83        self.base.extend(elements)
84    }
85}