Skip to main content

fc_ui/capabilities/effects/
magnetic_button.rs

1//! Button whose position subtly shifts toward cursor when nearby.
2
3use gpui::{prelude::FluentBuilder as _, *};
4
5pub struct MagneticButtonState {
6    mouse_offset: Point<f32>,
7    bounds: Option<Bounds<Pixels>>,
8    is_hovering: bool,
9}
10
11impl MagneticButtonState {
12    pub fn new(_cx: &mut Context<Self>) -> Self {
13        Self {
14            mouse_offset: Point::default(),
15            bounds: None,
16            is_hovering: false,
17        }
18    }
19}
20
21impl Render for MagneticButtonState {
22    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
23        Empty
24    }
25}
26
27#[derive(IntoElement)]
28pub struct MagneticButton {
29    id: ElementId,
30    state: Entity<MagneticButtonState>,
31    strength: f32,
32    range: Pixels,
33    style: StyleRefinement,
34    children: Vec<AnyElement>,
35}
36
37impl MagneticButton {
38    pub fn new(id: impl Into<ElementId>, state: Entity<MagneticButtonState>) -> Self {
39        Self {
40            id: id.into(),
41            state,
42            strength: 0.3,
43            range: px(100.0),
44            style: StyleRefinement::default(),
45            children: Vec::new(),
46        }
47    }
48
49    pub fn strength(mut self, strength: f32) -> Self {
50        self.strength = strength.clamp(0.0, 1.0);
51        self
52    }
53
54    pub fn range(mut self, range: Pixels) -> Self {
55        self.range = range;
56        self
57    }
58}
59
60impl Styled for MagneticButton {
61    fn style(&mut self) -> &mut StyleRefinement {
62        &mut self.style
63    }
64}
65
66impl ParentElement for MagneticButton {
67    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
68        self.children.extend(elements);
69    }
70}
71
72impl RenderOnce for MagneticButton {
73    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
74        let user_style = self.style;
75        let state = self.state.read(cx);
76        let strength = self.strength;
77        let range = self.range;
78
79        let (final_x, final_y) = if state.is_hovering {
80            (
81                state.mouse_offset.x * strength,
82                state.mouse_offset.y * strength,
83            )
84        } else {
85            (0.0, 0.0)
86        };
87
88        let state_bounds = self.state.clone();
89        let state_move = self.state.clone();
90        let state_hover = self.state.clone();
91
92        div()
93            .id(self.id)
94            .relative()
95            .cursor_pointer()
96            .child(
97                div()
98                    .ml(px(final_x))
99                    .mt(px(final_y))
100                    .children(self.children),
101            )
102            .child(
103                canvas(
104                    move |bounds, _window, cx| {
105                        state_bounds.update(cx, |s, _| s.bounds = Some(bounds));
106                    },
107                    |_bounds, _, _window, _cx| {},
108                )
109                .absolute()
110                .inset_0()
111                .size_full(),
112            )
113            .on_mouse_move(move |event: &MouseMoveEvent, _window, cx| {
114                state_move.update(cx, |s, cx| {
115                    if let Some(bounds) = s.bounds {
116                        let range_f32: f32 = range.into();
117                        let center_x: f32 = bounds.center().x.into();
118                        let center_y: f32 = bounds.center().y.into();
119                        let event_x: f32 = event.position.x.into();
120                        let event_y: f32 = event.position.y.into();
121                        s.mouse_offset.x = (event_x - center_x).clamp(-range_f32, range_f32);
122                        s.mouse_offset.y = (event_y - center_y).clamp(-range_f32, range_f32);
123                        cx.notify();
124                    }
125                });
126            })
127            .on_hover(move |hovered: &bool, _window, cx| {
128                state_hover.update(cx, |s, cx| {
129                    s.is_hovering = *hovered;
130                    if !*hovered {
131                        s.mouse_offset = Point::default();
132                    }
133                    cx.notify();
134                });
135            })
136            .map(|this: Stateful<Div>| {
137                let mut el = this;
138                el.style().refine(&user_style);
139                el
140            })
141    }
142}