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
308
309
310
311
312
313
314
315
use std::{
    fmt::Display,
    str::FromStr,
    convert::Infallible,
};
use rooting::{
    El,
    el,
};
pub use rooting_forms_proc_macros::Form;
use wasm_bindgen::JsCast;
use web_sys::HtmlInputElement;

/// Republished types for macro use.
pub mod republish {
    pub use web_sys::HtmlSelectElement;
}

/// Used for the text label before form fields.
pub const CSS_CLASS_LABEL: &'static str = "form_label";

/// Used for single-column inputs (text entry, checkbox). Exclusive with other
/// `form_input_` classes.
pub const CSS_CLASS_SMALL_INPUT: &'static str = "form_input_small";

/// Used for two-column inputs like text area. Exclusive with other `form_input_`
/// classes.
pub const CSS_CLASS_BIG_INPUT: &'static str = "form_input_big";

/// Used by the checkbox for options. Exclusive with other `form_input_` classes.
pub const CSS_CLASS_OPTION_ENABLE: &'static str = "form_input_option";

/// Used for validation errors, appears before the input (also before the
/// associated label, if there is one).
pub const CSS_CLASS_ERROR: &'static str = "form_error";

/// Used for nested struct/enum fields, namely within variants or options.
pub const CSS_CLASS_SUBFORM: &'static str = "subform";

/// Used to hide disabled variants - hidden to keep user input in case they
/// re-enable later.
pub const CSS_CLASS_HIDDEN: &'static str = "disable_hide";

/// This should be used on all inputs, since `<label>` isn't used.
pub const ATTR_LABEL: &'static str = "aria-label";

pub struct FormElements {
    /// The error display element, with `CSS_CLASS_ERROR`. This may be placed before
    /// the label in a struct context.
    pub error: Option<El>,
    /// The input, and any additional controls.
    pub elements: Vec<El>,
}

/// An object representing a form (the state of the form).
pub trait FormState<T> {
    /// Get the elements for this form or subform.
    fn elements(&self) -> FormElements;

    /// Parse the elements into the resulting type.
    fn parse(&self) -> Result<T, ()>;
}

/// This represnts a rust datatype that can be included in a form.
pub trait Form {
    /// Generates a form for a new value (no existing value).
    ///
    /// * `field` - is the field name, for accessibility using `aria-label`. `<label>`
    ///   isn't used sometime due to anonymous fields in tuples.
    fn new_form(field: &'static str) -> Box<dyn FormState<Self>>;
}

/// A minimal string wrapper that creates a password form input.
pub struct Password(String);

impl FromStr for Password {
    type Err = Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        return Ok(Password(s.to_string()));
    }
}

/// A minimal string wrapper that creates a textarea form input.
pub struct BigString(String);

impl FromStr for BigString {
    type Err = Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        return Ok(BigString(s.to_string()));
    }
}

/// A helper form type for rust types that implement `FromStr`.
pub struct FromStrFormState {
    el: El,
    error_el: El,
}

impl FromStrFormState {
    pub fn new<E: Display, T: FromStr<Err = E>>(label: &str, type_: &str) -> Box<dyn FormState<T>> {
        let error_el = el("span").classes(&[CSS_CLASS_ERROR]);
        return Box::new(FromStrFormState {
            el: el("input")
                .classes(&[CSS_CLASS_SMALL_INPUT])
                .attr(ATTR_LABEL, label)
                .attr("type", type_)
                .on("change", {
                    let error_el = error_el.clone();
                    move |ev| {
                        let text = ev.target().unwrap().dyn_ref::<HtmlInputElement>().unwrap().value();
                        if text.len() >= 1 {
                            match T::from_str(&text) {
                                Err(e) => {
                                    error_el.ref_text(&e.to_string());
                                    return;
                                },
                                _ => { },
                            }
                        }
                        error_el.ref_text("");
                    }
                }),
            error_el: error_el,
        });
    }
}

impl<E: Display, T: FromStr<Err = E>> FormState<T> for FromStrFormState {
    fn elements(&self) -> FormElements {
        return FormElements {
            error: Some(self.error_el.clone()),
            elements: vec![self.el.clone()],
        };
    }

    fn parse(&self) -> Result<T, ()> {
        match T::from_str(&self.el.raw().dyn_ref::<HtmlInputElement>().unwrap().value()) {
            Ok(v) => {
                self.error_el.ref_text("");
                return Ok(v);
            },
            Err(e) => {
                self.error_el.ref_text(&e.to_string());
                return Err(());
            },
        }
    }
}

impl Form for String {
    fn new_form(field: &'static str) -> Box<dyn FormState<Self>> {
        return FromStrFormState::new::<_, String>(field, "text");
    }
}

