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
use crate::file_data::FileEngine;
use crate::file_data::HasFileData;
use std::ops::Deref;
use std::{collections::HashMap, fmt::Debug};

use dioxus_core::Event;

pub type FormEvent = Event<FormData>;

/// A form value that may either be a list of values or a single value
#[cfg_attr(
    feature = "serialize",
    derive(serde::Serialize, serde::Deserialize),
    // this will serialize Text(String) -> String and VecText(Vec<String>) to Vec<String>
    serde(untagged)
)]
#[derive(Debug, Clone, PartialEq)]
pub enum FormValue {
    Text(String),
    VecText(Vec<String>),
}

impl From<FormValue> for Vec<String> {
    fn from(value: FormValue) -> Self {
        match value {
            FormValue::Text(s) => vec![s],
            FormValue::VecText(vec) => vec,
        }
    }
}

impl Deref for FormValue {
    type Target = [String];

    fn deref(&self) -> &Self::Target {
        self.as_slice()
    }
}

impl FormValue {
    /// Convenient way to represent Value as slice
    pub fn as_slice(&self) -> &[String] {
        match self {
            FormValue::Text(s) => std::slice::from_ref(s),
            FormValue::VecText(vec) => vec.as_slice(),
        }
    }
    /// Convert into Vec<String>
    pub fn to_vec(self) -> Vec<String> {
        self.into()
    }
}

/* DOMEvent:  Send + SyncTarget relatedTarget */
pub struct FormData {
    inner: Box<dyn HasFormData>,
}

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

impl PartialEq for FormData {
    fn eq(&self, other: &Self) -> bool {
        self.value() == other.value() && self.values() == other.values()
    }
}

impl Debug for FormData {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FormEvent")
            .field("value", &self.value())
            .field("values", &self.values())
            .finish()
    }
}

impl FormData {
    /// Create a new form event
    pub fn new(event: impl HasFormData + 'static) -> Self {
        Self {
            inner: Box::new(event),
        }
    }

    /// Get the value of the form event
    pub fn value(&self) -> String {
        self.inner.value()
    }

    /// Get the value of the form event as a parsed type
    pub fn parsed<T>(&self) -> Result<T, T::Err>
    where
        T: std::str::FromStr,
    {
        self.value().parse()
    }

    /// Try to parse the value as a boolean
    ///
    /// Returns false if the value is not a boolean, or if it is false!
    /// Does not verify anything about the event itself, use with caution
    pub fn checked(&self) -> bool {
        self.value().parse().unwrap_or(false)
    }

    /// Get the values of the form event
    pub fn values(&self) -> HashMap<String, FormValue> {
        self.inner.values()
    }

    /// Get the files of the form event
    pub fn files(&self) -> Option<std::sync::Arc<dyn FileEngine>> {
        self.inner.files()
    }

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

/// An object that has all the data for a form event
pub trait HasFormData: HasFileData + std::any::Any {
    fn value(&self) -> String {
        Default::default()
    }

    fn values(&self) -> HashMap<String, FormValue> {
        Default::default()
    }

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

impl FormData {
    #[cfg(feature = "serialize")]
    /// Parse the values into a struct with one field per value
    pub fn parsed_values<T>(&self) -> Result<T, serde_json::Error>
    where
        T: serde::de::DeserializeOwned,
    {
        use serde::Serialize;

        fn convert_hashmap_to_json<K, V>(hashmap: &HashMap<K, V>) -> serde_json::Result<String>
        where
            K: Serialize + std::hash::Hash + Eq,
            V: Serialize,
        {
            serde_json::to_string(hashmap)
        }

        let parsed_json =
            convert_hashmap_to_json(&self.values()).expect("Failed to parse values to JSON");

        serde_json::from_str(&parsed_json)
    }
}

#[cfg(feature = "serialize")]
/// A serialized form data object
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
pub struct SerializedFormData {
    value: String,
    values: HashMap<String, FormValue>,
    files: Option<crate::file_data::SerializedFileEngine>,
}

#[cfg(feature = "serialize")]
impl SerializedFormData {
    /// Create a new serialized form data object
    pub fn new(
        value: String,
        values: HashMap<String, FormValue>,
        files: Option<crate::file_data::SerializedFileEngine>,
    ) -> Self {
        Self {
            value,
            values,
            files,
        }
    }

    /// Create a new serialized form data object from a traditional form data object
    pub async fn async_from(data: &FormData) -> Self {
        Self {
            value: data.value(),
            values: data.values(),
            files: match data.files() {
                Some(files) => {
                    let mut resolved_files = HashMap::new();

                    for file in files.files() {
                        let bytes = files.read_file(&file).await;
                        resolved_files.insert(file, bytes.unwrap_or_default());
                    }

                    Some(crate::file_data::SerializedFileEngine {
                        files: resolved_files,
                    })
                }
                None => None,
            },
        }
    }

    fn from_lossy(data: &FormData) -> Self {
        Self {
            value: data.value(),
            values: data.values(),
            files: None,
        }
    }
}

#[cfg(feature = "serialize")]
impl HasFormData for SerializedFormData {
    fn value(&self) -> String {
        self.value.clone()
    }

    fn values(&self) -> HashMap<String, FormValue> {
        self.values.clone()
    }

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

#[cfg(feature = "serialize")]
impl HasFileData for SerializedFormData {
    fn files(&self) -> Option<std::sync::Arc<dyn FileEngine>> {
        self.files
            .as_ref()
            .map(|files| std::sync::Arc::new(files.clone()) as _)
    }
}

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

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

impl_event! {
    FormData;

    /// onchange
    onchange

    /// oninput handler
    oninput

    /// oninvalid
    oninvalid

    /// onreset
    onreset

    /// onsubmit
    onsubmit
}