leptos_use/
use_mouse_in_element.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
use crate::core::{ElementMaybeSignal, Position};
use crate::{
    use_mouse_with_options, use_window, UseMouseCoordType, UseMouseEventExtractor, UseMouseOptions,
    UseMouseReturn, UseMouseSourceType, UseWindow,
};
use cfg_if::cfg_if;
use default_struct_builder::DefaultBuilder;
use leptos::*;
use std::convert::Infallible;
use std::marker::PhantomData;

/// Reactive mouse position related to an element.
///
/// ## Demo
///
/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/use_mouse_in_element)
///
/// ## Usage
///
/// ```
/// # use leptos::*;
/// # use leptos::html::Div;
/// # use leptos_use::{use_mouse_in_element, UseMouseInElementReturn};
/// #
/// # #[component]
/// # fn Demo() -> impl IntoView {
/// let target = create_node_ref::<Div>();
/// let UseMouseInElementReturn { x, y, is_outside, .. } = use_mouse_in_element(target);
///
/// view! {
///     <div node_ref=target>
///         <h1>Hello world</h1>
///     </div>
/// }
/// # }
/// ```
///
/// ## Server-Side Rendering
///
/// On the server this returns simple Signals with the `initial_value` for `x` and `y`,
/// no-op for `stop`, `is_outside = true` and `0.0` for the rest of the signals.
pub fn use_mouse_in_element<El, T>(target: El) -> UseMouseInElementReturn<impl Fn() + Clone>
where
    El: Into<ElementMaybeSignal<T, web_sys::Element>> + Clone,
    T: Into<web_sys::Element> + Clone + 'static,
{
    use_mouse_in_element_with_options(target, Default::default())
}

/// Version of [`use_mouse_in_element`] that takes a `UseMouseInElementOptions`. See [`use_mouse_in_element`] for how to use.
pub fn use_mouse_in_element_with_options<El, T, OptEl, OptT, OptEx>(
    target: El,
    options: UseMouseInElementOptions<OptEl, OptT, OptEx>,
) -> UseMouseInElementReturn<impl Fn() + Clone>
where
    El: Into<ElementMaybeSignal<T, web_sys::Element>> + Clone,
    T: Into<web_sys::Element> + Clone + 'static,
    OptEl: Into<ElementMaybeSignal<OptT, web_sys::EventTarget>> + Clone,
    OptT: Into<web_sys::EventTarget> + Clone + 'static,
    OptEx: UseMouseEventExtractor + Clone + 'static,
{
    let UseMouseInElementOptions {
        coord_type,
        target: use_mouse_target,
        touch,
        reset_on_touch_ends,
        initial_value,
        handle_outside,
        ..
    } = options;

    let UseMouseReturn {
        x, y, source_type, ..
    } = use_mouse_with_options(
        UseMouseOptions::default()
            .coord_type(coord_type)
            .target(use_mouse_target)
            .touch(touch)
            .reset_on_touch_ends(reset_on_touch_ends)
            .initial_value(initial_value),
    );

    let (element_x, set_element_x) = create_signal(0.0);
    let (element_y, set_element_y) = create_signal(0.0);
    let (element_position_x, set_element_position_x) = create_signal(0.0);
    let (element_position_y, set_element_position_y) = create_signal(0.0);
    let (element_width, set_element_width) = create_signal(0.0);
    let (element_height, set_element_height) = create_signal(0.0);
    let (is_outside, set_outside) = create_signal(true);

    cfg_if! { if #[cfg(feature = "ssr")] {
        let stop = || ();

        let _ = handle_outside;

        let _ = set_element_x;
        let _ = set_element_y;
        let _ = set_element_position_x;
        let _ = set_element_position_y;
        let _ = set_element_width;
        let _ = set_element_height;
        let _ = set_outside;
        let _ = target;
    } else {
        use crate::use_event_listener;
        use leptos::ev::mouseleave;

        let target = target.into();
        let window = window();

        let stop = watch(
            move || (target.get(), x.get(), y.get()),
            move |(el, x, y), _, _| {
                if let Some(el) = el {
                    let el: web_sys::Element = el.clone().into();
                    let rect = el.get_bounding_client_rect();
                    let left = rect.left();
                    let top = rect.top();
                    let width = rect.width();
                    let height = rect.height();

                    set_element_position_x.set(left + window.page_x_offset().unwrap_or_default());
                    set_element_position_y.set(top + window.page_y_offset().unwrap_or_default());

                    set_element_height.set(height);
                    set_element_width.set(width);

                    let el_x = *x - element_position_x.get_untracked();
                    let el_y = *y - element_position_y.get_untracked();

                    set_outside.set(
                        width == 0.0
                            || height == 0.0
                            || el_x <= 0.0
                            || el_y <= 0.0
                            || el_x > width
                            || el_y > height,
                    );

                    if handle_outside || !is_outside.get_untracked() {
                        set_element_x.set(el_x);
                        set_element_y.set(el_y);
                    }
                }
            },
            false,
        );

        let _ = use_event_listener(document(), mouseleave, move |_| set_outside.set(true));
    }}

    UseMouseInElementReturn {
        x,
        y,
        source_type,
        element_x: element_x.into(),
        element_y: element_y.into(),
        element_position_x: element_position_x.into(),
        element_position_y: element_position_y.into(),
        element_width: element_width.into(),
        element_height: element_height.into(),
        is_outside: is_outside.into(),
        stop,
    }
}

