Skip to main content

fc_ui/capabilities/effects/
confetti.rs

1//! Pre-configured celebration particle burst.
2
3use gpui::{prelude::FluentBuilder as _, *};
4use std::time::Duration;
5
6const DEFAULT_CONFETTI_COLORS: [u32; 6] =
7    [0xFF6B6B, 0x4ECDC4, 0x45B7D1, 0xFFA07A, 0x98D8C8, 0xF7DC6F];
8
9#[derive(Clone)]
10pub struct ConfettiParticle {
11    pub position: Point<f32>,
12    pub velocity: Point<f32>,
13    pub rotation_speed: f32,
14    pub size: f32,
15    pub color: Hsla,
16    pub age: f32,
17    pub lifetime: f32,
18}
19
20pub struct ConfettiState {
21    is_active: bool,
22    particles: Vec<ConfettiParticle>,
23    particle_count: usize,
24    colors: Vec<Hsla>,
25    gravity: f32,
26    origin: Point<f32>,
27    spread: f32,
28}
29
30impl ConfettiState {
31    pub fn new(_cx: &mut Context<Self>) -> Self {
32        Self {
33            is_active: false,
34            particles: Vec::new(),
35            particle_count: 80,
36            colors: DEFAULT_CONFETTI_COLORS
37                .iter()
38                .map(|&c| {
39                    let color: Rgba = rgb(c);
40                    Hsla::from(color)
41                })
42                .collect(),
43            gravity: 120.0,
44            origin: Point { x: 0.5, y: 0.5 },
45            spread: 300.0,
46        }
47    }
48
49    pub fn set_particle_count(&mut self, count: usize) {
50        self.particle_count = count;
51    }
52
53    pub fn set_colors(&mut self, colors: Vec<Hsla>) {
54        if !colors.is_empty() {
55            self.colors = colors;
56        }
57    }
58
59    pub fn set_gravity(&mut self, gravity: f32) {
60        self.gravity = gravity;
61    }
62
63    pub fn set_origin(&mut self, origin: Point<f32>) {
64        self.origin = origin;
65    }
66
67    pub fn is_active(&self) -> bool {
68        self.is_active
69    }
70
71    pub fn burst(&mut self, cx: &mut Context<Self>) {
72        let was_active = self.is_active;
73        self.particles.clear();
74        self.is_active = true;
75
76        let count = self.particle_count;
77        let color_count = self.colors.len().max(1);
78
79        for i in 0..count {
80            let seed = i as u32;
81            let angle = pseudo_random_f32(seed) * std::f32::consts::TAU;
82            let speed = self.spread * (0.3 + pseudo_random_f32(seed + 3) * 0.7);
83
84            let vx = angle.cos() * speed;
85            let vy = angle.sin() * speed - self.spread * 0.5;
86
87            let color_idx =
88                (pseudo_random_f32(seed + 7) * color_count as f32) as usize % color_count;
89            let particle_size = 4.0 + pseudo_random_f32(seed + 11) * 6.0;
90            let rotation_spd = (pseudo_random_f32(seed + 17) - 0.5) * 10.0;
91            let lifetime = 1.5 + pseudo_random_f32(seed + 23) * 1.5;
92
93            self.particles.push(ConfettiParticle {
94                position: Point {
95                    x: self.origin.x,
96                    y: self.origin.y,
97                },
98                velocity: Point { x: vx, y: vy },
99                rotation_speed: rotation_spd,
100                size: particle_size,
101                color: self.colors[color_idx],
102                age: 0.0,
103                lifetime,
104            });
105        }
106
107        if !was_active {
108            self.schedule_tick(cx);
109        }
110        cx.notify();
111    }
112
113    fn update_particles(&mut self, dt: f32) {
114        let gravity = self.gravity;
115
116        for particle in &mut self.particles {
117            particle.age += dt;
118            particle.velocity.y += gravity * dt;
119            particle.velocity.x *= 0.99;
120            particle.position.x += particle.velocity.x * dt;
121            particle.position.y += particle.velocity.y * dt;
122        }
123
124        self.particles.retain(|p| p.age < p.lifetime);
125
126        if self.particles.is_empty() {
127            self.is_active = false;
128        }
129    }
130
131    pub fn particles(&self) -> &[ConfettiParticle] {
132        &self.particles
133    }
134
135    fn schedule_tick(&self, cx: &mut Context<Self>) {
136        if !self.is_active {
137            return;
138        }
139
140        cx.spawn(async |this, cx| {
141            cx.background_executor()
142                .timer(Duration::from_millis(16))
143                .await;
144
145            _ = this.update(cx, |state, cx| {
146                if !state.is_active {
147                    return;
148                }
149
150                let dt = 1.0 / 60.0;
151                state.update_particles(dt);
152
153                if state.is_active {
154                    state.schedule_tick(cx);
155                }
156
157                cx.notify();
158            });
159        })
160        .detach();
161    }
162}
163
164impl Render for ConfettiState {
165    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
166        div()
167    }
168}
169
170struct ConfettiPaintData {
171    particles: Vec<ConfettiParticle>,
172}
173
174#[derive(IntoElement)]
175pub struct Confetti {
176    id: ElementId,
177    state: Entity<ConfettiState>,
178    style: StyleRefinement,
179}
180
181impl Confetti {
182    pub fn new(id: impl Into<ElementId>, state: Entity<ConfettiState>) -> Self {
183        Self {
184            id: id.into(),
185            state,
186            style: StyleRefinement::default(),
187        }
188    }
189
190    pub fn particle_count(self, count: usize, cx: &mut App) -> Self {
191        self.state.update(cx, |s, _| s.particle_count = count);
192        self
193    }
194
195    pub fn colors(self, colors: Vec<Hsla>, cx: &mut App) -> Self {
196        self.state.update(cx, |s, _| s.set_colors(colors));
197        self
198    }
199
200    pub fn gravity(self, gravity: f32, cx: &mut App) -> Self {
201        self.state.update(cx, |s, _| s.gravity = gravity);
202        self
203    }
204}
205
206impl Styled for Confetti {
207    fn style(&mut self) -> &mut StyleRefinement {
208        &mut self.style
209    }
210}
211
212impl RenderOnce for Confetti {
213    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
214        let user_style = self.style;
215        let state = self.state.read(cx);
216        let paint_data = ConfettiPaintData {
217            particles: state.particles().to_vec(),
218        };
219
220        div()
221            .id(self.id)
222            .relative()
223            .size_full()
224            .child(
225                canvas(
226                    move |_bounds, _window, _cx| paint_data,
227                    move |bounds, data, window, _cx| {
228                        paint_confetti(bounds, &data, window);
229                    },
230                )
231                .absolute()
232                .inset_0()
233                .size_full(),
234            )
235            .map(|this| {
236                let mut el = this;
237                el.style().refine(&user_style);
238                el
239            })
240    }
241}
242
243fn paint_confetti(bounds: Bounds<Pixels>, data: &ConfettiPaintData, window: &mut Window) {
244    if bounds.size.width <= px(0.0) || bounds.size.height <= px(0.0) {
245        return;
246    }
247
248    let bw = bounds.size.width / px(1.0);
249    let bh = bounds.size.height / px(1.0);
250
251    for particle in &data.particles {
252        let x = bounds.left() + px(particle.position.x * bw);
253        let y = bounds.top() + px(particle.position.y * bh);
254        let half = particle.size * 0.5;
255
256        if x + px(half) < bounds.left()
257            || x - px(half) > bounds.right()
258            || y + px(half) < bounds.top()
259            || y - px(half) > bounds.bottom()
260        {
261            continue;
262        }
263
264        let fade = 1.0 - (particle.age / particle.lifetime).clamp(0.0, 1.0);
265        let alpha = particle.color.a * fade;
266
267        let wobble = (particle.age * particle.rotation_speed).sin().abs();
268        let w = particle.size * (0.5 + wobble * 0.5);
269        let h = particle.size;
270
271        window.paint_quad(PaintQuad {
272            bounds: Bounds {
273                origin: point(x - px(w * 0.5), y - px(h * 0.5)),
274                size: gpui::size(px(w), px(h)),
275            },
276            corner_radii: Corners::all(px(1.0)),
277            background: hsla(particle.color.h, particle.color.s, particle.color.l, alpha).into(),
278            border_widths: Edges::default(),
279            border_color: transparent_black(),
280            border_style: BorderStyle::default(),
281            continuous_corners: false,
282            transform: Default::default(),
283            blend_mode: Default::default(),
284        });
285    }
286}
287
288fn pseudo_random_f32(seed: u32) -> f32 {
289    let mut x = seed.wrapping_add(0x9E3779B9);
290    x ^= x >> 16;
291    x = x.wrapping_mul(0x45D9F3B);
292    x ^= x >> 16;
293    (x & 0xFFFF) as f32 / 65535.0
294}