dioxus_html/events/
composition.rs

1use dioxus_core::Event;
2
3pub type CompositionEvent = Event<CompositionData>;
4
5pub struct CompositionData {
6    inner: Box<dyn HasCompositionData>,
7}
8
9impl std::fmt::Debug for CompositionData {
10    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11        f.debug_struct("CompositionData")
12            .field("data", &self.data())
13            .finish()
14    }
15}
16
17impl<E: HasCompositionData> From<E> for CompositionData {
18    fn from(e: E) -> Self {
19        Self { inner: Box::new(e) }
20    }
21}
22
23impl PartialEq for CompositionData {
24    fn eq(&self, other: &Self) -> bool {
25        self.data() == other.data()
26    }
27}
28
29impl CompositionData {
30    /// Create a new CompositionData
31    pub fn new(inner: impl HasCompositionData + 'static) -> Self {
32        Self {
33            inner: Box::new(inner),
34        }
35    }
36
37    /// The characters generated by the input method that raised the event
38    pub fn data(&self) -> String {
39        self.inner.data()
40    }
41
42    pub fn downcast<T: 'static>(&self) -> Option<&T> {
43        self.inner.as_any().downcast_ref()
44    }
45}
46
47#[cfg(feature = "serialize")]
48/// A serialized version of CompositionData
49#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
50pub struct SerializedCompositionData {
51    data: String,
52}
53
54#[cfg(feature = "serialize")]
55impl From<&CompositionData> for SerializedCompositionData {
56    fn from(data: &CompositionData) -> Self {
57        Self { data: data.data() }
58    }
59}
60
61#[cfg(feature = "serialize")]
62impl HasCompositionData for SerializedCompositionData {
63    fn data(&self) -> String {
64        self.data.clone()
65    }
66
67    fn as_any(&self) -> &dyn std::any::Any {
68        self
69    }
70}
71
72#[cfg(feature = "serialize")]
73impl serde::Serialize for CompositionData {
74    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
75        SerializedCompositionData::from(self).serialize(serializer)
76    }
77}
78
79#[cfg(feature = "serialize")]
80impl<'de> serde::Deserialize<'de> for CompositionData {
81    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
82        let data = SerializedCompositionData::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 a composition event
90pub trait HasCompositionData: std::any::Any {
91    /// The characters generated by the input method that raised the event
92    fn data(&self) -> String;
93
94    /// return self as Any
95    fn as_any(&self) -> &dyn std::any::Any;
96}
97
98impl_event! [
99    CompositionData;
100
101    /// oncompositionstart
102    oncompositionstart
103
104    /// oncompositionend
105    oncompositionend
106
107    /// oncompositionupdate
108    oncompositionupdate
109];