/// Options for [`use_mouse_in_element_with_options`].
#[derive(DefaultBuilder)]
pub struct UseMouseInElementOptions<El, T, Ex>
where
    El: Clone + Into<ElementMaybeSignal<T, web_sys::EventTarget>>,
    T: Into<web_sys::EventTarget> + Clone + 'static,
    Ex: UseMouseEventExtractor + Clone,
{
    /// How to extract the x, y coordinates from mouse events or touches
    coord_type: UseMouseCoordType<Ex>,

    /// Listen events on `target` element. Defaults to `window`
    target: El,

    /// Listen to `touchmove` events. Defaults to `true`.
    touch: bool,

    /// Reset to initial value when `touchend` event fired. Defaults to `false`
    reset_on_touch_ends: bool,

    /// Initial values. Defaults to `{x: 0.0, y: 0.0}`.
    initial_value: Position,

    /// If `true` updates the `element_x` and `element_y` signals even if the
    /// mouse is outside of the element. If `false` it doesn't update them when outside.
    /// Defaults to `true`.
    handle_outside: bool,

    #[builder(skip)]
    _marker: PhantomData<T>,
}

impl Default for UseMouseInElementOptions<UseWindow, web_sys::Window, Infallible> {
    fn default() -> Self {
        Self {
            coord_type: UseMouseCoordType::default(),
            target: use_window(),
            touch: true,
            reset_on_touch_ends: false,
            initial_value: Position { x: 0.0, y: 0.0 },
            handle_outside: true,
            _marker: PhantomData,
        }
    }
}

/// Return type of [`use_mouse_in_element`].
pub struct UseMouseInElementReturn<F>
where
    F: Fn() + Clone,
{
    /// X coordinate of the mouse pointer / touch
    pub x: Signal<f64>,

    /// Y coordinate of the mouse pointer / touch
    pub y: Signal<f64>,

    /// Identifies the source of the reported coordinates
    pub source_type: Signal<UseMouseSourceType>,

    /// X coordinate of the pointer relative to the left edge of the element
    pub element_x: Signal<f64>,

    /// Y coordinate of the pointer relative to the top edge of the element
    pub element_y: Signal<f64>,

    /// X coordinate of the element relative to the left edge of the document
    pub element_position_x: Signal<f64>,

    /// Y coordinate of the element relative to the top edge of the document
    pub element_position_y: Signal<f64>,

    /// Width of the element
    pub element_width: Signal<f64>,

    /// Height of the element
    pub element_height: Signal<f64>,

    /// `true` if the mouse is outside of the element
    pub is_outside: Signal<bool>,

    /// Stop watching
    pub stop: F,
}