impl Form for Password {
    fn new_form(field: &'static str) -> Box<dyn FormState<Self>> {
        return FromStrFormState::new::<_, Password>(field, "password");
    }
}

impl Form for BigString {
    fn new_form(field: &'static str) -> Box<dyn FormState<Self>> {
        return FromStrFormState::new::<_, BigString>(field, "text");
    }
}

impl Form for u8 {
    fn new_form(field: &'static str) -> Box<dyn FormState<Self>> {
        return FromStrFormState::new::<_, Self>(field, "text");
    }
}

impl Form for u16 {
    fn new_form(field: &'static str) -> Box<dyn FormState<Self>> {
        return FromStrFormState::new::<_, Self>(field, "text");
    }
}

impl Form for u32 {
    fn new_form(field: &'static str) -> Box<dyn FormState<Self>> {
        return FromStrFormState::new::<_, Self>(field, "text");
    }
}

impl Form for u64 {
    fn new_form(field: &'static str) -> Box<dyn FormState<Self>> {
        return FromStrFormState::new::<_, Self>(field, "text");
    }
}

impl Form for i8 {
    fn new_form(field: &'static str) -> Box<dyn FormState<Self>> {
        return FromStrFormState::new::<_, Self>(field, "text");
    }
}

impl Form for i16 {
    fn new_form(field: &'static str) -> Box<dyn FormState<Self>> {
        return FromStrFormState::new::<_, Self>(field, "text");
    }
}

impl Form for i32 {
    fn new_form(field: &'static str) -> Box<dyn FormState<Self>> {
        return FromStrFormState::new::<_, Self>(field, "text");
    }
}

impl Form for i64 {
    fn new_form(field: &'static str) -> Box<dyn FormState<Self>> {
        return FromStrFormState::new::<_, Self>(field, "text");
    }
}

impl Form for f32 {
    fn new_form(field: &'static str) -> Box<dyn FormState<Self>> {
        return FromStrFormState::new::<_, Self>(field, "text");
    }
}

impl Form for f64 {
    fn new_form(field: &'static str) -> Box<dyn FormState<Self>> {
        return FromStrFormState::new::<_, Self>(field, "text");
    }
}

struct BoolFormState {
    input: El,
}

impl FormState<bool> for BoolFormState {
    fn elements(&self) -> FormElements {
        return FormElements {
            error: None,
            elements: vec![self.input.clone()],
        };
    }

    fn parse(&self) -> Result<bool, ()> {
        return Ok(self.input.raw().dyn_ref::<HtmlInputElement>().unwrap().checked());
    }
}

impl Form for bool {
    fn new_form(field: &'static str) -> Box<dyn FormState<Self>> {
        return Box::new(
            BoolFormState {
                input: el("input")
                    .classes(&[CSS_CLASS_SMALL_INPUT])
                    .attr(ATTR_LABEL, field)
                    .attr("type", "checkbox"),
            },
        );
    }
}

struct OptionFormState<T> {
    elements: Vec<El>,
    subform: Box<dyn FormState<T>>,
}

impl<T: Form> FormState<Option<T>> for OptionFormState<T> {
    fn elements(&self) -> FormElements {
        return FormElements {
            error: None,
            elements: self.elements.clone(),
        };
    }

    fn parse(&self) -> Result<Option<T>, ()> {
        let checked = self.elements[0].raw().dyn_ref::<HtmlInputElement>().unwrap().checked();
        if checked {
            return Ok(Some(self.subform.parse()?));
        } else {
            return Ok(None);
        }
    }
}

impl<T: Form + 'static> Form for Option<T> {
    fn new_form(field: &'static str) -> Box<dyn FormState<Self>> {
        let subform = T::new_form(field);
        let subform_elements = subform.elements();
        let mut additional = vec![];
        additional.extend(subform_elements.error.iter().cloned());
        additional.extend(subform_elements.elements);
        for e in &additional {
            e.ref_modify_classes(&[(CSS_CLASS_HIDDEN, true)]);
        }
        let mut elements = vec![
            //. .
            el("input")
                .classes(&[CSS_CLASS_OPTION_ENABLE])
                .attr(ATTR_LABEL, &format!("{} - Enabled", field))
                .attr("type", "checkbox")
                .on("click", {
                    let additional = additional.clone();
                    move |ev| {
                        let checked = ev.target().unwrap().dyn_ref::<HtmlInputElement>().unwrap().checked();
                        for e in &additional {
                            e.ref_modify_classes(&[(CSS_CLASS_HIDDEN, checked)]);
                        }
                    }
                })
        ];
        elements.extend(additional);
        return Box::new(OptionFormState {
            elements: elements,
            subform: subform,
        });
    }
}