dioxus_html/events/
visible.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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
use std::{
    fmt::{Display, Formatter},
    time::SystemTime,
};

pub struct VisibleData {
    inner: Box<dyn HasVisibleData>,
}

impl<E: HasVisibleData> From<E> for VisibleData {
    fn from(e: E) -> Self {
        Self { inner: Box::new(e) }
    }
}

impl VisibleData {
    /// Create a new VisibleData
    pub fn new(inner: impl HasVisibleData + 'static) -> Self {
        Self {
            inner: Box::new(inner),
        }
    }

    /// Get the bounds rectangle of the target element
    pub fn get_bounding_client_rect(&self) -> VisibleResult<PixelsRect> {
        self.inner.get_bounding_client_rect()
    }

    /// Get the ratio of the intersectionRect to the boundingClientRect
    pub fn get_intersection_ratio(&self) -> VisibleResult<f64> {
        self.inner.get_intersection_ratio()
    }

    /// Get the rect representing the target's visible area
    pub fn get_intersection_rect(&self) -> VisibleResult<PixelsRect> {
        self.inner.get_intersection_rect()
    }

    /// Get if the target element intersects with the intersection observer's root
    pub fn is_intersecting(&self) -> VisibleResult<bool> {
        self.inner.is_intersecting()
    }

    /// Get the rect for the intersection observer's root
    pub fn get_root_bounds(&self) -> VisibleResult<PixelsRect> {
        self.inner.get_root_bounds()
    }

    /// Get a timestamp indicating the time at which the intersection was recorded
    pub fn get_time(&self) -> VisibleResult<SystemTime> {
        self.inner.get_time()
    }

    /// Downcast this event to a concrete event type
    pub fn downcast<T: 'static>(&self) -> Option<&T> {
        self.inner.as_any().downcast_ref::<T>()
    }
}

impl std::fmt::Debug for VisibleData {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("VisibleData")
            .field(
                "bounding_client_rect",
                &self.inner.get_bounding_client_rect(),
            )
            .field("intersection_ratio", &self.inner.get_intersection_ratio())
            .field("intersection_rect", &self.inner.get_intersection_rect())
            .field("is_intersecting", &self.inner.is_intersecting())
            .field("root_bounds", &self.inner.get_root_bounds())
            .field("time", &self.inner.get_time())
            .finish()
    }
}

impl PartialEq for VisibleData {
    fn eq(&self, _: &Self) -> bool {
        true
    }
}

#[cfg(feature = "serialize")]
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
pub struct DOMRect {
    bottom: f64, // The bottom coordinate value of the DOMRect (usually the same as y + height)
    height: f64, // The height of the DOMRect
    left: f64,   // The left coordinate value of the DOMRect (usually the same as x)
    right: f64,  // The right coordinate value of the DOMRect (usually the same as x + width)
    top: f64,    // The top coordinate value of the DOMRect (usually the same as y)
    width: f64,  // The width of the DOMRect
    x: f64,      // The x coordinate of the DOMRect's origin
    y: f64,      // The y coordinate of the DOMRect's origin
}

#[cfg(feature = "serialize")]
impl From<PixelsRect> for DOMRect {
    fn from(rect: PixelsRect) -> Self {
        let x = rect.origin.x;
        let y = rect.origin.y;
        let height = rect.height();
        let width = rect.width();

        Self {
            bottom: y + height,
            height,
            left: x,
            right: x + width,
            top: y,
            width,
            x,
            y,
        }
    }
}

#[cfg(feature = "serialize")]
impl From<&DOMRect> for PixelsRect {
    fn from(rect: &DOMRect) -> Self {
        PixelsRect::new(
            euclid::Point2D::new(rect.x, rect.y),
            euclid::Size2D::new(rect.width, rect.height),
        )
    }
}

#[cfg(feature = "serialize")]
/// A serialized version of VisibleData
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
pub struct SerializedVisibleData {
    pub bounding_client_rect: DOMRect,
    pub intersection_ratio: f64,
    pub intersection_rect: DOMRect,
    pub is_intersecting: bool,
    pub root_bounds: DOMRect,
    pub time_ms: u128,
}

#[cfg(feature = "serialize")]
impl SerializedVisibleData {
    /// Create a new SerializedVisibleData
    pub fn new(
        bounding_client_rect: DOMRect,
        intersection_ratio: f64,
        intersection_rect: DOMRect,
        is_intersecting: bool,
        root_bounds: DOMRect,
        time_ms: u128,
    ) -> Self {
        Self {
            bounding_client_rect,
            intersection_ratio,
            intersection_rect,
            is_intersecting,
            root_bounds,
            time_ms,
        }
    }
}

