trait based event system
This commit is contained in:
1 parent
a72718134b
commit
299b123446
28 files changed
+2407
-734
No files matched your search
@@ -1,10 +1,89 @@
|
||||
use dioxus_core::Event;
|
||||
|
||||
pub type CompositionEvent = Event<CompositionData>;
|
||||
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
|
||||
pub struct CompositionData {
|
||||
pub data: String,
|
||||
inner: Box<dyn HasCompositionData>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for CompositionData {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("CompositionData")
|
||||
.field("data", &self.data())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<E: HasCompositionData> From<E> for CompositionData {
|
||||
fn from(e: E) -> Self {
|
||||
Self { inner: Box::new(e) }
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for CompositionData {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.data() == other.data()
|
||||
}
|
||||
}
|
||||
|
||||
impl CompositionData {
|
||||
pub fn data(&self) -> String {
|
||||
self.inner.data()
|
||||
}
|
||||
|
||||
pub fn downcast<T: 'static>(&self) -> Option<&T> {
|
||||
self.inner.as_any().downcast_ref()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serialize")]
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
struct SerializedCompositionData {
|
||||
data: String,
|
||||
}
|
||||
|
||||
#[cfg(feature = "serialize")]
|
||||
impl From<&CompositionData> for SerializedCompositionData {
|
||||
fn from(data: &CompositionData) -> Self {
|
||||
Self { data: data.data() }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serialize")]
|
||||
impl HasCompositionData for SerializedCompositionData {
|
||||
fn data(&self) -> String {
|
||||
self.data.clone()
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serialize")]
|
||||
impl serde::Serialize for CompositionData {
|
||||
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
SerializedCompositionData::from(self).serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "serialize")]
|
||||
impl<'de> serde::Deserialize<'de> for CompositionData {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
let data = SerializedCompositionData::deserialize(deserializer)?;
|
||||
Ok(Self {
|
||||
inner: Box::new(data),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A trait for any object that has the data for a composition event
|
||||
pub trait HasCompositionData: std::any::Any {
|
||||
/// The characters generated by the input method that raised the event
|
||||
fn data(&self) -> String;
|
||||
|
||||
/// return self as Any
|
||||
fn as_any(&self) -> &dyn std::any::Any;
|
||||
}
|
||||
|
||||
impl_event! [
|
||||
|
||||
Reference in new issue
Block a user