dioxus_html/events/
image.rs

1use dioxus_core::Event;
2
3pub type ImageEvent = Event<ImageData>;
4pub struct ImageData {
5    inner: Box<dyn HasImageData>,
6}
7
8impl<E: HasImageData> From<E> for ImageData {
9    fn from(e: E) -> Self {
10        Self { inner: Box::new(e) }
11    }
12}
13
14impl std::fmt::Debug for ImageData {
15    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16        f.debug_struct("ImageData")
17            .field("load_error", &self.load_error())
18            .finish()
19    }
20}
21
22impl PartialEq for ImageData {
23    fn eq(&self, other: &Self) -> bool {
24        self.load_error() == other.load_error()
25    }
26}
27
28impl ImageData {
29    /// Create a new ImageData
30    pub fn new(e: impl HasImageData) -> Self {
31        Self { inner: Box::new(e) }
32    }
33
34    /// If the renderer encountered an error while loading the image
35    pub fn load_error(&self) -> bool {
36        self.inner.load_error()
37    }
38
39    pub fn downcast<T: 'static>(&self) -> Option<&T> {
40        self.inner.as_any().downcast_ref::<T>()
41    }
42}
43
44#[cfg(feature = "serialize")]
45/// A serialized version of ImageData
46#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
47pub struct SerializedImageData {
48    #[cfg_attr(feature = "serialize", serde(default))]
49    load_error: bool,
50}
51
52#[cfg(feature = "serialize")]
53impl From<&ImageData> for SerializedImageData {
54    fn from(data: &ImageData) -> Self {
55        Self {
56            load_error: data.load_error(),
57        }
58    }
59}
60
61#[cfg(feature = "serialize")]
62impl HasImageData for SerializedImageData {
63    fn as_any(&self) -> &dyn std::any::Any {
64        self
65    }
66
67    fn load_error(&self) -> bool {
68        self.load_error
69    }
70}
71
72#[cfg(feature = "serialize")]
73impl serde::Serialize for ImageData {
74    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
75        SerializedImageData::from(self).serialize(serializer)
76    }
77}
78
79#[cfg(feature = "serialize")]
80impl<'de> serde::Deserialize<'de> for ImageData {
81    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
82        let data = SerializedImageData::deserialize(deserializer)?;
83        Ok(Self {
84            inner: Box::new(data),
85        })
86    }
87}
88
89/// A trait for any object that has the data for an image event
90pub trait HasImageData: std::any::Any {
91    /// If the renderer encountered an error while loading the image
92    fn load_error(&self) -> bool;
93
94    /// return self as Any
95    fn as_any(&self) -> &dyn std::any::Any;
96}
97
98impl_event! [
99    ImageData;
100
101    /// onerror
102    onerror
103
104    /// onload
105    onload
106];