#[cfg(feature = "serialize")]
impl From<&VisibleData> for SerializedVisibleData {
    fn from(data: &VisibleData) -> Self {
        Self::new(
            data.get_bounding_client_rect().unwrap().into(),
            data.get_intersection_ratio().unwrap(),
            data.get_intersection_rect().unwrap().into(),
            data.is_intersecting().unwrap(),
            data.get_root_bounds().unwrap().into(),
            data.get_time().unwrap().elapsed().unwrap().as_millis(),
        )
    }
}

#[cfg(feature = "serialize")]
impl HasVisibleData for SerializedVisibleData {
    /// Get the bounds rectangle of the target element
    fn get_bounding_client_rect(&self) -> VisibleResult<PixelsRect> {
        Ok((&self.bounding_client_rect).into())
    }

    /// Get the ratio of the intersectionRect to the boundingClientRect
    fn get_intersection_ratio(&self) -> VisibleResult<f64> {
        Ok(self.intersection_ratio)
    }

    /// Get the rect representing the target's visible area
    fn get_intersection_rect(&self) -> VisibleResult<PixelsRect> {
        Ok((&self.intersection_rect).into())
    }

    /// Get if the target element intersects with the intersection observer's root
    fn is_intersecting(&self) -> VisibleResult<bool> {
        Ok(self.is_intersecting)
    }

    /// Get the rect for the intersection observer's root
    fn get_root_bounds(&self) -> VisibleResult<PixelsRect> {
        Ok((&self.root_bounds).into())
    }

    /// Get a timestamp indicating the time at which the intersection was recorded
    fn get_time(&self) -> VisibleResult<SystemTime> {
        Ok(SystemTime::UNIX_EPOCH + std::time::Duration::from_millis(self.time_ms as u64))
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

#[cfg(feature = "serialize")]
impl serde::Serialize for VisibleData {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        SerializedVisibleData::from(self).serialize(serializer)
    }
}

#[cfg(feature = "serialize")]
impl<'de> serde::Deserialize<'de> for VisibleData {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let data = SerializedVisibleData::deserialize(deserializer)?;
        Ok(Self {
            inner: Box::new(data),
        })
    }
}

pub trait HasVisibleData: std::any::Any {
    /// Get the bounds rectangle of the target element
    fn get_bounding_client_rect(&self) -> VisibleResult<PixelsRect> {
        Err(VisibleError::NotSupported)
    }

    /// Get the ratio of the intersectionRect to the boundingClientRect
    fn get_intersection_ratio(&self) -> VisibleResult<f64> {
        Err(VisibleError::NotSupported)
    }

    /// Get the rect representing the target's visible area
    fn get_intersection_rect(&self) -> VisibleResult<PixelsRect> {
        Err(VisibleError::NotSupported)
    }

    /// Get if the target element intersects with the intersection observer's root
    fn is_intersecting(&self) -> VisibleResult<bool> {
        Err(VisibleError::NotSupported)
    }

    /// Get the rect for the intersection observer's root
    fn get_root_bounds(&self) -> VisibleResult<PixelsRect> {
        Err(VisibleError::NotSupported)
    }

    /// Get a timestamp indicating the time at which the intersection was recorded
    fn get_time(&self) -> VisibleResult<SystemTime> {
        Err(VisibleError::NotSupported)
    }

    /// return self as Any
    fn as_any(&self) -> &dyn std::any::Any;
}

use dioxus_core::Event;

use crate::geometry::PixelsRect;

pub type VisibleEvent = Event<VisibleData>;

impl_event! {
    VisibleData;

    /// onvisible
    onvisible
}

/// The VisibleResult type for the VisibleData
pub type VisibleResult<T> = Result<T, VisibleError>;

#[derive(Debug)]
/// The error type for the VisibleData
#[non_exhaustive]
pub enum VisibleError {
    /// The renderer does not support the requested operation
    NotSupported,
    /// The element was not found
    OperationFailed(Box<dyn std::error::Error>),
    /// The target element had no associated ElementId
    NoElementId,
}

impl Display for VisibleError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            VisibleError::NotSupported => {
                write!(f, "The renderer does not support the requested operation")
            }
            VisibleError::OperationFailed(e) => {
                write!(f, "The operation failed: {}", e)
            }
            VisibleError::NoElementId => {
                write!(f, "The target had no associated ElementId")
            }
        }
    }
}

impl std::error::Error for VisibleError {}